jump to navigation

Create a master-detail Windows Forms application with EF March 15, 2012

Posted by fofo in C#, Visual Studio 2008, Visual Studio 2010.
Tags: ,
18 comments

I have been teaching in the past few weeks many people on how to use Entity Framework. I have decided to provide some of the samples I am using in my classes.

In this post I will show you a step by step example on how to build a Windows Forms (Master – Details) application with C# and Entity Framework. Have a look in this post if you would like to see how to implement similar functionality with WPF.

First let’s try to define what EF is and why it is going to help us to create easily data-centric applications.Entity Framework is an object-relational mapping (ORM) framework for the .NET Framework.EF addresses the problem of Object-relational impedance mismatch. I will not be talking about that mismatch because it is well documented in many sites on the Internet. Through that framework we can program against a conceptual application model instead of programming directly against a relational schema-model. By doing so we can decrease the amount of code we do write to access a data storage and thus decrease maintenance time.

In my other development blog (ASP.Net blog) you can find many posts on Entity Framework.Have a look if you want.

We will need a database and a version of SQL Server.You can download and install the free SQL Server Express edition from here. If you need the installation scripts for the sample AdventureWorkLT database, click here

Let’s start with our hands-on example.

1) Launch Visual studio 2010 Express edition or any other edition you may have installed.

2) Create a new class library project and name it AWEFModel. Choose C# as your language of development.Ιn this project I will keep my Entities Data Model in a separate project and then I will consume this project from a separate application (Windows Forms)

3) Remove the Class1.cs file.Right – click on your project from the Solutions Explorer window and Add a new Item. From the available templates choose ADO.NET Entity data model. Give it the name ΑdventureWorksLTEntities.edmx and click the Add button.

4) Then the Wizard pops up. Choose “Generate from Database”. Have a look at the picture below

5) Click Next and Create a New Connection (as you see in the picture below) and hit the Continue button.

6) Then follow the instructions as shown in the picture below.Select the local installation of your SQL Server and the database name and then click OK.


7) After you complete the steps above you will see something like the picture below. You can see the Entity connection string and where these setting will be saved.Hit the Next button.Then click Finish

8) If you notice you will see that there is something called Entity connection string that points to the actual database.It is saved in the App.config file of the

9)  Now the wizard will identify the database objects and let us choose which database objects we want to include in our model.I included all the database objects.Hit the Finish button.Ι will include only some of the tables. Have a look at the picture below

Finally, Visual Studio will add the model to the project and will add the necessary references.

10) Have a look at your entity model as it is visualized in the Entity Model Designer. Have a look at the Entity classes and their relationships/associations.Have a look at the properties of each Entity class. Have also a look at the Navigation Properties of each entity class.Basically the entity framework generates classes for all the entities in the designer. You can have a look at the generated code if you want by opening the class file, which in my case is AdventureWorksLTEntities.Designer.cs.

11) Add a new project to your solution, a Windows Forms Application. Name it WindowsFormsEFMD. Add a reference to the System.Data.Entity  and the Entity Framework Model project (AWEFModel)

12) Copy paste the App.config file from the AWEFModel project to the WindowsFormsEFMD project.

13) We will add a datasource to the Windows Forms application (Data–> Add new Datasource). We will add a datasource for the Customer Entity. In the wizard that pops up (Choose a Data Source Type) select Object and then click Next.In the Select the Data Objects choose from the AEFModel(It is already in the there) the Customer class /entity. Change the Customer Entity from GridView to Details. Drag and drop the Customer Entity from the Data Sources to the Form1 window.

Have a look at the picture below to see what I mean

Drag and drop from the Data Sources (SalesOrdersHeaders) entity to the Form1 form.

Have a look at the picture below.

14) In the Form1_Load event handling routine type,


private void Form1_Load(object sender, EventArgs e)
{
var ctx = new AdventureWorksLTEntities();

var query = ctx.Customers.Where(c=>c.SalesOrderHeaders.Any());

customerBindingSource.DataSource = query.ToList();

}

15) Ι am querying the database to find only customers that have orders. Run your application.

16) I will show you how easy it is to make changes. Please note that all the changes are made to the entities in the memory and then are persisted back to the database.

17) Go to the customerBindingNavigator control in the Form1 design view.Select the “Save” button and enable it (right-click on it).

18) Then in the customerBindingNavigatorSaveItem_Click event handling routine type.


private void customerBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{

      ctx.SaveChanges();
    }

I have made a very small change in the code. I have instantiated the context outside of the local scope

public partial class Form1 : Form
{      AdventureWorksLTEntities ctx = new AdventureWorksLTEntities();

public Form1()
{
InitializeComponent();
}

19) The ctx.SaveChanges() method persists the changes to the database.Run your application and make some changes in the Customers Grid. Click the Save button to persist the changes back to the database. Launch SQL Profiler to see what actually happens in the database.

Leave a comment if you need the source code.

Hope it helps!!!!

Advertisements

How to configure WAS for TCP endpoints in IIS March 5, 2012

Posted by fofo in C#, Visual Studio 2008, Visual Studio 2010, WCF, WCF Service.
Tags: ,
3 comments

In this post I would like to show you how to activate Windows Activation Services or WAS for TCP based activation.What this means is that it is possible to host WCF Services in IIS and expose TCP endpoints. Recently I have posted 3 posts on WCF hosting options. You can find them here , here and here.

1) We need to create our WCF Service first.We will use the exact same example we used when we hosted a WCF Service in IIS (full version) .Click here to see this post. You have to follow all the steps as they were described in that post. After you finish all the steps in that post you will have successfully hosted a WCF Service in IIS.

2) I will show you how to install WAS in your machine.Go to the Control Panel–> Program and Features and select Turn Windows features on or off.Then you need to select some options/components to install. Have a look at the picture below to see what those options are

3) Now I need to run some commands to enable TCP and other protocols on the Default Web Site. I will do that using the appcmd command.Open a Visual Studio 2010 command prompt as an administrator and browse to this folder C:\Windows\System32\inetsrv. Then type appcmd.exe set site “Default Web Site” -+bindings.[protocol=’net.tcp’,bindingInformation=’808:*’] and hit Enter.Then in the new command prompt type appcmd.exe set site “Default Web Site” -+bindings.[protocol=’net.pipe’,bindingInformation=’*’] and hit Enter. Then in the new command prompt type appcmd.exe set site “Default Web Site” -+bindings.[protocol=’net.msmq’,bindingInformation=’localhost’]

Hopefully these commands will execute successfully and these protocols are enabled on the Default Web Site.Now we need to enable those protocols on the CalculatorServiceSite website that hosts our WCF service.In the same Visual Studio 2010 command prompt window type

appcmd.exe set app “Default Web Site/CalculatorServiceSite /enabledProtocols:http,net.pipe,net.tcp,net.msmq

Now we have enabled those protocols for our site.Now we are ready to expose endpoints over alternate protocols e.g TCP,MSMQ. In this way we can have our WCF Service hosted in IIS and still consume it over the network with clients that support/understand the TCP/IP protocol.

Hope it helps!!!

Self-hosting WCF Services March 4, 2012

Posted by fofo in C#, Visual Studio 2008, Visual Studio 2010, VS 2010, WCF, WCF Service.
Tags:
5 comments

In this post I will show you how to host a WCF Service in your own applications.This is referred as self hosting, meaning the hosting of a WCF Service in a Console application or a Windows Forms application.  This is the third post in a series of posts on the various options we have when it comes to hosting WCF Services.If you want to know how to host the WCF Service in IIS have a look in this post.If you want to find out how to host a WCF Service in a windows service click here.

I will use a simple a WCF service that just completes some basic math tasks.The main focus in this post is not to implement a very complicated WCF Service. The main focus is demonstrating how to host the WCF Service in a console application.

Let’s build the WCF Service first.

1) Launch Visual Studio as an Administrator. From the available templates use “WCF Service Library”. Choose a suitable name for that project.I have named mine WCFCalcService. I will use C# as the development language.

2) Rename the IService.cs and Service.cs to ICalculator.cs and Calculator.cs

3) I will not be deleting anything from the existing code in those files. I will add some code in the ICalculator.cs

[ServiceContract]
public interface ICalculator
{

[OperationContract]
double Add(double a1, double a2);

[OperationContract]
double Multiply(double a1, double a2);

[OperationContract]
string GetData(int value);

[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);

// TODO: Add your service operations here
}

// Use a data contract as illustrated in the sample below to add composite types to service operations
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";

[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}

[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}

4) Now we need to implement the methods we wrote in the ICalculator.cs file.


public class Calculator : ICalculator
    {

        public double Add(double n1, double n2)
        {
            return n1 + n2;
        }

        public double Multiply(double n1, double n2)
        {
            return n1 * n2;
        }

        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }

5) Build and run your application.Visual Studio will launch the WCF Test Client  so we can test the service.The service will be hosted in the WCF Service Host application that VS launches automatically.Test that the service works as expected.

6) I am going to add a new project in my solution, a Console application and in there I will be hosting my service.I have named this new project CalcServiceHost.I am going to add a few references to this project.The first one will be to the System.ServiceModel and the second one will be to the WCF Service WCFCalcService. Then I am going to create a new instance of a class called ServiceHost inside the Program.cs file and specify the type of service (Calculator) that I want to host. Then I will open the host and by opening the host I will be able to read the configurations about our service from the config file and build the runtime to support all the endpoints that has found.

The whole code follows


static void Main(string[] args)
{

ServiceHost host = new ServiceHost(typeof(Calculator));

host.Open();

Console.WriteLine("Service is up and running");

Console.ReadLine();

host.Close();

}

7) Now we need to add a configuration file (app.config) to my Console project so I can configure my endpoints.The whole code for the app.config file follows

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="NewBehavior0">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="NewBehavior0" name="WCFCalcService.Calculator">
<endpoint address="main" binding="basicHttpBinding" bindingConfiguration=""
contract="WCFCalcService.ICalculator" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/calcservice" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>

You can type the code in the app.config file. There is full Intellisense support. You can also use the WCF configuration tool to achieve the same thing.I am not doing anything difficult. I set a base address for the service and configure an endpoint.I also enable the service’s metadata.

Hit CTRL+F5 and you will see the hosting console application with the message “Service is up and running”.If you launch your favorite browser and type

http://localhost:8080/calcservice&#8221; in the URL address, you will be able to browse to the WSDL definition of the service.

8) Now we can test the WCF service from the test client.Open a Visual Studio command prompt (Administrator) window and type

wcftestclient “http://localhost:8080/calcservice&#8221; and hit Enter. It is going to talk to our service and find its metadata.It is going to launch the familiar test client so we test the service.Test the WCF Service to see if it works as expected.Have a look at the picture below.

9) We see that the WCF service works as expected. If you close the Console application that hosts the WCF service, nothing will work.

Leave a comment if you want the source code.

Hope its helps!!!!

Host WCF Services in Window Services March 4, 2012

Posted by fofo in C#, Visual Studio 2008, Visual Studio 2010, WCF, WCF Service.
Tags: , ,
2 comments

In this post I will show you how to host a WCF Service in a Windows service.This is the second post in a series of posts on the various options we have when it comes to hosting WCF Services.If you want to know how to host the WCF Service in IIS have a look in this post.

I will use a simple a WCF service that just completes some basic math tasks.The main focus in this post is not to implement a very complicated WCF Service. The main focus is demonstrating how to host the WCF Service in IIS.

Let’s build the WCF Service first.

1) Launch Visual Studio. From the available templates use “WCF Service Library”. Choose a suitable name for that project.I have named mine WCFCalculatorService. I will use C# as the development language.

2) Rename the IService.cs and Service.cs to ICalculator.cs and Calculator.cs

3) I will not be deleting anything from the existing code in those files. I will add some code in the ICalculator.cs

[ServiceContract]
public interface ICalculator
{

[OperationContract]
double Add(double a1, double a2);

[OperationContract]
double Multiply(double a1, double a2);

[OperationContract]
string GetData(int value);

[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);

// TODO: Add your service operations here
}

// Use a data contract as illustrated in the sample below to add composite types to service operations
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";

[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}

[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}

4) Now we need to implement the methods we wrote in the ICalculator.cs file.


public class Calculator : ICalculator
    {

        public double Add(double n1, double n2)
        {
            return n1 + n2;
        }

        public double Multiply(double n1, double n2)
        {
            return n1 * n2;
        }

        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }

5) Build and run your application.Visual Studio will launch the WCF Test Client  so we can test the service.The service will be hosted in the WCF Service Host application that VS launches automatically.Test that the service works as expected.

6) Now we need to add a new project to our solution.I will add a Windows Service project and will name it WindowsServiceHost.This is the project that will host our WCF Service.

7) In the Service1.cs[Design] hit F4 to make the Properties window visible – and change the Name and ServiceName properties to CalculatorServiceHost.

8) We need to add some references to the Windows Service project – WindowsServiceHost. We need to add references to the System.ServiceModel and to the WCF Service Library project –WCFCalculatorService.

9) Let’s write some code inside the Service1.cs file.

public partial class CalculatorServiceHost : ServiceBase
    {

        ServiceHost host = new ServiceHost(typeof(Calculator));

        public CalculatorServiceHost()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            host.Open();
        }

        protected override void OnStop()
        {
            host.Close();
        }
    }

We construct a ServiceHost instance based on the Calculator Service class.Then we need to open the host ( host.Open() ) in the OnStart() method.We also need to close the host in the OnStop method ( host.Close() )

10) Then we need to add an app.config file in the WindowsServiceHost project.Inside this app.config file we will have the endpoints definition that is absolutely necessary.We copy the app.config from the WCFCalculatorService to the WindowsServiceHost project.

11) Now we need to add an installer to our project. We go to the Service1.cs[Design] right-click and choose “Add Installer”

12) In the ProjectInstaller.cs [Design] we select the service serviceProcessInstaller1 and hit F4 to show the properties window.Choose the Account property and set it to the LocalSystem.

13) Now we need to build the project and then we need to install and test the windows service.I will launch a Visual Studio 2010 command prompt window as an Administrator and then I will move to the WindowsServiceHost folder.In my case I type in the command prompt cd for blog\WCFCalculatorService\WindowsServiceHost\bin\Debug and hit Enter.Then I type

installutil WindowsServiceHost.exe”.Hopefully after that the service is installed.Go to the Services snap-in from the Control Panel->Administrative Tools.You will see the service CalculatorServiceHost (in my case) installed and you need to start it.

Have a look at the picture below

12) Now we have the WCF service hosted and we can get to its WSDL definition by opening a web browser and type in the URL address “http://localhost:8732/Design_Time_Addresses/WCFCalculatorService/Service1/“. In my case it works just fine and it provides me with the WSDL definition of the service.If you stop the service from the Services console and hit CTRL+F5 in the browser window then you will fail. So it is quite clear now that the service is hosted in the Windows service.

13) Now we can test the WCF service from the test client.Open a Visual Studio command prompt window and type

wcftestclient http://localhost:8732/Design_Time_Addresses/WCFCalculatorService/Service1/ and hit Enter. It is going to talk to our service and find its metadata.It is going to launch the familiar test client so we test the service.Test the WCF Service to see if it works as expected.

Have a look at the picture below to see what I mean.

We managed to host a WCF Service in a Windows Service and test its functionality by using the WCF Test Client provided by VS.

Email me if you need the source code.
Hope it helps!!!!!

Hosting WCF Services in IIS March 3, 2012

Posted by fofo in C#, Visual Studio 2010, WCF, WCF Service.
Tags: , ,
7 comments

I am going to start a series of posts regarding the various options we have when we want to host a WCF Service. I am going to show you (in seperate posts) how to host WCF Services in IIS, in Window Services and self-host them.

In this post I will show you to host WCF Services in ASP.Net Web Applications in IIS.I will use a simple a WCF service that just completes some basic math tasks.The main focus in this post is not to implement a very complicated WCF Service. The main focus is demonstrating how to host the WCF Service in IIS.

Let’s build the WCF Service first.

1) Launch Visual Studio. From the available templates use “WCF Service Library”. Choose a suitable name for that project.I have named mine WCFCalculatorWebHost. I will use C# as the development language.

2) Rename the IService.cs and Service.cs to ICalculator.cs and Calculator.cs

3) I will not be deleting anything from the existing code in those files. I will add some code in the ICalculator.cs

[ServiceContract]
public interface ICalculator
{

[OperationContract]
double Add(double a1, double a2);

[OperationContract]
double Multiply(double a1, double a2);

[OperationContract]
string GetData(int value);

[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);

// TODO: Add your service operations here
}

// Use a data contract as illustrated in the sample below to add composite types to service operations
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";

[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}

[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}

4) Now we need to implement the methods we wrote in the ICalculator.cs file.


public class Calculator : ICalculator
    {

        public double Add(double n1, double n2)
        {
            return n1 + n2;
        }

        public double Multiply(double n1, double n2)
        {
            return n1 * n2;
        }

        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }

5) Build and run your application.Visual Studio will launch the WCF Test Client  so we can test the service.The service will be hosted in the WCF Service Host application that VS launches automatically.Test that the service works as expected.

6) Now we are ready to host the WCF Service in an ASP.Net web application.Add a new website project to your solution.Αdd a WCF Service template.Give it an appropriate name. I have named it CalculatorServiceHost.Delete the IService.cs and Service.cs files from the App_Code special folder.

7) Add a reference to the WCF Service in the CalculatorServiceHost project.Right-click to the CalculatorServiceHost and simply choose add a reference and browse until you find the WCF Service and click OK in the dialog box.

8) Now I need to modify the Service.svc file in my hosting application project. I rename it firstly to Calculator.svc. The contents of this file are something like this

<%@ ServiceHost Language="C#" Debug="true" Service="WCFCalculatorWebHost.Calculator" %>

We have to locate the service in the Service attribute.What we have done now is to tell ASP.Net how to map requests to the .svc file to the WCF Service Library assembly.

9) Select the CalculatorServiceHost project and hit Ctrl+F5.The service will be hosted in the ASP.Net development server.In my case the address (the service is hosted) is

http://localhost:18578/CalculatorServiceHost/Calculator.svc

Have a look at the picture below to see what I mean.

10) Now we need to launch the test client.Open a Visual Studio command prompt window and type

wcftestclient http://localhost:18578/CalculatorServiceHost/Calculator.svc and hit Enter. It is going to talk to our service and find its metadata.It is going to launch the familiar test client so we test the service. Have a look at the picture below.

11) Now we need to host the service inside IIS ( the full version ). I assume that you have it installed or know how to install it. If you need any help have a look at this post.

12) Go to Start–>Run and type inetmgr to launch the IIS console.Go to the Default Web Site inside the console and add an Application.Give in a name in the Alias field. I have named it CalculatorServiceSite.Then in the Physical Path browse to the application (CalculatorServiceHost in my case) we created previously to host the WCF service in the ASP.Net development server and click OK. Have a look at the picture below.

Now choose CalculatorServiceSite and switch to the Content View.There you can find the Calculator.svc file.Right-click on this file and hit Browse.Now notice that I am hosting inside the full version of IIShttp://localhost/CalculatorServiceSite/Calculator.svc.Notice there is no port number.Have a look at the picture below.

13) Now we need to launch the test client again.Open a Visual Studio command prompt window and type

wcftestclient http://localhost/CalculatorServiceSite/Calculator.svc and hit Enter. It is going to talk to our service and find its metadata.It is going to launch the familiar test client so we test the service. Have a look at the picture below.

I have demonstrated how to host the WCF Service we created, in IIS and then use the default test client application provided by the VS to talk to it and test its functionality.You could obviously build your own client and test it.

Email me if you need the source code.

Hope it helps!!!