A day with .Net

My day to day experince in .net

Archive for October, 2012

SOAP Message inspector for SOAP WCF Web service proxy

Posted by vivekcek on October 31, 2012

I hope you know how to create a WCF proxy using SVCUTIL.EXE.
You can refer my old post ‘Create proxy of WCF web service with svcutil

Add the proxy class to your project and add reference to System.ServiceModel namespace.
use the below namespace’s in your project.

using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;

Now add a class MessageViewerInspector as a nested class.

internal class MessageViewerInspector : IEndpointBehavior, IClientMessageInspector
        {

            #region Properties
            public string RequestMessage { get; set; }
            public string ResponseMessage { get; set; }
            #endregion

            #region IEndpointBehavior Members
            public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
            {

            }

            public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
                // adds our inspector to the runtime
                clientRuntime.MessageInspectors.Add(this);
            }

            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {

            }

            public void Validate(ServiceEndpoint endpoint)
            {

            }
            #endregion

            #region IClientMessageInspector Members
            void IClientMessageInspector.AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                this.ResponseMessage = reply.ToString();
            }

            object IClientMessageInspector.BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
            {
                this.RequestMessage = request.ToString();
                return null;
            }
            #endregion
        }

Now create your proxy object as below.

MessageViewerInspector inspector = new MessageViewerInspector();
ServiceSoapClient _Client=new ServiceSoapClient()
_Client.Endpoint.EndpointBehaviors.Add(inspector);

the inspector object have 2 properties ‘RequestMessage’ and ‘ResponseMessage’ contain SOAP request and response after you called any operations through proxy.

Posted in WCF | Leave a Comment »

Append rows to table using SignalR,Jquery and ASP.NET

Posted by vivekcek on October 25, 2012

1. Create an ASP.NET website project in VS2012.

2. Use the Nuget package manager to add SignalR.

3. Create a class named signal in App_Code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SignalR;
using SignalR.Hubs;
/// <summary>
/// Summary description for signal
/// </summary>
[HubName("signals")]
public class signal:Hub
{
    public void GetList()
    {
        Employee emp = new Employee();
        emp.ID = "1";
        emp.Name = "Vivek";
        Address adrs = new Address();
        adrs.Value = "poomala";
        emp.Address = adrs;
        List<Employee> emps = new List<Employee>();
        emps.Add(emp);
        Caller.PostReslt(emps);
        System.Threading.Thread.Sleep(2000);

        emp = new Employee();
        emp.ID = "2";
        emp.Name = "chanthu";
        adrs = new Address();
        adrs.Value = "poomala";
        emp.Address = adrs;

        emps = new List<Employee>();
        emps.Add(emp);
        Caller.PostReslt(emps);
    }
    
    public class Employee
    {
        public string ID;
        public string Name;
        public Address Address;
    }
    public class Address
    {
        public string Value;
    }
}

4. Add a Webform named Default.aspx and paste the below code.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
    <script src="Scripts/jquery.signalR-0.5.3.min.js" type="text/javascript"></script>
    <script src="<%=ResolveClientUrl("~/signalr/hubs") %>"></script>
    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.signals;

            proxy.PostReslt = function (data) {

                for (i = 0; i < data.length;i++)
                {
                    var tbl = $('#tbl');
                    var row = $('<tr></tr>');
                    var col = $('<td></td>').text(data[i].ID)
                    var col1 = $('<td></td>').text(data[i].Name)
                    var col3 = $('<td></td>').text(data[i].Address.Value)
                    row.append(col);
                    row.append(col1);
                    row.append(col3);
                    tbl.append(row);
                }
               
            };

            $.connection.hub.start();

            $('#btn').click(

                function () {

                    proxy.getList();
                }
                );
        }
        );
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
        <input type="button" id="btn" value="Send"/>
        <table id="tbl">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Address</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </form>
</body>
</html>

Posted in SignalR | Tagged: , , | Leave a Comment »

Abstract class with MEF

Posted by vivekcek on October 12, 2012

I hope you have some experience in MEF. Sorry this is not a beginner article on MEF.

You can read my old post here. Managed Extensibility Framework

In this article i am using Abstract classes instead of interfaces for define our contracts.
Why i used abstract classes because you are not forced to implement the methods in your child classes.

1. Create a Visual Studio 2012 Console c# project.

2. Add reference to ‘System.ComponentModel.Composition’.

3. Create an abstract class like below.

 public abstract class AbstractClass
    {
        public abstract void DisplayName();
    }

4. Create a class A.

using System;
using System.ComponentModel.Composition;

namespace MEF
{
    [Export(typeof(AbstractClass))]
    class A:AbstractClass
    {
        public override void DisplayName()
        {
            Console.WriteLine("From class B");
        }
    }
}

5. Create a class named B.

using System;
using System.ComponentModel.Composition;
namespace MEF
{
    
    [Export(typeof(AbstractClass))]
    class B: AbstractClass
    {
        public override void DisplayName()
        {
            Console.WriteLine("From class B");
        }
    }
}

6. Now change your Program class like below.

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace MEF
{
    class Program
    {        
        static void Main(string[] args)
        {
            Assembler asm = new Assembler();
            asm.DoWork();
        }

    }
    class Assembler
    {
        [ImportMany(typeof(AbstractClass))]
        List<AbstractClass> Factory = new List<AbstractClass>();
        public void DoWork()
        {
            var catlog = new AggregateCatalog();
            catlog.Catalogs.Add(new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()));
            var container=new CompositionContainer(catlog);
            container.ComposeParts(this);
        }
    }
}

Posted in Managed Extensibility Framework | Tagged: , , | Leave a Comment »

Partitioning Data skip,skip-while,take,take-while

Posted by vivekcek on October 8, 2012

 string[] test5 = new string[] { "an", "apple", "a", "day", "keeps", "the", "doctor", "away" };
            IEnumerable<string> take = test5.Take(3);
            IEnumerable<string> skip = test5.Skip(3);
            IEnumerable<string> skipWhile = test5.SkipWhile(x => x.Substring(0, 1) == "a");
            IEnumerable<string> takeWhile = test5.TakeWhile(x => x.Length <= 3);

Posted in LINQ | Leave a Comment »

Sort a list by price ascending order – put null or zero values at the end

Posted by vivekcek on October 8, 2012

In this code we sort list by price in ascending order. But we place the zero price to the end using ThenBy

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Price> prices = new List<Price>()
            {
                new Price(){ name="a", price=5.0},
                new Price(){ name="b", price=4.0},
                new Price(){ name="c", price=2.0},
                new Price(){ name="d", price=0.0},
                new Price(){ name="e", price=0.0}
            };

            List<Price> sorted = prices.OrderBy(x => x.price == 0).ThenBy(x => x.price).ToList();

               
        }
    }
  
    class Price
    {
        public string name;
        public double price;
    }
}

Posted in LINQ | Leave a Comment »

Join two list using lambda expression

Posted by vivekcek on October 8, 2012

 List<Employee> employees = new List<Employee>()
            {
                new Employee(){ id="1", name= "Vivek"},
                 new Employee(){ id="2", name= "Chanthu"}
            };

            List<Address> address = new List<Address>()
            {
                new Address(){ Empid="1", Addres= "Eleyodu"},
                new Address(){ Empid="2", Addres= "Edakkadom"}
            };

            var query = employees.Join(
                address,
                emp => emp.id,
                adrs => adrs.Empid,
                (emp, adrs) => new { EmployeeName = emp, EmployeAddress = adrs })
                .Where(EmployeeAndAddress => EmployeeAndAddress.EmployeeName.id == EmployeeAndAddress.EmployeAddress.Empid).ToList();

            foreach (var item in query)
            {
                Console.WriteLine("Employee Name:{0},Address:{1}", item.EmployeeName.name, item.EmployeAddress.Addres);
            }
class Employee
        {
            public string id;
            public string name;
            public string department;
        }
        class Address
        {
            public string Empid;
            public string Addres;
        }

Posted in LINQ | Tagged: , | Leave a Comment »