How to add a static item to a databound dropdownlist

In this post i will show how to add static item to dropdownlist like a dropdown that displays one static item such as "select" while the rest of the items are data bound, then check out the code below: 


Set the AppendDataBoundItems property of the dropdownlist to True, and add in the static list item. Your dropdown will look something like this:


 <asp:DropDownList ID="ddlCountry" runat="server" AppendDataBoundItems="true">
            <asp:ListItem Text="Select" Value="-1"></asp:ListItem>
        </asp:DropDownList>

check out the complete code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddlCountry" runat="server" AppendDataBoundItems="true">
            <asp:ListItem Text="Select" Value="-1"></asp:ListItem>
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ddlCountry.DataSource = new Country().Get();
            ddlCountry.DataTextField = "CountryName";
            ddlCountry.DataValueField = "ID";
            ddlCountry.DataBind();
        }
    }
    public class Country
    {
        public int ID { get; set; }
        public string CountryName { get; set; }

        public List<Country> Get()
        {

            List<Country> list = new List<Country>()
            {
                new Country(){ID=1,CountryName="India"},
                new Country(){ID=2,CountryName="USA"},
                new Country(){ID=3,CountryName="UK"},
                new Country(){ID=4,CountryName="Denmark"}

            };
            return list;
        }
    }

}

How to use anonymous and Lambda expression in .net



In this post I will discuss how to use anonymous and lambda expression in .net.
Imagine we have a simple example in c# that simply add two numbers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
    public delegate int Fn(int a, int b);
    static void Main(string[] args)
    {
        Fn add = new Fn(Add);
        Console.WriteLine(add(1, 2));
    }
    public static int Add(int a, int b)
    {
        return (a + b);
    }
}

Let’s refactor the delegate instance version of the code to use an anonymous method.
What is anonymous method?
Anonymous methods are a new language feature in C# 2.0. Anonymous methods allow us to define a code block where a delegate object is acceptable.
Let’s convert the above code using anonymous code.
Remove the following method from the delegate instance version

        public static int Add(int a, int b)
        {
            return (a + b);
        }

And replace following code with

Fn add = new Fn(Add);

With this one.
Fn add =  delegate(int a,int b)
            {
                return (a+b);
            };

Now we can write code as shown below to use the above defined class using anonymous method as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


    class Program
    {
        public delegate int Fn(int a, int b);
        static void Main(string[] args)
        {
1.    Fn add = delegate(int a, int b)
2.    {
3.    return (a + b);
4.    };

            Console.WriteLine(add(1, 2));
        }

    }

Let’s go further and refactor our code using Lambda Expression.
What is lambda expression?
 Lambda expression is inline methods that are part of the Linq technology and converted to delegates or an expression tree at compile time.  Its use =>   operator to separate method. Meaning of => operator is goes to i.e. if you have a c# statement   x=>x+y  then you read this statement as x goes to x+y.
Go to the line 1 and remove the delegate keyword.


   Fn add = (int a, int b)
            {
                return (a + b);
           };
And place lambda sign => after method signature. 
 
 
   Fn add = (int a, int b)=>
            {
                return (a + b);
         };

So this final lambda expression version code looks something like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


    class Program
    {
        public delegate int Fn(int a, int b);
        static void Main(string[] args)
        {
            Fn add = (int a, int b) =>
            {
                return (a + b);
            };

            Console.WriteLine(add(1, 2));
        }

    }


I have summarized the above discussion into following image.


3 Tier Architecture in ASP.NET

In this post i will show how to create 3 -tier architecture in asp.net.Before going to technical details,I will describe some details about what is 3 tier architecture and what are the main components of 3 tier architecture.

The three-tier architecture was comes into existence to improve management of code and contents and to improve the performance of the web based applications.There are mainly three layers in three-tier architecture.
These are define as follows…





1.  UI(InsertCustomer.aspx): First layer Presentation contains mainly the interface code, and this is shown to user. This code could contain any technology that can be used on the client side like HTML, JavaScript or VBScript etc.

2. Business Logic(CustomerBL.cs) : Second layer is Business Logic which contains all the code of the server-side .This layer have code to interact with database database and to query, manipulate, pass data to user interface and handle any input from the UI as well.

3. DataAccess Layer(CustomerDAL.cs) : Third layer Data represents the data store like MS Access, SQL Server, an XML file, an Excel file or even a text file containing data also some addtional database are also added to that layers.


Let's start creating the project step by step.
  • Create a new website in visual studio and add two folder inside App_Code named BL and DAL (In real scenario, you can create separate projects for BAL, DAL  and UI )



  • Now,Create a class named CustomerDAL into App_Code->DAL by right clicking it and write following code into it.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;


/// <summary>
/// Summary description for CustomerDAL
/// </summary>
public class CustomerDAL
{


    public  static void AddCustomer(CustomerBL cs)
    {
        try
        {
            using (SqlConnection con = new SqlConnection(SQLHelper.GetConnectionString()))
            {
                SqlParameter[] par = new SqlParameter[7];
                par[0] = new SqlParameter("@ID", cs.ID);
                par[0].Direction = ParameterDirection.Output;
                par[1] = new SqlParameter("@name", cs.Name);
                par[2] = new SqlParameter("@address", cs.Address);
                par[3] = new SqlParameter("@phoneNumber", cs.PhoneNumber);
                par[5] = new SqlParameter("@email", cs.Email);
                int rowNo = SQLHelper.ExecuteNonQuery(con, CommandType.StoredProcedure, "proc_InsertCustomer", par);
                cs.ID = Convert.ToInt32(par[0].Value);
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }
    public static void DeleteCustomer(CustomerBL customer)
    {
        try
        {
            using (SqlConnection con = new SqlConnection(SQLHelper.GetConnectionString()))
            {
                SqlParameter[] par = new SqlParameter[1];
                par[0] = new SqlParameter("@ID", customer.ID);
                int rowNo = SQLHelper.ExecuteNonQuery(con, CommandType.StoredProcedure, "proc_DeleteCustomer", par);
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }
    public static void GetCustomer(CustomerBL customer)
    {
        try
        {
            using (SqlConnection con = new SqlConnection(SQLHelper.GetConnectionString()))
            {
                SqlParameter[] par = new SqlParameter[1];
                par[0] = new SqlParameter("@ID", customer.ID);
                using (SqlDataReader dr = SQLHelper.ExecuteReader(con, CommandType.StoredProcedure, "OMS_Customer_SelectByCustomerID", par))
                {
                    while (dr.Read())
                    {
                        customer.Name = SQLHelper.CheckStringNull(dr["Name"]);
                        customer.PhoneNumber = SQLHelper.CheckStringNull(dr["PhoneNo"]);
                        customer.Address = SQLHelper.CheckStringNull(dr["Address"]);
                        customer.ID = SQLHelper.CheckIntNull(dr["ID"]);
                        customer.Email = SQLHelper.CheckStringNull(dr["Email"]);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    public static List<CustomerBL> GetAllCustomers()
    {
        try
        {
            List<CustomerBL> cuList = new List<CustomerBL>();
            using (SqlConnection con = new SqlConnection(SQLHelper.GetConnectionString()))
            {
                using (SqlDataReader dr = SQLHelper.ExecuteReader(con, CommandType.StoredProcedure, "proc_SelectAllCustomer"))
                {
                    while (dr.Read())
                    {
                        CustomerBL customer = new CustomerBL();
                        customer.Name = SQLHelper.CheckStringNull(dr["Name"]);
                        customer.PhoneNumber = SQLHelper.CheckStringNull(dr["Phone"]);
                        customer.Address = SQLHelper.CheckStringNull(dr["Address"]);
                        customer.ID = SQLHelper.CheckIntNull(dr["ID"]);
                        cuList.Add(customer);
                    }
                }
            }
            return cuList;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}


  • Now,Create a class named CustomerBL into App_Code->BL by right clicking it and write following code into it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for CustomerBL
/// </summary>
public class CustomerBL
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string PhoneNumber { get; set; }
    public string Email { get; set; }
    public List<CustomerBL> Customers { get; set; }

    public void Add()
    {
        CustomerDAL.AddCustomer(this);
    }

    public void Delete()
    {
        CustomerDAL.DeleteCustomer(this);
    }


    public void GetAll()
    {
        this.Customers = CustomerDAL.GetAllCustomers();

    }
}


  • Now,Create a Page named InsertCustomer.aspx and add following code into it.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InsertCustomer.aspx.cs" Inherits="InsertCustomer" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    <table class="style1">
        <tr>
            <td>
                Name
            </td>
            <td>
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Address
            </td>
            <td>
                <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Phone
            </td>
            <td>
                <asp:TextBox ID="txtPhone" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Email
            </td>
            <td>
                <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                <asp:Button ID="btnInsert" runat="server" OnClick="btnInsert_Click" Text="Button" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>


and add follwoing code inside click event of button.



protected void btnInsert_Click(object sender, EventArgs e)
    {
        try
        {
            CustomerBL customer = new CustomerBL();
            customer.Name = txtName.Text;
            customer.PhoneNumber = txtAddress.Text;
            customer.Email = txtPhone.Text;
            customer.Address = txtEmail.Text;
            customer.Add();
        }
        catch (Exception)
        {
            
            throw;
        }



Download Code




CASE Statement Equivalent in LINQ

In this post i will show you how how to generate "Case statement" from linq.Let's say that you want to select rows from [Order Details] table in Northwind database something like this:
  1.  If the product UnitPrice is >10 then you want to display it as "High"
  2. If the product UnitPrice is <5 then you want to display it as "Low" otherwise "Average"

Our query should include the switch case  clause. Something like this:

SELECT
(
CASE
WHEN UnitPrice >10 THEN 'High'
WHEN UnitPrice <5 THEN 'Low'
ELSE 'Average'
END ) AS ProductPrice
FROM [Order Details]




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Linq_Tips
{
    class Program
    {
        static void Main(string[] args)
        {
            NorthwindDataContext dc = new NorthwindDataContext();
            var query = from o in dc.Order_Details
                        select new
                        {
                            //ternary operator of switch case
                            ProductPrice =
                           (
                           o.UnitPrice > 10 ? "High" :
                           o.UnitPrice < 5 ? "Low" :
                           "Average"
                          )
                        };
            Console.WriteLine(query);

        }
    }
}

Output of the above code will look something like this 


Linq and Sql "where in" Operator

In this post i will  show you how to generate "where in " clause in Linq to Sql. Imagine that we want to select rows from Products table in Northwind database where ProductId matches 3,4, 10. Our query should include the Where IN clause. Something like this:  

SELECT *FROM Products WHERE ProductID in (3,4,10)
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Linq_Tips
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a list
            List<int> list = new List<int>();
            //Add items in list
            list.AddRange(new int[] {3, 4, 10 });
            NorthwindDataContext dc = new NorthwindDataContext();
            //Query database
            var query = from product in dc.Products
                        where list.Contains(product.ProductID)
                        select product;
            Console.WriteLine(query);
          
        }
    }
}

The output of the above code snippet will look like this:

How to use Jquery fullcalender in asp.net

This snippet will show how how to use Jquery fullcalender in asp.net
Open Microsoft Visual Studio .NET. In Visual C# .NET, create a new website  named Fullcalender.Add  following code to Default.aspx page.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FullCalender.aspx.cs" Inherits="FullCalender" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/fullcalendar.js" type="text/javascript"></script>
    <script src="Scripts/gcal.js" type="text/javascript"></script>
    <link href="Styles/fullcalendar.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/json2.js" type="text/javascript"></script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next,today',
                    center: 'title',
                    right: 'month,basicWeek,basicDay'
                },
                events: "FullCalender.asmx/EventList"
                // events: [{ title: 'event1', start: '2010-06-01' }, { title: 'event2', start: '2010-06-05', end: '2010-06-07'}]
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="calendar">
    </div>
    </form>
</body>
</html>
 
 
 Create a WebService in existing project named FullCalender.asmx and add following code to
 webservice
 
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for FullCalender
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class FullCalender : System.Web.Services.WebService
{

    public FullCalender()
    {

    }

    [WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public string EventList(double startDate, double endDate)
    {
        var eventList = from e in new Events().GetAll()
                        select new
                        {
                            id = e.Id,
                            title = e.Title,
                            start = e.StartDate.ToString("s"),
                            end = e.EndDate.ToString("s"),
                            url = e.Url

                        };

        System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
        return js.Serialize(eventList);
    }

}
public class Events
{

    public int Id { get; set; }
    public string Title { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public string Url { get; set; }

    public List<Events> GetAll()
    {
        List<Events> lists = new List<Events>()
        {
            new Events{Id=1,StartDate=DateTime.Now,EndDate=DateTime.Now.AddDays(-1),Title="Client Call",Url="http://aspdotnetcodebook.blogspot.com"},
            new Events{Id=2,StartDate=DateTime.Now.AddDays(-5),EndDate=DateTime.Now.AddDays(-4),Title="Meeting with CEO",Url="http://aspdotnetcodebook.blogspot.com"},
            new Events{Id=3,StartDate=DateTime.Now.AddDays(-10),EndDate=DateTime.Now.AddDays(-9),Title="Travel Abroad",Url="http://aspdotnetcodebook.blogspot.com"},
        };
        return lists;


    }


    private static DateTime ConvertFromUnixTimestamp(double timestamp)
    {

        var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);

        return origin.AddSeconds(timestamp);

    }

}