Pages

Wednesday, September 26, 2012

WCF Service Returns List of Objects to WPF DataGrid

Today we will build WCF service that returns a list of objects, an Employee objects, in our case. And we will build a WPF client application which will show the result in DataGrid.

First, let's create WCF service. Choose WCF Service Application from the list:
Add new project (WCF Service)
Visual Studio will automatically create template project with IService.cs and Service.svc files, where actually all the service logic will be written. I added the Employee class and edited Service.cs and IService.cs in order to service be able to return a list of employees. Let's see:

Saturday, September 22, 2012

C# Custom Event Handling

There are a lot of examples on Event Handling and delegates in C# on the net, but most of them are just too complicated and confusing for a beginner. Today I'd like to share with you simple and clear example of event handling with custom event arguments.

Imaging that we have a simple Employee class. There are two properties - Name and Salary. We want a mechanism that will indicate that employee's salary has changed.Obviously we need create an event inside our Employee class and fire it each time when salary has changed.
Let's see Employee class source code:
public class Employee
{
    public delegate void PropertyChangedHandler(object sender, PropertyChangeEventArgs args);

    public event PropertyChangedHandler PropertyChange;

    public void OnPropertyChange(object sender, PropertyChangeEventArgs args)
    {
        // If there exist any subscribers call the event
        if (PropertyChange != null)
        {                
            PropertyChange(this, args);
        }
    }

    public string Name { get; set; }

    private int _salary = 5000;
    public int Salary
    {
        get { return _salary; }
        set
        {
            int oldValue = _salary;
            _salary = value;
            OnPropertyChange(this, new PropertyChangeEventArgs("Salary", value - oldValue));
        }
    }
}

Tuesday, September 18, 2012

C# Get Assembly Location Path

Often when developing different applications or services you need to know where is actually your exe or a dll located. For example, you developing a service which will create some files and directories in the same place where the service is running, so you need to know somehow in the run time the path to your service dllFortunately for these purposes we have Reflection mechanism in C#. 
First, include reflection library in your code:
using System.Reflection;

Now, to get the path to the assembly in the run time - use this command:
string assemblyPath = Assembly.GetAssembly(typeof(ClassName)).Location;

Or if you need the path to the assembly directory then you can apply this code:
string directoryPath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(ClassName)).Location);