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");

Thursday, September 11, 2008

Add On - Integrating Browser & Outlook

Browser add on to provide capabilities to use outlook stored information like contacts, emails etc without leaving the browser.

get contact mail address
attach mails from outlook to email in browser

Thursday, August 21, 2008

Enable Maintainanace plan for SQL Server 2005

run the script:

use msdb
GO
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Agent XPs', 1;
GO
RECONFIGURE
GO

go to maintainance plan to see details about how to create them

Wednesday, August 13, 2008

SMMS - Short Message Mailing System

SMMS i.e. Short Message Mailing System

A system which provides the feature of a mailing system like (address, lists, reply, forward etc) based on SMS.

Additionally it can have a feature where a person can expose a contact list to someone he know, without the other person being aware of who all are the contact list(acting as a middle man).

This can be a faster, reliable and social way to make people aware of  things going on.

 

Monday, August 11, 2008

Windows vista security - rendered useless by researchers

LAS VEGAS -- Two security researchers have developed a new technique that essentially bypasses all of the memory protection safeguards in the Windows Vista operating system, an advance that many in the security community say will have far-reaching implications not only for Microsoft, but also on how the entire technology industry thinks about attacks.

In a presentation at the Black Hat briefings, Mark Dowd of IBM Internet Security Systems (ISS) and Alexander Sotirov of VMware Inc. discussed the new methods they've found to get around Vista Protections such as Address Space Layout Randomization (ASLR), Data Execution Prevention (DEP) and others by using Java, ActiveX controls and .NET objects to load arbitrary content into Web browsers.

By taking advantage of the way that browsers, specifically Internet Explorer, handle active scripting and .NET objects, the pair have been able to load essentially whatever content they want into a location of their choice on a user's machine.

http://searchsecurity.techtarget.com/news/article/0,289142,sid14_gci1324395,00.html

 

Thursday, July 31, 2008

Image Decoder

An application which can add images to its collection as a encoded serialized bit.

Features
- add images files as encoded bits
- display images (encoded bits)

useful to hide what images you have because it can only be viewed by your own application

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, April 28, 2008

Visual Studios 2005 Addin Setup

The process to get a VS Addin working is divided into two steps

1. Create a Extensibility project
Step 1: Launch Visual Studio.

Step 2: Click File -> New -> Project.

Step 3: Select “Visual Studio Add-in” from the New Project dialog (under Other Project Types -> Extensibility as shown below) and give the project a name. In this case I’ve named the project BuildCompleteSample.



Step 4: Visual Studio Add-in Wizard: Click next.

Step 5: Visual Studio Add-in Wizard (Page 1 of 6): Select “Create an Add-in using Visual C#” and click next.

Step 6: Visual Studio Add-in Wizard (Page 2 of 6): Deselect “Microsoft Visual Studio 2005 Macros” and click next.

Step 7: Visual Studio Add-in Wizard (Page 3 of 6): Add a name and description and then click next. For this sample I set them as shown below:

Name: Platform Builder - Build Complete Sample
Description: This sample shows how to generate an action when a build is completed.

Step 8: Visual Studio Add-in Wizard (Page 4 of 6): Select “I would like my Add-in to load when the host application starts” and click next.

Step 9: Visual Studio Add-in Wizard (Page 5 of 6): Click next or fill in the information to be included in the About dialog box if you wish.

Step 10: Click finish.

Step 11: Open Connect.cs and scroll to the bottom and add a private member variable to store a reference to the BuildEvents.

private BuildEvents _buildEvents;

Step 12: Modify the OnStartupComplete method to get the reference to the BuildEvents and register an OnBuildDone event handler.

public void OnStartupComplete(ref Array custom)
{
_buildEvents = _applicationObject.Events.BuildEvents;
_buildEvents.OnBuildDone += new _dispBuildEvents_OnBuildDoneEventHandler(_buildEvents_OnBuildDone);
}

Step 13: Implement the event handler and add code to start your favorite sound. There are a lot of ways to play sounds but the following is a very simple way that gets the job done for this sample.

///
/// The method that handles the on build done event.
///

/// Represents the scope of the build.
/// Represents the type of build action that is occurring, such as a build or a deploy action.
private void _buildEvents_OnBuildDone(vsBuildScope Scope, vsBuildAction Action)
{
if (Action == vsBuildAction.vsBuildActionBuild)
{
// Get the path to the executing assembly
System.Windows.Forms.DialogResult done;
if(Action == vsBuildAction.vsBuildActionBuild)
done = System.Windows.Forms.MessageBox.Show("Build Done"); }
}

Step 14: Compile the add-in

2. Create a setup

Step 1. Goto File -> Add -> New Project

Step 2. Other Project Type -> Setup and Deployment -> type in the name of the project.

Step 3. Select Application Folder -> right Click -> Add -> Project Output.

Step 4. Select Application Folder -> right Click -> Add -> Assembly.

Step 5. Select and Add 'extensility.dll' from the .Net tab.

Step 6. Select Application Folder -> right Click -> Add -> Assembly.

Step 7. Repeat step 6&7 for all the .dll files required for the addin project (in this case I added "System.Windows.Forms.dll"

Setp 8: Build The project

You will get a msi and an exe at the target directory.

Reffernces :
Setup&Deployment
VS Addin

Tuesday, April 15, 2008

Organize Windows Files

A windows application which can display files categorically like music, picture etc from a list of locations.

Application Settings :
1) List of locations to search for files.
2) List of categories (label).
3) List of extensions under a category.


Application Capabilities :
1) Delete
2) Drag & Drop to copy/paste files to other locations
3) Rename
4) Open

Friday, April 11, 2008

Auto Web Surfing

Dated: 11 Apr 2008
As i have multiple mailing account, i always feel the need to login so that the account doesnt expire. A solution would be to auto login. This can span not only to mail server but to any site where login is required.

Design Details

Register a site.
Provide login details.
Record various step's followed during the logged in time.

Furthermore there can also be a option to save snapshot/html of the data viewed.



References

Web Browser/Content in a C# Application

Code Project Article - Capture IE Page Snapshot

Wednesday, April 2, 2008

Application Vulnerability(Threat Modeling)

An important part of developing a more secure application is to understand the threats to it. Microsoft has developed a way to categorize threats(STRIDE):
Spoofing
Tampering
Repudiation
Information disclosure
Denial of service
Elevation of authority
The sections below briefly describe these threats and how they apply to Web applications.

1)Spoofing
To spoof is to impersonate a user or process in an unauthorized way. At its simplest, spoofing can mean typing in a different user's credentials. A malicious uses might also change the contents of a cookie to pretend that he or she is a different user or that the cookie comes from a different server.

In general, you can help prevent spoofing by using stringent authentication. Any time someone requests access to non-public information, be sure they are who they say they are. You can also help defend against spoofing by keeping credential information safe. For example, do not keep a password or other sensitive information in a cookie, where a malicious user can easily find or modify it.

2)Tampering
Tampering means changing or deleting a resource without authorization. One example is defacing a Web page, where the malicious user gets into your site and changes files. An indirect way to tamper is by using a script exploit. A malicious user manages to get code (script) to execute by masking it as user input from a page or as a link.

A primary defense against tampering is to use Windows security to lock down files, directories, and other Windows resources. The application should also run with minimum privileges. You help guard against script exploits by not trusting any information that comes from a user or even from a database. Whenever you get information from an untrusted source, take steps to be sure it does not contain any executable code.

3)Repudiation
A repudiation threat involves carrying out a transaction in such a way that there is no proof after the fact of the principals involved in the transaction. In a Web application, this can mean impersonating an innocent user's credentials. You can help guard against repudiation by using stringent authentication. In addition, use the logging features of Windows to keep an audit trail of any activity on the server.

4)Information Disclosure
Information disclosure simply means stealing or revealing information that is supposed to be private. A typical example is stealing passwords, but information disclosure can involve access to any file or resource on the server.

The best defense against information disclosure is to have no information to disclose. For example, if you avoid storing passwords, malicious users cannot steal them. An alternative to storing passwords is to store only a hash of the password. When a user presents credentials, you can hash the user's password and compare only the hashes of the two. If you do store sensitive information, use Windows security to help secure it. As always, you should use authentication to help ensure that only authorized users can access restricted information. If you must expose sensitive information, it is recommended that you encrypt the information when stored and use Secure Sockets Layer (SSL) to encrypt the information when sent to and from the browser.

5)Denial of Service
A denial of service attack is to deliberately cause an application to be less available than it should be. A typical example is to overload a Web application so that it cannot serve ordinary users. Alternatively, malicious users might try to simply crash your server.

IIS enables you to throttle applications, which means that it limits the number of requests it will serve. You might be able to deny access to users or IP addresses known to be malicious. Keeping your applications online is a matter of running robust code. You should test your application thoroughly and respond appropriately to error conditions wherever possible.

6)Elevation of Privilege
An elevation of privilege attack is to use malicious means to get more permissions than normally assigned. For example, in a successful elevation-of-privilege attack, a malicious user manages to get administrative privileges to your Web server, giving himself or herself access to any data on the server as well as control over server capabilities.

To help protect against elevation of privilege, run the application in a least-privilege context if practical. For example, it is recommended that you do not run ASP.NET applications as the SYSTEM (administrative) user.

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

Monday, January 14, 2008

Response.Write() verse Response.Output.Write()

the difference between Response.Write() and Response.Output.Write() in ASP.NET. Well sir, I'm glad you asked, because it's damned interesting. :) The short answer is that the latter gives you String.Format-style output and the former doesn't. The long answer follows.

In ASP.NET the Response object is of type HttpResponse and when you say Response.Write you're really saying (basically) HttpContext.Current.Response.Write and calling one of the many overloaded Write methods of HttpResponse.

Response.Write then calls .Write() on it's internal TextWriter object:

public void Write(object obj){ this._writer.Write(obj);}

HttpResponse also has a Property called Output that is of type, yes, TextWriter, so:

public TextWriter get_Output(){ return this._writer; }

Which means you can to the Response whatever a TextWriter will let you. Now, TextWriters support a Write() method ala String.Format, so you can do this:

Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);

But internally, of course, this this is happening:

public virtual void Write(string format, params object[] arg)
{
this.Write(string.Format(format, arg));
}

thanks to Scott Hanselman's ComputerZen.com