Posts Tagged ‘Windows Communication Foundation’

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!

Windows Communication Foundation (WCF)

Sunday, November 30th, 2008

Windows Communication Foundation (WCF) (code-named “Indigo”) is a set of .NET technologies for building and running connected systems. It is a new breed of communications infrastructure built around the Web services architecture. Windows Communication Foundation, or just WCF, is a programming framework used to build applications that inter-communicate. Here is one sample which demonstrates WCF.

First create a blank solution in Visual Studio .NET 2005. I’ll call it “WSFSample”.

Then add New Project to your solution, language C#, type of project Class Library.
Let’s call this project “ServiceLibrary”. When you do this, Visual Studio cretes new file in your project. By default it is named: Class1.cs. Let’s rename it to MathService.cs. If you renamed the file name, you can see that the class name was renamed too. Add a reference to System.ServiceModel. After that let’s put some code to our class MathService. This is how our class looks like when you put few lines of code there.

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

namespace ServiceLibrary
{
    [ServiceContract]
    public class MathService
    {
        [OperationContract]
        public Int32 AddFunction(Int32 a, Int32 b)
        {
            return a + b;
        }

        [OperationContract]
        public Int32 SquareFunction(Int32 a)
        {
            return a * a;
        }
    }
}

Now we will create Service Hosts. Add new project to your solution. Right click on solution and then select: Solution -> Add New Web Site->WCF Service.
Select WCF service template. For language select C#. Take care where is location of your WCF service because by default it is in your Document and Settings folder. I prefer to hold all project files in the root of my solution file.
I’ll call my WCF service project: “WebServiceHost”.


If you take a look at your new project, you will find a file named “Service.svc”.




add this line to file:

<% @ServiceHost Language=VB Service="ServiceLibrary.MathService" %>

As you can see there is a file named “Service.cs” under App_Code folder. Because we will not use it, you can delete it. Now, please rebuid your application and set WCF service to be Startup Project. Before we test it we need to ad some end points to Web.config and we need to add refernce to the project “ServiceLibrary”. Add this lines to Web.config




  
    
      
        
          
        
      
    
    
      
        
      
    
  

  
    
  


and add Reference in your wcf service project to “ServiceLibrary” project and press “F5″ please. You must have something like this on your screen.



Now we can create some client to consume this web service. Once again we add new project to our solution. This time it will be Windows application, language C# off course. I’ll call it “WindowsClient”.We will add 3 text boxes and one button control to our windows form. As you can imagine 2 text boxes will be for integers “a” and “b” and third text box will be result. Also we need to add “Service Reference” (not web reference as we did with *.asmx) to our wcf service. To do this right click on Windows project we’ve just created and click on “Add Service Reference”.But before that we must know URL of our WCF. We can just start with F5 our application and copy paste address from address bar of Service.svc. In my case it is: http://localhost:1157/WebServiceHost/Service.svc and this address I’ll put for “Service Reference”. Now click to add Service Reference, after you enter Service URI: http://localhost:1157/WebServiceHost/Service.svc
, your service reference name is “localhost” by default. I’ll rename it to “WCFMathService”. If you want your application to be ready for test you must check your app.config file. But Visual Studio set up all for your. Just for remember, you must specify end points element in your App.config too. Here is how it looks like:



    
        
            
                
                    
                    

                        
                    
                
            
        
        
            
        
    

.
Also you must add “System.ServiceModel” reference into your Windows client application.

Here is the code of our form which will call WCF Service when we press button on the form.
Just before I show tou you my code to say how I called controls on form:
button is called: bntCallWebService

2 text boxes txtA and txtB

The third textbox is called” txtResult

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

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

        private void bntCallWebService_Click(object sender, EventArgs e)
        {
            using( WCFMathService.MathServiceClient ws = new WCFMathService.MathServiceClient())
            {
                txtResult.Text = ws.AddFunction(Convert.ToInt32(txtA.Text), Convert.ToInt32(txtB.Text)).ToString();
            }
        }
    }
}


Before I finish I want to tell you to pay attention to this class: WCFMathService


And before we test this we must be carefull because our application will not work if WCF is not started. One way to do this is following: you must specify multiple startup projects: like this:



Just for case rebuild your solution and press “F5″.
Here is what I got!




heappy programming :)

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