Calling cross domain wcf service using Jquery

In this post,I will show you how to call cross domain service using jquery.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.IO;
using System.ServiceModel.Web;
using System.Runtime.Serialization.Json;

namespace CorssDomainService
{
    [DataContract]
    public class Order
    {
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public DateTime OrderDate { get; set; }
        [DataMember]
        public string Name { get; set; }

    }
    [ServiceContract]
    public interface IOrderService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/",
           ResponseFormat = WebMessageFormat.Json
   )]
        string ProcessOrder();

    }
    [ServiceBehavior]
    public class OrderService : IOrderService
    {
        [OperationBehavior]
        public string ProcessOrder()
        {
            Order order = new Order
            {
                ID = 1,
                OrderDate = DateTime.Now,
                Name = "Laptop"

            };

            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Order));
            MemoryStream stream = new MemoryStream();
            json.WriteObject(stream, order);
            return Encoding.UTF8.GetString(stream.ToArray());

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(OrderService));
            host.Open();
            Console.WriteLine("Service is ready");
            Console.ReadLine();
        }
    }
}
<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="CorssDomainService.OrderService" behaviorConfiguration="serviceBehave">
        <endpoint address="rest" bindingConfiguration="crossDomain"  behaviorConfiguration="enableScriptBehaviour"
                  binding="webHttpBinding"
                  contract="CorssDomainService.IOrderService"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9090/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehave">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="mex"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="enableScriptBehaviour">
          <webHttp></webHttp>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="crossDomain" crossDomainScriptAccessEnabled="true"></binding>
      </webHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
Now,create a website in visual studio,and paste following code into it
<%@ 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 type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.getJSON("http://localhost:9090/Rest?callback=?", null, function (data) {
                alert(data);
            });

        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

How to submit(Post) a webfrom from python/IronPython

In this post,I am going to show you how to post data from python to a webfrom from python.
import urllib.parse
import urllib.request
url='http://www.dijksterhuis.org/test/post.php'
values={'keyword':'Void',
        'data':'aspdotnetcodebook'
        }
data=urllib.parse.urlencode(values)
binary_data = data.encode('utf-8')
req=urllib.request.Request(url,binary_data)
response=urllib.request.urlopen(req)
the_page=response.read()
print (the_page)

How to create self signed certificate using makecert

In this post,I will show you how to create self signed certificate for wcf application.For this,I will used the utility makecert.MakeCert.exe allows you to (for test/dev purposes) generate both a trusted root certificate and a certificate signed by that trusted root certificate for encryption purposes (also for signature purposes.


Open visual studio command prompt (Admin mode) and type following command 
    C:\cert>makecert -pe -n "CN=RootCA" -ss My -sr LocalMachine -a sha1 -sky signatu re -r "RootCA.cer"
  • -pe Marks the generated private key as exportable. This allows the private key to be included in the certificate.
  • -Specifies the subject's certificate name. This name must conform to the X.500 standard. The simplest method is to specify the name in double quotes, preceded by CN=; for example, "CN=myName".
  • -ss Specifies the subject's certificate store name that stores the output certificate.
  • sr >localmachine
  • -a Specifies the signature algorithm. Must be either 
  • -sky Specifies the subject's key type, which must be signatureexchange, or an integer that represents a provider type. By default, you can pass 1for an exchange key and 2 for a signature key.
  • -r Creates a self-signed certificate.


Above command will create a certificate named RootCA.cer in the cert directory ,and also placed this certificate into Person folder
After executing the above command do the following steps


  • Start/Run/MMC

  • File/Add-Remove Snap-In

  • Click Add


  • Select Certificates and click Add

  • Select Computer Account and hit Next

  • Select Local Computer

  • Click Close

  • Click OK
Go back to the certificates snap-in, right-click the "RootCA" certificate and copy it to the "Trusted Root Certification Authorities" node. Once done, if you expand this node, and then select certificates your newly created root cert should be present.

Now,It's time to create the server certificate.Type the following command and press enter
    C:\cert>makecert -pe -n "CN=santosh-pc" -ss My -sr LocalMachine -sky exchange -a

 sha1 -in "RootCA" -is My -ir LocalMachine -sy 12 santosh-pc.cer



How to validate asp.net form using Jquery

In this post I will show you how to validate asp.net form using jqery. Create a new website,add a new js file ,and add following code inside it
function validateForm(e) {
    var formIsValid = true;
    // check that a valid email address has been entered
    var emailRegExp = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/;
    if (!emailRegExp.test(String($("#txtEmail").val()).toUpperCase())) {
        addError("txtEmail", "Please enter a valid email address.");
        formIsValid = false;
    } else {
        removeError("txtEmail");
    }

    // check that first name has one or more characters
    if ($("#txtFirstName").val() == '') {
        addError("txtFirstName", "This field is required.");
        formIsValid = false;
    } else {
        removeError("txtFirstName");
    }
    // check that last name has one or more characters
    if ($("#txtLastName").val() == '') {
        addError("txtLastName", "This field is required.");
        formIsValid = false;
    } else {
        removeError("txtLastName");
    }

    // check that a valid phone number is entered
    var phoneRegExp = /^\(?[1-9]\d{2}\)?\s?\-?\.?\d{3}\s?\-?\.?\d{4}$/;
    if (!phoneRegExp.test($("#txtPhone").val())) {
        addError("txtPhone", "Valid phone number required.");
        formIsValid = false;
    } else {
        removeError("txtPhone");
    }

    if (!formIsValid) {
        e.preventDefault();
    }
}

function addError(id, msg) {
    if ($("#" + id).parent().find("label[class=error]").attr("generated") == "true") {
        $("#" + id).parent().find("label[class=error]").css("display", "block");
    } else {
        $("#" + id).parent().append('<label for="' + id + '" generated="true" class="error">' + msg + '</label>').css("display", "block");
    }
}
function removeError(id) {
    $("#" + id).parent().find("label[class=error]").css("display", "none");
}
Add a new page.Then add reference of jquery and above js file
<%@ 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">
    <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript" src="Scripts/Validation.js"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".submitForm").click(function (e) {
                validateForm(e);
            });
        });
    </script>
    <style type="text/css">
    .error{color:Red;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <table class="style1">
        <tr>
            <td>
                FirstName
            </td>
            <td>
                <asp:TextBox ID="txtFirstName"  runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                LastName
            </td>
            <td>
                <asp:TextBox ID="txtLastName"  runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Phone Number
            </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>
    </table>
    <div>
        <input type="button" id="btnSubmit" class="submitForm" value="Submit" />
    </div>
    </form>
</body>
</html>

How to enable/disable dropdownlist through a checkbox selection

In this post,I will show you how to enable/disable dropdownlist control through checkbox selection in asp.net.

  • Create a new website 
  • Right click on the website,add a new webpage,and add following code into it



<%@ 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>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#chkEnable").click(function () {
                if (this.checked)
                    $('#ddlList').attr('disabled', 'disabled');
                else
                    $('#ddlList').removeAttr('disabled');
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBox ID="chkEnable" runat="server" Text="Enable/Disable" /><br />
        <asp:DropDownList ID="ddlList" runat="server">
            <asp:ListItem Text="Select" Value="-1">
            </asp:ListItem>
            <asp:ListItem Text="Option1" Value="1" />
            <asp:ListItem Text="Option2" Value="2" />
            <asp:ListItem Text="Option3" Value="3" />
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

{Click here for live demo}

How to change default binding in WCF 4.0

With WCF 3.x, if you try to host a service without any configured endpoints, the ServiceHost instance will throw an exception informing you that you need to configure at least one endpoint. With WCF 4, this is no longer the case because the runtime automatically adds one or more “default endpoints” for you, thereby making the service usable without any configuration.
If you want to change default binding then open web.config and do following entry in <system.serviceModel>

<system.serviceModel>

<protocolMapping>

<add binding="basicHttpBinding" scheme="Http"/>

</protocolMapping>


</system.serviceModel>

How to upload/Download file from wcf service

In this post,I will show you how to stream (upload and download) data through wcfservice.


  • Create a new website
  • Right click on the website and add new wcf service named FileStream.svc
  • Open the IFileStream.cs and add following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
[ServiceContract]
public interface IFileStream
{
    [OperationContract]
    string Upload(Stream inputStream);
    [OperationContract]
    Stream Download(string fileId);
    [OperationContract]
    string[] GetAvailableFiles();
}

Open FileStream.cs file and add following code inside it


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Web;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class FileStream : IFileStream
{
    private const string FILEPATH = @"C:\temp\download";
    private string GetDirectoryPath()
    {
    return FILEPATH;
    }
    public string Upload(System.IO.Stream inputStream)
    {
    string fileID = string.Format(@"{0}\{1}.txt", GetDirectoryPath(), Guid.NewGuid().ToString());
        StreamReader reader = new StreamReader(inputStream);
    string contents = reader.ReadToEnd();
        File.WriteAllText(fileID, contents);
    return fileID;
    }
    public System.IO.Stream Download(string fileId)
    {
        MemoryStream stream = new MemoryStream();
    byte[] buffer = File.ReadAllBytes(fileId);
        stream.Write(buffer, 0, buffer.Length);
        stream.Position = 0;
    return stream;
    }
    public string[] GetAvailableFiles()
    {
    return new DirectoryInfo(GetDirectoryPath()).GetFiles().Select(x => x.FullName).ToArray();
    }
}

Now,It's time to configure the service.There are two way to configure the service.First through the code ,and second through the config file.I will followlatter approach.Open web.config and go to section and add following code

<?xml version="1.0"?>
<configuration>
    <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    </system.web>
    <system.serviceModel>
    <services>
    <service behaviorConfiguration="streamServiceBehaviour" name="FileStream">
    <endpoint address="" binding="basicHttpBinding" contract="IFileStream" bindingConfiguration="streamBindingConfig"/>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
    </services>
    <behaviors>
    <serviceBehaviors>
    <behavior name="streamServiceBehaviour">
    <serviceDebug includeExceptionDetailInFaults="true"/>
    <serviceMetadata httpGetEnabled="true"/>
    </behavior>
    </serviceBehaviors>
    </behaviors>
    <bindings>
    <basicHttpBinding>
    <binding name="streamBindingConfig" transferMode="Streamed">
    </binding>
    </basicHttpBinding>
    </bindings>
    </system.serviceModel>
</configuration>

In the above configuration,I have used basicHttpBinding and transferMode is Streamed..

Let's consume the service.Right click on the project and add new page and add following code into it


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ServiceExample.aspx.cs" Inherits="ServiceExample" %>
<!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:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
    </div>
    <asp:Button ID="btnDownload" runat="server" onclick="btnDownload_Click" 
    Text="Download" />
    <asp:TextBox ID="TextBox1" runat="server" Height="235px" Width="377px"></asp:TextBox>
    </form>
</body>
</html>
using System.Collections.Generic;
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class ServiceExample : System.Web.UI.Page
{
    StreamService.FileStreamClient client = new StreamService.FileStreamClient();
    string fileId = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
 
     fileId=client.Upload(new MemoryStream(FileUpload1.FileBytes));
     Session["fileID"] = fileId;
    }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        Stream stream = client.Download((String)Session["fileID"]);
        StreamReader reader = new StreamReader(stream);
        TextBox1.Text = reader.ReadToEnd();
    }
}