Showing posts with label C Sharp. Show all posts
Showing posts with label C Sharp. Show all posts

Friday, October 10, 2008

Easy File Download from web

Its a single line code to download a file given a url and downlaod dir

(new WebClient()).DownloadFile(url, downlaoddir);

But if there is windows authentication required on the site the maybe three lines :)

WebClient client = new WebClient();
client.UseDefaultCredentials = true;
client.DownloadFile(url, downloaddir);

But it seems to a very easy option to work with.
It also provides multiple async downloads etc.

Ex:

WebClient wc = new WebClient();
string website1 = "http://remote1.ispnet.net";
string website2 = "http://remote2.ispnet.net";
string website3 = "http://remote3.ispnet.net/login";


NetworkCredential nc1 = new NetworkCredential("mike", "guitars");
NetworkCredential nc2 = new NetworkCredential("evonne", "singing", "home");
NetworkCredential nc3 = new NetworkCredential("alex", "drums");

CredentialCache cc = new CredentialCache();
cc.Add(new Uri(website1), "Basic", nc1);
cc.Add(new Uri(website2), "Basic", nc2);
cc.Add(new Uri(website3), "Digest", nc3);

wc.Credentials = cc;

wc.DownloadFile(website1, "website1.htm");
wc.DownloadFile(website2, "website2.htm");
wc.DownloadFile(website3, "website3.htm");

form - Example Reference

Read/Modify Application Configuration .config file

Read
string value = ConfigurationManager.AppSettings["oldPlace"];

Write

System.Configuration.Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings["oldPlace"].Value = "3";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

Friday, May 9, 2008

ICollection & IEnumerator

ICollection inerface is used to make a custom collection type.
Function which must be used are - Add, Clear, Count, GetEnumerator
IEnumerator interface is used to enumerator through a collection.
Functions which must be used are - MoveNext, Current, Reset

The example below is the most basic and is used to create a string - string collection where each item in second list is dependent upon the item in the first list at the same index position.

Example

Collection class

public class CustomCollection : ICollection
{
List customMainList = new List();
List customDependentList = new List();


public virtual void Add(string x, string y)
{
customDependentList.Add(y);
customMainList.Add(x);
}

public virtual void Clear()
{
customMainList.Clear();
customDependentList.Clear();
}

#region ICollection Members

public void CopyTo(Array array, int index)
{
throw new Exception("The method or operation is not implemented.");
}

public int Count
{
get { return customMainList.Count; }
}

public bool IsSynchronized
{
get { throw new Exception("The method or operation is not implemented."); }
}

public object SyncRoot
{
get { throw new Exception("The method or operation is not implemented."); }
}

#endregion

#region IEnumerable Members

public IEnumerator GetEnumerator()
{
return new CustomCollectionEnumerator(customMainList, customDependentList);
}

#endregion
}


Enumerator for collection class

public class CustomCollectionEnumerator : IEnumerator
{
List customMainList = null;
List customDependent = null;
int position = -1;

public CustomCollectionEnumerator(List main, List dep)
{
customMainList = main;
customDependent = dep;
}

#region IEnumerator Members

public object Current
{
get { return new KeyValuePair(customMainList[position], customDependent[position]); }
}

public bool MoveNext()
{
position++;
return (position < customMainList.Count);
}

public void Reset()
{
position = -1;
}

#endregion
}


Used in a program


CustomCollection cus = new CustomCollection();
cus.Add("wts1", "admin");
cus.Add("wts1", "suzie");
cus.Add("wts2", "admin");
cus.Add("wts3", "sally");
cus.Add("wts2", "dam");
foreach (KeyValuePair pair in cus)
{
Console.WriteLine(pair.Key + " : " + pair.Value);
}
Console.ReadKey();

Monday, March 24, 2008

Custom Controls

Introduction(Design Web Control)

Post back data is not the only thing that you may want to deal with in your custom controls. You may want your control to cause a post back and raise some server side event such as Click or SelectedIndexChanged. Handling a post back event requires that your control implements IPostBackEventHandler interface. In this article I explain how that can be done.
IPostBackEventHandler Interface

The IPostBackEventHandler interface must be implemented by your custom control class if it requires to handle post back event. This interface contains a single method as shown below:

void RaisePostBackEvent(string eventArgument)

The PaisePostBackEvent() method gives you a chance to raise a server side post back event (e.g. Click or SelectedIndexChanged). The method receives an event argument parameter of type string which may contain event argument data if any.
Example

Let's create a simple custom control that implements IPostBackEventHandler interface and raises Click event upon post back. Begin by creating a new web site in Visual Studio.

Add App_Code to your web site and further add a new class named GraphicButton. The following code shows the class definition.

namespace BinaryIntellect.UI
{
public class GraphicButton : WebControl, IPostBackEventHandler
{
public GraphicButton(): base(HtmlTextWriterTag.Span)
{

}
...

Here, you create a class named GraphicButton that resides in BinaryIntellect.UI namespace. The GraphicButton class inherits from WebControl base class and implements IPostBackEventHandler interface. The constructor of GraphicButton class calls its base class constructor by passing HtmlTextWriterTag. This indicates that your control builds over tag.

Now add two public properties viz. ImageUrl and Text to the GraphicButton class.

public string ImageUrl
{
get { return ViewState["imgurl"] as string; }
set { ViewState["imgurl"] = value; }
}

public string Text
{
get { return ViewState["text"] as string; }
set { ViewState["text"] = value; }
}

The ImageUrl property specifies the image URL to be displayed and Text property specifies the text to be rendered. Both of the property values are stored in ViewState. Then declare Click event as shown below:

public event EventHandler Click;

The Click event is raised when user clicks on the image rendered by the GraphicButton control. Now override the RenderContents() method of the WebControl base class and emit the required markup.

protected override void RenderContents(HtmlTextWriter writer)
{
base.RenderContents(writer);
writer.WriteFullBeginTag("center");
writer.WriteBeginTag("img");
writer.WriteAttribute("name", this.UniqueID);
writer.WriteAttribute("src", ImageUrl);
writer.WriteAttribute("onclick",
Page.ClientScript.GetPostBackEventReference
(this, string.Empty));
writer.Write("/>");
writer.Write("
");
writer.Write(Text);
writer.WriteEndTag("center");
}

Here, we render an image tag and set its name and src attributes. It also renders the Text property value below the image. In order that the image tag triggers a post back event you need to handle its client side onclick event handler. Notice the call to GetPostBackEventReference() method. This method returns a javascript function (__doPostBack()) that actually causes the post back. The GetPostBackEventReference() method accepts two parameters viz. the control that will receive the post back and event arguments if any. If you supply some event arguments then they will be passed on to RaisePostBackEvent() method.

Finally, implement the IPostBackEventHandler interface by writing RaisePostBackEvent() method.

public void RaisePostBackEvent(string eventArgument)
{
Click(this, EventArgs.Empty);
}

Here, you simply raise the Click event of GraphicButton control.

This completes the control. In order to use it on a web form register it with the page framework as shown below:

<%@ Register
Namespace="BinaryIntellect.UI"
TagPrefix="mycontrols" %>

Also create an instance of the GraphicButton control on the web form.

Text="Save changes to database"
ImageUrl="SaveButton.gif"
onclick="button1_Click"
Font-Bold="True" />

Set the ImageUrl and Text properties to some image URL and text respectively and run the web form. Handle the Click event of the GraphicButton as follows:

protected void button1_Click
(object sender, EventArgs e)
{
Label1.Text = "Button clicked";
}

The following figure shows a sample run of the web form.




Introduction(Enhance Web Control)

Developing a nice custom control is just one part of the story. As a control author you should also pay attention about the experience of other developers who will be using your control. In most of the real world cases developers use Visual Studio as the IDE for developing .NET applications. You can enhance the experience of other developers using your control by providing proper designer support. For example, you can control how your control properties and events are displayed in property window and toolbox. A set of attributes often called as Design Time Attributes allow you to accomplish this.
Common Design Time Attributes

The following sections explain the common design time attributes that allow you to change how the control behaves in the property window and toolbox. Most of these attributes reside in System.ComponentModel namespace. In the following sections we use the GraphicButton control that we created earlier in this series.
Deciding whether a property will be visible in the property window

By default all the public properties of a custom control are displayed in the property window. Sometimes you may want that developers should set a property only via code and not via property window. The [Browsable] attribute allows you to control just that. The usage of this attribute is as follows:

[Browsable(false)]
public string ImageUrl
{
get { return ViewState["imgurl"] as string; }
set { ViewState["imgurl"] = value; }
}

The value of false indicates that the ImageUrl property will not be displayed in the property window.
Adding description to a property

Have a look at the screen capture below:

Can you notice a one line description of the Text property at the bottom portion of the property window? Such description can be added using [Description] attribute.

[Description("Specifies the caption of the graphic button")]
public string Text
{
get { return ViewState["text"] as string; }
set { ViewState["text"] = value; }
}

Grouping related properties

The property windows allows you list properties either alphabetically or grouped in categories. Grouping properties by category makes it simple to locate them as per their functionality. Have a look below where the ImageUrl and Text properties are grouped together under Control Values category.

The [Category] attribute allows you to specify category for your property.

[Category("Control Value")]
public string Text
{
get { return ViewState["text"] as string; }
set { ViewState["text"] = value; }
}

Enabling data binding for a property

You may want to use your custom control as a child control of some data bound control (say DataList). Further, you may want to data bind some of the control properties. In other words you want to list your control properties in the data bindings editor as shown below:

The [Bindable] attribute enables this behavior for you.

[Bindable(true)]
public string Text
{
get { return ViewState["text"] as string; }
set { ViewState["text"] = value; }
}

Making a property read only

At times you may want that a control property be listed in the property window but it should be read only. This behavior can enabled using [ReadOnly] attribute.

[ReadOnly(true)]
public string Text
{
get { return ViewState["text"] as string; }
set { ViewState["text"] = value; }
}

Setting a property of multiple control instances

When you select multiple instance of the same control and set a property in the property window all the instances bear the same property value. You may not always this default behavior. You can use [MergableProperty] attribute to indicate this to the IDE.

[MergableProperty(true)]
public string Text
{
get { return ViewState["text"] as string; }
set { ViewState["text"] = value; }
}

Refreshing other properties when a property value changes

Some times your properties are interdependent in that if value of one property changes then it causes value of some other property to change. In such cases you would like to refresh the property window when a property value changes. The [RefreshProperties] attribute allows you to indicate such a behavior.

[RefreshProperties(RefreshProperties.All)]
public string Text
{
get { return ViewState["text"] as string; }
set { ViewState["text"] = value; }
}

The [RefreshProperties] attribute accepts a parameter of type RefreshProperties enumeration. The three possible enumeration values are None, All and Repaint.
Setting a default property and event

When yu drag and drop a control instance on the web form you may want to show a particular property (or event) selected by default in the property window. This can be accomplished with the help of [DefaultProperty] and [DefaultEvent] attributes respectively.

[DefaultEvent("Click")]
[DefaultProperty("Text")]
public class GraphicButton :
WebControl, IPostBackEventHandler
...

Notice that unlike other attributes we discussed so far the [DefaultProperty] and [DefaultEvent] attributes are class level attributes. Both of these attributes take a string parameter indicating the name of the default property and event respectively.
Changing icon displayed in the toolbox

By default a newly created custom control is shown in the toolbox as shown below (see the gear icon):

You may want to change the default icon displayed along with your control. You do this by adding a bitmap file to your custom control project and naming it same as the custom control class. For example, for our BinaryIntellect.UI.GraphicButton control you would add a bitmap with name BinaryIntellect.UI.GraphicButton.bmp. The bitmap must be 16x16 pixels and should use no more than 16 colors.

There is another way to set toolbox bitmap - the [ToolboxBitmap] class level attribute.

[ToolboxBitmap(@"C:\BinaryIntellect.UI.GraphicButton.bmp")]

The [ToolboxBitmap] attribute takes the full path of the bitmap file. Remember that the [ToolboxBitmap] attribute resides in System.Drawing namespace.

The following figure shows how a custom bitmap looks like in the toolbox.


Introduction(Custom Control Complex Type Code Serialization)

Whenever you set any property of a control in the property window, the property window needs to save this property value in the .aspx file. This process is known as code serialization. For properties that are of simple types (such as integer and string) this code serialization happens automatically. However, when property data types are user defined complex types then you need to do that work yourself. This is done via what is called as Type Converters. This article is going to examine what type converters are and how to create one for your custom control.
Type Converters

A type converter is a class that converts values entered in the property window to the actual data type of the property and vice a versa. The type converter class is inherited from TypeConverter or ExpandableObjectConverter base class. If you inherit from TypeConverter base class then you need to supply a delimited string in the property window where each part of the string corresponds to a property of the underlying complex type. If you inherit from ExpandableObjectConverter base class then Visual Studio makes your job easy by providing an expandable tree to enter the individual property values. The following figure shows how this expandable region looks like:

Creating an Expandable Type Converter

As an example of creating a type converter let's assume that you have a custom control that displays full name in the web form. The Name property of the control allows you to specify the full name to be displayed. The Name property is of type FullName. The FullName class consists of two public properties namely FirstName and LastName.
Creating FullName class

To begin developing this example first of all create a new Web Control project in Visual Studio. Add a new class to the project and name it as FullName. Code the FullName class as shown below:

[Serializable]
public class FullName
{
private string strFName;
private string strLName;

public string FirstName
{
get
{
return strFName;
}
set
{
strFName = value;
}
}

public string LastName
{
get
{
return strLName;
}
set
{
strLName = value;
}
}

public FullName()
{
}

public FullName(string fname, string lname)
{
strFName = fname;
strLName = lname;
}
}

The FullName class simply consists of two public properties namely FirstName and LastName. Notice that the FullName class is marked as [Serializable]
Creating FullNameConverter class

Now add another class to the project and name it as FullNameConvertor. Inherit the FullNameConvertor class from ExpandableObjectConverter base class. As a convention the type converter class names should have name of the class they convert attached with "Converter" at the end. Once created you need to override certain methods of the base class. These methods are explained next.

* bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
The CanConvertFrom method tells the property window whether the source type can be converted to the property data type. Most of the cases you will ensure that if the source type is string then the method returns true; false otherwise.
* bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
The CanConvertTo method tells the property window whether a property value can be converted to the destination data type. Most of the cases you will ensure that if the destination type is string then the method returns true; false otherwise.
* object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
The actual task of converting a source value (string) into the destination type (FullName) is done inside ConvertFrom method
* object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
The actual task of converting a property value (FullName) to the destination type (string) is done inside ConvertTo method.

The following code shows all these methods for FullNameConverter class.

public override bool CanConvertFrom
(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
else
{
return base.CanConvertFrom(context, sourceType);
}
}

public override bool CanConvertTo
(ITypeDescriptorContext context,
Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
else
{
return base.CanConvertTo(context, destinationType);
}
}

public override object ConvertFrom
(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value)
{
if(value is string)
{
string[] names = ((string)value).Split(' ');
if (names.Length == 2)
{
return new FullName(names[0],names[1]);
}
else
{
return new FullName();
}
}
else
{
return base.ConvertFrom(context,culture,value);
}
}

public override object ConvertTo
(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value, Type destinationType)
{
if (value is string)
{
FullName name = value as FullName;
return name.FirstName + " " + name.LastName;
}
else
{
return base.ConvertTo(context, culture, value,
destinationType);
}
}

The CanConvertFrom() method checks if the data type of proposed value is string. If so it returns true otherwise base class version of CanConvertFrom() method is called. Similar job is done inside CanConvertTo() method. Remember that these two methods though sound similar are called at different times. The CanConvertFrom() method is called when you enter a value in the property window whereas CanConvertTo() method is called when property window reads previously serialized property value.

The ConvertFrom() method converts a supplied string value into an instance of type FullName. It does so by splitting the source string (e.g. Nancy Davalio) at the occurrence of a white space. An instance of FullName class is returned based on the supplied FirstName and LastName values.

The ConvertTo() method does reverse of ConvertFrom() method. It converts a FullName instance into its string representation. This is done by simply concatenating FirstName property, a white space and the LastName property. The resultant string is returned from the ConvertTo() method.

Note that in the above example we inherited FullNameConverter class from ExpandableObjectConverter base class. Even if you inherit from TypeConverter base class the process of overriding the methods remains the same.
Attaching type converter to FullName class

Now that you have completed the FullNameConverter class it's time to attach it to the FullName class. This is done as follows:

[TypeConverter(typeof(FullNameConvertor))]
[Serializable]
public class FullName
...

You need to decorate the FullName class with [TypeConverter] attribute. The TypeConverter attribute accepts the type information of a class that is acting as a type converter for this class.
Synchronizing markup and property window

Whenever you make any change in the property window immediately the new values should be saved to the .aspx file. To enable this behavior you need to mark the FirstName and LastName properties with the following additional attributes.

[RefreshProperties(RefreshProperties.All)]
[NotifyParentProperty(true)]

The RefreshProperties() attribute should be familiar to you because we discussed it in the previous article of this series. It simply refreshes the property window by re-querying all the property values. More important is the NotifyParentProperty() attribute. This attribute governs whether the parent property (Name) is to be notified when any of the child properties (FirstName and LastName) are changed. This way the parent property can reflect the newly assigned values.
Coding the custom control

Now it's time to develop our custom control. We will call it as FullNameLabel and it resembles as shown below:

public class FullNameLabel : WebControl
{
[DesignerSerializationVisibility
(DesignerSerializationVisibility.Visible)]
[PersistenceMode(PersistenceMode.InnerProperty)]
public FullName Name
{
get
{
return ViewState["_fullname"] as FullName;
}
set
{
ViewState["_fullname"] = value;
}
}

protected override void Render(HtmlTextWriter writer)
{
if (Name != null)
{
writer.WriteFullBeginTag("span");
writer.Write(Name.FirstName);
writer.Write(" ");
writer.Write(Name.LastName);
writer.WriteEndTag("span");
}
}
}

The code inside the FullNameLabel control is not a rocket science. It simply declares a public property called Name that is of type FullName. It then emits the first name and last name separated by a white space in the overridden Render() method.

Carefully notice the declaration of FullNameLabel class. It is marked with two special attributes viz. [DesignerSerializationVisibility] and [PersistenceMode]. The [DesignerSerializationVisibility] attribute governs whether a property will be serialized. The DesignerSerializationVisibility enumeration has four possible values viz. Default, Visible, Content, Hidden. The value of Content indicates that the contents of the property will be serialized.

The [PersistenceMode] attribute governs how a property will be serialized. The PersistenceMode enumeration has four values namely Attribute, InnerProperty, InnerDefaultProperty and EncodedInnerDefaultProperty. The value of InnerProperty indicates that the Name property will be serialized as a nested tag of the custom control tag.

You can see details of other enumerated values of DesignerSerializationVisibility and PersistenceMode enumeration in MSDN help.

If you use the FullNameLabel control on a web form you should see its Name property in the property window as shown below:

Notice how the FirstName and LastName properties appear as sub-properties of Name property. The serialized markup of the control after the Name property is set looks like this:

runat="server" EnableTheming="True">



Notice how the Name tag appears as a nested tag of tag.


Referrence articles

Create Custom Control
Enhance Experience
Code Serialization

Thursday, January 31, 2008

Fusion - .net tool (binds refernces/probing)

fusion (fuslogvw.exe - default location c:\program files\microsoft visual studio 8\SDK\\bin ) does the job of finding assembly references at a fixed number of location.

Probing looks for references in the current dir as well as the dir/
eg: lets say current dir is Pro. so searching for foo.dll, fusion looks in Pro and Pro/foo directories for the dll.


to view the search log we need to enable a registry key -
goto vs command prompt
reg add HKLM\Software\Microsoft\Fusion /v EnableLog /t REG_DWORD /d 1
--adds a registry key 'EnableLog' under fusion(codename of the assembly loader component of the CLR) of type DWORD


You can create a simple program which refers a dll and then move the refered dll to some other location(other then dir\)

after enabling fusion log u'll get message that define the search process otherwise u'll just get a .net exception message.

references -

Wednesday, January 16, 2008

Performance Counter

PerformanceCounterCategory class can be used to create key and type-value inside it.
It creates it under "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services" in the regedit.

PerformanceCounterCategory.Exists - weather the specified custom counter exists.
PerformanceCounterCategory.Create - creates a new custom counter.

Eg:

if (!PerformanceCounterCategory.Exists("MySingleCategory"))
{
PerformanceCounterCategory.Create ("MySingleCategory",
"My New Perf Category Description", "MyCounter",
"My New Perf Counter Desc");
}
else
{
Console.WriteLine("Counter already exists");
}


Another class 'CounterCreationDataCollection' can be used to add more then one custom counter. Create multiple instance of counter using 'CounterCreationData'. Add them to the collection and create the performanceCounterCategory using this collection.


Eg:

CounterCreationDataCollection col =
new CounterCreationDataCollection();

// Create two custom counter objects.
CounterCreationData counter1 = new CounterCreationData();
counter1.CounterName = "Counter1";
counter1.CounterHelp = "Custom counter 1";
counter1.CounterType = PerformanceCounterType.NumberOfItemsHEX32;

CounterCreationData counter2 = new CounterCreationData();

// Set the properties of the 'CounterCreationData' object.
counter2.CounterName = "Counter2";
counter2.CounterHelp = "Custom counter 2";
counter2.CounterType = PerformanceCounterType.NumberOfItemsHEX32;

// Add custom counter objects to CounterCreationDataCollection.
col.Add(counter1);
col.Add(counter2);

// Bind the counters to a PerformanceCounterCategory
// Check if the category already exists or not.
if(!PerformanceCounterCategory.Exists("MyMultipleCategory"))
{
PerformanceCounterCategory category =
PerformanceCounterCategory.Create("MyMultipleCategory",
" My New Perf Category Description ", col);
}
else
{
Console.WriteLine("Counter already exists");
}


To access a already existing performance counter. Use the 'category name' and 'counter name' to make the performance counter accessible.

Eg:

PerformanceCounter counter = new PerformanceCounter();
counter.CategoryName = "mySingleCategory";
counter.CounterName = "myCounter";
counter.ReadOnly = false;

Best way to find execution time of a part of code

Instead of using DateTime Object to find out the execution time (which gives only milliseconds of difference) use QueryPerformanceCounter and QueryPerformanceFrequency Win32 API menthods.

QueryPerformanceCounter(), queries the actual value of the high-resolution performance counter at any point. The second function, QueryPerformanceFrequency(), will return the number of counts per second that the high-resolution counter performs. therefore execution time = (start QueryPerformanceCounter - stop QueryPerformanceCounter)/ QueryPerformanceFrequency


using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;

namespace Win32
{
internal class HiPerfTimer
{
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(
out long lpPerformanceCount);

[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(
out long lpFrequency);

private long startTime, stopTime;
private long freq;

// Constructor

public HiPerfTimer()
{
startTime = 0;
stopTime = 0;

if (QueryPerformanceFrequency(out freq) == false)
{
// high-performance counter not supported

throw new Win32Exception();
}
}

// Start the timer

public void Start()
{
// lets do the waiting threads there work

Thread.Sleep(0);

QueryPerformanceCounter(out startTime);
}

// Stop the timer

public void Stop()
{
QueryPerformanceCounter(out stopTime);
}

// Returns the duration of the timer (in seconds)

public double Duration
{
get
{
return (double)(stopTime - startTime) / (double) freq;
}
}
}
}

This class is very simple to use. Just create an instance of HiPerfTimer, call Start() to start timing and call Stop() to stop timing. To retrieve the elapsed time, just call the Duration() function and you will get the elapsed time.

The following sample should explain that.

HiPerfTimer pt = new HiPerfTimer(); // create a new PerfTimer object

pt.Start(); // start the timer

Console.WriteLine("Test\n"); // the code to be timed

pt.Stop(); // stop the timer

Console.WriteLine("Duration: {0} sec\n",
pt.Duration); // print the duration of the timed code

Friday, October 19, 2007

Creational Design Pattern

Singleton

The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made either private or protected. Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, you really have to make it a singleton.

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.

The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated.



C# (using generics)

This example is thread-safe with lazy initialization.

///
/// Generic class implements singleton pattern.
///

///
/// Reference type.
///

public class Singleton where T : class, new()
{
///
/// Get the Singleton Instance.
///

public static T Instance
{
get { return SingletonCreator._instance ; }
}

class SingletonCreator
{
static SingletonCreator() { }

internal static readonly T _instance = new T();
}
}

C# (using generics and reflection)

This example is thread-safe with lazy initialization. In addition, this example is suit for classes which have private constructor.

///
/// Generic class implements singleton pattern.
///

///
[CLSCompliant(true)]
public static class Singleton where T : class, new()
{
private static T _instance;

static Singleton() {
Type type = typeof(T);
BindingFlags searchPattern = BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance;
ConstructorInfo constructor = type.GetConstructor(searchPattern,
null,
Type.EmptyTypes,
null);

_instance = (T)constructor.Invoke(new object[0]);
}

///
/// Get the singleton instance of the type.
///

public static T Instance {
get { return _instance; }
}
}

public class Session
{
private Session() {
}
}

public class Program
{
private static void Main() {
Session instanceA = Singleton.Instance;
Session instanceB = Singleton.Instance;

// Are they the same?
Console.WriteLine(instanceA == instanceB); // true
}
}

Source :

Tuesday, July 31, 2007

Rounding Off decimal places

what is the output of the following statements :

Console.WriteLine(decimal.Round(Convert.ToDecimal("0.05"), 1)); --0.0--
Console.WriteLine(decimal.Round(Convert.ToDecimal("0.15"), 1)); --0.2--

5 at 2nd decimal place is rounded to 1 if first decimal places is non-zero else zero
Why?



Explanation
The decimal.Round version that take 2 parameters
rounds midpoints to the even number (Banker's Rounding)
rather than rounding them away from zero

i.e
decimal.Round(0.05, 1); // 0.0
decimal.Round(0.15, 1); // 0.2
decimal.Round(0.25, 1); // 0.2
decimal.Round(0.25, 1); // 0.2
decimal.Round(0.35, 1); // 0.4
etc.

To get 'normal' rounding (midpoints are rounded away from zero)
you can use a overloaded version of the decimal.Round
method that takes a thrid parameter, which
specifies how to treat midpoints:

ie
decimal.Round(0.05, 1, MidpointRounding.ToEvent); // 0.0 Banker's Rounding

decimal.Round(0.05, 1, MidpointRounding.AwayFromZero); // 0.1

Monday, July 16, 2007

Basics

Value and Refference types
By default in C# everything is passed as value type.

Structs are value type and Classes are reference type. Value types are assigned memory in stack with an exception of In-Line value types asssigned in heap. Reference types are always assigned memory in heap.

value type means a copy of whatever is being passed either a reference type or a value type.



Interface - Abstract Class
What is an Interface?

An interface is a contract, a specification that concrete classes MUST follow. It defines method signatures but cannot have any implementations; the latter must be provided by the classes that implement the interface.
For example,
public interface Vehicles
{
string Engine
{
get;
set;
}
void Accelerator();
}

what is an abstract class?

An Abstract class lets you define some behaviors and force your subclasses to provide others.
For example,
public abstract class Vehicles
{
private int noOfWheel;
private string color;
public abstract string Engine
{
get;
set;
}
public abstract void Accelerator();
}


Differences between Interfaces and Abstract classes ?

I. multiple inheritance

A class may implement several interfaces but can only extend one abstract class.

II. default implementation

An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.

III. adding functionality

If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method.
If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.

IV. is-a vs -able or can-do

Interfaces are often used to describe the abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

An abstract class defines the core identity of its descendants.


Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).

Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract.


With abstract classes we can provide a default/general method implementation for all overridding classes whereas in case of interfaces, every implementing class must provide its own specific implementation.




Static (Type) or Instance Constructer
Static or Type Constructor :

used to provide a one way access to the class object. you can restrict the class intance to itself using a static constructer. it also provide ways to make singelton class or a clone function, which always returns the class object.
Only one class constructor per type is permitted.
It cannot use the vararg (variable argument) calling convention.

Instance Constructor :

is executed every time a new object is created and is specific to that object instance.
Multiple instance construtor are allowed with different parameter list (return type ie void and name are fixed).
It cannot use the vararg (variable argument) calling convention.
Instance constructors are not allowed to be a virtual type.




Ex :

using System;
class SomeClass {

private Int32 member1;
private static Int32 member2;

//Type constructor
static SomeClass(){}

//Instance constructor
public SomeClass(){} //default instance Constructor
public SomeClass(Int32 memberval){ member1 = memberval;}


}



Working Ex:

public class A

{

//Static Constructor of Class A

static A()

{

Console.WriteLine("Static Constructor of Class A");

}

//Constructor of Class A

public A()

{

Console.WriteLine("Constructor of Class A");

}

}

public class B: A

{

//Static Constructor of Class B

static B()

{

Console.WriteLine("Static Constructor of Class B");

}

//Constructor of Class B

public B()

{

Console.WriteLine("Constructor of Class B");

}

}

public class C: B

{

//Static Constructor of Class A

static C()

{

Console.WriteLine("Static Constructor of Class C");

}

//Constructor of Class C

public C()

{

Console.WriteLine("Constructor of Class C");

}

}

#endregion

class ConstructerDestructer

{

static void Main(string[] args)

{

C c = new C();

Console.ReadKey();

}

}



Output :

Static Constructor of Class C

Static Constructor of Class B

Static Constructor of Class A

Constructor of Class A

Constructor of Class B

Constructor of Class C





Interview

ref and out?
A ref parameter must be assigned a value by the CALLER before it is sent to the callee. An out parameter, on the other hand, is sent unassigned by the caller and must be assigned by the CALLEE


why cant i use static and const together?
All constants declarations are implicitly static, and the C# specification states that the (redundant) inclusion of the static modifier is prohibited.


Difference b/w const(compile time constant) and static readonly(set at run time, containing class is allowed to modify) ?


Can we const array of class/struct ?

const int constIntArray = 2; -valid-
int [] xconstIntArray = new int [] {2, 3, 4}; -valid-
const int [] xconstIntArray = new int [] {2, 3, 4}; -not valid- 'const can only be applied to a field or local whose value is known at compile time.'


What is a delegate? Comparision with function pointers?

A delegate is a data structure that refers to a static method or to an object instance and an instance method of that object.
function pointer can only reference static functions, a delegate can reference both static and instance methods.( In the latter case, the delegate stores not only a reference to the method’s entry point, but also a reference to the object instance for which to invoke the method.)


AppDomain & WebServices?

Assembly(physical) & Namespaces(logical)?

Assembly(contains verious modules) & Module(smallest executable part in a assembly)?

Can i generate and load a Assembly at runtime?
yes, use System.Reflection.Emit



Comparision b/w Equals and ReferenceEquals?

if ReferenceEquals true, then Equals true; but vice versa is always not true. ReferenceEquals compare the object pointed to whereas Equals(String) compare value. In case of object type Equals comparision, it compares the object pointed to.

ex:

public static void ReferenceValue(object a1, object a2){

if(object.ReferenceEquals(a1,a2))

Console.WriteLine("Reference Equals");

else

Console.WriteLine("Reference Not Equals");

if(object.Equals(a1,a2))

Console.WriteLine("Value Equals");

else

Console.WriteLine("Value Not Equals");}



string a = "luck"; string b = "luck"; string c = "l"; int s = 1;

Program.ReferenceValue(a, b); // 'Reference Equals' , 'Value Equals'

Program.ReferenceValue(a, c); // 'Reference Not Equals' , 'Value Not Equals'

Program.ReferenceValue(a, s); // 'Reference Not Equals' , 'Value Not Equals'

a = Console.ReadLine(); // enter 'luck'

Program.ReferenceValue(a, b); // 'Reference Not Equals' , 'Value Equals'

Console.ReadKey();

Console.Clear();

a = Console.ReadLine(); //enter 'luck'

b = Console.ReadLine(); //enter 'luck'

Program.ReferenceValue(a, b); // 'Reference Not Equals' , 'Value Equals'

Console.ReadKey();



Virtual Function?

Ex:

using System;
namespace SomeCorpProject
{
public class BaseBusinessObject
{
public BaseBusinessObject() {
}
public override string ToString() {
return "BaseBusinessObject";
}
}
}

using System;
namespace SomeCorpProject
{
public class NCapacitor : BaseBusinessObject
{
public NCapacitor()
{
}
}

public class Capacitor : BaseBusinessObject
{
public Capacitor() {
}
public override string ToString() {
return "Capacitor";
}
}
}

using System;
namespace SomeCorpProject
{
class Class1 {
[STAThread]
static void Main(string[] args) {
BaseBusinessObject bizObj = new Capacitor();
System.Console.WriteLine(bizObj.ToString());
BaseBusinessObject NbizObj = new NCapacitor();
System.Console.WriteLine(NbizObj.ToString());
}
}
} What will happen when this code is compiled and run?

(BaseBusinessObject overrides object.ToString)
---------The word "Capacitor" will be written to the console.(overrides BaseBusinessObject's object.ToString)
---------The word "BaseBusinessObject" will be written to the console.(doesnt overrides BaseBusinessObject's object.ToString)

Properties

Properties
Properties can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers. For example, the get may be public to allow read-only access from outside the type, and the set may be private or protected.
A property may be declared as a static property using the static keyword. This makes the property available to callers at any time, even if no instance of the class exists.
A property may be marked as a virtual property using the virtual keyword. This allows derived classes to override the property behavior using the override keyword.
A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual. Lastly, a property can be declared abstract, meaning there is no implementation in the class, and derived classes must write their own implementation.

*It is an error to use a virtual, abstract, or override modifier on an accessor of a static property

Abstract Properties
-------------------
A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors.
If the abstract class contains only set accessor, we can implement only set in the derived class.
The following program shows an abstract property in action.

using System;
abstract class Abstract
{
public abstract int X
{
get;
set;
}
}
class Concrete : Abstract
{
public override int X
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1.X = 10;
Console.WriteLine(c1.X);//Displays 'SET GET 10'
}
}

Static Properties
-----------------
C# also supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also.
The following program shows a class with a static property.

using System;
class MyClass
{
private static int x;
public static int X
{
get {return x;}
set {x = value;}
}
}
class MyClient
{
public static void Main()
{
MyClass.X = 10;
int xVal = MyClass.X;
Console.WriteLine(xVal);//Displays 10
}
}
Remember that set/get accessor of static property can access only other static members of the class. Also static properties are invoking by using the class name.
Properties & Inheritance
------------------------
The properties of a Base class can be inherited to a Derived class.

using System;
class Base
{
public int X
{
get{Console.Write("Base GET");return 10;}
set{Console.Write("Base SET");}
}
}
class Derived : Base
{}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.X = 10;
Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'
}
}
The above program is very straightforward. The inheritance of properties is just like inheritance any other member.

Properties & Polymorphism
-------------------------
A Base class property can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.

using System;
class Base
{
public virtual int X
{
get{Console.Write("Base GET");return 10;}
set{Console.Write("Base SET");}
}
}
class Derived : Base
{
public override int X
{
get{Console.Write("Derived GET");return 10;}
set{Console.Write("Derived SET");}
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.X = 10;
Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'
}
}

Variable argument methods

Variable argument methods
sometimes a general purpose requirements is to provide a variable number of parameters to a common logical unit. 'params' keyword in c# helps you perform such sometiems difficult tasks.

only care that should be take while passing variable argument is the type of variable. if you fix the type, then it might become easy but it wont fulfill the variable argument feature.
we will discuss both options :

fixed argument type :

void Ex(params string[] args)
{
foreach(string ar in args)
{
Console.WriteLine(ar);
}
}

Ex("a","d","r","t");


different argument types :

void Ex(params object[] args)
{
foreach(object ar in args)
{
Console.WriteLine(ar);
}
}
//the implementation will be similar to printf function in c

Ex(1, 'a', "text");

ps: problem comes when you need to work on the args and compute some result, which needs the actual conversion on the args to their original type. to do that we need to pass the args type in sequence with actual args sequence, as a string.

void Ex(string sequentialArgsTypeList, params object[] args)
{
//convert each arg based on its corresponding type defined in 'sequentialArgsTypeList'
}
//the implementation will be similar to printf function in c

Ex("int,string,Employee", ob1, ob2, ob3);