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

Friday 25 May 2012

LINQ also includes many operators you can execute on enumerable objects.
Most of these operators are available to use and are similar to operators that you find in SQL, such as Count, Min, Max, Average, and Sum.
Here are sample example of using this operators.

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; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var bookslist = GetBooksList();
        int intBookCount = bookslist.Count();
        string strMaxPages = bookslist.Max(b => b.Pages).ToString();
        string strMinPages = bookslist.Min(b => b.Pages).ToString();
        string strAveragePages = bookslist.Average(b => b.Pages).ToString();
       
    }
    public List<Books> GetBooksList()
    {
        return new List<Books> {
                        new Books { Title="ASP.NET",ISBN="asp1",ReleaseDate= DateTime.Parse( "11/11/2010") ,Pages=200},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400 }
        
        };

    }

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
    End Class
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim bookslist = GetBooksList()
        Dim intBookCount As Integer = bookslist.Count()
        Dim strMaxPages As String = bookslist.Max(Function(b) b.Pages).ToString()
        Dim strMinPages As String = bookslist.Min(Function(b) b.Pages).ToString()
        Dim strAveragePages As String = bookslist.Average(Function(b) b.Pages).ToString()
    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}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400}}

        Return lstBooks
    End Function

Thursday 24 May 2012

You can also perform Grouping in LINQ to Objects using a LINQ Query.
This LINQ query uses the group keyword to group the Books data by pages.
Additionally, because a group action does not naturally result in any output, the query creates a custom query projection using the techniques discussed earlier.

Using LINQ to do this grouping enables you to significantly reduce the lines of code required.
This is also improve the readability and clarity of the code.

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; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var bookslist = GetBooksList();
        //var query = from bl in bookslist select bl;
        var query = from bl in bookslist
               group bl by bl.Pages into g
                    select new {Pages= g.Key,Count=g.Count() };
        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},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400 }
        
        };

    }

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
    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
        Dim query = From bl In bookslist _
                    Group By bl.Pages Into g = Group, Count()
        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}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400}}

        Return lstBooks
    End Function

Wednesday 23 May 2012

You always need to filter the records based on certain fileds.
Using LINQ query you are able to get this.

Here are sample example for this.
In this example We add where clause in LINQ query to get filtered records, Here we wants only records whose ISBN Number is "asp1".

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; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var bookslist = GetBooksList();
        //var query = from bl in bookslist select bl;
        var query = from bl in bookslist
                    where bl.ISBN=="asp1"
                    select new {FullTitle= bl.Title,ISBNNumber=bl.ISBN };
        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},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400 }
        
        };

    }
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
    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
        Dim query = From bl In bookslist _
                    Where bl.ISBN = "asp1" _
                    Select New With {.FullTitle = bl.Title, .ISBNNumber = bl.ISBN}
        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}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400}}

        Return lstBooks
    End Function

Tuesday 22 May 2012

An interesting feature of LINQ is its delayed execution behavior. Means that even though you may execute the query statements at a specific point in your code, LINQ is smart enough to delay the actual execution of the query until it is accessed.
For example, in the previous samples, although the LINQ query was written before the binding of the GridView controls, LINQ will not actually execute the query you have defined until the GridView control begins to enumerate through the query results.

Monday 21 May 2012

You can also set data ordering and custom field name using linq query.
Here are sample example for that.
In this example Title and ISBN Column names changed to FullTitle and ISBNNumber, and data is order by Title in ascending. You can also set multiple column by comma like ", bl.ISBN". And also set fordescending order.

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; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var bookslist = GetBooksList();
        //var query = from bl in bookslist select bl;
        var query = from bl in bookslist
                    orderby bl.Title ascending
                    select new {FullTitle= bl.Title,ISBNNumber=bl.ISBN };
        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},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400 }
        
        };

    }
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
    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
        Dim query = From bl In bookslist _
                    Order By bl.Title Ascending _
                    Select New With {.FullTitle = bl.Title, .ISBNNumber = bl.ISBN}
        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}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400}}

        Return lstBooks
    End Function
GMM6ZC2HF693

Friday 18 May 2012

Some time you Database Physical file Address and file size using sql script.

SQL Script :
SELECT DB_NAME(database_id) AS DatabaseName,Name AS Logical_Name,Physical_Name,(size*8)/1024 Size_MB
FROM sys.master_files

You can also query for particular database name like :
SELECT DB_NAME(database_id) AS DatabaseName,Name AS Logical_Name,Physical_Name,(size*8)/1024 Size_MB
FROM sys.master_files
WHERE DB_NAME(database_id) = 'TempDatabase'

Output :

(To view original image , click on image)

Thursday 17 May 2012

There are situations where you do not want all fields in LINQ query you want only selected fields.
You can also say that Creating a custom projection with LINQ.
Here are sample example for that.
In this Example we only want Title and ISBN Fields.

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; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var bookslist = GetBooksList();
        //var query = from bl in bookslist select bl;
        var query = from bl in bookslist
                    select new { bl.Title,bl.ISBN };
        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},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400 }
        
        };

    }

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
    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
        Dim query = From bl In bookslist _
                    Select New With {bl.Title, bl.ISBN}
        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}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400}}

        Return lstBooks
    End Function

Wednesday 16 May 2012

Now a days LINQ is more popular for query.
We can also query to object using LINQ.
Here are sample example of select query LINQ To Objects.

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; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var bookslist = GetBooksList();
        var query = from bl in bookslist
                    select bl;
        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},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400 }
        
        };

    }
In this example we simply query the Books list object using LINQ and bind it's results to grid view.

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
    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
        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}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400}}

        Return lstBooks
    End Function

Tuesday 15 May 2012

You are able to upload a file on FTP server from your application.
Using FtpWebRequest and FtpWebResponse classes executing File Transfer Protocol (FTP) commands from your Web page easy.
In this example we are using System.Net and System.IO namespaces.
Here is exmple for how to upload file on FTP server.

C# Example :
string filename = Server.MapPath("file1.txt");
string ftpServerIP = "ftp.demo.com/";
string ftpUserName = "dummy";
string ftpPassword = "dummy";

FileInfo objFile = new FileInfo(filename);
FtpWebRequest objFTPRequest;

// Create FtpWebRequest object 
objFTPRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + objFile.Name));

// Set Credintials
objFTPRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);

// By default KeepAlive is true, where the control connection is 
// not closed after a command is executed.
objFTPRequest.KeepAlive = false;

// Set the data transfer type.
objFTPRequest.UseBinary = true;

// Set content length
objFTPRequest.ContentLength = objFile.Length;

// Set request method
objFTPRequest.Method = WebRequestMethods.Ftp.UploadFile;

// Set buffer size
int intBufferLength = 16 * 1024;
byte[] objBuffer = new byte[intBufferLength];
        
// Opens a file to read
FileStream objFileStream = objFile.OpenRead();

try
{
    // Get Stream of the file
    Stream objStream = objFTPRequest.GetRequestStream();

    int len = 0;

    while ((len = objFileStream.Read(objBuffer, 0, intBufferLength)) != 0)
    {
        // Write file Content 
        objStream.Write(objBuffer, 0, len);
                
    }
                        
    objStream.Close();
    objFileStream.Close();
}
catch (Exception ex)
{
    throw ex;
}

In this example set appropriate Server and Set credentials if required.

VB.net Example :
Dim filename As String = Server.MapPath("file1.txt")
Dim ftpServerIP As String = "ftp.demo.com/"
Dim ftpUserName As String = "dummy"
Dim ftpPassword As String = "dummy"

Dim objFile As New FileInfo(filename)
Dim objFTPRequest As FtpWebRequest

' Create FtpWebRequest object 
objFTPRequest = DirectCast(FtpWebRequest.Create(New Uri(("ftp://" & ftpServerIP & "/") + objFile.Name)), FtpWebRequest)

' Set Credintials
objFTPRequest.Credentials = New NetworkCredential(ftpUserName, ftpPassword)

' By default KeepAlive is true, where the control connection is 
' not closed after a command is executed.
objFTPRequest.KeepAlive = False

' Set the data transfer type.
objFTPRequest.UseBinary = True

' Set content length
objFTPRequest.ContentLength = objFile.Length

' Set request method
objFTPRequest.Method = WebRequestMethods.Ftp.UploadFile

' Set buffer size
Dim intBufferLength As Integer = 16 * 1024
Dim objBuffer As Byte() = New Byte(intBufferLength - 1) {}

' Opens a file to read
Dim objFileStream As FileStream = objFile.OpenRead()

Try
    ' Get Stream of the file
    Dim objStream As Stream = objFTPRequest.GetRequestStream()

    Dim len As Integer = 0

    len = objFileStream.Read(objBuffer, 0, intBufferLength)
    While len <> 0
         ' Write file Content 
         objStream.Write(objBuffer, 0, len)
         len = objFileStream.Read(objBuffer, 0, intBufferLength)
    End While
    objStream.Close()
    objFileStream.Close()
Catch ex As Exception
    Throw ex
End Try

Monday 14 May 2012

You are able to download file from FTP server and save to your desire location using .Net
Using FtpWebRequest and FtpWebResponse classes executing File Transfer Protocol (FTP) commands from your Web page easy. Using these classes, implementing an entire FTP client right from your Web application is now possible.
In this example we are using System.Net and System.IO namespaces.

C# Example :
Uri url = new Uri("ftp://ftp.demo.com/file1.txt");
if (url.Scheme == Uri.UriSchemeFtp)
{
    FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(url);
    //Set credentials if required else comment this Credential code
    NetworkCredential objCredential = new NetworkCredential("FTPUserName", "FTPPassword");
    objRequest.Credentials = objCredential;
    objRequest.Method = WebRequestMethods.Ftp.DownloadFile;
    FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse();
    StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
    byte[] buffer = new byte[16 * 1024];
    int len = 0;
    FileStream objFS = new FileStream(Server.MapPath("file1.txt"), FileMode.Create, FileAccess.Write, FileShare.Read);
    while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        objFS.Write(buffer, 0, len);
    }
    objFS.Close();
    objResponse.Close();
}
In this example put your URI appropriate and Set credentials if required.

VB.net Example :
Dim url As New Uri("ftp://ftp.demo.com/file1.txt")
If url.Scheme = Uri.UriSchemeFtp Then
    Dim objRequest As FtpWebRequest = DirectCast(FtpWebRequest.Create(url), FtpWebRequest)
    'Set credentials if required else comment this Credential code
    Dim objCredential As New NetworkCredential("FTPUserName", "FTPPassword")
    objRequest.Credentials = objCredential
    objRequest.Method = WebRequestMethods.Ftp.DownloadFile
    Dim objResponse As FtpWebResponse = DirectCast(objRequest.GetResponse(), FtpWebResponse)
    Dim objReader As New StreamReader(objResponse.GetResponseStream())
    Dim buffer As Byte() = New Byte(16 * 1024 - 1) {}
    Dim len As Integer = 0
    Dim objFS As New FileStream(Server.MapPath("file1.txt"), FileMode.Create, FileAccess.Write, FileShare.Read)
    len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
    While len <> 0
         objFS.Write(buffer, 0, len)
         len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
    End While
    objFS.Close()
    objResponse.Close()
End If

Friday 11 May 2012

There are situations where you want to post data to remote server and other external URL.
We can do this using System.Net namespace.
In this sample example we have this "http://www.dummydomain.com/pagename.aspx" URL and we want to post query string data like "pageid=1&search=.net" and capture response of this in our code.
We are using HttpWebRequest and HttpWebResponse class for this.


C# Example :
Uri url = new Uri("http://www.dummydomain.com/pagename.aspx");
string strParameter = "pageid=1&search=.net";
string data = string.Format("{0}", strParameter);
if (url.Scheme == Uri.UriSchemeHttp)
{
    //Create Request for given url
    System.Net.HttpWebRequest objRequest =(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
    //Set Request Method
    objRequest.Method = System.Net.WebRequestMethods.Http.Post;
    objRequest.ContentLength = data.Length;
    objRequest.ContentType = "application/x-www-form-urlencoded";
    //Write request stream
    System.IO.StreamWriter objWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
    objWriter.Write(data);
    objWriter.Close();
    //Get Response from url
    System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();
    //Read Response
    System.IO.StreamReader objReader = new System.IO.StreamReader(objResponse.GetResponseStream());
    string result = objReader.ReadToEnd();
    objResponse.Close();
    pnlScreen.GroupingText = result;
}

VB.net Example :
Dim url As New Uri("http://www.dummydomain.com/pagename.aspx")
Dim strParameter As String = "pageid=1&search=.net"
Dim data As String = String.Format("{0}", strParameter)
If url.Scheme = Uri.UriSchemeHttp Then
    'Create Request for given url
    Dim objRequest As System.Net.HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(url), System.Net.HttpWebRequest)
    'Set Request Method
    objRequest.Method = System.Net.WebRequestMethods.Http.Post
    objRequest.ContentLength = data.Length
    objRequest.ContentType = "application/x-www-form-urlencoded"
    'Write request stream
    Dim objWriter As New System.IO.StreamWriter(objRequest.GetRequestStream())
    objWriter.Write(data)
    objWriter.Close()
    'Get Response from url
    Dim objResponse As System.Net.HttpWebResponse = DirectCast(objRequest.GetResponse(), System.Net.HttpWebResponse)
    'Read Response
    Dim objReader As New System.IO.StreamReader(objResponse.GetResponseStream())
    Dim result As String = objReader.ReadToEnd()
    objResponse.Close()
    pnlScreen.GroupingText = result
End If

Thursday 10 May 2012

Screen scrapping means to get other sites data from given URL.
You can do this using the HttpWebRequest and HttpWebResponse classes to screen scrape, you can use the following code to build a Web page that will serve as a simple Web browser. You also learn how to display another Web page inside of yours using an HttpWebRequest. In this example, you scrape the "http://msdn.microsoft.com/en-US/" URL and display it in a panel on your Web page.
For this example we are using System.Net and System.IO Namespaces.

ASPX Code : 
 <asp:Panel runat="server" ID="pnlScreen" ScrollBars=Auto
Width="800px" Height="500px"></asp:Panel>

C# Example :
Uri url = new Uri("http://msdn.microsoft.com/en-US/");
if (url.Scheme == Uri.UriSchemeHttp)
{
    //Create Request Object
    HttpWebRequest objRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    //Set Request Method
    objRequest.Method = WebRequestMethods.Http.Get;
    //Get response from requested url
    HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
    //Read response in stream reader
    StreamReader reader = new StreamReader(objResponse.GetResponseStream());
    string tmp = reader.ReadToEnd();
    objResponse.Close();
    //Set response data to container
    this.pnlScreen.GroupingText = tmp;
}

The HttpWebRequest to the "http://msdn.microsoft.com/en-US/" page returns a string containing the scraped HTML. The sample assigns the value of this string to the GroupingText property of the Panel control. When the final page is rendered, the browser renders the HTML that was scraped as literal content on the page.

VB.net Example :
Dim url As New Uri("http://msdn.microsoft.com/en-US/")
If url.Scheme = Uri.UriSchemeHttp Then
    'Create Request Object
    Dim objRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
    'Set Request Method
    objRequest.Method = WebRequestMethods.Http.[Get]
    'Get response from requested url
    Dim objResponse As HttpWebResponse = DirectCast(objRequest.GetResponse(), HttpWebResponse)
    'Read response in stream reader
    Dim reader As New StreamReader(objResponse.GetResponseStream())
    Dim tmp As String = reader.ReadToEnd()
    objResponse.Close()
    'Set response data to container
    Me.pnlScreen.GroupingText = tmp
End If
Output :
(To view original image , click on image)

Wednesday 9 May 2012

Using streams does have a couple problems that might encounter in certain scenarios.
  1. When you open a file using a stream, reading the file contents is done sequentially. This can be a problem if you are searching for a specific section of a very large file because you have to read the entire file from the beginning in order to locate the content.
  2. Opening a file using a stream can lock the file, preventing other applications or threads from reading or writing to the file.

.NET Framework includes the System.IO.MemoryMappedFiles namespace, which includes a number of classes that allow you to create memory-mapped files. Memory-mapped files can be useful when you encounter the limitations of the stream objects.

Memory-mapped files allow to create views that start in a random location over very large files, rather than reading the file from the beginning. Memory-mapped files also allow multiple processes to map to the same portion of a file without locking the file.

C# Example :
byte[] bytes = new byte[100];
using (System.IO.MemoryMappedFiles.MemoryMappedFile objMF = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(MapPath("TextFile.txt"), System.IO.FileMode.Open, "NewTextFile"))
{
    using (System.IO.MemoryMappedFiles.MemoryMappedViewAccessor accessor = objMF.CreateViewAccessor(100, 100))
    {
        accessor.ReadArray(0, bytes, 0, bytes.Length);
    }
}
Response.Write(ASCIIEncoding.Default.GetString(bytes));
This Example loads the TextFile.txt file into a MemoryMappedFile class using the static CreateFromFile method, which creates a named memory-mapped file. It then creates a MemoryMappedViewAccessor over the file using the MemoryMappedFiles CreateViewAccessor method. This method’s parameters allow  to specify an offset where the view accessor should start, the length of the view, and the access rights the view will have to the file.

The MemoryMappedFile class also allows to create memory-mapped files that are not associated with a physical file on disk, but are rather simply a named portion of memory. You can do this using the class’s static CreateNew method, which accepts a name and a length parameter.

VB.net Example :
Dim bytes As Byte() = New Byte(99) {}
    Using objMF As System.IO.MemoryMappedFiles.MemoryMappedFile = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(MapPath("TextFile.txt"), System.IO.FileMode.Open, "NewTextFile")
        Using accessor As System.IO.MemoryMappedFiles.MemoryMappedViewAccessor = objMF.CreateViewAccessor(100, 100)
            accessor.ReadArray(0, bytes, 0, bytes.Length)
        End Using
    End Using
Response.Write(ASCIIEncoding.[Default].GetString(bytes))

Tuesday 8 May 2012

There are a situations where you want to fill or populate dropdownlist of listbox using Enum.
Here are sample example for this.

C# Example :
public enum ProgrammingLanguage
{
    CSharp,
    VB,
    JAVA
}
foreach (ProgrammingLanguage enmLnaguage  in Enum.GetValues(typeof(ProgrammingLanguage)))
{
     cboProgrammingLanguage.Items.Add(new ListItem(enmLnaguage.ToString(), Convert.ToInt32( enmLnaguage).ToString()));
}

VB.net Example :
Public Enum ProgrammingLanguage
   CSharp
   VB
   JAVA
End Enum 
For Each enmLnaguage As ProgrammingLanguage In [Enum].GetValues(GetType(ProgrammingLanguage))
   cboProgrammingLanguage.Items.Add(New ListItem(enmLnaguage.ToString(), enmLnaguage))
Next

Click Here to view "Populating or Fill dropdownlist from Database table with C# Examples and VB.Net Examples". Click Here...

This type of C# 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.


Monday 7 May 2012

There is a situation where you need to capital first letter of each word.
You can also say that Title Case to string.
Here are useful code snippets for this.

C# Example :
string strSample = "this is a sample string.";
Response.Write( System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(strSample));


Output :
This Is A Sample String.


VB.net Example :
Dim strSample As String = "this is a sample string."
Response.Write(System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(strSample))


Output :
This Is A Sample String.

Saturday 5 May 2012

The StreamReader by default attempts to determine the encoding format of the file. If one of the supported encodings such as UTF-8 or UNICODE is detected, it is used. If the encoding is not recognized,the default encoding of UTF-8 is used. Depending on the constructor you call, you can change the default encoding used and optionally turn off encoding detection.

Below syntax shows how you can control the encoding that the StreamReader uses.
Syntax :
StreamReader reader = new StreamReader(MapPath(TextFile.txt"),System.Text.Encoding.Unicode);

The default encoding for the StreamWriter is also UTF-8, and you can override it in the same manner as with the StreamReader class.