Skip to main content

Miscellaneous

New Assignment instead of Virtual/Override
The "new" keyword can be used with methods, it provides a type of inheritance similar to polymorphism.
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
ChildClass cc = new ChildClass();
bc.Foo();
bc.Bar();
Console.WriteLine("=======================");
((BaseClass)cc).Foo();
((BaseClass)cc).Bar();
Console.WriteLine("=======================");
cc.Foo();
cc.Bar();
Console.WriteLine("=======================");
Console.ReadLine();
}
}

class BaseClass
{
public void Foo() { Console.WriteLine("BaseClass.Foo"); }
public virtual void Bar() { Console.WriteLine("BaseClass.Bar"); }
}

class ChildClass : BaseClass
{
new public void Foo()
{
Console.WriteLine("ChildClass.Foo");
base.Foo();
}
public override void Bar()
{
Console.WriteLine("ChildClass.Bar");
base.Bar();
}
}
Output:
BaseClass.Foo
BaseClass.Bar
=======================
BaseClass.Foo
ChildClass.Bar
BaseClass.Bar
=======================
ChildClass.Foo
BaseClass.Foo
ChildClass.Bar
BaseClass.Bar
=======================
In the above the use of new in the method signature indicates that we the ClildClass wishes to override the BaseClass method Foo().
As we can see from the output the call to
((BaseClass)cc).Foo();
results in
BaseClass.Foo
as we would expect. You could use Virual/Override to do the same thing. But note in the above case we use DownCasting, and in this case the Virtual/Override still calls the ChildClass.Foo and the new assignment version does not, this is suprising to me at least as I would have thought the opposite were true.



Calling one Constructor from another with CSharp

This allows us to create an instance with either of these 2 overloads.
Note that if we use the first overload then the second parameter is null, usually a check would be done in the second overload for null and some default applied
public MyClass(string param1) : this(param1, null)
{
}
public MyClass(string param1, string param2)
{
if(param2==null)
param2 = "default";
}
These could also be called vice versa of course
public MyClass(string param1)
{
_param2 = "default";
}
public MyClass(string param1, string param2) : this(param1)
{
_param2 = param2;
}


Request a Web Page from outside a Web Application

using System.Net;
using System.Xml;
using System.IO;

namespace UrlCall
{
class Program
{
static void Main(string[] args)
{

string url = "http://localhost:3703/ServerProject/Cookie/GetCookie.aspx";

HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myWebRequest.Method = "GET";
// make request for web page
HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());
string myPageSource = myWebSource.ReadToEnd();
myWebResponse.Close();

}
}
}

Reflection, how the metadata works
CodeProject has an explanation of the internals of a .NET assembly.

Training/Certification
dotNetSlackers has a good description of the .NET Certification available.

Tools

.NET Framework Tools (msdn).
CFF Explorer (Tool to investigate the internals of a .NET assembly).

Fix ASP.NET

If you've installed a new version of .NET you'll have to register it, it's required for ASP.NET to use the correct version
aspnet_regiis.exe -i
Depending on where you call this from will determine which .NET gets used with ASP.NET
e.g.
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -i
Errors that this may fix are
"Some of all identity References could not be translated"
"iis metadata access rights.

GAC (installing assemblies in the GAC)
The GAC is a location on Windows where Assemblies can be stored, the idea is that all applications can access this one assembly. It's also versioned. The GAC contents can be viewed at C:\Windows\Assembly.
To install your assembly in the GAC you can use to methods
The exe from the .NET SDK
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\gacutil.exe /i
or the Visual Studio SDK
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe /i
or programmically using the GacInstall class
try
{
System.EnterpriseServices.Internal.Publish gac = new System.EnterpriseServices.Internal.Publish();
gac.GacInstall(assemblyName);
}
catch (System.Security.SecurityException se)
{

}

Assembly Code Analysis Tool (FxCop)
FXCop is a MS Tool which analyzes you Managed Code by loading your assembly, reading the manifest and analysing the MSIL in the CLR.
FxCop bried description (TechRepublic)
FxCop (msdn)


Download from gotdotnet.com



Http debugging tool

So you want to view the Http traffic between client and server. Fiddler's your man.
You can view the traffic on requests including Cookies and Cached data.
For more see msdn and fiddler.com.

Some useful dotNET methods etc

  • Ref and Out
  • Use these keywords to pass a reference to another method so that it the reference itself can be changed. All objects are passed by reference in C#, meaning if you wish another object to change values in another object you simply pass the objects reference (the variable name) to the method as normal.
  • Class Passer
    {
    List messages = new List();
    Receiver r = new Receiver();
    r.Method(messages);
    }
  • Class Reveiver
    {
    void Method(List messages)
    {
    message.add("I'm adding a new item to the Passers member messages, this affects the original");
    }
  • However if you want another method or object to change the instance itself, I mean new-up a new memory location with your original reference then you use Ref.
  • The difference between Ref and Out is that Ref is initialized by the passing object and Out is initialized by the receiving object e.g.
  • Class Passer
    {
    List refMessages = new List();
    Receiver r = new Receiver();
    r.RefMethod(ref refMessages);

List outMessages; //not initialized here in the passing object
r.OutMethod(ref refMessages);
}


    Class Reveiver
    {
    void RefMethod(ref List refmessages)
    {
    refmessage.add("I'm adding a new item to the Passers member messages");
    }
void OutMethod(out List outmessages)
{
List outmessages = new List();
outmessage.add("I'm adding a new item to the Passers member messages");
}

}



  • To determine if it's a web app or a windows app use
    • System.Web.HttpContext.Current;
    • If null it's a windows app.
  • TryParse can now be used to determine if 2 values are equal.
    • It can presently be used for int, double, DateTime ....
    • There are 2 params, the value your comparing to and the out which is the result boolean value which is set.
  • Using statement
    • If you are using an Object which implements the Dispose/Inherits from IDisoposing then you can use Using to ensure the object is GC'd after use.
e.g. instead of StopWatch sw = new StopWatch try
using(StopWatch sw = new StopWatch try)
{....
}//sw is deleted here.


  • Get the name of the current method at runtime, useful for printing:
System.Reflection.MethodBase mb = System.Reflection.MethodBase.GetCurrentMethod();
Get the name of the Current Method
string currentMethod = mn.Name;
Get the Current Class name
string currentClassName = mb.DeclaringType.Name;
Or Get a Method at a particular location in the stack: System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(0, true); //To get the calling method name, use 1 instead of 0.
string currentMethodName = System.Reflection.MethodBase mb = sf.GetMethod();
string methodName = mb != null ? mb.Name : "nothing found";
  • Creating Disposable Objects
  • Visual Studio Project Macros/Variable/Properties
  • Here's a useful static method for dumping messages (debugging) to a file:

  • public class DebugWriter
    {
    public static void WriteDebugToFile(string message)
    {
    string path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "DebugFile.txt"));
    StreamWriter sw = null;
    if (!File.Exists(path))
    {
    using (sw = File.CreateText(Path.GetFullPath(Path.Combine (Environment.CurrentDirectory, "DebugFile.txt"))))
    {
    }
    }
    using (sw = File.AppendText(path))
    {
    sw.WriteLine(message);
    sw.Close();
    }
    }
    }



Comments

Popular posts from this blog

dotNET - Debugging

Debugging with .NET MSIL assemblies Visual Studio and debugging the CLR are different, I'll talk about both. MSIL Assemblies Assemblies compiled with .NET tools such as the CLR compiler are compiled into a file which contains MSIL (Microsoft Intermediate Language). At runtime the contents of the assembly are loaded into the CLR and ran as machine code. When you compile an assembly in debug a PDB file is generated alongside the DLL or EXE you've just created. The link between these 2 files is that the PDB contains the line numbers of the methods and classes as well as the file names of the original source code that created the assembly. When you launch the debugger in Visual Studio the assembly is loaded into the Debugger (similar to the CLR) along with the PDB file. The debugger now uses your PDB file contents to match the running code found in the assembly to locations in source files (hopefully in your present project). CLR CLR Inside Out (msdn magazine) .NET Framework Tools:...

Installer CustomAction, Debugging the CustomAction, InstallState

Custom Action The Custom Action is added to the Setup Project, select the Project node and hit the Custom Action button. This allows you add an Action to a particular phase in the Installation. But first you must create the Custom Action. To Add a Custom Action you must first have a Custom Action created, this is usually in the form of a Installer Class, this should be created in a seperate project, the Installer Class is actually one of the File Templates in the C# Projects. So it's File->New Project and select Visual C# Projects. Then add a Class Library, this will prompt you for the Class Library Types , select "Installer Class". Walkthrough - Creating Custom Action (msdn). Also here's a more comprehensive document on Setup/Installer implementations, it delves into the Registry etc Getting Started with Setup Projects (SimpleTalk). Visual Studio Setup Projects and Custom Actions (Simple Talk). Create your Installer Class and then add it as a Custom Action to the ...

dotNET - Use app.config ApplicationSettings and UserSettings

When using Settings in an Assembly or .exe you can use the Settings Designer to generate a config file using Settings. The Settings Designer provides a wrapper class which allows you to provide defaults and access the config data using Properties. But what if you're not working inside that Assembly or .exe? this presents a problem. If your loading the Assembly externally and want to access that Assembly's .config file you'll probably wish to use something in the System.Configuration namespace... unfortunately it's not of much use if you've created the .config file from the Settings Designer in Visual Studio!! This is because the Designer creates Sections and ApplicationSettings and UserSettings, the System.Configuration namespace does not provide a method to access these (it has a method to access AppSettings which are a different thing. Below I've written a workaround which locates the app.config and accesses the ApplicationSettings and UserSettings using XML i...