Home   Notes 

.NET

Local

External


Windows.Web how to make it available

Windows.web is not available in the .NET Framework Client Profile.
You must pick the full .NET Framework to be available.
To change the profile go to the project settings and changed the value for Target framework:
After the correct framework is chosen you can find System.Web under the .NET tab of the
Add References dialog.

Services


Threading

using System.Threading; class Test { public run() { // no param thread Thread tNo = new Thread(new ThreadStart(ThreadProcNo)); tNo.Start(); // param thread Thread tYes = new Thread(new ParameterizedThreadStart(ThreadProcParam)); tYes.Start(this); } private static void ThreadProcNo() { // in thread } private static void ThreadProcParam(Object obj) { // in thread } }

Databinding

See: http://www.akadia.com/services/dotnet_databinding.html


Application Domains

An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process. The primary purpose of the AppDomain is to isolate applications from each other, and so it is particularly useful in hosting scenarios such as ASP.NET. An AppDomain can be destroyed by the host without affecting other AppDomains in the process.

Win32 processes provide isolation by having distinct memory address spaces. This is effective, but expensive. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory.

One non-obvious use of AppDomains is for unloading types. Currently the only way to unload a .NET type is to destroy the AppDomain it is loaded into. This is particularly useful if you create and destroy types on-the-fly via reflection.

It is important to note that only type-safe code can be managed in this way (the runtime cannot guarantee isolation when unsafe code is loaded in an application domain).

Some of the advantage of using AppDomain are:

From http://mihirsolanki.com/blog/archive/2005/12/05/1891.aspx


Multi Form Apps

private int GetValueViaModal()
{
	// using lets the system know it can dispose of this as soon as it goes out of scope.
	using( FormInputValue form = new FormInputValue())
	{
		DialogResult dr;
		
		dr = form.ShowDialog();
		if ( dr == DialogResult.OK) {
			return form.GetInputtedValue;
		}
	}
}

Validating Win Forms

using SWF = System.Windows.Forms;

public static void IsInteger( object sender, System.ComponentModel.CancelEventArgs e)
{
	SWF.TextBox txt;
	txt = (SWF.TextBox) sender;
	
	try {
		int.Parse(txt.Text);
	} catch {
		SWF.MessageBox.Show("Bad input.", "Note");
		e.Cancel = true; // makes focus stay in control so user can fix problem
	} 
}

private Form_Load( object sender, System.EventArgs e)
{
	txtField1.Validating += new System.ComponentModel.CancelEventHandler( IsInteger);
}

private Form_RemoveValidation( object sender, System.EventArgs e)
{
	txtField1.Validating -= new System.ComponentModel.CancelEventHandler( IsInteger);
}

Config Files


Tracing

Code to Get and Hold Trace flag

public class Globals
{
	public static readonly bool Trace;
	
	static Globals()
	{
		try {
			Trace = System.Convert.ToBoolean( System.Configuration.ConfigurationSettings.AppSettings["Tracing"] );
		} catch {
			Trace = true;
		}
	}
}

Where Trace flag setting lives

Same name as executable with .config appended to it, and it lives in the same directory as the executable.

For example if the app is App.exe the config file is App.exe.config

Note: In Visual Studio you can Project | Add New Item | Application Config File to create a config file that automatically gets placed where the app goes and will name it correctly on copy (for example: Deubug or Release

<configuration>
	<appSettings>
		<add key="Tracing" value="true" />
	</appSettings>
</configuration>

Doing it (with built in trace)

using T = System.Diagnostics.Trace;

try {
	T.WriteLineIf( Globals.Trace, "Entering Something");
	T.Indent();
	T.WriteLineIf( Globals.Trace, "Doing something");
} catch {
	T.WriteLineIf( Globals.Trace, ex.GetType() + ": " + ex.Message);
	T.WriteLineIf( Globals.Trace, ex.StackTrace);
} finally {
	T.Unindent();
	T.Flush();
}

To make trace goto a file

public static void Main()
{
	string logfile = System.AppDomain.CurrentDomain.BaseDirectory + "TraceLog.txt";
	System.IO.TextWriter log = new System.IO.StreamWriter( logfile);
	
	if ( Globals.Trace) {
		System.Diagnostics.TextWriterTraceListener logger;
		logger = new System.Diagnostics.TextWriterTraceListener( log);
		System.Diagnostics.Trace.Listeners.Add( logger);
		System.Diagnostics.Trace.WriteLine("App starting: " + DateTime.Now);
	}
}

Programming Rules

Based upon webcasts by Joe Hummel

  1. Override the ToString method.
  2. Initialize via Constructor
  3. Have multiple constructors call the base constructor (this should be in the next version of c++ as well!)
  4. Use static constructor to initialize static values (java has something like this)
  5. Declare constants as readonly fields.
    This way they exist in only one component, and if the value changes, code in other modules that use the value will use the new value without a recompile.
  6. Use enums for sets of constants
  7. Use properties when possible.
  8. Consider overriding Equals( object obj)
    Note that the default Equals just compares if the reference pointers are the same.
  9. If you override Equals, you should always override GetHashCode()
  10. Define Dispose() (and make the class inherit IDisposable ) if your objects need cleanup.
    Either design classes not to hold on to resources
    Or Implement IDisposable and supply Dispose() and Close methods.
  11. If you implement IDisposable then you should have a finalizer as well ~Classname
  12. Consider inheriting from ICloneable and then define Clone
    Note that this.MemberwiseClone() will return a shallow clone.
    But in v2.0 ICloneable is Depricated so maybe use these 2 methods instead DeepClone() and ShallowClone
  13. Avoid error messages, and returning error numbers, instead try to use throw new Exception("Exception Text");
  14. Use XML comments and auto generate class level documentation Visual Studio .NET will extract the comments into docs Tools | Build Comment Web Pages set the property Config | Build to generate .xml file
    Then use "NDoc" (from sourceforge) to convert to nice MSDN style docs.
  15. At the end of the Application do something like this, call a method something like waitForPendingFinalizers() on the Garbage Collector. Otherwise the program may exit before all Dispose()'s are called
public enum Weekdays
{
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday
}

/// <summary>
/// This is an example class
/// </summary>
public class Example
{
	private string      m_strName;
	private int         m_nAge;
	static int  m_nSecretNumber;
	public static readonly float PI = 3.14;
	
	private int m_value1; // field used by property starting on next line
	public string Value1 // property
	{
		get { return m_value1; }
		set {
			if ( m_value1 >= 0) {
				m_value1 = value;
			}
		}
	}
	
	// readonly property:
	private int m_value2; // field used by property starting on next line
	public string Value2 // property
	{
		get { return m_value2; }
	}
	
	// writeonly property
	private int m_value3; // field used by property starting on next line
	public string Value3 // property
	{
		set {
			if ( m_value3 >= 0) {
				m_value3 = value;
			}
		}
	}

	public Example( string strName, int nAge) {
		m_strName   = strName;
		m_nAge      = nAge;
	}
	
	// finalizer:
	~Example()
	{
	}

	// Constructor that calls base constructor
	public Example( string strName)
	: this( strName, -1) {
	}

	// static constructor:
	static Example() {
	m_nSecretNumber = 42;
	}

	public override ToString() {
	return "Example Object";
	}
	
	/// <summary>
	/// Custom Equal because
	/// </summary>
	public override bool Equal( Object obj) {
		if ( obj == null)
			return false;
		if ( !(obj.GetType().Equals( this.GetType())) )
			return false
		Example other = (Example)obj;
		return 
			m_strName.Equals( other.m_strName()) &&
			(m_nAge == other.m_nAge);
		return true;
	}
	public override int GetHashCode() {
		return m_strName.GetHashCode() + m_nAge.GetHashCode();
	}
}

Value Types


Namespace Aliases

Provide a way to have a short name for a namespace.

using SW = System.Windows;

Disassembler

ildasm

Anakrino

Disassembles to high level code


Questions


Tools

ToolUse
gacutil.exeManage Global Assemblies, list, empty from cache, etc.

Strong Name Creation


Thread, Background

A thread that has its IsBackground property set to true, will not stop the application from exiting.


Assembly Pathing, how an Assembly finds one it uses


Terms

TermDefinition
Application DomainsEffectively 'Process Boundries', but you can make code in the same app be seperated into Application Domains as well. There are ways that you can access objects in another Application Domain
Boxed TypeValue type that has been converted to an object (in Java this would be Integer which wraps int)
CLSCommon Language Specification (a set of rules that allow cross language interoperability)
Managed codeCode run in the CLR. It is garbage collected, must obey security polices, and is verified safe to other code (i.e. no bad pointers can damage data of other apps or things running in a different Application Domain)
Managed C++C++ supporting .NET (has garbage collection)
Side-by-Side ExecutionAllows multiple versions of libraries to be co-exist on the same computer, or even the same process
Value TypeBasically a built-in type (like int or double)