break
May 28

When I had a WCF Service, the next step was to host the WCF Service. I was amazed when I noticed that the Class1.cs file (created by visual studio while I was trying to create a WCF Service Library project) has instructions of how to host a WCF service.

They suggest this can be done in 9 steps:
1- Create a Host project. I personally added a new project to the solution that had the WCF service. To do this you right click the solution, select add, select new project, and then I choose a Console Application project.

2- Add to your host project a CodeFile, which is a blank C# file.
3- In this blank codefile you need to pase a code they provide in the Class1.cs file which is the following:

using System;
using System.ServiceModel;
internal class MyServiceHost
{
internal static ServiceHost myServiceHost = null;
internal static void StartService()
{
//Consider putting the baseAddress in the configuration system
//and getting it here with AppSettings
Uri baseAddress = new Uri("http://localhost:8080/service1");
//Instantiate new ServiceHost
myServiceHost = new ServiceHost(typeof(WCFServiceLibraryExample.service1), baseAddress);
//Open myServiceHost
myServiceHost.Open();
}
internal static void StopService()
{
//Call StopService from your shutdown logic (i.e. dispose method)
if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}
}

If you notice this internal class has an instantiated object of the ServiceHost class set to null. A ServiceHost class according to MSDN “implements the host used by the Windows Communication Foundation (WCF) service model programming model”. This instantiation of the class (myServiceHost) will help us to start and stop our service. Notice that the open and close of the service happens inside the methods StartService and StopService. This methods will be extremely helpful when we will attempt to write a little console application that can start and stop our service.

4-At this point we need to add an Application Configuration File to our host project.
5-In this blank App.config file you need to pase a code they provide in the Class1.cs file which is the following:

<system.servicemodel>
<services>
<service name=”WCFServiceLibraryExample.service1″>
<endpoint contract=”WCFServiceLibraryExample.IService1″ binding=”wsHttpBinding”>
</endpoint>
</service>
</services>
</system.servicemodel>

The tag “system.servicemodel” you could think of it as the tag you use to start connecting web service. In the “services” tag you can specify a specific “service” which you need to give a name with the name attribute of the service tag. Inside the “service” tag you specify the “endpoint” and the contract attribute of the endpoint tag. The contract attribute (which is what the endpoint is going to communicate to the outside world about our service) will be the interface that I had in my example “WCF: Creating a WCF Service”.
6- After this you want to add the code that will host, start and stop the service. This is my code for this step:

using System;
using System.Collections.Generic;
using System.Text;
namespace WCFConsoleService
{
class Program
{
static void Main(string[] args)
{
MyServiceHost.StartService();
Console.WriteLine("To stop the service type 'e'");
string exit = Console.ReadLine();
while (!exit.Equals("e"))
{
Console.WriteLine("To stop the service type 'e'");
exit = Console.ReadLine();
}
MyServiceHost.StopService();
}
}
}

I basically start the service, and wait for the user to type the character ‘e’ to stop the service.
7- After this you need to add a Reference to System.ServiceModel.dll in your host project. This is required because in your codefile the namespace System.ServiceModel is used. To do this right click on your host project, select add reference,select “System.ServiceModel.dll” in the .NET tab.
8- Now you need to add a Reference from your Host project to your Service Library project. To do this right click on your host project, select add reference, and in the projects tab select your wcf service project.
9-Set the host project as the “StartUp” project for the solution.

After this step you are ready to host your WCF Service. You can press F5 in Visual Studio and you should see a console with the following message:

This means your wcf service is running and you can stop it by pressing ‘e’. If you go to http://localhost:8080/service1 you should see the following:

Congratulations, you are now hosting a WCF Service.

May 28

I was trying to create a WCF Service Library in order to get more familiar with WCF. When I created a WCF Service Library project, a Class1.cs file was created.

This file has an interface and a public class that implements the interface. Basically just by creating a WCF Service Library project you get a WCF Service example. What’s good about this example, is that if you are new to this, you can use this example as a guideline to create your own WCF Service. I’m going to explain the file created by visual studio.

Class1.cs
using System.ServiceModel;
[ServiceContract()]
public interface IService1
{
[OperationContract]
string MyOperation1(string myValue);
[OperationContract]
string MyOperation2(DataContract1 dataContractValue);
}

If you noticed before the interface it says [ServiceContract()]. According to MSDN this is “a collection of Operations that specifies what the Endpoint” (when 2 entities are transferring data, the endpoint is the name for an entity on one end of the transfer ) “communicates to the outside world. Each operation is a simple message exchange.”

So basically the outside world is only going to be able to communicate with the methods MyOperation1 and MyOperation2 in this WCF Service. This methods need to be annotated with the attribute [OperationContract]. This is because they are methods of the service.

The implementation of the interface is

public class service1 : IService1
{
public string MyOperation1(string myValue)
{
return "Hello: " + myValue;
}
public string MyOperation2(DataContract1 dataContractValue)
{
return "Hello: " + dataContractValue.FirstName;
}
}

This class is very straightforward, it inherits an interface, and implements the methods of the interface. However if you notice the method MyOperation2 receives a DataContract1 parameter. This is a class this file created by visual studio also provides. I’ll show the code of this class and explain some interesting things about the class.

[DataContract]
public class DataContract1
{
string firstName;
string lastName;
[DataMember]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
[DataMember]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}

Before the class definition there is something like this [DataContract]. According to MSDN “a data contract is an abstract description of a set of fields with a name and data type for each field”. In this case the set of fields of the class will be firstName and lastName, the data type will be string. In this class only properties that include [DataMember] will be accessed.

May 21

I was trying to convert an object to a long in C# and tried it like this at first:

value = row.Cells[columnIndex].Tag as long;

I got the following error:

“The as operator must be used with a reference type (’long’ is a value type)”

The Solution

value = Convert.ToInt64(row.Cells[args.ColumnIndex].Tag);

Using Convert.ToInt64 will let you convert an object to a long.

May 17

When I usually display data in a datagrid, I have a DataSet, i fill the dataset, and then assign it to the datasource of the datagrid. But what if you need to control the way the records are displayed in the datagrid?

For example, if i have a table called “Employees”, and i bind the dataset to the datagrid, the results will be displayed like this:

ID Name

1 Daniel

2 Lesseps

3 Isaacs

4 Diaz

But what if you would like to have control of the data and display it like this:

ID Name ID Name

1 Daniel 2 Lesseps

3 Isaacs 4 Diaz

This can be done setting the datagridview in a Virtual Mode. Virtual Mode according to the Visual Studio description “indicates whether you have provided your own data-management operations for the DataGridView Control”.

In order to display data in a datagridView in virtual mode you need to set the VirtualMode property in the datagridview to True and handle the dataGridView1_CellValueNeeded event.

In the following example I have a struct which will hold data about an employee , specifically their name and id. I’m going to initialize the data, create the columns of the datagridview, and finally I’m going to implement the event that is going to display the data as I want it.


public partial class Form1 : Form
{
private List< Employee > m_Employees = new List< Employee >();
public Form1()
{
InitializeComponent();
InitializeData();
CreateColumns();
}
///


/// Create and initialize several Employee structures
/// and add them to a List.
///

private void InitializeData()
{
Employee emp = new Employee();
emp.id = 1;
emp.name = “Daniel”;
Employee emp2 = new Employee();
emp2.id = 2;
emp2.name = “Lesseps”;
Employee emp3 = new Employee();
emp3.id = 3;
emp3.name = “Isaacs”;
Employee emp4 = new Employee();
emp4.id = 4;
emp4.name = “Diaz”;
m_Employees.Add(emp);
m_Employees.Add(emp2);
m_Employees.Add(emp3);
m_Employees.Add(emp4);
}
///
/// Create the datagridView columns, give them
/// a name and finally I add two rows
///

private void CreateColumns()
{
// create four columns
dataGridView1.ColumnCount = 4;
dataGridView1.Columns[0].Name = “ID”;
dataGridView1.Columns[1].Name = “Name”;
dataGridView1.Columns[2].Name = “ID”;
dataGridView1.Columns[3].Name = “Name”;
// add two rows
dataGridView1.Rows.Add();
dataGridView1.Rows.AddCopies(0, 1);
}
///
/// In this event, I manage the way the data is displayed in the datagridView.
/// If it’s the first column and the first row I add the first record id.
/// If it’s the first column and the second row I add the third record id.
/// If it’s the third column and the first row I add the second record id.
/// If it’s the third column and the second row I add the fourth record id.
///

private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
if (e.ColumnIndex == 0)
{
if (e.RowIndex == 0)
{
e.Value = m_Employees[e.RowIndex].id;
}
else
{
e.Value = m_Employees[e.RowIndex + 1].id;
}
}
else if (e.ColumnIndex == 1)
{
if (e.RowIndex == 0)
{
e.Value = m_Employees[e.RowIndex].name;
}
else
{
e.Value = m_Employees[e.RowIndex + 1].name;
}
}
else if (e.ColumnIndex == 2)
{
if (e.RowIndex == 0)
{
e.Value = m_Employees[e.RowIndex + 1].id;
}
else
{
e.Value = m_Employees[e.RowIndex + 2].id;
}
}
else if (e.ColumnIndex == 3)
{
if (e.RowIndex == 0)
{
e.Value = m_Employees[e.RowIndex + 1].name;
}
else
{
e.Value = m_Employees[e.RowIndex + 2].name;
}
}
}
}
struct Employee
{
public int id;
public string name;
}

I believe the code is pretty easy to understand, I would only like to point out that in the event that handles the way the data is displayed, in this line for example:
e.Value = m_Employees[e.RowIndex].id;
The ID of the employee is added to a cell in the datagridView.

Hope this was helpful to you. If there are any questions or observations , they will be highly appreciated.

May 10

I have a contextMenuStrip with 2 items. I have several columns in my datagridview, and I wanted to display one menu when the user right clicks on a specific column (named Allocated), and display the other menu when the user right clicks on any other column.

There’s not an event in a datagridview for a right click, but to do this you can use the CellMouseDown event, and find out there if the user did a right click.

Here’s a solution to this problem:
private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
string column = dataGridView.Columns[e.ColumnIndex].Name;
if (column == "Allocated")
{
contextMenuStrip1.Items[0].Visible = false;
contextMenuStrip1.Items[1].Visible = true;
}
else
{
contextMenuStrip1.Items[0].Visible = true;
contextMenuStrip1.Items[1].Visible = false;
}
}
}

Basically in this line : if (e.Button == MouseButtons.Right)
You find out, if the user did a right click with their mouse.