posts - 216, comments - 195, trackbacks - 68

My Links

News




I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net) and born in Bangladesh.
I work for Ocean Informatics Pty Ltd as a Senior Developer - Analyst.
I am also co-founder and core developer of Pageflakes www.pageflakes.com
and most recently created SmartCodeGenerator

My Articles
Flexible and Plugin based .Net Application..
Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker'
Write your own Code Generator or Template Engine in .NET
Smart Code Generator .NET: Usage Overview
Smart Code Generator .NET: Architectural Overview
Smart Code Generator .NET: using with NAnt and Cassini

Archives

Free Programming Language Training

Saturday, August 23, 2008

ASP.NET Tips: DropDownList.ClearSelection() to avoid "Cannot have multiple items selected in DropDownList"

Problem
I was facing the following Exception when I was programmatically assigning Selected Value of a DropDownList with the following piece of code.

ListItem item = DropDownListTest.Items.FindByValue("Test");
  if (item != null)
     item.Selected = true;

Exception

Cannot have multiple items selected in a DropDownList.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Cannot have multiple items selected in a DropDownList.
Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[HttpException (0x80004005): Cannot have multiple items selected in a DropDownList.]
   System.Web.UI.WebControls.DropDownList.VerifyMultiSelect() +107
   System.Web.UI.WebControls.ListControl.RenderContents(HtmlTextWriter writer) +1825978
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +29
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +199
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +20
   System.Web.UI.Control.Render(HtmlTextWriter writer) +7
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   CSSFriendly.WizardAdapter.RenderStep(HtmlTextWriter writer, Wizard wizard) +137
   CSSFriendly.WizardAdapter.RenderContents(HtmlTextWriter writer) +93
   System.Web.UI.WebControls.Adapters.WebControlAdapter.Render(HtmlTextWriter writer) +23
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +2116097
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +199
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +20
   System.Web.UI.Control.Render(HtmlTextWriter writer) +7
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +199
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +20
   System.Web.UI.UpdatePanel.RenderChildren(HtmlTextWriter writer) +236
 

Solution

The solution is to remember to call ClearSelection() Method before calling FindByValue("") or FindByText("") Method.

The following piece of code will work fine.

DropDownListTest.ClearSelection();

ListItem item = DropDownListTest.Items.FindByValue("Test");
  if (item != null)
     item.Selected = true;

I also noticed, I do not get the "Cannot have multiple items" exception when I use SelectedIndex instead. i.e.

DropDownListTest.SelectedIndex = 12;


Hope this saves some of your time. Happy Coding.

posted @ Saturday, August 23, 2008 4:50 PM | Feedback (1) |

Wednesday, August 06, 2008

Reflection Tips: Generate Mock objects for Test Cases.

Filling up Mock objects with random data is possibly one of the most time consuming and boring chapter of writing test cases. Let say we have the following classes and we want to write some mock objects.

SmartDataManagement - Microsoft Visual Studio

 

Mock Object Code Example

       private Client GetMockClient()
        {
            Client Client1 = new Client();
            Client1.FirstName = "Random String 6dc22d70-ad0c-4552-9c86-2925e723a326";
            Client1.LastName = "Random String 3e08dc98-495a-4a70-bff4-b7b21489b0d0";

            ClientAddress ClientAddress2 = new ClientAddress();

            ContactAddress ContactAddress3 = new ContactAddress();
            ContactAddress3.Address = "Random String e5957034-893b-4d2c-a29a-5b23e2561c00";
            ContactAddress3.Phone = "Random String 8d034e87-ece3-42b8-ae97-35fad1639f41";
            ContactAddress3.Mobile = "Random String 73a6abad-3268-4ae4-b01c-1732ab0f5f52";
            ClientAddress2.HomeAddress = ContactAddress3;

            ContactAddress ContactAddress4 = new ContactAddress();
            ContactAddress4.Address = "Random String 117ef00d-f29d-4697-97ae-123a6b56da4f";
            ContactAddress4.Phone = "Random String 8e4d0bbe-f470-4438-8940-06d9889e3943";
            ContactAddress4.Mobile = "Random String 6f0cba5c-5a88-4e5b-88ae-32a569cffa41";
            ClientAddress2.ShippingAddress = ContactAddress4;

            Client1.ClientAddress = ClientAddress2;

            Misc Misc5 = new Misc();
            Misc5.OrderDate = DateTime.Now;
            Misc5.Quaitity = 945515547;
            Misc5.DeliveryDate = DateTime.Now;

            Customer Customer6 = new Customer();

            CustomerDemographics CustomerDemographics7 = new CustomerDemographics();
            CustomerDemographics7.FirstName = "Random String 9b9542e6-2eb9-4ac8-bbd9-46272c8531b4";
            CustomerDemographics7.LastName = "Random String 275ca427-9373-41a7-8249-9a3fd94631bd";

            ContactAddress ContactAddress8 = new ContactAddress();
            ContactAddress8.Address = "Random String c9d18341-cb7e-4086-ba09-76fd7eb09f71";
            ContactAddress8.Phone = "Random String d88849f2-f443-46b1-9d21-3eaed1739696";
            ContactAddress8.Mobile = "Random String 984cfe2b-c35e-46f4-8eb1-27342d3e21b2";
            CustomerDemographics7.HomeAddress = ContactAddress8;

            ContactAddress ContactAddress9 = new ContactAddress();
            ContactAddress9.Address = "Random String e67ae73f-8edd-47d1-add0-b1e84ddb6b05";
            ContactAddress9.Phone = "Random String 91b8d44e-3718-4cc7-be8a-194d308b8969";
            ContactAddress9.Mobile = "Random String a0d19e07-2b80-4f7a-acd2-7a507455c000";
            CustomerDemographics7.ShippingAddress = ContactAddress9;

            Customer6.CustomerDemographics = CustomerDemographics7;

            Misc5.AlternativeCustomer1 = Customer6;

            Client1.Misc = Misc5;

            return Client1;

        }


As you can see we will need to spare significant amount of time to prepare a Mock object for "Client" class. But you will be happy to know that I did not write a single line of the code that I pasted above. Yes, I generated it using Reflection. Let me share that magical piece of code with you which can save you a heaps of time.

The Mock Helper

    public class MockHelper
    {
        public MockHelper()
        {
            this.MaxDepth = 100;
        }

        int index = 1;   

        Dictionary<string, string> keys = new Dictionary<string, string>();
        List<string> assemblyList = new List<string>();
        StringBuilder codeBuilder = null;

        public int MaxIndexValue { get; set; }
        public string Generate(object obj)
        {
            //Assembly List that we are interested in for recursive calls, add according to your need.
            assemblyList.Add("SmartDataManagement.Blog");

            codeBuilder = new StringBuilder();
            GenerateCode(obj, string.Empty);
            return codeBuilder.ToString();
        }       

        private void GenerateCode(object obj, string theKey)
        {         
            string instanceName = string.Format("{0}{1}", obj.GetType().Name, index);
            codeBuilder.AppendLine(String.Format("{0} {1} = new {0}();", obj.GetType().Name, instanceName));
            keys.Add(theKey, instanceName);
            //Iterate through the list of Public Properties of the object instance
            foreach (System.Reflection.PropertyInfo property in obj.GetType().GetProperties())
            {     
                //Decide to dig deeper, if a PropertyType belongs to the assemblies that we are interested in, we go deep.
                if (GoDeeper(property))
                {
                    index = index + 1;                  
                    //Avoid infinite Loop situation
                    if (index < this.MaxIndexValue)
                    {
                        object propertyInstance = property.GetValue(obj, null);                       
                        if (propertyInstance == null)
                        {
                            //Dynamically create Property Instance
                            propertyInstance = Activator.CreateInstance(property.PropertyType);
                            if (property.CanWrite)
                                property.SetValue(obj, propertyInstance, null);
                            string key = Guid.NewGuid().ToString();
                            codeBuilder.AppendLine();
                            //Recursive call
                            GenerateCode(propertyInstance, key);

                            codeBuilder.AppendLine(String.Format(@"{0}.{1} = {2};", instanceName, property.Name, keys[key]));
                            codeBuilder.AppendLine();
                        }
                    }
                }
                else if (property.PropertyType == typeof(string))
                {
                    codeBuilder.AppendLine(String.Format(@"{0}.{1} = ""{2}"";", instanceName, property.Name, GetRandomString()));
                }
                else if (property.PropertyType == typeof(DateTime))
                {
                    codeBuilder.AppendLine(String.Format(@"{0}.{1} = DateTime.Now;", instanceName, property.Name));
                }
                else if (property.PropertyType == typeof(int))
                {
                    codeBuilder.AppendLine(String.Format(@"{0}.{1} = {2};", instanceName, property.Name, GetRandomInt()));
                }
            }
        }

        private bool GoDeeper(PropertyInfo property)
        {
            //Dig deeper for interested Assemblies only, Please feel free to extend and put complex logics to serve your purpose.
            foreach (string assemblyName in assemblyList)
            {
                if (property.PropertyType.Assembly.FullName.Contains(assemblyName))
                    return true;
            }
            return false;
        }

        private string GetRandomString()
        { 
            return String.Format("Random String {0}", Guid.NewGuid().ToString());           
        }

        private int GetRandomInt()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt32(buffer, 0);
        }
    }

The above code is self explanatory, I also commented to give an idea of how this is working, In short, I take an instance of the desired class, iterate through all of its Properties using Reflection and generate desired piece of code. While iterating, I also create property instance  as required and loop thorough the properties of the child in a recursive manner until all of them are served. The assemblyList object maintains the list of the assemblies that we are interested in for recursion.  Its worth mentioning the above piece of code has limitations, it will not work in the cases where there are circular references of Types for properties, that is why I kept a check for MaxIndexValue to break the infinite loop scenario.



SmartDataManagement - Microsoft Visual Studio (2) 

Fig, shows an example of circular references of Types, here Client has Misc property (of Type: Misc), and Misc has AlternativeClient1 property (of Type: Client).

The MockHelper has very simple logic to decide to create dynamic instances and to do recursive calls, it will get stuck within Client and Misc for this example. We can definitely overcome this by putting more complex logics and checks. I wanted to keep it simple and moreover it serves my purpose. Also here I cater with int, string and DateTime only, please feel free to extend to serve your purpose. You will notice I used StringBuilder above to accumulate the generated codes, but I normally use my SmartCodeGenerator and write simple templates for this kind of tricks, SmartCodeGenerator provides a lot more flexibility and comes with robust templating feature for purposes like this.

Usage


            MockHelper helper = new MockHelper();
            //Your desired class instance
            Client client = new Client();
            string code = helper.Generate(client);

Its quite simple to use the above helper, just create an instance of the MockHelper, then pass an instance of your desired class, it will return you the mock object code as we have seen above. Infact, the above piece of code can speed you up for any cases where you need to create instances of a class and need to write code to fill all its properties, moreover the generated code can also reduce chances of errors and typos that normally happens when we do it manually.

Thank you for being with me so far, hope this saves you some time, Happy coding :)

posted @ Wednesday, August 06, 2008 12:20 AM | Feedback (0) |

Thursday, July 24, 2008

C# Reflection Tips: Data transformation using Reflection

.NET Reflection can be quite handy to transform one object to another, and specially when the target data structure varies a lot. Lets say, a "source party" has a stable Source data structure. But different clients have different requirement and expects to served with data in different format. These clients may pass their object instances in their own format and expect to be served with data in their structure. Let me make up an Example here: 

Source Data Structure which is consistent and never changes.

SmartDataManagement - Microsoft Visual Studio

Client 1 wants data to be transformed/served in the following structure 

Customer
Client 2 wants data to be transformed/served in the following structure

Client
and there may be other N-number of clients with N-number of structures, on which "Source Party" has no control.


The use of .NET Attribute and .NET Reflection can produce a very powerful solution to address this kind of scenario. So instead of writing different transforms for different clients, "source party" can simply ask clients to mark their class properties with custom attributes that the "source party" can understand. When clients mark their classes with custom attributes the  "source party" can easily take advantage of .NET Reflection to analyze those objects runtime and can act accordingly.

A .NET Attribute class can be designed to keep track of of the Mapping between the source and target data structure.

attribute

The client can mark their class/properties with this custom attribute for the (target -> source) mapping.

attributeMapping

As the mapping has been performed, we can take advantage of .NET Reflection to transform/serve data in different structure ( infact any structure - considering mapping is done properly ). Lets look at the following magical piece of code.

public class TransformHelper
{
    public Source SourceObject { get; set; }
    public object GetTransformedObjectObject(object obj)
    {
        foreach (PropertyInfo property in obj.GetType().GetProperties())
        {
            FillObject(property, obj);
        }
        return obj;
    }

    private void FillObject(PropertyInfo property, object obj)
    {
        //Identify Custom attribute
        SourceMapAttribute attribute = (SourceMapAttribute)Attribute.GetCustomAttribute(property, typeof(SourceMapAttribute));
        if (attribute != null)
        {
            //Check propertyName
            /*Put your desired code and logic here.*/
            if (attribute.PropertyName != string.Empty)
            {                           
                /*Put your desired code and logic here.
                I have simply demonstrated with one attribute property,
                you can have as many as you like, and can perform any complex operation you prefer.*/

                //Get Source Object Value
                object sourceValue = GetSourceValue(attribute.PropertyName);
                if (property.CanWrite)
                {
                    //Assign source value to the mapped property
                    property.SetValue(obj, sourceValue, null);
                }
            }

            Type propertyType = property.PropertyType;
            object propertyInstance = property.GetValue(obj, null);

            if (propertyInstance == null)
            {
                //Instantiate when Property is not instantiated
                propertyInstance = Activator.CreateInstance(property.PropertyType);
                if (property.CanWrite)
                    property.SetValue(obj, propertyInstance, null);
            }

            foreach (PropertyInfo info in propertyType.GetProperties())
            {
                //recursive call
                FillObject(info, propertyInstance);
            }
        }
    }

    private object GetSourceValue(string propertyName)
    {
        if (SourceObject == null)
        {
            SourceDataProvider provider = new SourceDataProvider();
            this.SourceObject = provider.GetSource();
        }

        switch (propertyName)
        {
            case "FirstName":
                return SourceObject.FirstName;
            case "LastName":
                return SourceObject.LastName;
            case "ContactAddress":
                return this.SourceObject.ContactAddress;
            case "ContactPhone":
                return this.SourceObject.ContactPhone;
            case "ContactMobile":
                return this.SourceObject.ContactMobile;
            case "ShippingAddress":
                return this.SourceObject.ShippingAddress;
            case "ShippingPhone":
                return this.SourceObject.ShippingPhone;
            case "ShippingMobile":
                return this.SourceObject.ShippingMobile;
            default:
                return string.Empty;
        }
    }
}

Its worth talking a little bit about the above code snippet, all it does is takes an instance of the target class, uses reflection to loop through all its properties, while doing that identifies the custom attributes, checks for the mapping property and assigns values from the Source. This also creates property instances as required and recursively keeps working until all the properties ( including all descendents ) are checked and served.

Lets look at this Transformer in action.

Serve Client 1:

Client1

Here is what we see after transformation.

serveclient 1


Serve Client 2:

client2
and here is the result.

serveclient2

 


In this way we can serve any clients objects in any structure ( considering, mapping is done properly ). You will sure agree with me Transforming one object to another by taking advantage of .NET Attribute and .NET Reflection is quite cool. Thank you for being with me so far, Happy coding :)

posted @ Thursday, July 24, 2008 5:52 AM | Feedback (2) |

Thursday, June 26, 2008

ASP.NET tips: Golden rules for Dynamic Controls.

1. Make sure your dynamic controls are Loaded on every postback.

Lets play with a very simple example,

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>


C# Code Behind

public partial class _Default : System.Web.UI.Page
{   
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox t = new TextBox();
        t.ID = "textBox";
        this.PlaceHolder1.Controls.Add(t);        
    }

}

The above code works fine, but a common mistake is to try to conditionally load dynamic controls, if we tweak the code a little bit you will notice we loose our TextBox after any postback. The following code will not load the TextBox after our first postback.

public partial class _Default : System.Web.UI.Page
{   
    protected void Page_Load(object sender, EventArgs e)
    {      
       if (!IsPostBack)
        {
            TextBox t = new TextBox();
            t.ID = "textBox";
            this.PlaceHolder1.Controls.Add(t);
        }
    }

}

Its recommended to load the dynamic controls during the Page_Init instead, because we may want to hook up our events with proper handler at an early stage.

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        TextBox t = new TextBox();
        t.ID = "textBox";
        t.TextChanged+=new EventHandler(t_TextChanged);
        this.PlaceHolder1.Controls.Add(t);
    }

}


2. Do not assigning properties of a dynamic control (viewstate enabled), during Page_Init, it will not be reflected.

Here is scenario of another common mistake, "123" assigned to the Text property during Page_Init,

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        TextBox t = new TextBox();
        t.ID = "textBox";
       t.Text = "123";
        this.PlaceHolder1.Controls.Add(t);
    }

}

controllifecycle

the above code will not work because, Initialization happens before LoadViewState during the control lifecycle. The value assigned to the properties during Initialization will simply get overwritten by the ViewState values.

 

3. If you are expecting your ViewState to retain after the postback, always assign same ID to the dynamic control

The following piece of code will not work, as I am assigning a new ID to the dynamic control after each postback. The LoadViewState retrieves previously saved viewstate data using the control ID, as the control ID has changed, it doesn't know anymore what to load, as a result it cannot load previously saved viewstate data any more.

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        TextBox t = new TextBox();
        t.ID = Guid.NewGuid().ToString();
        this.form1.Controls.Add(t);       
    }
}

Thank you for being with me so far.

posted @ Thursday, June 26, 2008 2:36 AM | Feedback (2) |

Tuesday, June 17, 2008

ASP.NET tips, Making Custom Validators work in Partial Rendering mode.

Introduction

There are many situations where we need to identify if partial rendering is supported in a page, especially when a control uses javascript, to get the control work in partial rendering mode, the script needs to be registered using a ScriptManager Type instead. A classic example will be Validators.

The ASP.NET Page class exposes the Validators property, which is a list of all the IValidator types on the page. A page keeps track of its validators, and registers a javascript array of validators automatically to the page. Example, When we add 3 RequiredFieldValidator in a page the following javascript Array will be automatically generated and added in our page automatically during the page load. 

Page_Validators = new Array(document.getElementById("RequiredFieldValidator1"),
document.getElementById("RequiredFieldValidator2"),
document.getElementById("RequiredFieldValidator3"));

The ASP.NET Page also registers couple of other script which eventually hooks up different events ( onclick, onkeypress, onchange, onblur ) to the the target control (ControlToValidate), to some predefined javascript functions that resides in WebUIValidation.js file. So when we add a validator in our Page we also notice the following script is automatically added. [WebUIValidation.js ships with ASP.NET and resides in the following folder "/aspnet_client/system_web/<version>/WebUIValidation.js".]

<script type="text/javascript">
<!--
var Page_ValidationActive = false;
if (typeof(ValidatorOnLoad) == "function") {
ValidatorOnLoad();
}

function ValidatorOnSubmit() {
if (Page_ValidationActive) {
return ValidatorCommonOnSubmit();
}
else {
return true;
}
}
// -->
</script>

ValidatorOnLoad plays the big role of hooking up the the events mentioned above, and here is a code snippet from this function,

for (i = 0; i < Page_Validators.length; i++) {
val = Page_Validators[i];
if (typeof(val.evaluationfunction) == "string") {
eval("val.evaluationfunction = " + val.evaluationfunction + ";");
}
...

if (typeof(val.controltovalidate) == "string") {
ValidatorHookupControlID(val.controltovalidate, val);
}
...
}

keen eyes may have already noticed the val.evaluationfunction property, yes every validators needs to have this property for it to work properly under the ASP.NET validation framework. Custom validators takes advantage of this property to point to custom js functions. Custom validator developers normally use RegisterExpandoAttribute method to register this attribute.

protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
{
   base.AddAttributesToRender(writer);
   if (this.RenderUplevel)
   {
      string clientID = this.ClientID;
      Page.ClientScript.RegisterExpandoAttribute(clientID, "evaluationfunction", "EntryValidatorEvaluateIsValid");
   }
}

Problem
When I used Update Panel with partial rendering enabled the Page.ClientScript.RegisterExpandoAttribute did not work for me. My validators always stopped working after the first postback, which was performed via partial rendering and triggering. I found the "evaluationfunction" in the javascript to be undefined.

Solution
I started looking under the hood, and soon discovered, that the ASP.NET Validators that ships out of the box, ( eg. RangeValidator, RequiredFieldValidator ) uses a different internal method "AddExpandoAttribute" to register the property. Here is a code snippet from the RangeValidator.

protected override void AddAttributesToRender(HtmlTextWriter writer)
{
    base.AddAttributesToRender(writer);
    if (base.RenderUplevel)
    {
        string clientID = this.ClientID;
        HtmlTextWriter writer2 = base.EnableLegacyRendering ? writer : null;
        base.AddExpandoAttribute(writer2, clientID, "evaluationfunction", "RangeValidatorEvaluateIsValid", false);  
        ...
    }
}

and code snippet from BaseValidator, the internal method AddExpandoAttribute.

internal void AddExpandoAttribute(HtmlTextWriter writer, string controlId, string attributeName, string attributeValue, bool encode)
{
    AddExpandoAttribute(this, writer, controlId, attributeName, attributeValue, encode);
}

After digging further I realized, AddExpandoAttribute checks the ASP.Page whether partial rendering is supported, then it registers the attribute using ScriptManager instead. I did the same with my validation control and it works for me. Here is the piece of code that solved my problem.

protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
       {
           base.AddAttributesToRender(writer);
           if (this.RenderUplevel)
           {
               string clientID = this.ClientID;
               if (!this.IsPartialRenderingSupported)
               {
                   Page.ClientScript.RegisterExpandoAttribute(clientID, "evaluationfunction", "EntryValidatorEvaluateIsValid");                   
               }
               else
               {
                   Type scriptManagerType = BuildManager.GetType("System.Web.UI.ScriptManager", false);
                   scriptManagerType.InvokeMember("RegisterExpandoAttribute", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new object[] { this, clientID, "evaluationfunction", "QuantityEntryValidatorEvaluateIsValid", false });
               }
           }
       }

Note, the I am first checking whether Partial Rendering is Supported and using the ScriptManager  Type to register the property instead.

The following piece of code uses Reflection to figure out whether partial rendering is supported.

internal bool IsPartialRenderingSupported
{
    get
    {
        if (!this.PartialRenderingChecked)
        {
            Type scriptManagerType = BuildManager.GetType("System.Web.UI.ScriptManager", false);
            if (scriptManagerType != null)
            {
                object obj2 = this.Page.Items[scriptManagerType];
                if (obj2 != null)
                {
                    PropertyInfo property = scriptManagerType.GetProperty("SupportsPartialRendering");
                    if (property != null)
                    {
                        object obj3 = property.GetValue(obj2, null);
                        this.IsPartialRenderingEnabled = (bool)obj3;
                    }
                }
            }
            this.PartialRenderingChecked = true;
        }
        return this.IsPartialRenderingEnabled;
    }

}

private bool PartialRenderingChecked
{
    get
    {
        object val = ViewState["PartialRenderingChecked"];
        if (val != null)
            return (bool)val;
        return false;
    }
    set
    {
        ViewState["PartialRenderingChecked"] = value;
    }
}

private bool IsPartialRenderingEnabled
{
    get
    {
        object val = ViewState["IsPartialRenderingEnabled"];
        if (val != null)
            return (bool)val;
        return false;
    }
    set
    {
        ViewState["IsPartialRenderingEnabled"] = value;
    }
}

 

Conclusion

The Page.ClientScript.RegisterExpandoAttribute may not work in Partial Rendiring mode, when a postback is performed via triggering,
to get this work we need to determine whether partial rendering is supported and use the ScriptManager Type instead like described above.

Hope this helps, and saves some of your time, Thank you for being with me so far.

posted @ Tuesday, June 17, 2008 5:43 AM | Feedback (1) |

Wednesday, June 11, 2008

C# 3.0 tips, Automatic Property

Declaring a property in C# 3.0 is super easy and super short.

public class Student
{
  public string Name {  get; set; }
}

yes that's it, the framework will take care of the rest, the private variables will be automatically created and the getter and setter will be automatically implemented.

Here is how we can assign value to an automatic property via the constructor

public class Student
{
    public string Name {  get; set; }
    public Student (string name)
    {

       this.Name = name;

    } 
}

And finally, here is how we can declare a Readonly property

public class Student

     public string Name {  get; private set; }  

   public Student (string name)
   {

     this.Name = name;

   } 
}

Hope this helps, Enjoy coding.

posted @ Wednesday, June 11, 2008 12:21 AM | Feedback (0) |

Monday, June 09, 2008

System.Net.WebClient().DownloadString(url) for Web Scrapeing

WebRequest is the abstract base class for the .NET Framework's request/response model for accessing data from the Internet.

To get content of a website, in .NET 1.0. we used to use WebRequest, which is good and also works asynchronously.

public static string GetContent(string url)
{
System.Net.WebRequest request = System.Net.WebRequest.Create(url);
using (System.Net.WebResponse response = request.GetResponse())
{
  using (System.IO.StreamReader reader =new System.IO.StreamReader(response.GetResponseStream()))
  {
   return reader.ReadToEnd();
  }
}
}

But in .NET 2.0, we can also use the WebClient class. It can also work asynchronous and works the same as the other one.

public static string GetContent(string url)
{
using (System.Net.WebClient client =new System.Net.WebClient())
{
  return client.DownloadString(url);
}
}

We can use any of the above method for web scrapeing in .NET. But the second approach is probably more cleaner.

posted @ Monday, June 09, 2008 3:28 PM | Feedback (1) |

Friday, May 23, 2008

Project SOAK winner of 2008 Imagine Cup Australia.

The theme of this year’s Imagine Cup is "Imagine a world where technology enables a sustainable environment." It had been a great honorary for me to take part as one the Judges of the 2008 Imagine Cup Australia. All the teams worked real hard and came up with breathtaking solutions. The interesting part was  solutions were built on top of cutting edge technologies technologies ie. Silverlight, Virtual Earth, LINQ, ASP.NET 3.5, WCF, .NET 3.5 and SQL2005.

The Project SOAK is announced the winner of Australian Imagine Cup 08. SOAK which stands for “Smart Operational Agriculture toolKit” is an integrated hardware and softwares platform that aims to help farmers make the most of the water (and other) resources on their land. It does this through an integration of a wide range of sensors which gathers data about the environment in real time, provide rich visual information to end-user about the status of the farm, and electronically controls various systems such as sprinklers. The team members of SOAK blogged more about the project, can be found here

http://davidburela.wordpress.com/2008/05/22/2008-imagine-cup-australian-winner-project-soak/

http://www.istartedsomething.com/20080523/imagine-cup-australian-winner-project-soak/

Australian PC Magazine has just published published a very insightful story on this project and the competition

I found SOAK to be a brilliant piece of work, where the team combined latest technologies together and came up with a environment friendly cost effective solution.

The winning team will now represent Australia at the World Imagine Cup finals in Paris in July.

 

Imagine Cup 2008 - Australia - Judging Panel

 

The Imagine Cup’s judging panel consisted of Roger Lawrence, Microsoft Australia’s Manager Developer Evangelism; Nigel Watson, Microsoft Australia Architect Evangelist; Shekhar Kalra, computer science lecturer at RMIT University; Shahed Khan, Senior Software Engineer at Ocean Informatics MVP C#.NET, and APC, represented by its editor, Tony Sarno.

posted @ Friday, May 23, 2008 11:41 PM | Feedback (0) |

Saturday, May 03, 2008

ASP.NET Bug, Multi View control do not save ViewState, of dynamically added controls

Couple of days back me and my colleague, we discovered an issue with the ASP.NET Multi View Control.
We were surprised  to see that it do not add ViewState, of the dynamically added controls, of the Inactive Tabs.

ASP.NET 2.0

       <asp:MultiView ID="MultiView1" runat="server" EnableViewState="true">       
        </asp:MultiView>

C# Code Behind

        if (!IsPostBack)
        {
            int index = 1;
            foreach (View v in MultiView1.Views)
            {                
                    TextBox t = new TextBox();
                    t.ID = index.ToString();
                    t.Text = "This text will not be assigned, to any Inactive Tabs, unless you put a breakpoint on this line and watch the value of this line explicitly";
                    v.Controls.Add(t);
                    index = index + 1;                
            }
        }

 

Surprisingly, you will notice only the Textbox.Text of the Active Tab will have value,
however if you go to any other Tab of the MultiViewControl, you will notice that the TextBoxes are empty.

After investigating further we realized that the Viewstates of the dynamically added controls are not saved (for any of the inactive tabs).
It became more interesting, when we started to debug, by putting a breakpoint to watch TextBox.Text, surprisingly every TextBox gets populated with desired Text ( for all tabs including the inactive tab, only when you explicitly watch ). Also it saves all ViewState correctly.

Not sure whether its a bug,  the ASP.NET team may have wanted this behavior to enhance performance of the Multi View control,

but if that is the case, why does it populate the TextBox.Text and also saves into Viewstate, when we try to debug !!!

 

Do not believe me?  Try it by yourself !!

posted @ Saturday, May 03, 2008 3:31 AM | Feedback (2) |

Monday, April 28, 2008

ASP.NET in VISTA ( IIS7 ) with VS2005 or VS2008

The following 2 links may help.

VS 2005: http://learn.iis.net/page.aspx/431/using-visual-studio-2005-with-iis-70/
VS 2008: http://learn.iis.net/page.aspx/387/using-visual-studio-2008-with-iis-70/

posted @ Monday, April 28, 2008 4:13 PM | Feedback (0) |

Saturday, April 12, 2008

ASP.NET Tips: Using Image as Embedded Resource for ASP.NET CustomControl

Problem

I started writing an ASP.NET Custom Server Control, where I wanted an Image to be Embedded Resource of the Assembly itself,
so that, I do not need to ship the images separately, but surprisingly it did not work straightway for me.

The following line was not working for me:
writer.AddAttribute(HtmlTextWriterAttribute.Src, Page.ClientScript.GetWebResourceUrl(typeof(MyControls.MyImageControl), "ferrari.jpg"));

Ok, lets elaborate what I did and what I missed,

Step 1, I created my ClassLibrary project, added an Image, added a Custom Control class.

Image1

Step 2, Made the image an embedded resource of the Assembly.

 

Image2

 

Step3, Written my very simple Custom Control, where I assigned the image "src" to the WebResource URL


Image3
 

Step 4, Then I wanted to tryout this CustomControl in my Test Website

Image5

 

Step 5, But I got the following result.

Image4
Image6

 

Solution

After investigating a bit, I realized I missed some critical bits.


1. I did not put the correct Resource URL. I discovered this by opening up the assembly via Reflector, I found that the resource URL is different than what I have put in my code.

Image8

I corrected the resource URL in my code, (but still it did not work).

writer.AddAttribute(HtmlTextWriterAttribute.Src,
               Page.ClientScript.GetWebResourceUrl(typeof(MyControls.MyImageControl),
               "MyControls.images.ferrari.jpg"));


 Image9



2. I investigated further and found that I did not explicitly declare the image as WebResource in my assembly info . To get the embedded resource bit working, the following line is very important, and this solved my problem.


[assembly: System.Web.UI.WebResource("MyControls.images.ferrari.jpg", "image/jpg")]

Image7

Note: We can also put this directly in the class file itself.


After the fix I got the following result as I have desired.

Image10

 

Summary

I have discussed here, how to embed image in an Assembly and how to use it as WebResource. Two points to note here, which are
1. After embedding a resource it is very important to explicitly declare itself as WebResource in the assembly,
2. We need correct resourceURL to access resouces from the assembly. Note: its case-sensitive as well.

I hope this discussion will save you some time. Thank you for being with me so far.

posted @ Saturday, April 12, 2008 8:45 PM | Feedback (0) |

Saturday, March 22, 2008

DataTable to JSON and ToJSON() Extension

Very recently I wrote an application where I had to deal with DataSet from a Web Service.

Please note, I have no control on the Web Service and I ended up writing a small function which converts DataTable to JSON.

I understand I haven't gain anything on the web traffic, but it surely simplified my JavaScript programming.


Let me go through what I did

Step 1.  Extract the XML Schema.
DataTable has two handy methods to extract Xml and Xml Schema. I extracted the Xml Schema to be able to generate a C# class using the xsd.exe.

    string path = "Your File Path";
    myDataTable.WriteXml(path);
    myDataTable.WriteXmlSchema(path);


Step 2. Generate C# Class using Xsd.exe that ships with the .NET Framework.

    C:\temp>xsd mydatatable.xsd /l:cs /c
    Microsoft (R) Xml Schemas/DataTypes support utility
    [Microsoft (R) .NET Framework, Version 2.0.50727.42]
    Copyright (C) Microsoft Corporation. All rights reserved.
    Writing file 'C:\temp\mydatatableclass.cs'.

 

Step 3. DataTable to Object conversion

The Web Service returns DataSet/ DataTable, and I want to transform all data that I I receive in the DataTable, to an instance of the class that I just generated in the above step.  Something like this:   

    private T DataTableToT<T>(DataTable dataTable, T obj)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            dataTable.WriteXml(ms);
            Type thetype = obj.GetType();
            XmlSerializer x = new XmlSerializer(thetype);
            ms.Position = 0;
            return (T)x.Deserialize(ms);           
        }
    }

The above method uses the WriteXml() to write the data of DataTable in to a MemoryStream, then using the XmlSerializer I deserialize the xml to a .NET object. Here is how we may use the this method:

    DataSet ds = WebService.GetDataSet();
    DataTable myDataTable = ds.Tables[0];
    MyDataTableClass obj = DataTableToT(myDataTable, new MyDataTableClass());


Step 4. Serialize .NET object to JSON

We have done the hard part above, now we have .NET object so we have all the flexibility as you can imagine. I found that there is a handful amount of libraries which can serialize .Net Objects to JSON string ie. JavaScriptSerializer, DataContractJsonSerializer, JSON.NET etc.

JavaScriptSerializer ships with System.Web.Extensions.dll and you can locate it under Namespace:  System.Web.Script.Serialization. The following method returns JSON from a .NET object using JavaScriptSerializer.

    private string GetJSONUsingJavaScriptSerializer<T>(T obj)
    {       
       JavaScriptSerializer serializer = new JavaScriptSerializer();
       string json =   serializer.Serialize(obj);
       return json;       
    }


DataContractJsonSerializer also does pretty much the same as above, it ships with .NET Framework 3.5 :  System.ServiceModel.Web.dll, and you can locate this under  Namespace:  System.Runtime.Serialization.Json, But we need to decorate the class with DataContract and DataMember attributes. Example

    [DataContract]
    class Order
    {
        [DataMember]
        public int OrderID { get; set; }
        [DataMember]
        public DateTime OrderDate { get; set; }
    }


and the following method can return a JSON string.

    private string GetJSONUsingDataContractJsonSerializer<T>(T obj)
    {
        using (MemoryStream ms = new MemoryStream())
        {           
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            serializer.WriteObject(ms, obj);           
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }


Conclusion

Here we have discussed how we can easily transform a DataTable to JSON. Sometimes we do not have enough control over the Web Service, or we may need to invoke a legacy Web Service that returns DataSet/ DataTable. In those scenarios sometimes converting DataTable to JSON comes very handy in AJAX programming. In the above example I have shown plain vanilla .NET methods, but we can even take it further and implement Extention methods to return JSON string. Scott has shown in his blog how to produce JSON using JavascriptSerializer. Here I show how we can do the same using DataContractJsonSerializer.

Example:

        public static string ToJSON<T>(this T obj)
        {
            using (MemoryStream ms = new MemoryStream())           
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                serializer.WriteObject(ms, obj);
                return Encoding.UTF8.GetString(ms.ToArray());
            }           
        }

and then we will be able to use it like this on a order collection,

     string json = orders.ToJSON();


 

Hope this helps.

posted @ Saturday, March 22, 2008 5:31 PM | Feedback (1) |

Tuesday, March 18, 2008

Visual Studio 2005 Debugging in Vista

Problem: I was trying to debug in Visual Studio 2005 in my new machine which came with Vista Home Premium. Surprisingly I found that none of the break points are touched and I cannot debug. I tried giving all types of permission to the folder but no luck.

 

Solution: After googling a bit, I found that I needed to run VisualStudio2005 as an Administrator, and everything started working as I expected.

So all I had to do is :
Right-click the Visual Studio icon and select the "Run as administrator" option from the context menu.

 

vs05run

Hope this saves some of your time.

posted @ Tuesday, March 18, 2008 2:39 PM | Feedback (3) |

Thursday, February 21, 2008

Javascript Tips: Carefully use "this" when writing classes, else you may cause memory leak.

Lets say we want to declare a class in Javascript, which is equivalent to the following C# class.

public class Student
{
  public string FirstName = "";
  public string LastName = "";

  public Student( string firstname, string lastname)
  {
    this.FirstName = firstname;
    this.LastName = lastname;
  }
  
  public string GetFullName()
  {
    return FirstName + LastName;
  }
}

To write a similar class in JavaScript we can do something like the following [ but this will create memory leak, I am explaining that in a moment ]

function Student ( firstname, lastname)
{
  this.FirstName = firstname;
  this.LastName = lastname;

  this.GetFullName = function()
  {
    return this.FirstName + this.LastName;
  }

}


now in C# if we want to instantiate an object of Student and want to call the GetFullName() method, we do the following.
Student student = new Student("Shahed", "Khan");
string fullname = student.GetFullName();


and we can create as many objects as we want and call its methods, each of the object will maintain its own state, and all objects will use the same copy of the GetFullName()  method.

But Javascript has different behaviour when we do the following on the above Javascript class.

var student = new Student("Shahed","Khan");
car fullname = student.GetFullName();


In Javascript, functions are treated as variables as a result when we create a new object of Student it creates  new sets of firstname, lastname and also a new copy of GetFullname method, as a result we are creating memoryleak.

Do not worry too much, there is a workaround for this, lets redefine the class in a different way.

function Student ( firstname, lastname)
{
  this.FirstName = firstname;
  this.LastName = lastname;

  this.GetFullName = GetFullName;

}

function GetFullName()
{
  return this.FirstName + this.LastName;
}

Notice I have moved the GetFullName function out of the class, and for this tweaking all new objects of the Student class will share the same instance of of GetFullName method and avoid memory leak.

Thank you for being with me so far.

Updated 24th Feb
===============
Laurent from Galasoft gave some good feedback, 
JavaScript object oriented should be done by modifying the prototype property of the object, and never by storing methods using the "this" keyword. The workaround provided above is not good practice, as it forces the use of a global function. We should always declare methods in JavaScript object like this:
 
function Student(firstName, lastName)
{
 this.firstName = firstName;
 this.lastName = lastName;
}

Student.prototype =
{
 getFullName : function()
 {
   return this.firstName + " " + this.lastName;
 }
}

also note correct naming convension, ( Javascript follows Java notation not C#). For JavaScript best practices please refer to the work of Microsoft Silverlight team.

posted @ Thursday, February 21, 2008 5:38 PM | Feedback (1) |

Tuesday, February 19, 2008

Solving DNN deployment issues, Redirecting to localhost and Running DNN in a different port

I was trying to host a small DNN application in one of our Server and I was facing couple of  issues.

Problem 1:
The first problem I faced is it was always redirecting to localhost, whenever I tried http://domain.com/dnn it was redirecting to http://localhost/dnn as a result the site was un-accessible from outside.


Solution

This was easy to solve.
1. I needed to log in as host account.
2. Then I needed to go to the Admin > Site Settings page
3. And finally In the Portal Alias section I added a new Http Alias "domain.com/dnn"

This solved my problem when I hosted the site in port 80.

clip_image002[14]

Problem 2:

Now I tried to host the application in a different port 8080. I.e. http://domain.com:8080/dnn. and somehow when I clicking to redirect to any other page the port started to disappear. The http://domain.com:8080/ automatically turned to http://domain.com/ .

Solution

After googling and looking at the web.config carefully I found, its clearly documented in web.config that

<!-- set UsePortNumber to true to preserve the port number if you're using a port number other than 80 (the standard)
    <add key="UsePortNumber" value="true" /> -->

clip_image002[12]

I tweaked my appsettings section  and added the magic key

<add key="UsePortNumber" value="true" />

Also I had to add a new Http Alias "domain.com:8080"

This solved my problem and started retaining the port for my http://localhost:8080 but not http://domain.com:8080.  The http://domain.com:8080 was still turning to http://domain.com

Note: I later discovered this was not a problem of DNN and the issue happened because of the setup of our router settings and port forwarding, which I'll discuss next.


Problem 3: 
Even after adding the "UsePortNumber" key it did not solve my problem

Solution

Our Router was Port Forwarding all traffic of 8080 to the port 80 of the machine where DNN app is hosted. I.e. 8080 --> 80. As a result even from a browser I as typing http://domain.com:8080 , the DNN Request object was getting http://domain.com and when DNN handlers and url rewriters spitting the reformatted url it was spitting http://domain.com.

This was a big problem for me, initially I thought I would write a HttpHandler for 404 page not found, but soon realized it will never hit the server with the spitted Url so that didn't work. Then I thought I would tweak the DNN handlers to handle this scenario, but later tweaked the IIS and Router to handle this.

1. In IIS I added, support for 8080  to my Default Website.

 

clip_image002

 

2. In Router instead of forwarding to port 80 I started forwarding 8080 to 8080.
3. Made sure that in my DNN Site Settings, I have added Http Alias "domain.com:8080/dnn".

Waaa la, This solved my issue.

Hope this helps and Thank you for being with me so far.

posted @ Tuesday, February 19, 2008 5:14 PM | Feedback (2) |

Powered by: