Showing posts with label Generic. Show all posts
Showing posts with label Generic. Show all posts

Thursday, 23 May 2013

You can get element from array until your given condition is satisfied.
TakeWhile LINQ method to return elements starting from the beginning of the array until a number is read whose value satisfied according to our given criteria.


Here is LINQ "TakeWhile" Method example.

Wednesday, 22 May 2013

Using LINQ we can check sequence match on all elements in same order for two different array.
We are using "SequenceEqual" LINQ method to check. This method returns "true" if sequence match else return "false".

Here is LINQ "SequenceEqual" Method example.

Tuesday, 14 May 2013

There are situations were we have string array which contains many value and we want to check that particular word or string part exist in all values.
We want to avoid iteration of array at that time we can use LINQ's "Any" method. Using one line code we can check.

Here is example for this :
In this example we take on string array "ProductArray" and insert some values. Now we want to check that "er" word is contain any values of this array or not using "Contains" method. You can check output below.

C#. Net Example :
        string[] ProductArray = { "CPU", "Computer", "DVD", ".Net" };

        bool isExist = ProductArray.Any(o => o.Contains("er"));

        Response.Write("There is a word in the list that contains 'er': <b>" + isExist + "</b>");

VB.Net Examples :
        Dim ProductArray As String() = {"CPU", "Computer", "DVD", ".Net"}

        Dim isExist As Boolean = ProductArray.Any(Function(o) o.Contains("er"))

        Response.Write("There is a word in the list that contains 'er': <b>" & isExist & "</b>")

Output :

Wednesday, 8 May 2013

Using LINQ we can convert array in to dictionary object. We can use "ToDictionary" LINQ method to get dictionary object from array.
But we need to make sure that the key value should be unique in array, otherwise it will generate error "An item with the same key has already been added.".

Here is example for that.
In this example we take one two dimensional array "CustomerDetails". This array contains ID and Name of customer. Now using "ToDictionary" method of this array we can get dictionary object of type "Dictionary<int, string>". You can get your desirable type of Dictionary object.

Thursday, 2 May 2013

Using LINQ we can get specific type of object from Object Type array which contains many types of object. We are using "OfType" generic method to return only the elements of the array that  we specified.

Here is example for this.
In this example we take one array whose type is object and which contains many types of object, i.e. string, integer, double, Dictionary etc...
Now we get only doubles value using LINQ and display, after that, we get Dictionary object using LINQ and display. You can see the output for that.


Friday, 1 February 2013

Click to Download C# Example ImageMappedHandlerInCSharp.zip
Click to Download VB.NET Example ImageMappedHandlerInVBNET.zip


Http Handler using ".ashx" file extension and this is very convenient and understandable to all of us. But we can also custom this file extension with our requirement. To make customization in file extension we need to do add class file in "App_Code" folder and this class file implement "IHttpHandler" interface. And also mapping file extension in IIS and add settings in "web.config" file.

This configuration tell the application to show which file extension this handler serves. We can You do this by adding an <httpHandlers> section to the web.config file.
Here is configuration setting :
    <system.web>
      <httpHandlers>
        <add verb="*" path="ImageHandler.img" type="ImageMappedHandler, App_Code"/>
      </httpHandlers>
    </system.web>

This settings direct the application to use the "ImageMappedHandler" class to process incoming requests for ImageHandler.img. We can also specify wildcards for the path. By specifying *.img for the path which indicates that we want the application to use the ImageMappedHandler class to process any request with the
.img file extension. By specifying * indicates that we want all requests to the application to be processed using the handler.

Additional Configuration for IIS 7 :
If we run out web application on IIS 7 then we also must add the <handlers> configuration section to the <system.webServer> configuration section in our application’s config file. When adding the handler configuration in this section, we must also include the name attribute.

Configuration for IIS 7 :
  <system.webServer>
    <handlers>
      <add name="ImageHandler" verb="*" path="ImageHandler.img" type="ImageMappedHandler, App_Code" />
    </handlers>
  </system.webServer>

Now after doing this settings we can directly call ImageHandler.img from browser and we can get image from that.

Here is example for this.

Tuesday, 1 January 2013

Click to Download C# Example ImplementHttpHandlersInCSharp.zip
Click to Download VB.NET Example ImplementHTTPHandlersInVBNET.zip

HttpHandlers is different from HttpModules. HttpHandlers positions in the request-processing pipeline is different from HttpModules. Using HttpHandlers we can map to a specific file extension.

Handlers are the final stop for incoming HTTP requests and the point in the request processing pipeline that is responsible for serving the requested content or data like. HTML , ASPX page, plain text, or an image.

Using HttpHandlers we can handle dynamic file download request.
HttpHandler using an ".ashx" file extension that allows to get started quickly and requires no server configuration.

You can add generic HttpHandler by simply select the Generic Handler file type from the Add New Item dialog in your project. Here below sample screen shot display. You may change the extension of file but this will require additional configuration in your deployment server. With ".ashx" extension you do not require any additional configuration.
When you add generic http handler in your application or project class stab is automatically added in ".ashx" file.

This class stub implements the IHttpHandler interface, which need you to implement the Process Request method and IsReusable property.

  • In ProcessRequest method you use to actually process the incoming HTTP request. By default, the class stub changes the content type to plain and then writes the “Hello World” string to the output stream.
  •  The IsReusable property lets ASP.NET know whether incoming HTTP requests can reuse the sample instance of this HttpHandler.

The handler generated automatically in you added file is ready to run right away. You can run this ".ashx" file in browser and see the result. This result depends on various factors like...
  • Browser type and version
  • Applications loaded on the system that may map to the MIME type
  • Operating system and service pack level

Based on these factors, you might see the text returned in the browser, you might see Notepad open and display the text, or you might receive the Open/Save/Cancel prompt from IE.

Here is example for this.
In this example we get images from "ImageHandler.ashx" file base on query string and display images directly in "<img>" tag. For that we added on "ImageHandler.ashx" file in our project and set content type "image/jpeg" in "ProcessRequest" method and depending on query string variable "id" value we can get image.

ASPX Code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>
            HTTP Handler class Impliment in Img tag
        </h1>
        <h1>Id : 1</h1>
        <img src="ImageHandler.ashx?id=1" alt="Dynamic Image" />

        <h1>Id : 2</h1>
        <img src="ImageHandler.ashx?id=2" alt="Dynamic Image" />

    </div>
    </form>
</body>
</html>

C# Examples (ImageHandler.ashx File) :

<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System;
using System.Web;

public class ImageHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        context.Response.ContentType = "image/jpeg";
        if (context.Request.QueryString["id"] == "1")
        {
            context.Response.WriteFile("bamboo.jpg");
        }
        else
        {
            context.Response.WriteFile("palmtree.jpg");
        }
        
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

VB.Net Examples :
 
<%@ WebHandler Language="VB" Class="ImageHandler" %>

Imports System
Imports System.Web

Public Class ImageHandler : Implements IHttpHandler
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        'context.Response.ContentType = "text/plain"
        'context.Response.Write("Hello World")
        
        context.Response.ContentType = "image/jpeg"
        If context.Request.QueryString("id") = "1" Then
            context.Response.WriteFile("bamboo.jpg")
        Else
            context.Response.WriteFile("palmtree.jpg")
        End If
        
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

Output (Add new Generic Handler ".ashx" File): 

Add new Generic Handler ".ashx" File
(To view original image , click on image)


Output (Get Image from "ImageHandler.ashx" file) : 

Implement Generic HTTPHandler
(To view original image , click on image)


Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles according to that.



Wednesday, 19 December 2012

You can bind list of strings to gird view and display very uniform manner in a very easy way. List may be a generic list of strings. Generic List class is available in "System.Collections.Generic" namespace. We are using "DataSource" property of Grid view to set data source and "DataBind" method to bind data.

Here is example for this.

Friday, 19 October 2012


This is a situations where you have an string array which contains some string element or values and some integer values and we want to parse that integer values from that List or array and retrieve only integer values. We can do with the help of LINQ. We can create an extension method of linq and achieve this.
This LINQ extension method is very useful.

Here is example for this.
In this example we take one List of string object. This List of string object contains both integer and string values.We parse that List of string object and get integer values from that.

In Vb.Net Example we need to add "Module" to create custom LINQ Extension method.

Monday, 15 October 2012

Click Here to Download ImplementIComparableInterface.zip

You can compare two object of same class with your predefine rules. You can also say comparison between two objects. 
You can provide compare custom types with your predefined business rules. This also allow to sort collections of instances of those types.
For comparison we implement generic System.IComparable<T> interface. For the comparison of a type based on more than one characteristic, we need to create separate types that implement the generic System.Collections.Generic.IComparer<T> interface.

If you compare two different object of same class with equal (=) operator , at that time this will check only reference location number, this will not check actual fields value property. To avoid this we need to implement IComparable interface and implements it's "CompareTo" Method.

You can call this method like this "X.CompareTo(Y)". X and Y is the object of custom class.
This method return Three possible values.

  • If X value is less than Y value, it will return less than zero (for example, -1).
  • If X value same value as Y value , it will return zero.
  • If X value is greater than Y value, It will return greater than zero (for example, 1).

Here is example for this.

Thursday, 5 July 2012

XDocument is Introduce in System.Xml.Linq namespace.
XDocument is more friendlier and easy to use than XMLDocument.
Earlier we are using XMLDocument for read and processing XML File.
Syntax of retrieving element from XML document is different than XMLDocument.
Every .Net Beginners needs to know this. 

Here is example for this.
In this example We load Books.xml file and read data from this file using LINQ to XML and display in grid as well as display count of books.

XML File : (Books.xml)
<?xml version="1.0" encoding="utf-8" ?>
<Books>
   <Book>
    <Title>ASP.NET</Title>
    <ISBN>asp1</ISBN>
    <ReleaseDate>11/11/2010</ReleaseDate>
    <Pages>200</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>C#.NET</Title>
    <ISBN>c#2</ISBN>
    <ReleaseDate>10/11/2010</ReleaseDate>
    <Pages>500</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>VB.NET</Title>
    <ISBN>vb3</ISBN>
    <ReleaseDate>5/5/2009</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>SQL Server</Title>
    <ISBN>sql4</ISBN>
    <ReleaseDate>6/9/2010</ReleaseDate>
    <Pages>300</Pages>
    <PublisherId>2</PublisherId>
  </Book>
  <Book>
    <Title>JAVA</Title>
    <ISBN>java5</ISBN>
    <ReleaseDate>8/5/2011</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>3</PublisherId>
  </Book>
</Books>


ASPX Code :
<form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvBooks" runat="server">
        </asp:GridView>
    </div>
</form>

C# Example :
        XDocument objBooksXML = XDocument.Load(Server.MapPath("books.xml"));
        var objBooks = from book in
                       objBooksXML.Descendants("Book")
                       select new { 
                                    Title = book.Element("Title").Value, 
                                    Pages = book.Element("Pages").Value 
                                  };

        Response.Write(String.Format("Total {0} books.", objBooks.Count()));
        gvBooks.DataSource = objBooks;
        gvBooks.DataBind();

VB.net Example :
        Dim objBooksXML As XDocument = XDocument.Load(Server.MapPath("books.xml"))
        Dim objBooks = From book In objBooksXML...<Book>
                       Select New With {.Title = book.<Title>.Value, .Pages = book.<Pages>.Value}
        Response.Write(String.Format("Total {0} books.", objBooks.Count()))
        gvBooks.DataSource = objBooks
        gvBooks.DataBind()

Output : 


Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that. 


Thursday, 7 June 2012

Using a group join you can get group wise data using LINQ.
Here are sample example for this.
In this example there are two classes Books and Publishers. Now we want to display Publisher wise books, One publishers has multiple books. We can do this using LINQ.
Using a group join you can get all the publishers that match a books as a sequence.

C# Example :
    public class Books
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Pages { get; set; }
        public int PublisherId { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        var bookslist = GetBooksList();
        var publisherslist = GetPublishers();
        var query = from pl in publisherslist
                    join bl in bookslist on pl.PublisherId equals bl.PublisherId into plbl
                    select new { pl.PublisherName, BooksLst = plbl };
        foreach (var publishers in query)
        {
            Response.Write("<b>"+ publishers.PublisherName + ":</b><br/>" );
            foreach (var b in publishers.BooksLst)
            {
                Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;" + b.Title + "<br/>");
            }
        }
        Response.Write("<br/><br/>");

    }
    public List<Books> GetBooksList()
    {
        return new List<Books> {
                        new Books { Title="ASP.NET",ISBN="asp1",ReleaseDate= DateTime.Parse( "11/11/2010") ,Pages=200,PublisherId=1},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500,PublisherId=1},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400,PublisherId=1},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300,PublisherId=2 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400,PublisherId=3 },
                        new Books { Title="HTML",ISBN="html6",ReleaseDate= DateTime.Parse( "9/5/2011"),Pages=400 }
        
        };

    }

    public class Publisher
    {
        public int PublisherId { get; set; }
        public string PublisherName { get; set; }
    }

    public List<Publisher> GetPublishers()
    {
        return new List<Publisher> {
                        new Publisher { PublisherId=1, PublisherName="Microsoft" } ,
                        new Publisher { PublisherId=2, PublisherName="Wrox" } ,
                        new Publisher { PublisherId=3, PublisherName="Sun Publications" }
        };
    }

VB.net Example :
    Public Class Books
        Public Property Title() As String
        Public Property ISBN As String
        Public Property ReleaseDate As Date
        Public Property Pages As Integer
        Public Property PublisherId As Integer
    End Class

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim bookslist = GetBooksList()
        Dim publisherslist = GetPublishers()
        Dim query = From pl In publisherslist _
                    Group Join bl In bookslist On pl.PublisherId Equals bl.PublisherId Into Group _
                    Select New With {.PublisherName = pl.PublisherName, .BooksLst = Group}

        For Each publishers In query
            Response.Write("<b>" + publishers.PublisherName + ":</b><br/>")
            For Each b In publishers.BooksLst
                Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;" + b.Title + "<br/>")
            Next
        Next
        Response.Write("<br/><br/>")

    End Sub
    Public Function GetBooksList() As List(Of Books)
        Dim lstBooks As New List(Of Books) From { _
                                New Books With {.Title = "ASP.NET", .ISBN = "asp1", .ReleaseDate = DateTime.Parse("11/11/2010"), .Pages = 200, .PublisherId = 1}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500, .PublisherId = 1}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400, .PublisherId = 1}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300, .PublisherId = 2}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400, .PublisherId = 3}, _
                                New Books With {.Title = "HTML", .ISBN = "html6", .ReleaseDate = DateTime.Parse("9/5/2011"), .Pages = 400}}

        Return lstBooks
    End Function
    Public Class Publisher
        Public Property PublisherId() As Integer
        Public Property PublisherName() As String
    End Class
    Public Function GetPublishers() As List(Of Publisher)
        Dim publishers As Publisher() = { _
        New Publisher With {.PublisherId = 1, .PublisherName = "Microsoft"}, _
        New Publisher With {.PublisherId = 2, .PublisherName = "Wrox"}, _
        New Publisher With {.PublisherId = 3, .PublisherName = "Sun Publications"} _
        }
        Return New List(Of Publisher)(publishers)
    End Function

Output :

 

Tuesday, 5 June 2012

You can also do left outer join using LINQ.

Here are sample example of this.
In this example there is book class which has PublisherId field , this fields contains only numeric values.
If we need to display Publisher Name we have to join this book class object to Publishers class object which has Publisher Name of each Publisher Id key.
There are also some records in Book class which does not have PublisherId and still we want that records and display some special text like "(No Publisher)" in this records.
In this example you can see that "HTML" book does not have publisher id so we can display "(No Publisher)" in Publisher Name column of this record.
In this example we are using special method like DefaultIfEmpty() of LINQ.

ASPX Code :
<form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvBooks" runat="server">
        </asp:GridView>
    </div>
</form>

C# Example :
    public class Books
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Pages { get; set; }
        public int PublisherId { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        var bookslist = GetBooksList();
        var publisherslist=GetPublishers();
        var query = from bl in bookslist
                    join p in publisherslist on bl.PublisherId equals p.PublisherId into joinData
                    from blp in joinData.DefaultIfEmpty()
                    select new { Title = bl.Title, PublisherName = blp == null ? "(No Publisher)" : blp.PublisherName };
        this.gvBooks.DataSource = query;
        this.gvBooks.DataBind();
    }
    public List<Books> GetBooksList()
    {
        return new List<Books> {
                        new Books { Title="ASP.NET",ISBN="asp1",ReleaseDate= DateTime.Parse( "11/11/2010") ,Pages=200,PublisherId=1},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500,PublisherId=1},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400,PublisherId=1},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300,PublisherId=2 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400,PublisherId=3 },
                        new Books { Title="HTML",ISBN="html6",ReleaseDate= DateTime.Parse( "9/5/2011"),Pages=400 }
        
        };

    }

    public class Publisher
    {
        public int PublisherId { get; set; }
        public string PublisherName { get; set; }
    }

    public List<Publisher> GetPublishers()
    {
        return new List<Publisher> {
                        new Publisher { PublisherId=1, PublisherName="Microsoft" } ,
                        new Publisher { PublisherId=2, PublisherName="Wrox" } ,
                        new Publisher { PublisherId=3, PublisherName="Sun Publications" }
        };
    }

VB.net Example :
    Public Class Books
        Public Property Title() As String
        Public Property ISBN As String
        Public Property ReleaseDate As Date
        Public Property Pages As Integer
        Public Property PublisherId As Integer
    End Class

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim arrayNumbers As Integer() = {1, 2, 5, 9, 10, 1, 0, 9, 5, 6, 4, 3, 2}
        Dim selectedNumber As Integer() = (From an In arrayNumbers Where an > 5 Select an).ToArray()
        Dim selectedNumberLambda As Integer() = arrayNumbers.Where(Function(o) o > 5).ToArray()



        Dim bookslist = GetBooksList()
        Dim publisherslist = GetPublishers()
        Dim query = From bl In bookslist _
                    Group Join p In publisherslist On bl.PublisherId Equals p.PublisherId Into Group _
                    From blp In Group.DefaultIfEmpty() _
                    Select bl.Title, PublisherName = If(blp Is Nothing, "(No Publisher)", blp.PublisherName)

        gvBooks.DataSource = query
        gvBooks.DataBind()
    End Sub
    Public Function GetBooksList() As List(Of Books)
        Dim lstBooks As New List(Of Books) From { _
                                New Books With {.Title = "ASP.NET", .ISBN = "asp1", .ReleaseDate = DateTime.Parse("11/11/2010"), .Pages = 200, .PublisherId = 1}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500, .PublisherId = 1}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400, .PublisherId = 1}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300, .PublisherId = 2}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400, .PublisherId = 3}, _
                                New Books With {.Title = "HTML", .ISBN = "html6", .ReleaseDate = DateTime.Parse("9/5/2011"), .Pages = 400}}

        Return lstBooks
    End Function
    Public Class Publisher
        Public Property PublisherId() As Integer
        Public Property PublisherName() As String
    End Class
    Public Function GetPublishers() As List(Of Publisher)
        Dim publishers As Publisher() = { _
        New Publisher With {.PublisherId = 1, .PublisherName = "Microsoft"}, _
        New Publisher With {.PublisherId = 2, .PublisherName = "Wrox"}, _
        New Publisher With {.PublisherId = 3, .PublisherName = "Sun Publications"} _
        }
        Return New List(Of Publisher)(publishers)
    End Function

Output :
 

Monday, 4 June 2012

Using LINQ to XML you can also join multiple files and get result based on LINQ query.
LINQ to XML uses System.Xml.Linq namespace.

Here are example for this.

In this examples we have to XML files first "Books.xml" and second "Publishers.xml",
we are joining this two files with one common field "PublisherId". We are fetching "PublisherName" from "Publishers.xml" file to display in grid.

Here are examples :

XML File : (Books.xml)
<?xml version="1.0" encoding="utf-8" ?>
<Books>
   <Book>
    <Title>ASP.NET</Title>
    <ISBN>asp1</ISBN>
    <ReleaseDate>11/11/2010</ReleaseDate>
    <Pages>200</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>C#.NET</Title>
    <ISBN>c#2</ISBN>
    <ReleaseDate>10/11/2010</ReleaseDate>
    <Pages>500</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>VB.NET</Title>
    <ISBN>vb3</ISBN>
    <ReleaseDate>5/5/2009</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>SQL Server</Title>
    <ISBN>sql4</ISBN>
    <ReleaseDate>6/9/2010</ReleaseDate>
    <Pages>300</Pages>
    <PublisherId>2</PublisherId>
  </Book>
  <Book>
    <Title>JAVA</Title>
    <ISBN>java5</ISBN>
    <ReleaseDate>8/5/2011</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>3</PublisherId>
  </Book>
</Books>

XML File : (Publishers.xml)
<?xml version="1.0" encoding="utf-8" ?>
<Publishers>
  <Publisher>
    <PublisherId>1</PublisherId>
    <PublisherName>Microsoft</PublisherName>
  </Publisher>
  <Publisher>
    <PublisherId>2</PublisherId>
    <PublisherName>Wrox</PublisherName>
  </Publisher>
  <Publisher>
    <PublisherId>3</PublisherId>
    <PublisherName>Sun Publications</PublisherName>
  </Publisher>
</Publishers>

ASPX Code :
<form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvBooks" runat="server">
        </asp:GridView>
    </div>
</form>

C# Example :
    protected void Page_Load(object sender, EventArgs e)
    {
        var query = from bl in
                    XElement.Load(MapPath("Books.xml")).Elements("Book")
                    join g in XElement.Load(MapPath("Publishers.xml")).Elements("Publisher")
                    on (int)bl.Element("PublisherId") equals (int)g.Element("PublisherId")
                    select new 
                    {
                        Title = (string)bl.Element("Title"),
                        ISBN = (string)bl.Element("ISBN"),
                        ReleaseDate = (DateTime)bl.Element("ReleaseDate"),
                        Pages = (int)bl.Element("Pages"),
                        PublisherName = (string)g.Element("PublisherName")
                    };

        gvBooks.DataSource = query;
        gvBooks.DataBind();
    }

VB.net Example :
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim query = From bl In XElement.Load(MapPath("Books.xml")).Elements("Book") _
                    Join g In XElement.Load(MapPath("Publishers.xml")).Elements("Publisher") _
                    On CInt(bl.Element("PublisherId")) Equals CInt(g.Element("PublisherId")) _
                    Select New With { _
                        .Title = CStr(bl.Element("Title")), _
                        .ISBN = CStr(bl.Element("ISBN")), _
                        .ReleaseDate = CDate(bl.Element("ReleaseDate")), _
                        .Pages = CInt(bl.Element("Pages")), _
                        .PublisherName = CStr(g.Element("PublisherName")) _
                    }
        gvBooks.DataSource = query
        gvBooks.DataBind()
    End Sub

Output :

Saturday, 2 June 2012

You can also query the array variables using LINQ.
Here are sample example for this.
In this example there is an array of integer values which contains various number, Now we want to get numbers in array which is greater then 5.
We can do this without FOR loop.

There are two possible way to do this. One is using LINQ Query and Second is Using LAMBDA Expression


C# Example using LINQ Query :
int[] arrayNumbers = new[] { 1,2,5,9,10,1,0,9,5,6,4,3,2};
int[] selectedNumber = (from an in arrayNumbers where an > 5 select an).ToArray();

C# Example using LAMBDA Expression:
int[] arrayNumbers = new[] { 1,2,5,9,10,1,0,9,5,6,4,3,2};
int[] selectedNumberLambda = arrayNumbers.Where(an => an > 5).ToArray();

Wednesday, 30 May 2012

Using LINQ to XML we can use the same basic LINQ syntax to query XML documents.
LINQ to XML uses System.Xml.Linq namespace.
Here are example for this.
In this example we have Books.xml file which contains books details. Now we query this xml files and display it's data in grid using LINQ .
In LINQ to XML we have to provide mapping logic in LINQ query.

Here are examples :

XML File : (Books.xml)
<?xml version="1.0" encoding="utf-8" ?>
<Books>
   <Book>
    <Title>ASP.NET</Title>
    <ISBN>asp1</ISBN>
    <ReleaseDate>11/11/2010</ReleaseDate>
    <Pages>200</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>C#.NET</Title>
    <ISBN>c#2</ISBN>
    <ReleaseDate>10/11/2010</ReleaseDate>
    <Pages>500</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>VB.NET</Title>
    <ISBN>vb3</ISBN>
    <ReleaseDate>5/5/2009</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>SQL Server</Title>
    <ISBN>sql4</ISBN>
    <ReleaseDate>6/9/2010</ReleaseDate>
    <Pages>300</Pages>
    <PublisherId>2</PublisherId>
  </Book>
  <Book>
    <Title>JAVA</Title>
    <ISBN>java5</ISBN>
    <ReleaseDate>8/5/2011</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>3</PublisherId>
  </Book>
</Books>

ASPX Code :
<form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvBooks" runat="server">
        </asp:GridView>
    </div>
</form>

C# Example :
 public class Books
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Pages { get; set; }
        public int PublisherId { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var query = from m in
                    XElement.Load(MapPath("Books.xml")).Elements("Book")
                    select new Books
                    {
                        Title = (string)m.Element("Title"),
                        ISBN = (string)m.Element("ISBN"),
                        ReleaseDate = (DateTime)m.Element("ReleaseDate"),
                        Pages = (int)m.Element("Pages"),
                        PublisherId = (int)m.Element("PublisherId")
                    };

        gvBooks.DataSource = query;
        gvBooks.DataBind();
    }

VB.net Example :
 Public Class Books
        Public Property Title() As String
        Public Property ISBN As String
        Public Property ReleaseDate As Date
        Public Property Pages As Integer
        Public Property PublisherId As Integer
    End Class

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim query = From m In XElement.Load(MapPath("Books.xml")).Elements("Book") _
                    Select New Books With { _
                        .Title = CStr(m.Element("Title")), _
                        .ISBN = CStr(m.Element("ISBN")), _
                        .ReleaseDate = CDate(m.Element("ReleaseDate")), _
                        .Pages = CInt(m.Element("Pages")), _
                        .PublisherId = CInt(m.Element("PublisherId")) _
                    }
        gvBooks.DataSource = query
        gvBooks.DataBind()
    End Sub

Output : 


For Beginning .Net articles. Click Here...

This type of .Net Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.




 

Tuesday, 29 May 2012

Using LINQ we can achive paging logic in your application much easier by exposing the Skip and Take methods. The Skip method enables you to skip a defined number of records in the resultset. The Take method enables you to specify the number of records to return from the resultset. By calling Skip and then Take, you can return a specific number of records from a specific location of the resultset.
You can use Skip and Take methods Take method in any LINQ Query either Simple query or Joining Query.

In this sample example We skip first 10 records and take next 10 records for second page , For first page skipp zero records like this ".skip(0)" and take 10 records. This will give first 10 records for first page.

Here are example.

C# Example :
    public class Books
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Pages { get; set; }
        public int PublisherId { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var bookslist = GetBooksList();
        var query = (from bl in bookslist select bl).Skip(10).Take(10);
        this.gvBooks.DataSource = query;
        this.gvBooks.DataBind();
    }
    public List<Books> GetBooksList()
    {
        return new List<Books> {
                        new Books { Title="ASP.NET",ISBN="asp1",ReleaseDate= DateTime.Parse( "11/11/2010") ,Pages=200,PublisherId=1},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500,PublisherId=1},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400,PublisherId=1},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300,PublisherId=2 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400,PublisherId=3 }
        
        };

    }
VB.net Example :
    Public Class Books
        Public Property Title() As String
        Public Property ISBN As String
        Public Property ReleaseDate As Date
        Public Property Pages As Integer
        Public Property PublisherId As Integer
    End Class

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim bookslist = GetBooksList()
        Dim query = (From bl In bookslist _
                    Select bl).Skip(10).Take(10)
        gvBooks.DataSource = Query
        gvBooks.DataBind()
    End Sub
    Public Function GetBooksList() As List(Of Books)
        Dim lstBooks As New List(Of Books) From { _
                                New Books With {.Title = "ASP.NET", .ISBN = "asp1", .ReleaseDate = DateTime.Parse("11/11/2010"), .Pages = 200, .PublisherId = 1}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500, .PublisherId = 1}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400, .PublisherId = 1}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300, .PublisherId = 2}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400, .PublisherId = 3}}

        Return lstBooks
    End Function

Monday, 28 May 2012

LINQ also supports the joining of data from different collections using a familiar SQL-like join syntax.
Here are sample example of this.
In this example there is book class which has PublisherId field , this fields contains only numeric values.
If we need to display Publisher Name we have to join this book class object to Publishers class object which has Publisher Name of each Publisher Id key.
In this example we display book title from Books class and it's publisher name from publishers class.

C# Example :
    public class Books
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Pages { get; set; }
        public int PublisherId { get; set; }
    }
    public class Publisher
    {
        public int PublisherId { get; set; }
        public string PublisherName { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var bookslist = GetBooksList();
        var publisherslist=GetPublishers();
        var query = from bl in bookslist
                    join p in publisherslist on bl.PublisherId equals p.PublisherId
                    select new { bl.Title,p.PublisherName};
        this.gvBooks.DataSource = query;
        this.gvBooks.DataBind();
    }
    public List<Books> GetBooksList()
    {
        return new List<Books> {
                        new Books { Title="ASP.NET",ISBN="asp1",ReleaseDate= DateTime.Parse( "11/11/2010") ,Pages=200,PublisherId=1},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500,PublisherId=1},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400,PublisherId=1},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300,PublisherId=2 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400,PublisherId=3 }
        
        };

    }
    public List<Publisher> GetPublishers()
    {
        return new List<Publisher> {
                        new Publisher { PublisherId=1, PublisherName="Microsoft" } ,
                        new Publisher { PublisherId=2, PublisherName="Wrox" } ,
                        new Publisher { PublisherId=3, PublisherName="Sun Publications" }
        };
    }

VB.net Example :
    Public Class Books
        Public Property Title() As String
        Public Property ISBN As String
        Public Property ReleaseDate As Date
        Public Property Pages As Integer
        Public Property PublisherId As Integer
    End Class
    Public Class Publisher
        Public Property PublisherId() As Integer
        Public Property PublisherName() As String
    End Class
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim bookslist = GetBooksList()
        Dim publisherslist = GetPublishers()
        Dim query = From bl In bookslist _
                    Join p In publisherslist On p.PublisherId Equals bl.PublisherId _
                    Select bl.Title, p.PublisherName
        gvBooks.DataSource = Query
        gvBooks.DataBind()
    End Sub
    Public Function GetBooksList() As List(Of Books)
        Dim lstBooks As New List(Of Books) From { _
                                New Books With {.Title = "ASP.NET", .ISBN = "asp1", .ReleaseDate = DateTime.Parse("11/11/2010"), .Pages = 200, .PublisherId = 1}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500, .PublisherId = 1}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400, .PublisherId = 1}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300, .PublisherId = 2}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400, .PublisherId = 3}}

        Return lstBooks
    End Function

    Public Function GetPublishers() As List(Of Publisher)
        Dim publishers As Publisher() = { _
        New Publisher With {.PublisherId = 1, .PublisherName = "Microsoft"}, _
        New Publisher With {.PublisherId = 2, .PublisherName = "Wrox"}, _
        New Publisher With {.PublisherId = 3, .PublisherName = "Sun Publications"} _
        }
        Return New List(Of Publisher)(publishers)
    End Function