Software Architecture-New Features of Visual Studio 2010 / .Net 4.0

February 27, 2011

Presentation
Topic: New Features of Visual Studio 2010 / .Net 4.0
Date: 28 Feb 2010
By: Shahzad Sarwar

Advertisements

Software Architecture-ExpandoObject Class of System.Dynamic namespace in C# 4.0

February 26, 2011

In previous few posts[ Introduction to Dynamic Type , Overloading with dynamic and Dynamicobject Class ] we explored new type dynamic in c# 4.0.
In System.Dynamic namespace, Microsoft introduced many classes related to dynamic language support in c#. One of the main class is ExpandoObject, which according to MSDN is defined as: “Represents an object whose members can be dynamically added and removed at run time.”
The ExpandoObject class is an implementation of the dynamic object concept that enables getting, setting, and invoking members.
Lets do some testing on this class.

dynamic calculator = new ExpandoObject();

            // Set properties
            calculator.Name = "Shahzad's Calulator....";
            calculator.Made= "Cesco";
            calculator.Price = 100;

            // Add methods
            calculator.AddNumbers = new Action<int, int>((i1, i2) => Console.WriteLine("Result for AddNumbers : {0}", (i1 + i2)));

            // Show state
            Console.WriteLine("Properties: Name:{0} , Made:{1}  , Price:{2}", calculator.Name, calculator.Made, calculator.Price);

            // Call method
            calculator.AddNumbers(5, 6);

            //Listing all properties
            Console.WriteLine("Listing all properties");
            foreach (var property in (IDictionary<String, Object>)calculator)
            {
                Console.WriteLine(property.Key + ": " + property.Value);
            }

            // Remove property
            ((IDictionary<String, Object>)calculator).Remove("Name");

            //Listing all properties
            Console.WriteLine("Listing all properties- After Removal of Name");
            foreach (var property in (IDictionary<String, Object>)calculator)
            {
                Console.WriteLine(property.Key + ": " + property.Value);
            }

            Console.WriteLine("Lets see: " + calculator.Color); //'System.Dynamic.ExpandoObject' does not contain a definition for 'Color'

            Console.ReadLine();

Comments explain everything.

Reference: http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx


Software Architecture-DynamicObject Class of System.Dynamic namespace in C# 4.0

February 26, 2011

In previous few posts[ Introduction to Dynamic Type and Overloading with dynamic] we explored new type dynamic in c# 4.0.
In System.Dynamic namespace of C# 4.0, Microsoft introduced many classes related to dynamic language support in c#.
One of the main class is DynamicObject Class, which according to MSDN is identified as: “Provides a base class for specifying dynamic behavior at run time.”
Lets see details about this class, on IDE click on DynamicObject(Go to definition). You will notice that this class can’t be instantiated because its constructor is protected. Secondly it has many virtual method for providing implementation about dynamic behavior by overriding in derived classes.
See below:

Lets do some testing of this concept, by deriving a class from it. (Modified version of MSDN sample)

public  class DynamicCalculator : DynamicObject
    {
        // The inner dictionary.
        Dictionary<string, object> dictionary
            = new Dictionary<string, object>();

        // This property returns the number of elements
        // in the inner dictionary.
        public int Count
        {
            get
            {
                return dictionary.Count;
            }
        }

        // If you try to get a value of a property 
        // not defined in the class, this method is called.
        public override bool TryGetMember(
            GetMemberBinder binder, out object result)
        {
            // Converting the property name to lowercase
            // so that property names become case-insensitive.
            string name = binder.Name.ToLower();

            // If the property name is found in a dictionary,
            // set the result parameter to the property value and return true.
            // Otherwise, return false.
            return dictionary.TryGetValue(name, out result);
        }

        // If you try to set a value of a property that is
        // not defined in the class, this method is called.
        public override bool TrySetMember(
            SetMemberBinder binder, object value)
        {
            // Converting the property name to lowercase
            // so that property names become case-insensitive.
            dictionary[binder.Name.ToLower()] = value;

            // You can always add a value to a dictionary,
            // so this method always returns true.
            return true;
        }
        /// <summary>
        /// provide a method calling machism
        /// </summary>
        /// <param name="binder"></param>
        /// <param name="args"> input parameters</param>
        /// <param name="result">output parameters</param>
        /// <returns> bool resuklt of method call to caller< /returns>
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            result = 0;
            bool IsFound = false;
            switch (binder.Name.ToLower())
            {
                case "add":
                    result = (int)args[0] + (int)args[1];
                    IsFound= true;
                    break;

                case "multi":
                    result = (int)args[0] * (int)args[1];
                    IsFound = true;
                    break;
            }
            return IsFound;
        }
    }
  

Notice here that basically, there is a dictionary maintained via overrided members TrySetMember and TryGetMember for setting and getting members. Simple…
Secondly TryInvokeMember provided implementation for calling methods dynamically.
Lets do some testing on this class as:

dynamic cal = new DynamicCalculator();
        // Setting members/propertie to dynamic class
        cal.Name = "Shahzad Calculator";
        cal.Made = "Cieco";
        cal.Price = 100;
        // Getting members/propertie so dynamic class
        Console.WriteLine("Members of DynamicCalculator: Name: " + cal.Name + "  Made: " + cal.Made + " Price: " + cal.Price);
        // Invoking call to methods
        Console.WriteLine("Result of Add is : " + cal.Add(5, 6));
        Console.WriteLine("Result of Multi is : " + cal.Multi(5, 6));
        // Console.WriteLine("Result is : " + cal.Sub(5, 6));  //'SystemDynamicApp.DynamicCalculator' does not contain a definition for 'Sub'

Comments explain everything.

Happy coding for Dynamic behavior in C# 4.0

Reference: http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx


Software Architecture-C# Unity 2.0 – Basic Features

February 19, 2011

I have covered different elements of Unity 2.0, in last we posts as:

>>Software Architecture- C# – Unity 2.0 – First lession

>>Software Architecture C-Sharp Unity-2.0 Second Lession

>>Software Architecture – C#- Unity-2.0-Creating Instance Registrations

>>Software Architecture-Dependency Injection with Unity for Constructor Injection

>>Software Architecture- Interception / Decorator Pattern with Unity

Hope you have liked these posts!


Software Architecture-Change of name of machine for Team Foundation Server 2008 + Visual Studio 2008

February 16, 2011

Environment:
Team Foundation Server 2008 + Visual Studio 2008
Problem:
Suppose that you have changed the name of machine where TFS 2008 client is installed as Source control tool for Visual studio. After this name change, your binding to TFS will mess up, you will be lost.
Solution:
Solution is to run “Visual studio 2008 command Prompt”, and write following command

tf workspaces /owner:"demo1\sarwars" /computer:SHAHZADW2K3VPC /server:http://tfs1apptier:8080
 /updatecomputername:akhtarvpc

where demo1\sarwars is user name of TFS, SHAHZADW2K3VPC is the new name of machine, tfs1apptier is name of TFS Server, akhtarvpc is the old name of machine.
If you are not administrator of TFS, add login phrase to command and provide administrative creditial.

Reference:
http://msdn.microsoft.com/en-us/library/y901w7se(v=vs.80).aspx


Software Architecture-Page Methods of ASP .Net/AjAX with DataTable control-Yahoo UI library

February 16, 2011

Objective:To use Page Methods of ASP .Net/AjAX with Yahoo UI library.

Explanation:
There are three approaches to Programming in ASP.NET AJAX.
1. UpdatePanel: Contains a group of server controls and monitors their postbacks and rendering process. Any requests for postback that originate from the contained controls are hijacked and served via script. Changes to the page are applied using DHTML.
2. Remote method calls: Blanket term for asynchronous calls to page methods and local and external Web services. Calls move input arguments and receive return values via JSON streams in a type-independent manner. Strongly typed JavaScript code is required to trigger the call and apply changes back on the client.
3. Client-side data binding: Two client-side controls written entirely in AJAX JavaScript to implement template-based binding. They are ListView, for multiple-records view, and ItemView, for single-record view. These two controls are combined together with client data source and filtering components.
In this Post, we will use Page Methods with Yahoo UI Library.
Page Method is a public static method defined in the codebehind class and decorated with the same WebMethod attribute used for Web service methods.
Yahoo UI Lib is really power full client side UI library.
For details about it, please visit at:
http://developer.yahoo.com/yui/For details about DataTable control, visit:
http://developer.yahoo.com/yui/datatable/
DataTable control major features includes sortable columns, pagination, scrolling, row selection, resizeable columns, and inline cell editing.
Steps:
1. Consider a entity class for showing History Items:

// Sample Object to be returned to client end via Page Method.
    public class HistoryItem{
        public Int32 ID { get; set; }
        public String Name { get; set;}
        public String Desc { get; set; }
        public DateTime Date { get; set;}
    }

2. Define a Page Method as below:

/// <summary>
        ///  Page Method for client side data return
        /// </summary>
        /// <returns> List of HistoryItem object to be returned... </returns>
        [System.Web.Services.WebMethod]
        public static List<HistoryItem> GetPageMethod()
        {
            // Prepare Sample Data
            List<HistoryItem> lst = new List<HistoryItem>
                        { 
                        new HistoryItem { ID = 1, Name = "Created 1" , Desc= "Description 1......Description.....Description....." , Date =  DateTime.Now} ,  new HistoryItem { ID=2 , Desc= "Description 2......Description.....Description.....", Date =  DateTime.Now , Name = "Updated 2" } ,
                        new HistoryItem { ID = 3, Name = "Created 3"  , Desc= "Description 3......Description.....Description.....",Date =  DateTime.Now} ,  new HistoryItem { ID=4 , Desc= "Description 4......Description.....Description.....", Date =  DateTime.Now , Name = "Updated 4 " } ,
                        new HistoryItem { ID = 5, Name = "Created 5"  , Desc= "Description 5......Description.....Description.....",Date =  DateTime.Now} ,  new HistoryItem { ID=6 , Desc= "Description 6......Description.....Description.....", Date =  DateTime.Now , Name = "Updated 6" },
                        new HistoryItem { ID = 7, Name = "Created 7" , Desc= "Description 7......Description.....Description....." , Date =  DateTime.Now} ,  new HistoryItem { ID=8 , Desc= "Description 8......Description.....Description.....", Date =  DateTime.Now , Name = "Updated 8" } ,
                        new HistoryItem { ID = 9, Name = "Created 9"  , Desc= "Description 9......Description.....Description.....",Date =  DateTime.Now} ,  new HistoryItem { ID=10 , Desc= "Description 10......Description.....Description.....", Date =  DateTime.Now , Name = "Updated 10 " }                         
                        };
            // Return Sample Data
            return lst;
        }

3. In ASP .Net page define some includes related to Yahoo UI Library as:

<!--CSS file (default YUI Sam Skin) -->
<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.8.2r1/build/datatable/assets/skins/sam/datatable.css">
 
<!-- Dependencies -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/element/element-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/datasource/datasource-min.js"></script>
 
<!-- OPTIONAL: JSON Utility (for DataSource) -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/json/json-min.js"></script>
 
<!-- OPTIONAL: Connection Manager (enables XHR for DataSource) -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/connection/connection-min.js"></script>
 
<!-- OPTIONAL: Get Utility (enables dynamic script nodes for DataSource) -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/get/get-min.js"></script>
 
<!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/dragdrop/dragdrop-min.js"></script>
 
<!-- OPTIONAL: Calendar (enables calendar editors) -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/calendar/calendar-min.js"></script>
 
<!-- Source files -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/datatable/datatable-min.js"></script>

4. Define some ASP .Net tags as:

    <asp:ScriptManager ID="ScriptManager1" runat="server"   
      EnablePageMethods="True">
</asp:ScriptManager>
    <input id="Button1" type="button" value="Get History data........." onclick='return getData();' /><br /><br />
    <div id="myContainer"></div>

5. Call to Page Method is done via Javascript as below:

<script language="javascript" >
    function getData() {        
        PageMethods.GetPageMethod(onSucceed, onError);
        return false;
    }
    function onSucceed(result) {            
    
       // DataSource for a JavaScript function that returns data
        var dsLocalArray = new YAHOO.util.LocalDataSource(result);
        
       // DataTable columns defination
        var myColumnDefs = [{ key: "ID", label: "ID" }, { key: "Name", label: "Name" }, { key: "Desc", label: "Desc" }, { key: "Date", label: "Date"}];
       
       // DataTable constructor syntax
        var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, dsLocalArray, { sortedBy: { colKey: "Name", dir: "desc" }, rowSingleSelect: true });               
    }
    function onError(result) {
        // Perform Error handling logic here.....
        alert('There is some thing wrong, Check again  .......');
    }

So we are done with sample for fetching data via Javascript via Page methods.

The output will look like as:

Sample code can be downloaded from here. Rename file to pagemethodapp.zip, then extract to get code files
Reference:
http://msdn.microsoft.com/en-us/magazine/cc163480.aspx