How to use jquery dialog in asp.net


In this post I am going to show you how to use jquery model dialog in asp.net.
Note:Please make sure that you have downloaded the jquery and jqueyui   library. 

Photobucket

  • Start visual studio
  • Select File/New Project
  • Choose a Web Site Template -for this example I used Empty Web Site 
  • Right click on empty web site and add new class named Person.cs and paste following code




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

public class Person
{
    public string Name { get; set; }
    public string Email { get; set; }

    public static List<Person> GetAll()
    {
        List<Person> list = new List<Person>()
            {
                new Person{Name="John",Email="john@doe.com"},
                new Person{Name="Admin",Email="admin@doe.com"},
            };
        HttpContext.Current.Session["Add"] = list; 
        return list;
    }
}

  • Right click on empty website and add new item (Ajax Enabled WCF Service) and modified the code of Service.cs as below

Service.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Web;

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
    [WebGet(UriTemplate = "Insert/?name={name}&email={email}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
    [OperationContract]
    public string InsertPerson(string name, string email)
    {
        string data = string.Empty;
        List<Person> list = null;
        if (HttpContext.Current.Session["Add"] == null)
        {
            list = Person.GetAll();

        }
        else
        {
            list = (List<Person>)HttpContext.Current.Session["Add"];
            if (!string.IsNullOrEmpty(name) || !string.IsNullOrEmpty(email))
            {
                list.Add(new Person { Name = name, Email = email });
                HttpContext.Current.Session["Add"] = list;
                data = "<tr><td>" + name + "</td> <td>" + email + "</td></tr>";

            }
            else
            {
                data = "Failure";
            }
         
        }

        return data;
    }
}


  • Right click on Website and add new item named Default.aspx and add following code 


<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeFile="Default.aspx.cs"
    Inherits="_Default" %>

<!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>
        body
        {
            font-size: 80%;
        }
        label, input
        {
            display: block;
        }
        input.text
        {
            margin-bottom: 12px;
            width: 95%;
            padding: .4em;
        }
        fieldset
        {
            padding: 0;
            border: 0;
            margin-top: 25px;
        }
        h1
        {
            font-size: 1.2em;
            margin: .6em 0;
        }
        div#users-contain
        {
            width: 350px;
            margin: 20px 0;
        }
        div#users-contain table
        {
            margin: 1em 0;
            border-collapse: collapse;
            width: 100%;
        }
        div#users-contain table td, div#users-contain table th
        {
            border: 1px solid #eee;
            padding: .6em 10px;
            text-align: left;
        }
        .ui-dialog .ui-state-error
        {
            padding: .3em;
        }
        .validateTips
        {
            border: 1px solid transparent;
            padding: 0.3em;
        }
    </style>
    <link href="Style/jquery-ui-1.8.7.custom.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.7.custom.min.js" type="text/javascript"></script>
    <script type="text/javascript">
      
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#editPerson').dialog({
                autoOpen: false,
                model: true,
                draggable: true, title: "Add Person",
                buttons: {
                    "Create an account": function () {
                        var name = $("#name").val();
                        var email = $("#email").val();
                        $.getJSON("Service.svc/Insert", { name: name, email: email }, function (data) {
                            $('#grdPerson tbody tr:last').after(data);
                            $("#editPerson").dialog("close");
                        });
                    },
                    Cancel: function () {
                        $(this).dialog("close");
                    }
                },
                open: function (type, data) {
                    $(this).parent().appendTo("form");
                }
            });
        });
        //Show Dialog function
        function showDialog(id) {
            $('#' + id).dialog("open");
        } 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align: center">
        <asp:GridView ID="grdPerson" runat="server" AutoGenerateColumns="false" Width="400">
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Email" HeaderText="Email" />
            </Columns>
        </asp:GridView>
        <div id="editPerson" title="Create new user">
            <fieldset>
                <label for="name">
                    Name</label>
                <input type="text" name="name" id="name" class="text ui-widget-content ui-corner-all" />
                <label for="email">
                    Email</label>
                <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
            </fieldset>
        </div>
        <input type="button" id="btnAdd" runat="server" value="Add New Person" onclick="showDialog('editPerson');" />
    </div>
    </form>
</body>
</html>

How to: Return multiple response from wcf

Imagine you have a wcf application that return xml response but after some time your requirements changed that we want to return multiple response (XML /Json) from the same service.How do you achieved this? Earlier it was nightmare for developer to return multiple response from .net. Now you have a good news that you can return multiple response from wcf 4.0 with a very minimal changes.

So In this post I am going to show you how to return multiple response from wcf in .net framework 4.0

Open visual studio and create an empty website.

 
Right click on the website project and add a new wcf service.It will create three files named Service.svc,IService and Service.cs.
Open IService.cs file and paste the following code



Open Service.cs file and add following code

Right click on App_Code folder and add new class named Person and add following code(This class contains dummy data for demo purpose only )
  
Till now whaterver I have created so for is normal process for creating wcf service application in .net.Now open web.config and go to endpointBehaviours section and set automaticFormatSelectionEnabled equal to true .


<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
    <system.serviceModel>
        <services>
            <service name="Service" behaviorConfiguration="ServiceBehavior">
                <endpoint address="" binding="webHttpBinding" behaviorConfiguration="JsonBehavior" bindingConfiguration="" contract="IService"/>
            </service>
        </services>
        <behaviors>
            <endpointBehaviors>
                <behavior name="JsonBehavior">
                    <webHttp automaticFormatSelectionEnabled="true"/>
                </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
                <behavior name="ServiceBehavior">
                    <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                    <serviceMetadata httpGetEnabled="true"/>
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
    <system.web>
        <compilation debug="true" targetFramework="4.0">
        </compilation>
        <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>
</configuration>

What does automaticFormatSelectionEnabled do? It is a new property introduced in wcf 4.0 that do following task.

When enabled, automatic formatting chooses the best format in which to return the response. It determines the best format by checking the following, in order:
  1. The media types in the request message’s Accept header.

  2. The content-type of the request message.

  3. The default format setting in the operation.

  4. The default format setting in the WebHttpBehavior.
 Now our wcf service application is complete and ready to use.Let's consume this service using Jquery.Open Default.aspx page (in my case ) and paste following code.


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

<!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 () {
            $("#btnJson").click(function () {
                JsonCall();
            });
            $("#btnXml").click(function () {
                XmlCall();
            });
        });
        function XmlCall() {
            $.ajax(
            {
                type: "POST",
                url: "Service.svc/GetAll",
                dataType: "xml",
                contentType: "application/xml",
                data: "",
                success: function (ret) {
                    alert(ret);
                }
            });
        }
        function JsonCall() {
            $.ajax(
            {
                type: "POST",
                url: "Service.svc/GetAll",
                dataType: "json",
                contentType: "application/json",
                data: "{}",
                success: function (ret) {
                    alert(ret);
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" id="btnJson" value="Get JSON" />
        <input type="button" id="btnXml" value="Get XML" />
    </div>
    </form>
</body>
</html>

In the above page I have added two functions XmlCall and JsonCall function and I am calling these two functions on button click.Run and test the application you will see that same service is returning multiple respnse.


I have attached the full source code


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

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

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