Sunday, January 31, 2010

AssociatedControlID of Asp.Label control in Asp.net

Hi All,

Today i have found one interesting part of Asp.Net Label control. Label server control have one property AssociatedControlID.

Problem : without asssigning the AssociatedControlID property a Asp.net Label server control rendered as "span" which is not satisfied the client requirement of 'it should render as label for accessibility'

Here is the output before and after,

Before,

span id="form_103_lblFirst_Name">First Name /span

Assigned "AssociatedControlID" property and Result after,

  123 lblTitle.AssociatedControlID = txtName.ID;



label id="form_103_lblFirst_Name" for="form_103_First_Name">First Name /label

Solution : I have assigned the AssociatedControlID to the Asp.net Label server control to the textbox.ID to which it refering to. and found that it is rendered to "label" html tag which i required it also includes 'for' property which references the ID of Associated Control.

Happy Coding :)

Wednesday, January 27, 2010

New keyword 'dynamic' in framework 4.0,Difference between var and dynamic/ object and dynamic.

Hi All,

C# 4.0 introduces a new keyword called 'Dynamic'. It can consume any object anything. Let's see some examples for that.


dynamic intExample = 1;
Console.Write(intExample);

dynamic floatExample = 3.6;
Console.Write(floatExample);

dynamic stringExample = "SharpFour";
Console.Write(stringExample);


will print 13.6SharpFour

I know you will all have one question in mind that,It could be also done with var keyword . Yes, you can do same thing with var but dynamic keyword is slightly different then var keyword.

Main Diffrence between var and dynamic :

var keyword will know the value assigned to it at compile time while dynamic keyword will resolve value assigned to it at run time. I know you guys don't believe me without example. So let's take example of string.

string s = "this is test string";
var varstring=s;
Console.Write(varstring.MyMethodCall());


while compiling above code it will not compile and it gives a error that 'string' does not contain a definition for 'MethodDoesnotExist' and no extension method 'MethodDoesnotExist' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?'. So var keyword knows that what value or object or anything assigned to it. Now lets try to compile same code with dynamic example like following.


string s = "this is test string";
dynamic varstring=s;
Console.Write(varstring.MyMethodCall());


Above line of code get compile. So it is the difference between dynamic and var keyword. With dynamic keyword anything assigned to it like property,objects operators anything that will be determined at compile time. It can be useful while we are doing programming with com,JavaScript which can have runtime properties.

similar thing is applied to the keyword type 'object'. we will discuss more on 'dynamic' keyword and 'object' keyword in my next post.

Happy Coding :-)

Sunday, January 24, 2010

Variable Methods and use of "params" in C#.

Hi All,

Recently in one of my requirements i require do make some method which will accepts n numbers of parameters, here i am not sure howmany parameters as argument will required.

I come up with solution with "params" keyword. below is a sample example of how i am able to solve it,i have used the console application to show how the "params" keyword will be used.



    6 public static void Main()


    7     {


    8         Console.Clear();


    9         Console.WriteLine("Hello World");


   10         Console.ReadLine();


   11         paramsExample(" vikas", 10, 11, " Aks");


   12     }


   13     public static void paramsExample(params object[] arglist)


   14     {


   15         foreach (object obj in arglist)


   16         {


   17             Console.Write("Hi{0}", obj);


   18         }


   19     }





The output of the above code will simply shows the,

"Hi vikas", "Hi 10","Hi 11","Hi Aks".

Hope you could be easily understand the code and use of "params" keyword.

Happy Coding :)

Sunday, January 17, 2010

Handling Exceptions in Using Expression Tree in C#

Hi All,

In my previous post i have explained how we can work with Expression Tree to access the Properties easily. The major consideration which we have to take here using Lambda Expressions is Expressions are failed if inputs are given wrong.

So here with this post i come up with the solution of Manage possible Exceptions, I have made some corrections in my previous post method named "GetName".

    8 public static string GetName<T>(Expression<Func<T>> e)

    9 {

   10     var member = e.Body as MemberExpression;

   11 

   12     // If the method gets a lambda expression

   13     // that is not a member access,

   14     // for example, () => FirstName + LastName, an exception is thrown.

   15     if (member != null)

   16         return member.Member.Name;

   17     else

   18         throw new ArgumentException(

   19             "'" + e +

   20             "': is not a valid expression for this method");

   21 }



Now code looks safer to show proper exception whenever wrong inputs are given to it.

Happy Coding :)

Using Expression Tree in C#

Hi All,

In my previous post i have explained the solution how to work around the Reflections to access the Property of class object. By analyzing code with different scenario my solution of Reflections get fails in case of ProeprtyName changed ( i.e suppose your User class previous have Surname afterword changed it with Lastname).

By digging more features availabes in .net framework i come up with the solution of using the Expression Tree instead of Reflections.

The Expression Tree classes are implemented in System.Query.dll and their namespace System.Linq.Expressions(might be change as product matures).

So say for example below is my sample class, with two property "FirstName" and "LastName"

    8 public class ExpressionTest

    9 {

   10     public string FirstName { get; set; }

   11     public string LastName { get; set; }

   12 }



and i want to show the name of property in my console application, so before that i will introduce the Expression Tree usage in this scenerio,

   13 public static string GetName<T>(Expression<Func<T>> e)

   14     {

   15         var member = (MemberExpression)e.Body;

   16         return member.Member.Name;

   17     }



Now to call this method and get the names of class properties we defined above we can call the Lambda Expression as given,

   18 ExpressionTest testsample = new ExpressionTest();

   19     Console.WriteLine("{0}", GetName(() => testsample.FirstName));

   20     // prints FirstName



So here is area of interest is utilization of Expression Tree classes with help of C# 3.0 onwards.

Happy Coding :)

Monday, January 11, 2010

Using Reflection to Access the Properties

Hi All,

In one of my coding requirement i need to map database fields to fields which user have been created self. I think a bit more on this and come with finally solution get gain of Reflection for fulfilling the requirement.

Here is how i get the list of Properties which i can map easily to User table to database, i used the GetProperties() method to achieve this things, then i do the Sorting on them to show in Sorted order, below is code snippet for this,

   39 User objUser = new User();

   40         Type t = objUser.GetType();

   41         PropertyInfo[] pi = t.GetProperties();

   42         Array.Sort(pi,

   43         delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)

   44         { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });

   45 

   46         UserProperties = new List<string>();

   47         foreach (MemberInfo mi in pi)

   48         {

   49             UserProperties.Add(mi.Name);

   50         }



here User is my class which contains the properties of "User" table in database.

Reflections provides vast collections of Methods which we can utilize to access within code.

Happy Coding :)

Friday, January 8, 2010

Open Source solution for Code Analysis in VS 2008

Hi All,

Microsoft Visual Studio Team System 2008 provides the inbuilt functionality with Code Matrices. Considering the cost factor VSTS-2008 is not affordable to developers like me, so i started to finding the some good tool which fulfill my requirement with no cost.

I found one nice application developed by Campwood Software named Source Monitor.

http://www.campwoodsw.com

Positive Points :

-Supports C++, C, C#, VB.NET, Java, Delphi, Visual Basic (VB6) or HTML.
-Displays and prints metrics in tables and charts
-Saves metrics in checkpoints for comparison during software development projects
-Exports metrics to XML or CSV files for further processing with other tools

Using this one can verify their own self the depth and quality of source written.

Hope this would help who looking for Code Analysis, Matrices.

Happy Coding :)

Thursday, January 7, 2010

Composite Controls and Compare Validator control

Hi All,

While working with Asp.net validators for Custom controls i have found one issue of Microsoft ASP.NET validations controls.

Problem : I need to validate one composite control with value of other composite control/ Web control. I decided to go with CompareValidator control provided by ASP.NET default. Problem comes on ControlTovalidate and ControlToCompare properties, i assigned this properties as usual, here i assigned email.ID(where email is my composite control object).

By doing this i got the error like following,

"Control 'Contact_Email' referenced by the ControlToCompare property of 'cvContact_Email' cannot be validated."

Solution : By spending many hours finally i come out with solution to this. to achieve goal we need to require expose one public property of that Control's Child control( Textbox in my case). Now and on page you can assign UniqueId property to ControlToCompare property.

Here is code snippet for same,
cvConfirm is a CompareValidator object which i am creating runtime,

  276 cvConfirm.ControlToValidate = txtconfirm.UniqueID;

  277                                 cvConfirm.ControlToCompare = email.Refemailbox.UniqueID;



Here is a property which i have exposed within composite control,

   73 /// <summary>

   74         /// Gets the reference of this control.

   75         /// </summary>

   76         /// <value>The refemailbox.</value>

   77         [Bindable(true)]

   78         [Category("Appearance")]

   79         [DefaultValue("")]

   80         [Localizable(true)]       

   81         public TextBox Refemailbox

   82         {

   83             get

   84             {

   85                 EnsureChildControls();

   86                 return this._emailTextBox;

   87             }           

   88         }



I hope this would help those who faced same situation.

Happy Coding :)