Category Archives: C#

Gridview Model binding with Control attribute as parameter

Asp.Net MVC had enjoyed the benefit of Model binding since its inception. It helped in few things such as

  • UI and data model separation.
  • Unit testing of the data binding method. (great! isn’t it?)

With Asp.Net 4.5, Model binding is now available for Web forms as well. Moreover it is integrated in a seamless manner.

so here we go!

UI Code:

New Gridview has two properties to be noticed.

  • ItemType:
  • It needs a type name that you are binding to. It can be a dll which contains the actual method.

  • SelectMethod:
  • It needs a method which returns an IEnumerable or IQueryable type.

    Similarly we have UpdateMethod which is not covered in this post.

    <asp:DropDownList ID="ddlNameFilter" runat="server" AutoPostBack="true" Width="500px" >
                    <asp:ListItem Value="" Text="-- Select word name starts with --" Selected="True" />
                    <asp:ListItem Value="KE" Text="KE" />
                    <asp:ListItem Value="TE" Text="TE" />
                </asp:DropDownList>
    
    </br></br>
                
             <asp:GridView ID="gvPersons" runat="server" 
                    AllowPaging="True" AutoGenerateColumns="False" PageSize="20"             
                 ItemType="WebFormSamples.Person" SelectMethod="GetPersonList" 
                 OnRowDataBound="gvPersons_RowDataBound"
    
                    OnPageIndexChanging="gvPersons_PageIndexChanging">
                    <Columns>
                        <asp:BoundField DataField="BusinessEntityID" HeaderText="Product"
                            SortExpression="BusinessEntityID" />
                        <asp:BoundField DataField="PersonType" HeaderText="PersonType"
                            ReadOnly="True" SortExpression="PersonType" />
                        <asp:BoundField DataField="FirstName" HeaderText="FirstName"
                            SortExpression="FirstName" />
                        <asp:BoundField DataField="LastName" HeaderText="LastName"
                            SortExpression="LastName" />
                    </Columns>
                    <PagerStyle HorizontalAlign="Right" />
                    <PagerSettings Mode="Numeric" />
                </asp:GridView>
    

    Code Behind:

     
            // ddlNameFIlter is a dropdown which user selects and selected value is passed as parameter to the below //<strong>SelectMethod</strong> of Gridview. 
            public IQueryable<Person> GetPersonList([Control("ddlNameFilter")] string searchName)
            {
                List<Person> persons = new List<Person>();
                if ( string.IsNullOrEmpty(searchName))
                {
                    persons = Person.GetPersonList();
                }
                else
                    persons = Person.GetPersonList().Where(p => p.FirstName.ToLower().StartsWith(searchName.ToLower())).ToList();
    
                return persons.AsQueryable();
            }

    There are few more Value providers introduced in Asp.Net 4.5. [QueryString],[Cookie] are also very useful.

    I hope it helps!

    Reading XML using C# Linq – Short and Simple

    Reading an XML has become easier by new Linq to XML queries. It is as simple as querying a List though there are differences in query as per XML structure you are trying to read.

    Here is simple way to parse/read/query an XML file in the following format.

    XML file:

    <?xml version="1.0" encoding="utf-8" ?>
    <Babies>
      <Baby>
        <Name>Aabhas</Name>
        <Gender>M</Gender>
        <Meaning>Feeling</Meaning>
      </Baby>
      <Baby>
        <Name>Balwan</Name>
        <Gender>M</Gender>
        <Meaning>Strong</Meaning>
      </Baby>
      <Baby>
        <Name>Chandra</Name>
        <Gender>M</Gender>
        <Meaning>Moon</Meaning>
      </Baby>
    </Babies>
    

    Below is the C# class representation of XML file

    public class Baby
    {
     public string Name { get; set; }
     public string Meaning { get; set; }
     public string Gender{ get; set; }
    
    }
    

    Below is the C# code to read the nodes and reading it as List

    XDocument xdoc = XDocument.Load(xmlFileName);
    List<Baby> babies = new List<Baby>();
    babies = (from b in xdoc.Descendants("Baby")
    select new Baby() { Name = b.Element("Name").Value, Meaning = b.Element("Meaning").Value ,Gender=b.Element("Gender").Value }
    ).ToList();
    

    Obviously we can apply search filter to the list and do all the possible list operations.
    I did not provide any analysis for performance here as of now but will test and update this post later.

    I hope it helps!

    Asp.Net webform popup in a new window – with a changed title text

    Recently came across with a small issue which actually took lot of valuable time of my team mate as it may sound simple but was really tricky.

    Issue description: You have a webform. On click of a button you need to open a popup window but title of the popup window should be changed. by default title is the url of the popup window.

    Solution:

    <pre><%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="PilotProject._Default" %>
    
    <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script type ="text/javascript" >
    
    function Test() {
            var popup = window.open('', 'name', 'height=200,width=300');
    var doc = popup.document;
    doc.write('<html><head><title>New popup title </title>');
    doc.write('<link rel="stylesheet" href="js.css">');
    doc.write('</head><body><p>New window in a popup.</p>');
    doc.write('<p><a href="javascript:self.close()">close</a> the popup.</p>');
    doc.write('</body></html>');
    doc.close();
    } </script>
    </asp:Content>
    <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
          <asp:Button ID="btntest" runat ="server" OnClientClick="Test();" Text ="Test" />
    </asp:Content>
    

    Output looks like below. PLease note the different title bar text on the popup window.

    Thing to notice here is that we are inserting a new html document in the popup window.and new <title> tage is also included.

    Caution: If you are trying to do this in form which already has a title then it will throw an error saying that you cannot have two title
    tags in a document. Though it will work it works fine if your webform has a master page with a title. Strange but it works 🙂

    UPDATE: As i mentioned if you will try  to open a popup page without master page using javascript then it will throw an error for multiple <title> tags.

    It happens because i was keeping the script in Head section of the parent page. If you keep the script in a .js file and include a reference in the parent page it will work fine. or just keep the script tag in <body> section.

    Here is the code- without master page.

    Parent.aspx:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Parent.aspx.cs" Inherits="PilotProject.Parent" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>Parent</title>
        <script src="Scripts/Common.js" type="text/javascript"></script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnTest" Text="Test" runat="server" OnClientClick="OpenPop();" />
        </div>
        </form>
    </body>
    </html>
    

    Here is the script to be included in a separate tag.

    Common.js:

    function OpenPop() {
        var popup = window.open('', 'name', 'width:300,height:400');
        if (popup != null) {
            var doc = popup.document;
            doc.write('<html><head> <title>I am new pop up</title></head>');
            doc.write('<body>New Window in pop up <a href="javascript:self.close();">Close this</a> </body>');
            doc.write('</html>');
            doc.close();
        }
    }
    
    

    The new popup window will have the new title.
    Thanks Robin for your input on this!
    I hope it helps!

    WebApi – Asp.Net “ROUTE” to “REST”

    WHAT: Webapi is a framework to build Http services that uses standard https verbs like GET, POST, PUT and DELETE to achieve data operations. WCF already had a way (i didn’t like it though 🙂 ) to achieve this but there were things that developers may find cumbersome. Few of them are as mentioned below

    1. Web browsers need to do a lot of XML parsing and DOM manipulation for SOAP based services.
    2. Only WebHttpBinding supports http services and those configuration settings were really painful (at least for me).

    “WebApi framework pretty much utilizes existing Asp.Net routing framework which comes with framework 4.0”

    WHY: Suddenly there is a huge demand of making our web applications available on different platforms/devices like mobiles,smart phones,tablets etc. Http services help us to provide seemless integration to our data access methodologies across all the platforms. One service for all devices and platform.

    WHERE: It comes in-built with Asp.Net MVC 4.0 framwork. you can download it from http://www.asp.net/mvc/mvc4 . Though WebApi implementation (which I am using) is not limited to MVC. Webforms can also enjoy the “Route to REST” :).

    You should have Fiddler tool to see how it works. Download it from http://www.fiddler2.com/fiddler2/ it is a web debugger proxy tool. You can simulate http calls using this tool. It won’t be necessary in my example though.

    HOW:  Once you install MVC 4.0, you will notice a new project template called WebApi. It will give you basic methods and a working sample created for you. Though i would prefer to use “Empty” project type because as a beginner i wanted to see how it works.

    • Install MVC4.0
    • Open new project in VS 2010.
    • select Asp.Net MVC 4 web application.
    • Choose “Empty” project.
    • goto project properties -> Web -> StartAction -> Specific Page -> give “employees/”
    • assign a port like 9090
    • Global.asax.cs : Add the new namespaces mentioned in code. Now we need to define a route format which we would use to access the endpoints which in our case is an action method.
    using System.Web.Http;
    using System.Web.Routing;
    protected void Application_Start(object sender, EventArgs e)
    {
    RouteTable.Routes.MapHttpRoute(
    "EmployeeRoute",
    "{controller}/{id}",
    new {id = RouteParameter.Optional  });
    }
    
    • this route defines that you can access this service by browing either http://localhost:9090/employees or http://localhost:9090/employees/1 . what it means is that for Get requests Id is optional. When we don’t pass id we will get all employees and if Id is specified you get only Employee with the same ID.
    • If you want to allow method names in url just need to modify your Route in Global.asax with “{controller}/{action}/id”. it will allow your web methods to be accessed as resources.
    • Add “Employee” class with public ID and Name properties.

    Add a controller name it “EmployeesController”. and paste the below code.

    </li>
    </ul>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Http;
    using System.Net.Http.Headers;
    namespace WebApiDemo.Controllers
    {
    public class EmployeesController : ApiController
    {
    static List<Employee> _employees = InitEmployeeCollection();
    private static List<Employee> InitEmployeeCollection()
    {
    var empList = new List<Employee>();
    empList.Add(new Employee { ID = 0, Name = "Praveen" });
    empList.Add(new Employee { ID = 1, Name = "Narsi" });
    empList.Add(new Employee { ID = 2, Name = "Ganesh" });
    empList.Add(new Employee { ID = 3, Name = "Venu" });
    return empList;
    
    }
    
    public IEnumerable<Employee> Get()
    {
    return _employees;
    }
    
    public Employee Get(int id)
    {
    var emp = (from e in _employees where e.ID == id
    select e).FirstOrDefault();
    
    if (emp == null)
    {
    //HttpResponseMessage is part .net 4.5
    //return type should be HttpResponseMessage<Employee>
    //var foundEmp = new HttpResponseMessage<Employee>(HttpStatusCode.NotFound );
    // return httpstatuscode.notfound =  404
    }
    return emp;
    }
    
    // insert
    public  Employee Post(Employee newEmployee)
    {
    newEmployee.ID  = _employees.Count() + 1;
    _employees.Add(newEmployee );
    //if success
    //var foundEmp = new HttpResponseMessage<Employee>(HttpStatusCode.Created );
    //return httpstatuscode.created i.e.  201
    return newEmployee;
    }
    
    //edit
    public Employee Put(Employee emp)
    {
    var changedEmp = (from e in _employees
    where e.ID == emp.ID
    select e).FirstOrDefault();
    changedEmp.Name = emp.Name;
    return changedEmp;
    }
    
    //delete
    public void Delete(Employee empToDelete)
    {
    _employees.Remove(empToDelete);
    
    }
    }
    }
    

    Please notice that name of controller methods are named as Get(),Post(),Put() and Delete(). These are pretty much like http verbs and your framwork is able to understand the kind of http action user is trying for just by these names itself . You can also name it like GetEmployee() etc. You can also keep other names but then we have to map it with URI (not covered in this post).Code is nothing new, plain CRUD operations.

    • Build the application and try to run. you would see it hits http://localhost:9090/employees/  as you have mentioned this starting point in project properties. It will not render anything but it will try to open a file (use notepad) which willl contain Json format output.
    • There is no Id specified in the url so it takes you to Get() method.
    • which returns the employee list but in Json format. to read about Json in this context refer to my post on Json .
    • if you type http://localhost:9090/employees/1  it will return employee id and  name with id equal to 1. It will hit overloaded Get method with Id as parameter which will return Employee object in json format.

    Now , your service is in place and you have tested using urls of course only Get verbs. To test Post and other requests you can use fiddler or developer tools (press F12).

    Step by step instructions to use developer tools and basic tutorial is also available on MVC official website .

    Now to consume this webservice as it is. you can read my post on consuming REST services you just need to change URI where your service is hosted.

    Otherwise you can use this class to consume the service.

    <pre>using System.Web.Services;
    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Net;
    using System.Runtime.Serialization.Json;
    public class ConsumerClient
    {
    public static List<Employee> Get()
    {
    WebClient proxy = new WebClient();
    //DownloadData sends data to server using the specific URI defined for your webmethod.
    byte[] data = proxy.DownloadData("http://localhost:9090/Employees/");
    Stream stream = new MemoryStream(data);
    // serializing the returned type which is Employee[]
    DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Employee>));
    var lstEmp = obj.ReadObject(stream) as List<Employee>;
    
    return lstEmp;
    
    }
    
    public static Employee Post(Employee emp)
    {
    Employee newItem = new Employee() { ID = 0, Name = emp.Name };
    WebClient proxy = new WebClient();
    proxy.Headers["Content-type"] = "application/json";
    MemoryStream ms = new MemoryStream();
    
    //serialize the input parameter
    DataContractJsonSerializer serializerToUpload = new DataContractJsonSerializer(typeof(Employee));
    serializerToUpload.WriteObject(ms, newItem);
    
    // upload the data to call AddEmployee web method which returns Employee object.
    byte[] data = proxy.UploadData("http://localhost:9090/Employees", "POST", ms.ToArray());
    Stream stream = new MemoryStream(data);
    // serialize the returned type
    DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(Employee));
    // read the returned type as Employee
    var newEmployee = obj.ReadObject(stream) as Employee;
    return newEmployee;
    }
    }</pre>
    

    Above deserialization method is inbuilt with Dot net framework 4.0 though there are few other libraries which helps you deserialize the
    json objects in an easier way. one of the best one i found is JSON.Net which is really easy to understand.
    To read more on this please refer to My post on Json.Net .

    I hope it helps you to start.
    All the best!!

    Json.Net – serialization and deserialization APIs for Json format

    Json has emerged as a new favorite data format to be sent over the wire. It is a thinner alternative to XML data format. In any integration project conversion of different data formats is the back bone of data communication. like XML Json is also compatible to any platform and easily convertible to native data types.

    What is Json.Net?    It is a portable class library developed by James Newton King which helps you serialize and deserialize Json strings to .Net objects.  Once you include this library in your project you can use it’s built – in classes like  JsonConvert to serialize and deserialize objects. You can also use its Linq to Json APIs which is really helpful and will remind you of  Linq to XML.

    Where do i get it from?   Download it from CodePlex.   Latest version is Json.Net 4.5. You can install it using Nuget package manager from Visual studio (10 onwards). I would recommend you to start using Nuget if you don’t have it already.

    Why Json.Net?    Nobody is going to start using any new library just because it is new and sounds cool. Right?

    In .Net paradigm, We already have few alternatives to serialize/deserialize json objects apart from new Json.Net.

    1)      DataContract serialization                   2)  JavaScript Serialization

    to read more about JavascriptSerializer for Json serialization please read my post on  JavascriptSerializer for Json

    Hence, main reason why should you choose Json.Net over DataContract serializer and JavaScript Serializer   is its performance and features it provides.  There is a very useful feature comparison done among three serialization techniques . Check it out on Json.Net features comparison

    In short below are the main features it provides. 

    1. Flexible JSON serializer for converting between .NET objects and JSON
    2. LINQ to JSON for manually reading and writing JSON
    3. High performance, faster than .NET’s built-in JSON serializers
    4. Write indented, easy to read JSON
    5. Convert JSON to and from XML
    6. Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone

    How Json.Net can be used?       finally some code 🙂

    Step 1. Download  it from CodePlex. or preferably install it using Nuget Package manager.

    Step 2. Make sure your project has Newtonsoft.Json dll in your bin folder.

    here, Product is a C# type.

    public class Product
     {
    public string Name { get; set; }
    public DateTime ExpiryDate { get; set; }
    public decimal Price { get; set; }
    public string[] Sizes { get; set; }
     }
    

    Converting a json string to C# product object.

    
    public Product JsonToProductObject(string jsonString)
     {
    var deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonString);
    return deserializedProduct;
     }
    

    Converting product object to json fromat string.

    public string ProductObjectToJson(Product product)
     {
     string json =JsonConvert.SerializeObject</strong>(product);
     return json;
     }
    

    Linq to Json: There are instances when we do not need to serialize the objects just want to read few properties of an object or json string. Just Like Linq to XML Json.Net library also provides you the awesome capability of querying the json objects using Linq.

    Below code is taken from the James.NewtonKing official website. Beauty of the code is to have the same declarative syntax that Linq users are so fond of.

    List<Post> posts = GetPosts();
    JObject rss =
    new JObject(
    new JProperty("channel",
    new JObject(
    new JProperty("title", "James Newton-King"),
    new JProperty("link", "http://james.newtonking.com"),
    new JProperty("description", "James Newton-King's blog."),
    new JProperty("item",
    new JArray(
    from p in posts
    orderby p.Title
    select new JObject(
    new JProperty("title", p.Title),
    new JProperty("description", p.Description),
    new JProperty("link", p.Link),
    new JProperty("category",
    new JArray(
    from c in p.Categories
    select new JValue(c)))))))));
    // here is the output which is a json string
    //{
    //  "channel": {
    //    "title": "James Newton-King",
    //    "link": "http://james.newtonking.com",
    //    "description": "James Newton-King's blog.",
    //    "item": [
    //      {
    //        "title": "Json.NET 1.3 + New license + Now on CodePlex",
    //        "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
    //        "link": "http://james.newtonking.com/projects/json-net.aspx",
    //        "category": [
    //          "Json.NET",
    //          "CodePlex"
    //        ]
    //      },
    //      {
    //        "title": "LINQ to JSON beta",
    //        "description": "Annoucing LINQ to JSON",
    //        "link": "http://james.newtonking.com/projects/json-net.aspx",
    //        "category": [
    //          "Json.NET",
    //          "LINQ"
    //        ]
    //      }
    //    ]
    //  }
    //}
    // Now we can query to get
    var categories =  from c in rss.PropertyValue<JObject>("channel")                                                          .PropertyValue<JArray>("item")                                                                            .Children<JObject>()                                                                                      .PropertyValues<JArray>("category")                                                                       .Children<string>()                                                                                       group c by c into g                                                                                       orderby g.Count() descending                                                                              select new { Category = g.Key, Count = g.Count() };
    foreach (var c in categories)                                                                             {
    Console.WriteLine(c.Category + " - Count: " + c.Count);                                                  }
    // below is the output
    //Json.NET - Count: 2
    //LINQ - Count: 1
    //CodePlex - Count: 1
    

    To understand the Json.Net library in detail, you can refer to the official Json.Net classes and APIs reference.

    James Newton King had really made our lives easy with this cool library which is not only new but performs great when compared to existing serialization techniques. Hats off to him 🙂

    Note: Examples and features are cited from the original json.Net website http://james.newtonking.com/