Archive for December, 2008

Policy Injection Application Block

Monday, December 29th, 2008

Here is how Microsoft describes it: “The Policy Injection Application Block provides a mechanism for automatically applying policies to object instances; this helps developers to better manage crosscutting concerns and maximize separation of concerns and encapsulation of behavior. Developers define the set of policies for the target classes and their members through configuration of the Policy Injection Application Block or by applying attributes to individual members of the target class.

The matching rules for each policy encompass a range of capabilities for selecting classes and members, including the name of the assembly, the namespace, the type, the member name, the member signature, attributes that are applied to the member, and more.

I’ll show you one small demo apllication which demonstrates how it works:
Create empty solution and add Class Library project called: BusinessObject. put those 2 files there: CellPhone.cs and ICellPhone.cs

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

namespace BusinessObject
{
    public interface ICellPhone
    {
        void SendSMS(String toPhoneMumber, String mesgSubject, String text);
        void Ring();
        void Dial(String toPhoneNumber);
        void Answer();
        void HangUp();
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace BusinessObject
{
    public class CellPhone : ICellPhone
    {
        private String phoneNumber;

        public CellPhone(String number)
        {
            phoneNumber = number;
        }

        public void SendSMS(String toPhoneMumber, String mesgSubject, String text)
        {
            Console.WriteLine("I am sending SMS to "
                + toPhoneMumber
                + ", with subject "
                + mesgSubject
                + " and text "
                + text
                );
        }
        public void Ring()
        {
            Console.WriteLine("Ringing ...");
        }

        public void Dial(String toPhoneNumber)
        {
            Console.WriteLine("I am dialing " + toPhoneNumber);
        }

        public void Answer()
        {
            Console.WriteLine("Yes plese!");
        }

        public void HangUp()
        {
            Console.WriteLine("Have a nice day.");
        }

    }
}

As you can see we have very simple class CellPhone which implements ICellPhone interface. Then, create and new project to your solution. It can be Console Application. I’ll call it client.
Add BusinessObject reference to your client project. Also you have to add some .NET references in order to use Policy Injection.
Microsoft.Practices.EnterpriseLibrary.Common
Microsoft.Practices.EnterpriseLibrary.PolicyInjection
Microsoft.Practices.EnterpriseLibrary.PolicyInjection
Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers

Now take a look of code for Program.cs

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

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.Logging;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            BusinessObject.CellPhone cellPhone = PolicyInjection.Create("222333");
            cellPhone.Dial("123123");
            cellPhone.Ring();
            cellPhone.Answer();
        }
    }
}

This line is interesting:
BusinessObject.CellPhone cellPhone = PolicyInjection.Create(”222333″);
I don’t use BusinessObject.CellPhone cellPhone = new BusinessObject.CellPhone(”222333″); as you can see. If you want to use Policy Injection, this is how you create your objects. And very important rule: your object must implement some interface or must inherits class: “MarshalByRefObject“. Now you can try to “Build” and start (F5) your application, but for now there is no some differences. It works as it should be.
We have to do 2 more things. Add new project type of class library and to add App.config file to our client application.
First, add new project, type of class library, called: “CustomPIABHandler”.
Rename Class1.cs to LogCallHandler.cs and add some references to project as it is shown on the pictire below:





Now select custom handler. Click on property for Custom Handler and click type. From new PopUp window click on button “Load Assembly” and select LogCallHandler. You should navigate to your bin folder of your CustomPiabHanlder project and select CustomPIABHandler.dll.

And at last, add value for namespace matching rule. Click on Namespace Matching Rule and select it’s Property. Click on collection and add value: BusinessObject. And for the end add Reference of CustomPIABHandler to Client project.

to be continued

Enterprise Library Logging Application Block

Wednesday, December 24th, 2008

Our today discussion is about logging in .NET apps. In this demonstration I will use Visual Studio 2005 and Enterprise Library 3.1 - May 2007.

The Microsoft Enterprise Library is a set of tools and programming libraries for the Microsoft .NET Framework. Enterprise Library Logging Application Block provides you tool for perform logging into your application easily.
All you need is this using directive:

using Microsoft.Practices.EnterpriseLibrary.Logging;

and reference to: “Microsoft.Practices.EnterpriseLibrary.Logging“.
And when you want to log some method, you do it like this:

            LogEntry log = new LogEntry();
            log.Priority = 1;
            log.Message = "Executing";
            log.Categories.Add("General");
            log.Title = "Executing method name";
            Logger.Write(log);

that is all you need to put into your code. Take a look this line: “log.Categories.Add(”General”);”.
At this moment developer doesn’t know how application perform the logging. Does it use some txt file, database or something else. That is why we use App.config file to specify things like that. For editing App.config I suggest to do this edit tool: right click on App.config and select “Edit Enterpise Library Confoguration” .

When we want to use logging, 1-st we have to add “Category”. Take a look at picture!

I will call my Category “General”. Category gets name by Default, so you use “Property” window to change it’s name. After that add trace reference to your category.

For trace reference we need trace listener! So let’s add some trace listener, like this:


I selected “Flat File Trace Listener“. Choose Property for your trace listener. I select Filename to be: C:\trace.log.

After that select “Trace Reference Listener” and in it’s property window connect it to FlatFileTraceListener. Like this:



And that would be all. Now start your application and take a look at file: C:\trace.log.

We can go one step further and create our Logging class. Here is how can we do that.

Create new project in your solution, and call it Logger, type of project: Class Library, language C#. You have to add reference to you project for: “Microsoft.Practices.EnterpriseLibrary.Logging“.
and here is your class:

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

using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace Logger
{
    public static class MyLogger
    {
        public static void Logg(String message, String category, Int32 priority, String title)
        {
            LogEntry log = new LogEntry();
            log.Priority = priority;
            log.Message = message;
            log.Categories.Add(category);
            log.Title = title;
            Logger.Write(log);
        }
    }
}

and here is how you call it from some of your method. First add reference to Logger project.

Logger.MyLogger.Logg("Exucuting method name", "General", 1, "before method start");

Business objects and WCF

Wednesday, December 24th, 2008

Let’s go further with WCF. In this post I will discuss about using business objects and WCF. For the beginning create blank solution named “SampleWCFWithBusinessObjetcs”, and put 4 projects there:
1. project type Class Library, language C#: “BusinessObjetcs
2. project type Windows Application, language C#: “Client
3. project type Console Application, language C#: “Host” and
4. project type Class Library, language C#: “Service

Project named “BusinessObjetcs” we will use to create business entites, project “Host” will host our WCF,
project “Service” will be wcf and project “Client” will be windows application for testing - our client.

Let’s start with “BusinessObjects”, create new class there called Person. Here is the code:

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

namespace BusinessObjetcs
{
    public class Person
    {
        private Int32  m_Id;
        private String m_Name;
        private DateTime m_BirthDate;

        public Person(Int32 id, String name, DateTime birthDate)
        {
            m_Id = id;
            m_Name = name;
            m_BirthDate = birthDate;
        }

        public Int32 Id
        {
            get { return m_Id; }
            set { m_Id = value; }
        }
        public String Name
        {
            get { return m_Name; }
            set { m_Name = value; }
        }
        public DateTime BirthDate
        {
            get { return m_BirthDate; }
            set { m_BirthDate = value; }
        }
    }
}

Then let’s focus to our “Service” project. I will create an interface and one class which implements that interface: IPerson and Person. As you can imagine IPerson is an itnerface and Person is a class. Before you start, add 2 references to “Service” project. The first one is System.ServiceModel and the other is reference to project “BusinessObjects“. After that create class and interface. Here is the code:


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

namespace Service
{
[ServiceContract]
public interface IPersonService
{
[OperationContract]
Person GetPersonByID(Int32 id);

[OperationContract]
void UpdatePerson(Person person);
}
}

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

namespace Service
{
    public class PersonService : IPersonService
    {
        private Dictionary m_People = new Dictionary();

        public PersonService()
        {
            m_People.Add(1, new Person(1, "Peter Petrovic", new DateTime(1977, 04, 5)));
            m_People.Add(2, new Person(2, "John Johnson", new DateTime(1987, 14, 6)));
            m_People.Add(3, new Person(3, "Mihajlo Lalic", new DateTime(1967, 24, 7)));
        }

        public Person GetPersonByID(Int32 id)
        {
            Person result = null;
            if(m_People.ContainsKey(id))
            {
                result = (Person)m_People[id];
            }
            return result;
        }

        public void UpdatePerson(Person person)
        {
            if(m_People.ContainsKey(person.Id) )
            {
                m_People[person.Id] = person;
            }
        }

    }
}

At this time you should try to build solution and if everything is OK, let’s go to create host for our wcf service.

In host project add reference to “System.ServiceModel” and to “Service” project. In “Host” project you’l find Program.cs

update this file to:

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

namespace Host
{
    class Program
    {
        static void Main(string[] args)
        {

            Type t;
            t = typeof(Service.PersonService);
            using (ServiceHost host = new ServiceHost(t))
            {
                host.Open();
                Console.WriteLine("Service started...");
                Console.ReadLine();
                host.Close();
            }
        }
    }
}

So if you run Host application our service will be started, but not so fast. We are missing one thing. end points!
Create App.config file for “Host” project and copy paste this.



  
    
      
        
          
        
      
    
    
      
        
      
    
  

Ok, I hope that is all for now, and I hope it’s works. Set your “Host” project to be startup project and press “F5″.

If you have some problems it is OK. You probably get message about: “Type ‘BusinessObjetcs.Person’ cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.”



Add an Using statement for System.Runtime.Serialization to the top of the source code file for the Person class and add Reference to System.Runtime.Serialization. Then add the DataContract attribute to the Person class declaration and the DataMember attribute to each of the properties. After that your “Person”class looks like this one:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace BusinessObjetcs
{
    [DataContract]
    public class Person
    {
        private Int32  m_Id;
        private String m_Name;
        private DateTime m_BirthDate;

        public Person(Int32 id, String name, DateTime birthDate)
        {
            m_Id = id;
            m_Name = name;
            m_BirthDate = birthDate;
        }

        [DataMember]
        public Int32 Id
        {
            get { return m_Id; }
            set { m_Id = value; }
        }

        [DataMember]
        public String Name
        {
            get { return m_Name; }
            set { m_Name = value; }
        }
        [DataMember]
        public DateTime BirthDate
        {
            get { return m_BirthDate; }
            set { m_BirthDate = value; }
        }
    }
}

Ok, now rebuild all and press “F5″. Wait for a while and then try to get “http://localhost:8081/PersonService”. Here is preview:


So, if everything works for now, let’s add Service Reference to “Client” project. I called it “PersonServiceProxy”. After adding service reference, Visual Studio created new file for you: “PersonServiceProxy.cs“. It is useful to take a look. There you can find some classes and interfaces:

Ok, now let’s finish our demo. Put some controls to your form.


and add some lines of code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadListBox();
        }

        private void LoadListBox()
        {
            using (PersonServiceProxy.PersonServiceClient ws = new PersonServiceProxy.PersonServiceClient())
            {

                lstPeople.DisplayMember = "Name";
                lstPeople.ValueMember = "Id";
                lstPeople.DataSource = ws.GetPeople();
            }

        }

        private void lstPeople_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (PersonServiceProxy.PersonServiceClient ws = new PersonServiceProxy.PersonServiceClient())
            {
                PersonServiceProxy.Person _person = ws.GetPersonByID(Convert.ToInt32(lstPeople.SelectedValue));
                txtBirthDate.Text = _person.BirthDate.ToString();
                txtName.Text = _person.Name;
                txtID.Text = _person.Id.ToString();
            }

        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            PersonServiceProxy.Person _person = new Client.PersonServiceProxy.Person();
            _person.BirthDate = Convert.ToDateTime(txtBirthDate.Text);
            _person.Name = txtName.Text;
            _person.Id = Convert.ToInt32(txtID.Text);
            using (PersonServiceProxy.PersonServiceClient ws = new PersonServiceProxy.PersonServiceClient())
            {
                ws.UpdatePerson(_person);
                LoadListBox();
            }
        }
    }
}



Now you have to set your solution to have multiple startup projects:
“Host” and “Client”.
When you hit “F5″ here is what you got.


try to play a litle bit with this!

Testing your web service with SOAP UI

Tuesday, December 16th, 2008

It is really fun! I hope you’ll find this interesting. The subject of this post is how to test your web service or some wcf service. You only need WSDL and SoapUI. Foe this demonstration we’ll use this service created in Windows Communication Foundation (WCF). If you start your Service you, you will see something like this in your web browser. In my case URL address is: http://localhost:3363/WebServiceHost/Service.svc

“You have created a service.

To test this service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line with the following syntax:

svcutil.exe http://localhost:3363/WebServiceHost/Service.svc?wsdl”

I need only this wsdl so I’ll click on this link: “http://localhost:3363/WebServiceHost/Service.svc?wsdl”.
That is the first step, remember location of your wsdl. Then start SoaupUI applcation, and under projects click “New WSDL project”.

Enter your project name, and enter URL of your WSDL and press OK.
Here is preview:

Now we will test method “FunctionAdd”. Click on Request 1 under the FunctionAdd and populate xml request.
Here is XML request:


And here is response



That is all. I find this tool “SoapUI” very interesting at all.

ASP.NET web service

Tuesday, December 9th, 2008

Creating web service in ASP.NET using Visual studio 2005 is very easy. Follow this steps:
Open Visual Studio and click New Web Site, and select ASP.NET web service.

After a second your project is created. You will find file named: “Service.cs” in your App_Code folder.
There is already default web methid implemented “Hello World”. Here is how it looks like:

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
}

we will change this method “HelloWorld” with an other method “IntigerAddition”. So copy/paste this code into Service.cs file.

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public Int32 IntigerAddition(int a, int b)
    {
        return a + b;
    }
}

It is always useful to try to build your code. If everything is fine, let’s see how it works.
Right click on Service.asmx file in solution explorer and select “View in browser”. The same is if you try to click on “F5″. If there is no web.config file, you’ll be asked to put it into solution.
when web page is opened, you will see listed all services you have. For now it is only “Integer Addition” and if you click on it, you will see SOAP 1.1 and SOAP 1.2 request and response. Also you can test your web service method there if you want.


Now, get us back to solution explorer and create one web page to test this web service.
In Solution Explorer right click on solution and select Add new web site. This is image preview how to do this:

ASP.NET Web service - ASMX

ASP.NET Web service - ASMX




I’ll call this new web site project: “DemoClientForWebService”.
In your new web site project, ther is a file Default.aspx. Open it and add 2 text boxes, one Button and one more text box. Like this:

Now, we need to add web reference in our web site from web service project. Right click on web site project and select Add Web Reference.
Right click on web project and select “Add web reference”.



Then you need to specify web reference. Select “Web service in this solution”.


Then select your reference and click on button “Add reference”.



Now let’s use this reference and connect our application to web service.
Here is the code for Default.aspx page. This is code behind, file: Deafult.aspx.cs:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using localhost; //this is how we called our web service

public partial class _Default : System.Web.UI.Page
{
    localhost.Service myWeb;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            myWeb = new Service();
        }
    }
    protected void bntGo_Click(object sender, EventArgs e)
    {
        txtResult.Text = myWeb.IntigerAddition(
                Convert.ToInt32(txtAdd1.Text),
                Convert.ToInt32(txtAdd2.Text)
                ).ToString();
    }
}

And now, let’s do some testing :)
But first be carefull. You must start your web service first.
It must be running when you try to call it from your web apps.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in