Friday, 28 September 2012

You can set holidays or note on particular date in calendar control. For that we are using "DayRender" Event of the calendar control. This event call on each day cell render, so we can check particular date make set tool tips and also set our user defined backcolor or apply any style in that particular day cell.
You can see tool tip on mouse over of that particular day.

Here is example for this.
In this example we display holidays and notes with two different colors.

ASPX Code :
        <asp:Calendar ID="Calendar1" runat="server"  BackColor="#FFFFCC" 
            BorderColor="#FFCC66" DayNameFormat="Shortest" Font-Names="Verdana" 
            Font-Size="8pt" ForeColor="#663399" Height="200px" Width="220px" 
            BorderWidth="1px" ShowGridLines="True" OnDayRender="Calendar1_DayRender" SelectionMode="None" >
            <DayHeaderStyle BackColor="#FFCC66" Font-Bold="True" Height="1px" />
            <NextPrevStyle Font-Size="9pt" ForeColor="#FFFFCC" />
            <OtherMonthDayStyle ForeColor="#CC9966" />
            <SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" />
            <SelectorStyle BackColor="#FFCC66" />
            <TitleStyle BackColor="#990000" Font-Bold="True" Font-Size="9pt" 
                ForeColor="#FFFFCC" />
            <TodayDayStyle BackColor="#FFCC66" ForeColor="White" />
        </asp:Calendar>

C# Examples :
    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {

        switch(e.Day.Date.ToString("dd/MM/yyyy"))
        {
            case "01/09/2012":
                e.Cell.ToolTip = "Holiday 1";
                e.Cell.BackColor = System.Drawing.Color.Red;
                break;
            case "05/09/2012":
                e.Cell.ToolTip = "Holiday 2";
                e.Cell.BackColor = System.Drawing.Color.Red;
                break;
            case "20/09/2012":
                e.Cell.ToolTip = "Note : Meeting with client";
                e.Cell.BackColor = System.Drawing.Color.Yellow;
                break;

        }

    }

VB.net Examples :
    Protected Sub Calendar1_DayRender(ByVal sender As Object, ByVal e As DayRenderEventArgs)

        Select Case e.Day.Date.ToString("dd/MM/yyyy")
            Case "01/09/2012"
                e.Cell.ToolTip = "Holiday 1"
                e.Cell.BackColor = System.Drawing.Color.Red
                Exit Sub
            Case "05/09/2012"
                e.Cell.ToolTip = "Holiday 2"
                e.Cell.BackColor = System.Drawing.Color.Red
                Exit Sub
            Case "20/09/2012"
                e.Cell.ToolTip = "Note : Meeting with client"
                e.Cell.BackColor = System.Drawing.Color.Yellow
                Exit Sub

        End Select

    End Sub

Output :
Set Holidays or Note on particular date in asp calendar control

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



Wednesday, 26 September 2012

Click Here to Download SelectWeekInCalendarControl.zip

You can select entire week or month in asp.net calendar control and get it's selected dates.
You can achieve using SelectionMode property of calendar control.
Selection mode property has an enum and it has four selection mode like Day , DayWeek , DayWeekMonth and None.

Here is example for this.
In this example we take calendar control and we set selection mode as DayWeek. When we set this mode after that calender control automatically add one column for select particular week.
You can specify "DayWeekMonth" value to selection mode property for select entire month and also specify "SelectMonthText" property to display select text.

ASPX Code :
        <asp:Calendar ID="Calendar1" runat="server" BackColor="White" BorderColor="Black" 
            Font-Names="Times New Roman" Font-Size="10pt" ForeColor="Black" Height="220px"
                NextPrevFormat="FullMonth" Width="400px" SelectionMode="DayWeek" 
            DayNameFormat="Shortest" TitleFormat="Month" SelectWeekText="Select" >
                <DayHeaderStyle Font-Bold="True" Font-Size="7pt" ForeColor="#333333" 
                    Height="10pt" BackColor="#CCCCCC" />
                <DayStyle Width="14%" />
                <NextPrevStyle Font-Size="8pt" ForeColor="White" />
                <OtherMonthDayStyle ForeColor="#999999" />
                <SelectedDayStyle BackColor="#CC3333" ForeColor="White" />
                <SelectorStyle BackColor="#CCCCCC" Font-Bold="True" Font-Names="Verdana" 
                    Font-Size="8pt" ForeColor="#333333" Width="1%" />
                <TitleStyle BackColor="Black" Font-Bold="True"
                    Font-Size="13pt" ForeColor="White" Height="14pt" />
                <TodayDayStyle BackColor="#CCCC99" />
        </asp:Calendar>
         <br />

         <asp:Button runat="server" ID="btnGetSelectedDate" Text="Get Selected Date" 
        /> &nbsp;&nbsp;&nbsp;
         <b>Date : </b><asp:Label runat="server" ID="lblDate" ></asp:Label>

C# Examples :
    protected void btnGetSelectedDate_Click(object sender, EventArgs e)
    {
        foreach (DateTime dt in Calendar1.SelectedDates)
        {
            lblDate.Text = lblDate.Text + " <br/> " + dt.ToString("dd/MM/yyyy");
        }
    }

VB.net Examples :
    Protected Sub btnGetSelectedDate_Click(ByVal sender As Object, ByVal e As EventArgs)
        For Each dt As DateTime In Calendar1.SelectedDates
            lblDate.Text = lblDate.Text + " <br/> " & dt.ToString("dd/MM/yyyy")
        Next
    End Sub

Output :



 For Beginning .Net articles. Click Here...

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



 

Monday, 24 September 2012

Click Here to Download ProcessRSSorATOMFeed.zip

You can process the content of an Atom 1.0 or RSS 2.0 feed to extract or get details of the feed. .Net framework provide classes to parse the feed data.
We are using System.ServiceModel.Syndication.SyndicationFeedFormatter and System.ServiceModel.Syndication.SyndicationFeed classes.

The SyndicationFeedItem  and SyndicationFeed classes gives a generic abstraction of Atom 1.0 and RSS 2.0 feeds and feed items, and provide a common interface to simplify the processing of both feed types. The Rss20FeedFormatter class allows to create a SyndicationFeed object from an RSS 2.0 feed, and the Atom10FeedFormatter class provides support for Atom 1.0 feeds. Both classes are available in the System.ServiceModel.Syndication namespace.
We are using "ReadFrom" method and "Feed" property of these classes.

Here is example for this.
In this example we read the feed and display it's details.

C# Examples :
        Uri objFeedUrl = null;
        string strUrl = "http://jayeshsorathia.blogspot.com/rss.xml";
        if (strUrl.Length == 0 || String.IsNullOrEmpty(strUrl) || !Uri.TryCreate(strUrl, UriKind.RelativeOrAbsolute, out objFeedUrl))
        {
            Response.Write("Invalid feed.");
            return;
        }

        // Create the web request.
        WebRequest objReqFeed = WebRequest.Create(objFeedUrl);

        // Get the data from the feed.
        WebResponse objResFeed = objReqFeed.GetResponse();

        
        SyndicationFeedFormatter objFeedFormatter = null;

        XElement feed = XElement.Load(objResFeed.GetResponseStream());

        // Check for the feed type
        if (feed.Name.LocalName == "rss")
        {
            objFeedFormatter = new Rss20FeedFormatter();
        }
        else if (feed.Name.LocalName == "feed")
        {
            objFeedFormatter = new Atom10FeedFormatter();
        }
        else
        {
            Response.Write("Unsupported feed type: " + feed.Name.LocalName);
            return;
        }

        // Read the feed data into the formatter.
        objFeedFormatter.ReadFrom(feed.CreateReader());

        // Display feed Details

        Response.Write("<b>Feed Title : </b>" + objFeedFormatter.Feed.Title.Text);
        Response.Write("<br/><br/>");
        Response.Write("<b>Feed Description : </b>" + objFeedFormatter.Feed.Description.Text);
        Response.Write("<br/><br/>");
        Response.Write("<b>Items in the Feed : </b>");
        Response.Write("<br/><br/>");
        
        foreach (var objItem in objFeedFormatter.Feed.Items)
        {
            Response.Write("<b>Title : </b> " + objItem.Title.Text);
            if (objItem.Summary != null)
            {
                Response.Write("<br/><b>Summary : </b>" + objItem.Summary.Text);
            }

            Response.Write("<br/><b>Publish Date : </b>" + objItem.PublishDate);
            Response.Write("<br/><br/>");
        }

VB.net Examples :
        Dim objFeedUrl As Uri = Nothing
        Dim strUrl As String = "http://jayeshsorathia.blogspot.com/rss.xml"
        If strUrl.Length = 0 Or String.IsNullOrEmpty(strUrl) Or Not Uri.TryCreate(strUrl, UriKind.RelativeOrAbsolute, objFeedUrl) Then
            Response.Write("Invalid feed.")
            Return
        End If

        ' Create the web request.
        Dim objReqFeed As WebRequest = WebRequest.Create(objFeedUrl)

        ' Get the data from the feed.
        Dim objResFeed As WebResponse = objReqFeed.GetResponse()


        Dim objFeedFormatter As SyndicationFeedFormatter = Nothing

        Dim feed As XElement = XElement.Load(objResFeed.GetResponseStream())

        ' Check for the feed type
        If feed.Name.LocalName = "rss" Then
            objFeedFormatter = New Rss20FeedFormatter()
        ElseIf feed.Name.LocalName = "feed" Then
            objFeedFormatter = New Atom10FeedFormatter()
        Else
            Response.Write("Unsupported feed type: " & feed.Name.LocalName)
            Return
        End If

        ' Read the feed data into the formatter.
        objFeedFormatter.ReadFrom(feed.CreateReader())

        ' Display feed Details

        Response.Write("<b>Feed Title : </b>" & objFeedFormatter.Feed.Title.Text)
        Response.Write("<br/><br/>")
        Response.Write("<b>Feed Description : </b>" & objFeedFormatter.Feed.Description.Text)
        Response.Write("<br/><br/>")
        Response.Write("<b>Items in the Feed : </b>")
        Response.Write("<br/><br/>")

        Dim objItem As SyndicationItem
        For Each objItem In objFeedFormatter.Feed.Items
            Response.Write("<b>Title : </b> " & objItem.Title.Text)
            If Not objItem.Summary Is Nothing Then
                Response.Write("<br/><b>Summary : </b>" & objItem.Summary.Text)
            End If

            Response.Write("<br/><b>Publish Date : </b>" & objItem.PublishDate.ToString())
            Response.Write("<br/><br/>")
        Next

Output : 
Read the Content of an Atom or RSS Feed output
(To view original image , click on image)

This is very useful .Net Tips.

For Beginning .Net articles. Click Here...

To learn more regarding XML. Click Here...

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



Saturday, 22 September 2012

Click Here to Download Sample MultipleDateSelectionInCalendarControl.zip

You can select multiple dates in calendar control.
There is a no direct way to select multiple dates in calendar control. You need to write some code for that.

Here is example for this.
In this example we take one calendar control and select multiple dates in that control and we display that selected dates in label.

ASPX Code : 
      <asp:Calendar ID="Calendar1" runat="server" BackColor="White" BorderColor="Black" 
            Font-Names="Verdana" Font-Size="9pt" ForeColor="Black" Height="250px"
                NextPrevFormat="ShortMonth" OnPreRender="Calendar1_PreRender" Width="330px" 
                OnSelectionChanged="Calendar1_SelectionChanged" BorderStyle="Solid" 
            CellSpacing="1">
                <DayHeaderStyle Font-Bold="True" Font-Size="8pt" ForeColor="#333333" 
                    Height="8pt" />
                <DayStyle BackColor="#CCCCCC" />
                <NextPrevStyle Font-Bold="True" Font-Size="8pt" ForeColor="White" />
                <OtherMonthDayStyle ForeColor="#999999" />
                <SelectedDayStyle BackColor="#333399" ForeColor="White" />
                <TitleStyle BackColor="#333399" Font-Bold="True"
                    Font-Size="12pt" ForeColor="White" BorderStyle="Solid" Height="12pt" />
                <TodayDayStyle BackColor="#999999" ForeColor="White" />
        </asp:Calendar>

         <br />
         <br />
         <asp:Button runat="server" ID="btnGetSelectedDate" Text="Get Selected Date" 
            onclick="btnGetSelectedDate_Click" /> &nbsp;&nbsp;&nbsp;<br />
         <b>Selected Dates : </b><asp:Label runat="server" ID="lblDate" ></asp:Label>


C# Examples :
    protected void Calendar1_PreRender(object sender, EventArgs e)
    {
        
        Calendar1.SelectedDates.Clear();

        foreach (DateTime dt in MultipleSelectedDates)
        {
            Calendar1.SelectedDates.Add(dt);
        }
    }
    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {

        if (MultipleSelectedDates.Contains(Calendar1.SelectedDate))
        {
            MultipleSelectedDates.Remove(Calendar1.SelectedDate);
        }
        else
        {
            MultipleSelectedDates.Add(Calendar1.SelectedDate);
        }
        
        ViewState["MultipleSelectedDates"] = MultipleSelectedDates;
    }
   

    public List<DateTime> MultipleSelectedDates
    {
        get
        {
            if (ViewState["MultipleSelectedDates"] == null)

                ViewState["MultipleSelectedDates"] = new List<DateTime>() ;
            return (List<DateTime>)ViewState["MultipleSelectedDates"];
        }
        set
        {
            ViewState["MultipleSelectedDates"] = value;
        }
    }


    protected void btnGetSelectedDate_Click(object sender, EventArgs e)
    {

        foreach (DateTime dt in MultipleSelectedDates)
        {
            lblDate.Text = lblDate.Text + " <br/> " + dt.ToString("dd/MM/yyyy");
        }
    }

VB.net Examples :
    Protected Sub Calendar1_PreRender(ByVal sender As Object, ByVal e As EventArgs)

        Calendar1.SelectedDates.Clear()

        For Each dt As DateTime In MultipleSelectedDates
            Calendar1.SelectedDates.Add(dt)
        Next
    End Sub
    Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs)

        If MultipleSelectedDates.Contains(Calendar1.SelectedDate) Then
            MultipleSelectedDates.Remove(Calendar1.SelectedDate)
        Else
            MultipleSelectedDates.Add(Calendar1.SelectedDate)
        End If

        ViewState("MultipleSelectedDates") = MultipleSelectedDates
    End Sub


    Public Property MultipleSelectedDates() As List(Of DateTime)
        Get
            If ViewState("MultipleSelectedDates") Is Nothing Then

                ViewState("MultipleSelectedDates") = New List(Of DateTime)()
            End If
            Return DirectCast(ViewState("MultipleSelectedDates"), List(Of DateTime))
        End Get
        Set(ByVal value As List(Of DateTime))
            ViewState("MultipleSelectedDates") = value
        End Set
    End Property

    Protected Sub btnGetSelectedDate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGetSelectedDate.Click
        For Each dt As DateTime In MultipleSelectedDates
            lblDate.Text = lblDate.Text + " <br/> " & dt.ToString("dd/MM/yyyy")
        Next
    End Sub

Output : 


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


Wednesday, 19 September 2012

You can get the selected date from calendar control.
There is a "SelectedDate" property of calendar control. This property is get and set property so you can also set date of calendar control. Calender control provided in asp.net.

Here is example for this.
In this example we take calendar control , button and label. First you select date in control. By Default today date is highlighted but not selected. When you select date at that time date background color will changed after that On click of button we retrieve selected date from calendar control and display in label.
We can also format the date and display in our specific date format. in this example we display date in "dd/MM/yyyy" format.

ASPX Code :
        <asp:Calendar ID="Calendar1" runat="server" BackColor="#FFFFCC" 
            BorderColor="#FFCC66" DayNameFormat="Shortest" Font-Names="Verdana" 
            Font-Size="8pt" ForeColor="#663399" Height="200px" Width="220px" 
            BorderWidth="1px" ShowGridLines="True">
            <DayHeaderStyle BackColor="#FFCC66" Font-Bold="True" Height="1px" />
            <NextPrevStyle Font-Size="9pt" ForeColor="#FFFFCC" />
            <OtherMonthDayStyle ForeColor="#CC9966" />
            <SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" />
            <SelectorStyle BackColor="#FFCC66" />
            <TitleStyle BackColor="#990000" Font-Bold="True" Font-Size="9pt" 
                ForeColor="#FFFFCC" />
            <TodayDayStyle BackColor="#FFCC66" ForeColor="White" />
        </asp:Calendar>

         <br />

         <asp:Button runat="server" ID="btnGetSelectedDate" Text="Get Selected Date" 
            onclick="btnGetSelectedDate_Click" /> &nbsp;&nbsp;&nbsp;
         <b>Date : </b><asp:Label runat="server" ID="lblDate" ></asp:Label>

C# Examples :
    protected void btnGetSelectedDate_Click(object sender, EventArgs e)
    {
        lblDate.Text = Calendar1.SelectedDate.Date.ToString("dd/MM/yyyy");
    }

VB.net Examples :
    Protected Sub btnGetSelectedDate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGetSelectedDate.Click
        lblDate.Text = Calendar1.SelectedDate.Date.ToString("dd/MM/yyyy")
    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.




Calendar control is available in asp.net.
You can set "asp:Calendar" control on page and set it's various properties.

Here is example for this.
In this example we put calendar control and set it's properties.

ASPX Code :
        <asp:Calendar ID="Calendar1" runat="server" BackColor="White" 
            BorderColor="Black" DayNameFormat="Shortest" Font-Names="Times New Roman" 
            Font-Size="10pt" ForeColor="Black" Height="220px" NextPrevFormat="FullMonth" 
            TitleFormat="Month" Width="400px">
            <DayHeaderStyle BackColor="#CCCCCC" Font-Bold="True" Font-Size="7pt" 
                ForeColor="#333333" Height="10pt" />
            <DayStyle Width="14%" />
            <NextPrevStyle Font-Size="8pt" ForeColor="White" />
            <OtherMonthDayStyle ForeColor="#999999" />
            <SelectedDayStyle BackColor="#CC3333" ForeColor="White" />
            <SelectorStyle BackColor="#CCCCCC" Font-Bold="True" Font-Names="Verdana" 
                Font-Size="8pt" ForeColor="#333333" Width="1%" />
            <TitleStyle BackColor="Black" Font-Bold="True" Font-Size="13pt" 
                ForeColor="White" Height="14pt" />
            <TodayDayStyle BackColor="#CCCC99" />
        </asp:Calendar>

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, 18 September 2012

 Click Here to Download Sample StickyJavascriptMenu.zip

Now a days sticky menu is most popular menu in websites.
You can generate sticky menu using JQuery and some CSS classes.
You are able to working menu in out downloadable samples.
In this example we integrate sticky menu into aspx page.

Here is example for this.
In this example we are using "jquery-1.4.1.js" JQuery file. You can find this file from JQuery website or in our sample application folder. We are displaying menu on screen and when user scoll down the page our sticky menu is stick at the top of the browser.
You can set many position using javascript and css classes.

ASPX Code :
    <div id="wrapper">
        <header>
        <h1>Simple Sticky Menu</h1>
        </header>
        <nav>
        <table><tr><td>Home</td><td>|</td><td>About Us</td><td>|</td><td>Contact Us</td></tr></table>
        </nav>
        <div id="content">
            Website informations. Website informations. Website informations. Website informations.
            Website informations. Website informations. Website informations. Website informations.
            Website informations.
        </div>
    </div>

Javascript Code :
  $(document).ready(function () {

            var intAboveHeight = $('header').outerHeight();
                    
            $(window).scroll(function () {
                    
                if ($(window).scrollTop() > intAboveHeight) {
                        
                    $('nav').addClass('fixed').css('top', '0').next().css('padding-top', '60px');

                } else {
                        
                    $('nav').removeClass('fixed').next().css('padding-top', '0');
                }
            });
        });

CSS classes :
        #wrapper
        {
            width: 940px;
            margin: 0 auto;
        }
        
        header
        {
            text-align: center;
            padding: 70px 0;
        }
        
        nav
        {
            background: url(bg.png) no-repeat;
            height: 60px;
            width: 960px;
            margin-left: -10px;
            line-height: 50px;
            position: relative;
        }
        
        #content
        {
            background: #fff;
            height: 1500px; /* presetting the height */
            box-shadow: 0 0 5px rgba(0,0,0,0.3);
        }
        
        .fixed
        {
            position: fixed;
        }

Output : 

(To view original image , click on image)

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.




Saturday, 15 September 2012

Alternate text for Image is helpful when certain reason Image is not displayed in browser. If Image is not displayed at that time alternate text is helpful to end user.
Alternate text display instead of image and end use know that here is image and this image is for what.
For that you need to set "alt" property of "Img" tag.

Here is example for this.
In this example we take one html image tag and set it's alternate text and we provide image source file name that does not exist.

ASPX Code : 

      Image : <img src="ttt.png"  alt="Click hete to know more." width="100" height="50" />

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.




Friday, 14 September 2012

There is a situation where you want to select an item from drop down list or combo box and raise server side event to do some processing at server side. You can raise or fire server side event on selection of item from drop down list or combo box. It will raise "onselectedindexchanged" event.
For that you need to set AutoPostBack="true" property.

Here is example for this.
In this example we take on product drop down list and select an item from that after item selected dropdonwlist's "onselectedindexchanged" event raised.

ASPX Code :
   <b>Product List :</b>  <asp:DropDownList runat="server" ID="ddlProductList" AutoPostBack="true"
                            onselectedindexchanged="ddlProductList_SelectedIndexChanged"></asp:DropDownList>

C# Examples :
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            ddlProductList.Items.Add(new ListItem("[select]", "-1"));
            ddlProductList.Items.Add(new ListItem("CPU", "1"));
            ddlProductList.Items.Add(new ListItem("LCD", "2"));
            ddlProductList.Items.Add(new ListItem("LED", "3"));
        }
    }

    protected void ddlProductList_SelectedIndexChanged(object sender, EventArgs e)
    {
        Response.Write("Selected Value : " + ddlProductList.SelectedValue);
        Response.Write("</br>Selected Text : " + ddlProductList.SelectedItem.Text);
        Response.Write("</br></br></br>");
    }

VB.net Example :
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Page.IsPostBack = False Then
            ddlProductList.Items.Add(New ListItem("[select]", "-1"))
            ddlProductList.Items.Add(New ListItem("CPU", "1"))
            ddlProductList.Items.Add(New ListItem("LCD", "2"))
            ddlProductList.Items.Add(New ListItem("LED", "3"))
        End If
    End Sub

    Protected Sub ddlProductList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Response.Write("Selected Value : " & ddlProductList.SelectedValue)
        Response.Write("</br>Selected Text : " & ddlProductList.SelectedItem.Text)
        Response.Write("</br></br></br>")
    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.



Thursday, 13 September 2012

Click Here to Download Sample CreateCustomLINQExtensionMethod.zip

You can create your own custom LINQ extension method in .Net Application. These extension methods are very handy in software development. Creating a LINQ extension method in VB.Net has Different approach than C#.Net . For that we need to create "Module" and in this Module we create a methods and add this "<Runtime.CompilerServices.Extension()>" attribute to this methods.

Here is example for this.
In this example we create one Module "LINQExtensions" and create one public method "GetTopTwo" in this Module. This Method return type "IEnumerable(Of String)". This Method get top two values in given list. We implement this in String Array and Generic List object.



VB.Net Examples :
Public Module LINQExtensions

    <Runtime.CompilerServices.Extension()> _
    Public Function GetTopTwo(ByVal source As IEnumerable(Of String)) As IEnumerable(Of String)
        Return source.Take(2)
    End Function

End Module

        Dim strArray As String() = {"C#", ".Net", "Java", "PHP"}

        Dim objArrayIEResult As IEnumerable(Of String) = strArray.GetTopTwo()

        Response.Write("<br/><b>String Array:</b><br/> ")
        For Each element As String In objArrayIEResult
            Response.Write("<br/>" & element)
        Next

        Response.Write("<br/>")


        Dim Lst As IList(Of String) = New List(Of String)() From { _
         ".Net", _
         "Java", _
         "C#", _
         "PHP" _
        }
        Dim objListIEResult As IEnumerable(Of String) = Lst.GetTopTwo()

        Response.Write("<br/><b>Generic List:</b><br/> ")

        For Each element As String In objListIEResult
            Response.Write("<br/>" & element)
        Next

Output :



View More LINQ Examples. Click Here... 

For Beginning .Net articles. Click Here...

Click here to view useful  C# Tips .

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



Wednesday, 12 September 2012

There is a situations where you want to know the column names and it's data type and other column relevant  information of a particular table.
In SQL server there is inbuilt stored procedure "sp_columns" which returns columns information of specified table name.
Many people uses this traditional way to see column information. Like , In Microsoft SQL Server Management Studio Go to particular tables then open tables in design view mode. This way is very lengthy.
Using this inbuilt SP you can get quick result.

SQL Syntax :
sp_columns @table_name

@table_name : Specify table name.

SQL Query :
sp_columns product_master

Output :


(To view original image , click on image) 

Note : This output screen image has few columns information display. To View all return result information download .CSV file from here. 

This is the very useful SQL Server Scripts.

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



Tuesday, 11 September 2012

Download Sample Application. Download...

Binary Deserialization is a reverse process of Binary Serialization.
In Binary Deserialization we fetch binary file that generated from Binary Serialization and get back orignal object.
In previous example we serialize one list object using binary serialization and store in file.

Here is example for this.
In this example we take binary serialized file and generate list object from that with data.
You can see in the output image that "booklist" object fill from the "books.bin" binary file.

C# Examples :
    [Serializable]
    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)
    {
        //Read Binary Serialized File
        System.IO.FileStream objFS = System.IO.File.OpenRead(Server.MapPath("books.bin"));
        BinaryFormatter objBF = new BinaryFormatter();
        // Deserialize File stream into object
        var bookslist = objBF.Deserialize(objFS);

    }
VB.net Examples :
    <Serializable()> _
    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

        ''Read Binary Serialized File
        Dim objFS As System.IO.FileStream = System.IO.File.OpenRead(Server.MapPath("books.bin"))
        Dim objBF As New BinaryFormatter()
        '' Deserialize File stream into object
        Dim bookslist = objBF.Deserialize(objFS)
    End Sub

Output : 

(To view original image , click on image)


Click Here to view "Serialize object and store in file using Binary Serialization with C# Examples and VB.Net Examples". Click Here...

This is very useful .Net Tips.

For Beginning .Net articles. Click Here...

To learn more regarding XML. Click Here...

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



Monday, 10 September 2012

 Download Sample Application. Download...

There is a need to serialize object and store into a file, and then deserialize when required.
For Binary Serialization we are using "BinaryFormatter" class which is available in "System.Runtime.Serialization.Formatters.Binary" namespace.
"BinaryFormatter" class produce a binary data of serialized object. If you want to serialize custom class object for that you have to declare that class as serializable and add "[Serializable]" attribute on that class name.

Here is example for this.
In this example we take one class name "Books" and generate books list object and do binary serialize of that list and store in "Books.bin" file. You can give any extension of that generated file name. The generated file is in binary so not easy to understand.


C# Examples :
    [Serializable]
    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 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 }
        
        };

    }

    private void BinarySerialization(System.Collections.Generic.List<Books> bookslist)
    {
        BinaryFormatter objBF = new BinaryFormatter();
        System.IO.FileStream objFS = System.IO.File.Create(Server.MapPath("books.bin"));
        objBF.Serialize(objFS, bookslist);
        objBF = null;
        objFS.Close();
        objFS = null;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Collections.Generic.List<Books> bookslist = GetBooksList();
        BinarySerialization(bookslist);
    }

VB.net Examples :
    <Serializable()> _
    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 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

    Private Sub BinarySerialization(ByVal bookslist As System.Collections.Generic.List(Of Books))
        Dim objBF As New BinaryFormatter()
        Dim objFS As System.IO.FileStream = System.IO.File.Create(Server.MapPath("books.bin"))
        objBF.Serialize(objFS, bookslist)
        objBF = Nothing
        objFS.Close()
        objFS = Nothing
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim bookslist As System.Collections.Generic.List(Of Books) = GetBooksList()
        BinarySerialization(bookslist)
    End Sub

Output : 

(To view original image , click on image)


Click Here to view "Binary Deserialization with C# Examples and VB.Net Examples". Click Here...

This is very useful .Net Tips.

For Beginning .Net articles. Click Here...


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




Saturday, 8 September 2012

There is a need in website that you want to add items manually in dropdownlist or combobox.
You can achieve this using "Items.Add" methods of dropdownlist.

Here is example for this.
In this example we take one dropdownlist control name "ddlProductList". We fill this dropdownlist manually from coding.

ASPX Code :
<b>Product List :</b>  <asp:DropDownList runat="server" ID="ddlProductList"></asp:DropDownList>


 C# Examples :
        ddlProductList.Items.Add(new ListItem("[select]", "-1"));
        ddlProductList.Items.Add(new ListItem("CPU", "1"));
        ddlProductList.Items.Add(new ListItem("LCD", "2"));
        ddlProductList.Items.Add(new ListItem("LED", "3"));

VB.net Example :
        ddlProductList.Items.Add(New ListItem("[select]", "-1"))
        ddlProductList.Items.Add(New ListItem("CPU", "1"))
        ddlProductList.Items.Add(New ListItem("LCD", "2"))
        ddlProductList.Items.Add(New ListItem("LED", "3"))

Output :
For Beginning .Net articles. 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.



Friday, 7 September 2012

There is a need to create a custom LINQ extension method in .Net Application. This is a very good .Net Framework feature. These extension methods are very handy in software development.
For that we need to create Static Class and Static Methods.

Here is example for this.
In this example we create one static class "LINQExtensions" and create one static method "GetTopTwo" in this class. This Method return type "IEnumerable<string>". This Method get get top two values in given list.
We implement this in String Array and Generic List object.

C# Examples :
static class LINQExtensions
{
    public static IEnumerable<string> GetTopTwo(
    this IEnumerable<string> source)
    {
        return source.Take(2);
    }
}
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] strArray = { "C#", ".Net", "Java", "PHP" };
        IList<string> Lst = new List<string> { ".Net", "Java", "C#", "PHP" };
        
        IEnumerable<string> IEResult1 = strArray.GetTopTwo();
        Response.Write("<br/><b>String Array:</b><br/> ");
        foreach (string element in IEResult1)
        {
            Response.Write("<br/>" + element);
        }

        Response.Write("<br/>");

        IEnumerable<string> IEResult2 = Lst.GetTopTwo();
        Response.Write("<br/><b>Generic List:</b><br/> ");
        foreach (string element in IEResult2)
        {
            Response.Write("<br/>" + element);
        }
    }


Output :


View More LINQ Examples. Click Here... 

For Beginning .Net articles. 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.

Thursday, 6 September 2012

There is a situations where you want to Concatenate Or Combine one or more data sources using  LINQ.
With the help of the Concat<> extension method to concatenate or combine multiple sources into a single data source.

Here is example of this.
In this example we execute two different LINQ Query on DataTable and find two different results object. After that we concatenate in one datasource and display.

C# Examples :
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        DataColumn dc;
        DataRow dr;
        ds.DataSetName = "products";
        dt.TableName = "product";

        dc = new DataColumn("product_id", long.MaxValue.GetType());
        dt.Columns.Add(dc);

        dc = new DataColumn("product_name");
        dt.Columns.Add(dc);

        dr = dt.NewRow();
        dr["product_id"] = 1;
        dr["product_name"] = "Monitor";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["product_id"] = 2;
        dr["product_name"] = "Mouse";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["product_id"] = 3;
        dr["product_name"] = "KeyBoard";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["product_id"] = 4;
        dr["product_name"] = "LCD";
        dt.Rows.Add(dr);

        ds.Tables.Add(dt);

        IEnumerable<DataRow> objResult1 = from tbl in dt.AsEnumerable()
                                          where tbl.Field<long>(0) >= 3
                                          select tbl;

        Response.Write("<b>Query Results 1</b>");
        foreach (DataRow row in objResult1)
        {
            Response.Write(string.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field<long>(0), row.Field<string>(1)));
        }

        IEnumerable<DataRow> objResult2 = from tbl in ds.Tables[0].AsEnumerable()
                                          let product_name = tbl.Field<string>(1)
                                          where product_name.StartsWith("Key")
                                          || product_name.StartsWith("Mo")
                                          select tbl;

        Response.Write("<br/><br/><b>Query Results 2</b>");
        foreach (DataRow row in objResult2)
        {
            Response.Write(string.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field<long>(0), row.Field<string>(1)));
        }


        IEnumerable<DataRow> objConcatenateResult = objResult1.Concat(objResult2);

        Response.Write("<br/><br/><b>Concatenate Or Combine Query Results</b>");
        foreach (DataRow row in objConcatenateResult)
        {
            Response.Write(string.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field<long>(0), row.Field<string>(1)));
        }

VB.net Examples :
        Dim ds As New DataSet()
        Dim dt As New DataTable()
        Dim dc As DataColumn
        Dim dr As DataRow
        ds.DataSetName = "products"
        dt.TableName = "product"

        dc = New DataColumn("product_id", Long.MaxValue.GetType())
        dt.Columns.Add(dc)

        dc = New DataColumn("product_name")
        dt.Columns.Add(dc)

        dr = dt.NewRow()
        dr("product_id") = 1
        dr("product_name") = "Monitor"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr("product_id") = 2
        dr("product_name") = "Mouse"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr("product_id") = 3
        dr("product_name") = "KeyBoard"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr("product_id") = 4
        dr("product_name") = "LCD"
        dt.Rows.Add(dr)

        ds.Tables.Add(dt)

        Dim objResult1 As IEnumerable(Of DataRow) = From tbl In dt.AsEnumerable()
                                      Where tbl.Field(Of Long)(0) >= 3
                                      Select tbl

        Response.Write("<b>Query Results 1</b>")
        For Each row As DataRow In objResult1
            Response.Write(String.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field(Of Long)(0), row.Field(Of String)(1)))
        Next

        Dim objResult2 As IEnumerable(Of DataRow) = From tbl In ds.Tables(0).AsEnumerable()
                                    Let product_name = tbl.Field(Of String)(1)
                                    Where product_name.StartsWith("Key") Or product_name.StartsWith("Mo")
                                    Select tbl

        Response.Write("<br/><br/><b>Query Results 2</b>")
        For Each row As DataRow In objResult2
            Response.Write(String.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field(Of Long)(0), row.Field(Of String)(1)))
        Next

        Dim objConcatenateResult As IEnumerable(Of DataRow) = objResult1.Concat(objResult2)

        Response.Write("<br/><br/><b>Concatenate Or Combine Query Results</b>")
        For Each row As DataRow In objConcatenateResult
            Response.Write(String.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field(Of Long)(0), row.Field(Of String)(1)))
        Next

Output : 


View More LINQ Examples. Click Here... 

For Beginning .Net articles. 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.