Saturday, December 18, 2010

How to:Create wcf application without using config file

In this post i am going to show you how to create wcf application without using config file. Let's start the tutorial.
  • Open visual studio and create a new console application
  • Right click on the project and add reference to following assembly
        using System.ServiceModel;

  • Open Program.cs file and paste following code

[ServiceContract]
    interface IService
    {
        [OperationContract]
        string HelloWorld(string strMessage);
    }
    public class ServiceImp : IService
    {
        [OperationBehavior]
        public string HelloWorld(string strMessage)
        {
            return ("Hello " + strMessage + "!");
        }
    }

  • Now Add following code inside main method


static void Main(string[] args)
        {
            //Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/MyService");
            //Create ServiceHost
            ServiceHost host = new ServiceHost(typeof(ServiceImp), httpUrl);
            //Add a service endpoint
            host.AddServiceEndpoint(typeof(IService), new WSHttpBinding(), "");
            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);
            Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding();
            //Adding metadata exchange endpoint
            host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");
            //Start the Service
            host.Open();
            Console.WriteLine("Host is running... Press  key to stop");
            Console.ReadLine();

        }

Now press F5 and see the message.If everything is fine then you will see a message "Host is running ...Press key to stop" 


Now it's time to create Client application
  • Right click on solution and create a new console application named WcfClient
  • Open the Program.cs file and paste the following code


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

namespace WCFClient
{
    [ServiceContract]
    interface IService
    {
        [OperationContract]
        string HelloWorld(string strMessage);


    }
    class Program
    {
        static void Main(string[] args)
        {
            //Create instance of Binding
            WSHttpBinding myBinding = new WSHttpBinding();
            //Instance of Endpoint address
            EndpointAddress myEndpoint = new EndpointAddress("http://localhost:8090/MyService");
            //Create instance of channel factory
            ChannelFactory<IService> myChannelFactory = new ChannelFactory<IService>(myBinding, myEndpoint);
            // Create a channel.
            IService wcfClient = myChannelFactory.CreateChannel();

            string s = wcfClient.HelloWorld("Wcf");
            Console.WriteLine(s.ToString());
            ((IClientChannel)wcfClient).Close();
            Console.Read();

        }
    }
}







Click below to download complete source code

Friday, December 17, 2010

Linq to Sql: Left outer join

In this post i am going to show how to generate left outer join using linq to sql. For this post i am going to use Categories and Product table of northwind.
First way to generate left outer join
var query=from p in Products
          join c in Categories
          on p.CategoryID equals c.CategoryID into pc
          where p.CategoryID==1
          from j in pc.DefaultIfEmpty()
          select new
          {
          CategoryName=j.CategoryName,
          ProductName=p.ProductName
          };
ouput generated code
SELECT [t1].[CategoryName] AS [CategoryName], [t0].[ProductName]
FROM [Products] AS [t0]
LEFT OUTER JOIN [Categories] AS [t1] ON [t0].[CategoryID] = ([t1].[CategoryID])
WHERE [t0].[CategoryID] = @p0
second way without using into operator
var query=from p in Products
          from c in Categories.Where(x=>x.CategoryID==p.CategoryID).DefaultIfEmpty()
          select new
          {
          CategoryName=c.CategoryName,
          ProductName=p.ProductName
          };

Linq to Sql:Inner join

In this post i am going to show you how to generate inner join using linq to sql.
For this post i am going to use Categories and Product table of northwind.



Let's imagine that you want to fetch CategoryName and ProductName from above table using linq.




var query=from p in Products
          join c in Categories
          on p.CategoryID equals c.CategoryID
          select new
          {
          CategoryName=c.CategoryName,
          ProductName=p.ProductName
          };
 
 
 

Tuesday, December 7, 2010

Jquery and CheckboxList

In this post i am going to show you how use jquery in asp.net to select the checkbox of Checkbox List
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RadioButtonListJquery.aspx.cs"
    Inherits="RadioButtonListJquery" %>

<!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.3.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#selectAll").click(function () {
                $("input[type='checkbox'").not("#selectAll").each(function () {
                    $(this).attr("checked", "true");

                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <input type="button" value="Select All" id="selectAll" />
    <div id="divLanguage">
        <asp:CheckBoxList ID="chkList" runat="server">
            <asp:ListItem Text="C#" Value="1"></asp:ListItem>
            <asp:ListItem Text="Java" Value="1"></asp:ListItem>
            <asp:ListItem Text="C++" Value="1"></asp:ListItem>
            <asp:ListItem Text="C" Value="1"></asp:ListItem>
        </asp:CheckBoxList>
    </div>
    </form>
</body>
</html>

How DataContract serialize CLR object into XML

In this post,I am going to show you how DataContract export DataContract into xsd ,and then how an object is converted into xml.





using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Xml.Schema;
using System.Xml;

namespace DataContract_Demo
{
    [DataContract(Namespace = "http://aspdotnetcodebook.blogspot.com", Name = "Person")]
    public class Person
    {
        [DataMember(Name = "FirstName")]
        public string FirstName { get; set; }
        [DataMember(Name = "LastName")]
        public string LastName { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            GenerateXsd();
            GenerateXML();


        }

        private static void GenerateXsd()
        {

            XsdDataContractExporter exporter = new XsdDataContractExporter();
            exporter.Export(typeof(Person));
            foreach (XmlSchema xml in exporter.Schemas.Schemas("http://aspdotnetcodebook.blogspot.com"))
            {
                var writer = new XmlTextWriter(Console.Out) { Formatting = Formatting.Indented };
                xml.Write(writer);

            }
        }

        private static void GenerateXML()
        {

            var Objwriter = new XmlTextWriter(Console.Out) { Formatting = Formatting.Indented };
            var ser = new DataContractSerializer(typeof(Person));
            ser.WriteObject(Objwriter, new Person() { FirstName = "X", LastName = "Y" });
        }
    }
}

Wednesday, September 15, 2010

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

}

Saturday, September 11, 2010

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.


Thursday, September 9, 2010

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




Sunday, August 29, 2010

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:

Friday, August 27, 2010

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

    }

}



 

Wednesday, August 25, 2010

Linq and Reflection

This snippet will show how LINQ can be used with reflection to retrieve specific metadata about type that match a specified search criterion
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)
        {
            Assembly assembly = Assembly.Load("System.Data, Version=3.5.0.0, Culture=neutral, " + "PublicKeyToken= b77a5c561934e089");
            var Query = from type in assembly.GetTypes()
                        where type.IsClass
                        select type;
            foreach (var item in Query)
            {
                Console.WriteLine(item.Name);

            }
            Console.WriteLine("Press any key to exit ... ");
            Console.ReadKey();

        }
    }
} 
 
 
 

How to extract number from string using Linq

Imagine you have a string("ABCDE99F-J74-12-89A") and you want to extract only number from the string. This snippet will show how to extract number from string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Linq_Tips
{
    class Program
    {
        static void Main(string[] args)
        {
            string aString = "ABCDE99F-J74-12-89A";
            // Select only those characters that are numbers 
            IEnumerable<char> stringQuery = from ch in aString
                                            where Char.IsDigit(ch)
                                            select ch;
            // Execute the query 
            foreach (char c in stringQuery)
                Console.Write(c + " ");

        }
    }
}

How to apply Left Outer join in Linq to Sql

In this post i am going to show you how to apply Left outer join in Linq to sql. Imagine that we want to apply left outer join in Products and Categories table in Northwind database Something like this:

SELECT [t1].[CategoryName] AS [CategoryId]
FROM [dbo].[Products] AS [t0]
LEFT OUTER JOIN [dbo].[Categories] AS [t1] ON [t0].[CategoryID] = ([t1].[Categor
yID])

As an example i will take northwind Products and Categories table.Both these tables contain CategoryId as common field.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Linq_Tips
{
    class Program
    {
        static void Main(string[] args)
        {
            NorthwindDataContext dc = new NorthwindDataContext();
            var filteredQuery = from p in dc.Products
                                join c in dc.Categories
                                on p.CategoryID equals c.CategoryID into joinData
                                from data in joinData.DefaultIfEmpty()
                                select new
                                {
                                    CategoryId = data.CategoryName
                                };
            Console.WriteLine(filteredQuery);
        }
    }
}
The code above gets translated into this SQL query.
SELECT [t1].[CategoryName] AS [CategoryId]
FROM [dbo].[Products] AS [t0]
LEFT OUTER JOIN [dbo].[Categories] AS [t1] ON [t0].[CategoryID] = ([t1].[Categor
yID])

Saturday, August 7, 2010

How to use flag enuemeration in c#/asp.net

Imagine we have a User class, and one of the user properties is Permission. The Permission enum can be defined as follows:
enum Permission
    {
        None = 0,
        Read = 2,
        Write = 4,
        ReadWrite = 8,
        All = Int16.MaxValue

    }
As you can see -these options could be combined in several ways like an user can have Read and Write permission or user can have only Read permission.Most of us will create seprate properties in user class but efficient way to resolve this problem is use flag enumeration.flag enumeration is an instance of the enumeration type to store any combination of the values that are defined in the enumerator list.You create a bit flags enum by applying the System.FlagsAttribute attribute and defining the values appropriately so that AND, OR, NOT and XOR bitwise operations can be performed on them.
[Flag]
  enum Permission
    {
        None = 0,
        Read = 2,
        Write = 4,
        ReadWrite = 8,
        All = Int16.MaxValue

    }

or

 [Flag]
  enum Permission
    {
        None = 0x,
        Read = 1x,
        Write = 2x,
        ReadWrite = 3x,
        All = Int16.MaxValue

    }

This means we can now use the bitwise OR|AND|NOT|XOR operator to combine these enum values. For instance:How to set a flag on an enum, use the bitwise OR operator as shown in the following example:

Permission permisson = Permission.Read | Permission.Write;
How to reset a flag on an enum

permisson &= ~Permission.Read;
How to filp a flag on an enum

permisson &= ~Permission.Read;
How to clear all flags

permission=Permission.None

Saturday, June 26, 2010

How to add tool tip for Dropdownlist Item in asp.net

In this post i am going to show you how to add tool tip for dropdownlist item in asp.net.


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

<!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="ddlDemo" runat="server">
            <asp:ListItem Text="Asp.net" Value="ASP.NET, the next version of ASP, is a programming framework used to create enterprise-class Web Applications" />
            <asp:ListItem Text="C#" Value="C# (pronounced C-sharp) is an object-oriented programming language from Microsoft" />
        </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 ToolTip_DropDownList: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        //Check it is postback or not.
        if (!IsPostBack)
        {
            BindToolTip(ddlDemo);

        }
    }
    /// <summary>
    /// Use of this function is to bind title attribute
    /// to each element of ListControl.
    /// </summary>
    /// <param name="list"></param>
    private void BindToolTip(ListControl list)
    {
        foreach (ListItem item in list.Items)
        {
            item.Attributes.Add("title", item.Value);

        }
    }
}

See here the {{demo}}