Saturday, October 6, 2012

How to read incoming and outgoing message in wcf

 

In this post,I will show you how to read outgoing and incoming message in wcf.

Create a new console application and add following assembly reference in the project

using System.ServiceModel;
using System.ServiceModel.Description;

and paste following code

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

namespace WCF_MessageInspector
{
    [ServiceContract]
    public interface IHelloService
    {
        [OperationContract]
        string Greet(string name);
    }
    [ConsoleServiceBehavior]
    [ServiceBehavior]
    public class HelloService : IHelloService
    {
        public string Greet(string name)
        {
            return "Hello ," + name;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string baseUrl = "http://localhost:12345";
            ServiceHost host = new ServiceHost(typeof(HelloService), new Uri(baseUrl));
            host.AddServiceEndpoint(typeof(IHelloService), new BasicHttpBinding(), "basic");
            // Check to see if the service host already has a ServiceMetadataBehavior
            ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
            // If not, add one
            if (smb == null)
                smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            host.Description.Behaviors.Add(smb);

            host.Open();
            Console.WriteLine("Service is ready");
            Console.Read();
        }
    }
}
Create a new class named  ConsoleMessageInspector and inherit it from following interfaces
IClientMessageInspector
IDispatchMessageInspector
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;

namespace WCF_MessageInspector
{
    public class ConsoleMessageInspector : IClientMessageInspector, IDispatchMessageInspector
    {
        public Message CreateMessage(Message message)
        {
            MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue);
            var messageCopy = buffer.CreateMessage();
            Console.WriteLine(messageCopy.ToString());
            return buffer.CreateMessage();

        }
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            request = CreateMessage(request);
            return null;
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            reply = CreateMessage(reply);
        }

        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            reply = CreateMessage(reply);
        }

        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            request = CreateMessage(request);
            return null;
        }
    }
}
Create a new class named ConsoleEndpointBehavior and inherit it from following iterface
IEndpointBehavior
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;

namespace WCF_MessageInspector
{
   public class ConsoleEndpointBehavior:IEndpointBehavior
    {

        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(new ConsoleMessageInspector());
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new ConsoleMessageInspector());
        }

        public void Validate(ServiceEndpoint endpoint)
        {
            
        }
    }
}
Now it’s time to apply custom inspector to the service.For this create a new class named  ConsoleServiceBehavior and inherit it from Attribute and IServiceBehavior
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;

namespace WCF_MessageInspector
{
   public class ConsoleServiceBehavior:Attribute,IServiceBehavior
    {
        public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            foreach (var item in serviceHostBase.Description.Endpoints)
            {
                item.Behaviors.Add(new ConsoleEndpointBehavior());
            }
        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            
        }
    }
}

Create a new Project named client and add service reference

Untitled

 

 

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

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            Proxy.HelloServiceClient client = new Proxy.HelloServiceClient();
            Console.WriteLine(client.Greet("Bill"));
        }
    }
}

 

Run both the application,and you will show that incoming and outgoing messages are captured

 

output

Complete code

Friday, October 5, 2012

How to read namespace based xml using Linq

In this post,I will show you how to read xml with namespace.For this demo,I will use following xml

structure

<?xml version="1.0" encoding="utf-8" ?>
<accounts xmlns="urn:account">
  <account>1001</account>
  <account>1002</account>
</accounts>

 

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

namespace XLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            var doc = XDocument.Load("accounts.xml");
            var query = from x in doc.Descendants("{urn:account}account")
                        select x;
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
        }
    }
}

Tuesday, September 25, 2012

How to send request from CURL command tool to wcf reset service

In this post,I will show you how to test your rest service from command prompt using CURL tool.
What is CURL:A command line tool for getting or sending files using URL syntax.

For this demo I have created a simple reset service which contains three method as below

Download Source Code

[ICurlService]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;


[ServiceContract(SessionMode = SessionMode.NotAllowed)]
public interface ICurlService
{
    [WebGet(UriTemplate = "date/{year}/{month}/{day}", ResponseFormat = WebMessageFormat.Xml)]
    [OperationContract]
    string GetDate(string day, string month, string year);

    [WebGet(UriTemplate = "greet", ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    string Greeting();

    [WebInvoke(Method = "POST", UriTemplate = "submit", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    [OperationContract]
    string Save(string data);

}
[ServiceType]

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

public class ServiceType : ICurlService
{
    public string GetDate(string day, string month, string year)
    {
        return new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day)).ToString("dddd, MMMM dd, yyyy");
    }
   public string Greeting()
    {
        return "Hello World";
    }
   public string Save(string data)
   {
       return data + "Has been saved!";
   }
}

Let's send request to first method


 [WebGet(UriTemplate = "date/{year}/{month}/{day}", ResponseFormat = WebMessageFormat.Xml)]
    [OperationContract]
    string GetDate(string day, string month, string year);

Go to command prompt and type following code

curl http://localhost:12576/CurlDemo/Service.svc/date/2012/1/12

Let's send request to second method from curl



  [WebGet(UriTemplate = "greet", ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    string Greeting();


curl http://localhost:12576/CurlDemo/Service.svc/greet

Now,let's send a post request to service from command prompt




  [WebInvoke(Method = "POST", UriTemplate = "submit", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    [OperationContract]
    string Save(string data);


curl  -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"data":"dummy data"}' http://localhost:12576/CurlDemo/Service.svc/submit


Monday, July 30, 2012

How to call python generator in c#

In this post,I will show you how to call python generator in c#.Create a console Application and then right click on the project and add new file fib.py and add following code
class Fib:

    def __init__(self,num):

        self.a=0

        self.b=1

        self.num=num

        self.index=0

    def __iter__(self):

        return self

    def next(self):

        if self.index > self.num:

            raise StopIteration

        else:

            self.index +=1

            self.a,self.b=self.b,self.a+self.b

            return self.a

Open Progrm.cs and add following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting.Hosting;
namespace IronPython_Tut1
{
        class Program
    {
        static void Main(string[] args)
        {
        //Create runtime
            ScriptRuntime runtime = IronPython.Hosting.Python.CreateRuntime();
        //excute 
            ScriptScope scope = runtime.ExecuteFile(@"Fib.py");
        //get the Fib object
            dynamic Fib = scope.GetVariable("Fib");
        foreach (var item in Fib(10))
            {
                Console.WriteLine(item);
            }
          
        }
    }
}


How to call python class in c#

In this post,I will show you how to call python class in c#,Create a new python class named Person.py and paste following code


class Person:
    def __init__(self,firstName,lastName,age):
        self.firstName=firstName
        self.lastName=lastName
        self.age=age
   
    def __str__(self):
        return self.firstName +","+self.lastName+","+self.age
    def get_full_name(self):
        return "%s,%s" % (self.firstName, self.lastName)
   
   


Open program.cs and add following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting.Hosting;
namespace IronPython_Tut1
{
    class Program
    {
    static void Main(string[] args)
        {
    //Create runtime
            ScriptRuntime runtime = IronPython.Hosting.Python.CreateRuntime();
    //excute 
            ScriptScope scope = runtime.ExecuteFile(@"Person.py");
    //get the Person object
            dynamic Person = scope.GetVariable("Person");
    //Create instanc of Person class.
            dynamic personObject = Person("santosh", "singh", 24);
    //call  the get_full_name method on person instancw
            Console.WriteLine(personObject.get_full_name());
            Console.ReadLine();
        }
    }
}

IronPython and C#


What is IronPython

IronPython is an open-source implementation of the Python programming language which is tightly integrated with the .Net Framework.
IronPython can use the .Net Framework and python libraries,and other .NET languaages can use Python code just as easily

In this post I will show you how to call Python method in c#.


Create a new Console application and visual studio
Right click on the project and click on Manage Nuget Packages and search for IronPython

After installing IronPython import following namespaces
using Microsoft.Scripting.Hosting;

Right click on project and add new file Calculator.py and add following python code


def add(a,b):
    return a+b

Open Program.cs file and add following code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting.Hosting;
namespace IronPython_Tut1
{
    class Program
    {
    static void Main(string[] args)
        {
    //Create runtime
            ScriptRuntime runtime = IronPython.Hosting.Python.CreateRuntime();
    //excute 
            dynamic scope = runtime.ExecuteFile(@"Calculator.py");
    //call the python method
            Console.WriteLine("Sum={0}", scope.add(1, 2));
            Console.ReadLine();
        }
    }
}

Saturday, July 14, 2012

How to implement twitter search in asp.net

In this post,I will show you how to implement twitter search in asp.net.In this project,I am using following things




<a href="http://search.twitter.com/search.json" target="_blank">Twitter search Api</a>
<a href="http://jquery.com/" target="_blank">Jquery</a>
<a href="http://handlebarsjs.com/" target="_blank">Handlebars jquery template</a>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Twitter.aspx.cs" Inherits="Twitter" %>
<!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">
        body
        {
            width: 600px;
            margin: auto;
        }
        .tweets
        {
            list-style-type: none;
        }
        img
        {
            float: left;
            padding-right: 1em;
        }
        a
        {
            text-decoration: none;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
    <script src="Scripts/Handlebars.js" type="text/javascript"></script>
    <script type="text/javascript">
    var Twitter =
         {
             init: function () {
    this.url = "http://search.twitter.com/search.json?q='" + $("#txtSearch").val() + "'&callback=?";
    this.template = $("#template").html();
    this.fetch();
             },
             fetch: function () {
    var self = this;
                 $.getJSON(this.url, function (data) {
                     self.tweets = $.map(data.results, function (tweet) {
    return {
                             author: tweet.from_user,
                             tweet: tweet.text,
                             thumb: tweet.profile_image_url,
                             url: 'http://twitter.com/' + tweet.from_user + '/status/' + tweet.id_str
                         };
                     });
                     self.parse();
                 });
             },
             parse: function () {
    var template = Handlebars.compile(this.template);
    var container = $(".tweets");
                 container.append(template(this.tweets));
             }
         };
        $(document).ready(function () {
            $("#btnSearch").click(function () {
                Twitter.init();
            });
        });
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="text" id="txtSearch" /><br />
        <input type="button" id="btnSearch" value="Search" />
        <ul class="tweets">
            <script type="text/x-handlebars-template" id="template">
            {{#each this}}
            <li>
            <img src="{{thumb}}" alt="{{author}}"></img>
            <p><a href="{{url}}"> {{tweet}} </a></p>
            </li>
            {{/each}}
       
    </script>
    </ul>
    </div>
    </form>
</body>
</html>

You can download the complete source code from below git location
code

Passing complex objects into a WCF Rest Service

In this post,I will show you how to pass complex json data from jquery to wcf service.
  • Create a new website in visual studio.
  • Add a new item wcf service named BlogService and replace the existing code with following
IBlog.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

[ServiceContract]

public interface IBlog
{
    [WebInvoke(UriTemplate = "blogs", Method = "POST",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    string SubmitBlock(Blog blogs);
}
IBlogService.cs

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

[ServiceBehavior]


public class BlogService : IBlog
{


    List<Blog> _blogs = null;
    [OperationBehavior]
    public string SubmitBlock(Blog blogs)
    {
        //Process your data.
    }
}
[DataContract]
[KnownType(typeof(BlogPost))]
public class Blog
{
    [DataMember]
    public string BlogID { get; set; }
    [DataMember]
    public string Title { get; set; }
    [DataMember]
    List<BlogPost> Blogs { get; set; }
}
[DataContract]
public class BlogPost
{
    [DataMember]
    public string BlogPostID { get; set; }
    [DataMember]
    public string BlogID { get; set; }
    [DataMember]
    public string BlogContent { get; set; }
}
  • Open web.config and made highlighted changes

<?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.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="Service1Behavior" name="BlogService">
        <endpoint address="" binding="webHttpBinding" behaviorConfiguration="EnableScript"  contract="IBlog">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>

        <behavior name="EnableScript">
          <webHttp></webHttp>

        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="Service1Behavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="false" />
  </system.serviceModel>
</configuration>

<%@ 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 type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">

        var DTO =
    {
        "BlogID": "1",
        "Title": "Aspdotnetcodebook",
        "Blogs": [
            {
                "BlogPostID": "1",
                "BlogID": "1",
                "BlogContent": "This is my first post"
            },
            {
                "BlogPostID": "2",
                "BlogID": "1",
                "BlogContent": "This is my second post"
            }
        ]
    };


        var blogs1 = {blogs: DTO };
        $(document).ready(function () {

            $.ajax(
            {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processdata:false,
                data:JSON.stringify(blogs1),
                url: "http://localhost:6548/Blog/BlogService.svc/blogs",
                success: function (data) {
                    alert(data);
                }
            }
            );
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>
Complete source code

Thursday, July 12, 2012

How to add Header and Footer on every page by using HttpModule in asp.net

In this post,I will show you a very simple way to add header and footer on every page using HttpModule.

  • Open visual studio and create a new website.
  • Right click on website and add a new class named HeaderAndFooter,and inherit this class with IHttpModule inteface.
using System;
using System.Web;
using System.IO;

public class HeaderAndFooter : IHttpModule
{
    const string PageHeaderText = "<h1>Header Added by Module<h1>";
    const string PageFooterText = "<h1>Footer added by Module</h1>";

    public void Init(HttpApplication app)
    {
        // Register for pipeline events
        app.BeginRequest += new EventHandler(OnBeginRequest);
        app.EndRequest += new EventHandler(OnEndRequest);
    }

    public void Dispose()
    {
        // Nothing to do here
    }

    public void OnBeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;
        HttpContext ctx = app.Context;

        // Add custom header to the HTTP response
        ctx.Response.AppendHeader("Author", "DinoE");
        ctx.Response.Write(PageHeaderText);
    }

    public void OnEndRequest(object sender, EventArgs e)
    {
        // Get access to the HTTP context 
        HttpApplication app = (HttpApplication)sender;
        HttpContext ctx = app.Context;

        // Append some custom text
        ctx.Response.Write(PageFooterText);
    }
}
  • Open the web.config and register the module as below
<?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.web>
    <httpModules>
      <add name="HeaderAndFooter" type="HeaderAndFooter,App_Code"/>
    </httpModules>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
</configuration>

Thursday, June 28, 2012

WCF self hosted service over HTTPS

In this post I will show you how to host self hosting wcf service over ssl.

Let's create a simple wcf service


Create a new console application in visual studio and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace SelfHostSSL
{
    [ServiceContract]
    public interface IGreeting
    {
        [OperationContract]
    string SendGreeting();
    }
    public class Implementation : IGreeting
    {
        
    public string SendGreeting()
        {
    return "Hello world";
        }
        
    }
    class Program
    {
    static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(Implementation));
            host.Open();
            Console.WriteLine("Service is ready");
            Console.ReadLine();
        }
    }
}

After that add new item app.config and paste following code in it

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  
    <system.serviceModel>
    <behaviors>
    <serviceBehaviors>
    <behavior name="serviceBehav">
    <serviceDebug />
    <serviceMetadata httpGetEnabled="true" httpGetUrl="mex" />
    </behavior>
    </serviceBehaviors>
    </behaviors>
    <services>
    <service behaviorConfiguration="serviceBehav" name="SelfHostSSL.Implementation">
    <endpoint address="basic" binding="basicHttpBinding"
    bindingConfiguration="" contract="SelfHostSSL.IGreeting" ></endpoint>
    <host>
    <baseAddresses>
    <add baseAddress="http://localhost:4490/"/>
    </baseAddresses>
    </host>
    </service>
          
    </services>
      
    </system.serviceModel>
</configuration>


Add new project named Client in same solution and paste following code in it


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace Client
{
    [ServiceContract]
    public interface IGreeting
    {
        [OperationContract]
    string SendGreeting();
    }
    
    class Program
    {
    static void Main(string[] args)
        {
            ChannelFactory<IGreeting> proxy = new ChannelFactory<IGreeting>(new BasicHttpBinding());
            proxy.Endpoint.Address = new EndpointAddress("http://localhost:4490/basic");
    string result = proxy.CreateChannel().SendGreeting();
            Console.WriteLine(result);
        }
    }
}

Our simple wcf service is ready now.Let's configure it for ssl. Open app.config and make highlighted changes

<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="serviceBehav" name="SelfHostSSL.Implementation">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="serviceBinding" contract="SelfHostSSL.IGreeting"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="https://localhost:8080/basic"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <bindings>
    <basicHttpBinding>
    <binding name="serviceBinding">
    <security mode="Transport">
    </security>
    </binding>
    </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehav">
          <serviceDebug/>
          <serviceMetadata httpsGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

When you run the service after making above changes service will throw following exception.


AddressAccessDeniedException: HTTP could not register URL http://+:8080/<…>.  Your process does not have access rights to this namespace.



To fix this problem, the owner of the HTTP namespace (built-in administrator) needs to delegate this ownership to the user account under which you are running your application (most of the times, it's the logged on user). To do this, start a command prompt using "Run as administrator" so that you have elevated privileges. Then, use netsh.exe to give some of the Administrator's HTTP namespace to your user account. You can look at the existing HTTP namespace delegations by using "netsh http show urlacl".





Execute the above command and run the service.If every thing is fine then you will see "service ready " message.

Try to browse the service from browser you will see page can not found error message

This is because our port is not open for SSL.Now you have to create a self -signed certificate for this follow the following two links and create a self signed certificate and note down the thumbprint value a remove the extra space.

How to create Self-Signed SSL Certificate using OpenSSL

How to create self signed certificate using makecert 

Now,It's time to configure the port for SSL (check out this for more details)
Open the command prompt in elevated mode and run the following command


Command Description:

netsh http add sslcert [Ipaddress:port] certhas=[thumbprint of certifcate] appid={unique id for application.you can use GUID for this]

How to create Self-Signed SSL Certificate using OpenSSL

In this
        post I will show you how to create a Self-Signed certificate using OpenSSL.


Generate Private Key and Certificate Signing Request

A private key and certificate signing request are required to create an SSL certificate. These can
be generated with a few simple commands.




C:\> openssl genrsa -des3 -out localhost.key 1024 
---------------------------------------------
Enter pass phrase for site.key: 
Verifying - Enter pass phrase for site.key: 
C:\> mv localhost.key localhost.org.key 
C:\> openssl rsa -in localhost.org.key -out localhost.key 
Enter pass phrase for localhost.org.key:
writing RSA key 
C:\> openssl req -new -key localhost.key -out server.csr
----------------------------------------------------            
Country Name (2 letter code) [AU]:IN 
State or Province Name (full name) [Some-State]:HR


Generate SSL Certificate

C:\> openssl x509 -req -days 365 -in server.cer -signkey localhost.key -out final.cer
The final.cer  file is your site certificate suitable for use with WCF service

Thursday, June 21, 2012

Project Euler Problem4[C#]


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

namespace ProjectEuler
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Problem4(600851475143UL));

        }
        /// <summary>
        /// http://projecteuler.net/problem=3
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static ulong Problem4(ulong number)
        {
            ulong i = 2;
            while (i * i < number)
            {
                while (number % i == 0)
                {
                    number = number / i;

                }
                i = i + 1;
            }
            return number;

        }

    }
}

Project Euler Problem2 [c#]


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

namespace ProjectEuler
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Problem2());
        }

        /// <summary>
        /// http://projecteuler.net/problem=2
        /// </summary>
        /// <returns></returns>
        public static ulong Problem2()
        {
            var sum = Fibonacci().Where(x => x % 2 == 0)
                                 .TakeWhile(x => x < 4000000)
                                 .Aggregate((add, x) => add + x);
            return sum;
        }

        public static IEnumerable<ulong> Fibonacci()
        {
            var a = 0UL;
            var b = 1UL;
            var c = a + b;

            while (true)
            {
                yield return c;

                c = a + b;
                a = b;
                b = c;
            }


        }
    }
}

Project Euler Problem1 [C#]


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

namespace ProjectEuler
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Problem1());
        }
        /*If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of                these multiples is 23.
          Find the sum of all the multiples of 3 or 5 below 1000.*/

        public static int Problem1()
        {
            var sum = Enumerable.Range(1, 999)
                    .Where(x => x % 3 == 0 || x % 5 == 0)
                    .Sum();
            return sum;
        }

    }
}

Thursday, June 7, 2012

How to used google chart in asp.net[google chart]

In this post,I will show you how to display google chart in asp.net.Before going to implementation details,go through the following link


Visualization: Pie Chart


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PieChart.aspx.cs" Inherits="PiChart" %>
<!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 id="Head1" runat="server">
    <title>jQuery Google Chart Demo</title>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
        google.load("visualization", "1", { packages: ["corechart"] });
    function drawChart() {
    var hdValue = document.getElementById("<%=hdData.ClientID%>").value;
    var response = $.parseJSON(hdValue);
    var data = new google.visualization.DataTable();
            data.addColumn('string', 'TaskType');
            data.addColumn('number', 'HoursPerDay');
    for (var i = 0; i < response.length; i++) {
    var row = new Array();
                row[0] = response[i].TaskType;
                row[1] = parseInt(response[i].HoursPerDay);
                data.addRow(row);
            }
    var options = {
                title: 'My Daily Activities'
            };
            chart = new google.visualization.PieChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }
    </script>
    <script type="text/javascript">
        $(document).ready(drawChart);
      
    </script>
</head>
<body>
    <form id="dform" runat="server">
    <div id="chart_div" style="width: 900px; height: 500px;">
    </div>
    <asp:HiddenField ID="hdData" runat="server" />
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.Script.Serialization;
public partial class PiChart : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
        {
            StringBuilder data = new StringBuilder();
            JavaScriptSerializer json = new JavaScriptSerializer();
            json.Serialize(GetSampleData(), data);
            hdData.Value = data.ToString();
        }
    }
  
    private List<Task> GetSampleData()
    {
        List<Task> tasks = new List<Task>
            {
    new Task{TaskType="Work",HoursPerDay=11},
    new Task{TaskType="Eat",HoursPerDay=2},
    new Task{TaskType="Commute",HoursPerDay=2},
    new Task{TaskType="Watch TV",HoursPerDay=2},
    new Task{TaskType="Sleep",HoursPerDay=7},
            };
    return tasks;
    }
    public class Task
    {
    public string TaskType { get; set; }
    public int HoursPerDay { get; set; }
    }
}