Pages

Monday, December 24, 2012

C# Object-to-Object Mapping - AutoMapper Example

Imaging this scenario: We have an Employee object with many properties in it, and we want to display our Employee in a DataGrid or some other control. For this purpose we need a lighter version of Employee, let's call it EmployeeViewItem. A list of EmployeeViewItem will need to bind to our DataGrid.
public class Employee
{
    public string Name { get; set; }
    public string Email { get; set; }
    public Address Address { get; set; }
    public string Position { get; set; }
    public bool Gender { get; set; }
    public int Age { get; set; }            
    public int YearsInCompany { get; set; }
    public DateTime StartDate { get; set; }
}

public class Address
{
    public string Country { get; set; }
    public string City { get; set; }
    public string Street { get; set; }
    public int Number { get; set; }            
}

public class EmployeeViewItem
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
    public string Position { get; set; }
    public string Gender { get; set; }
    public int Age { get; set; }            
    public int YearsInCompany { get; set; }
    public string StartDate { get; set; }
}
Ok, so what we usually do? Something like this, right?
EmployeeViewItem viewItem = new EmployeeViewItem();
viewItem.Name = employee.Name;
viewItem.Email = employee.Email;
viewItem.Address = employee.Address.City + employee.Address.Street + employee.Address.Number;
viewItem.Position = employee.Position;
viewItem.Gender = employee.Gender == true ? "Man" : "Female";
viewItem.Age = employee.Age;
viewItem.YearsInCompany = employee.YearsInCompany;
viewItem.StartDate = employee.StartDate.ToShortDateString();
Quite annoying, isn't it? What if we could do this mapping automatically in some way? I hasten to please you - yes, you can map these two object automatically with AutoMapper! As written on AutoMapper webpage - "AutoMapper is a simple little library built to solve a deceptively complex problem - getting rid of code that mapped one object to another."

Saturday, December 1, 2012

C# Reading XML Recursively (XmlDocument)

I'll be honest - I hate Recursion! But, nothing you can do, there are some situations when you know - this problem should be solved with Recursion. One of such problems is XML reading.
Today I'll show a simple example of reading XmlDocument recursively.

This is our XML:
<employees>
    <employee Id="1001" Name="John" Position="Developer">    
        <projects>
            <project Code="Rocket">                
                <budget>7000</budget>
            </project>
        </projects>
    </employee>

    <employee Id="1002" Name="Tomas" Position="Helpdesk">    
        <projects>
            <project Code="Orlando">                
                <budget>1000</budget>
            </project>
            <project Code="Newman">                
                <budget>900</budget>
            </project>
        </projects>
    </employee>
    
    <employee Id="1003" Name="Susan" Position="QA">        
        <projects>            
            <project Code="Newman">                
                <budget>900</budget>
            </project>
            <project Code="Rocket">                
                <budget>7000</budget>
            </project>
            <project Code="Orlando">                
                <budget>1000</budget>
            </project>
        </projects>
    </employee>  
</employees>

Saturday, November 24, 2012

WPF Start New Background Process using Task

In GUI programming there is exist some very common problem - if some operation takes too much time the GUI will become unresponsive. For example, if you want establish connection with a server, or fetch some data from database or a large file, this probably will take some time and if you perform this operation in the main thread your GUI will stuck. In order to keep your GUI responsive you need to run long-running operations on a separate thread. So far, in order to open a new thread we used Thread class or BackgroundWorkerStarting from .NET Framework 4.0 we have a Task class for this purpose. 

If you already switched to Visual Studio 2012 with Framework 4.5 then read my previous post - C# Async Programming Example in WPF (Async, Await).
If you still working with Visual Studio 2010 Framework 4.0 then this post is for you.
Today I'll show how to build WPF application with background thread using Task Framework 4.0.

WPF with new background process using Task Framework 4.0

Sunday, November 18, 2012

C# Async Await Example in WPF

C# 5.0 and .NET Framework 4.5 bring to developer a very nice feature called Asynchronous Programming. Asynchronous Programming is based on Task Parallel Library (TPL). As you probably know traditional techniques for writing asynchronous programs are very complicated in many aspects, so Async Programming comes to make our life easier when we write Multithreading applications. 

Today we'll see a very simple example of Async Programming using Async, Await and Task keywords in WPF application. Let's build a simple WPF application with a button and a textbox. By pressing the button we call for some slow method (I named it SlowDude :). I don't want GUI will be locked until the method will finish his job. In other words I want to call that method asynchronously.

C# 5.0 Asynchronous Programming with WPF GUI

Friday, November 16, 2012

C# Application Performance Wizard in Visual Studio

If you want to know how much resources your C# application consumes there is a very nice tool in Visual Studio for this purpose. It allows you to see how much CPU your program uses, amount of memory allocated for it, how much time your program running and many other useful things. Today I'll show how to build a performance test for your C# program in Visual Studio.

Ok, let's suppose we've created some C# application in Visual Studio. In order to run Performance Wizard go to main menu and click on Analyze and Launch Performance Wizard.

Launch Performance Wizard in Visual Studio 2010

Friday, November 9, 2012

7 Regular Expressions a C# Developer Must Know

Regular expressions, aka Regex, are very commonly used by any developer no matter what language he's writing his program. Today I'll show the most useful Regex that sooner or later you will need them.

1. URL Regex:

^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$

Match:
http://www.codearsenal.net/


Not Match:
http://www.codearsenal.net?/



2. IP Address Regex:

^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

Match:
73.180.213.135


Not Match:
255.255.255.256


Saturday, November 3, 2012

WPF ObjectDataProvider - Binding Enum to ComboBox

Let's say we created some Enum data type. Now we want to show our Enum values on WPF ComboBox or ListBox. How do we do that?
In order to achieve this, in WPF we have an ObjectDataProvider class which provides mechanism for creation a XAML object available as a binding source.
Here is our Enum:
public enum TimePeriods
{
    Year,
    Month,
    Day,
    Hour,
    Minute
}
Now let's see how we bind it to a ComboBox in XAML:

Saturday, October 20, 2012

C# Writing Custom Configuration Settings Section

Almost every C# application has its own Configuration Settings file also known as App.Config. If you look on your App.Config file you probably will see a list of key value pairs:
<add key="key0" value="value0" />
<add key="key1" value="value1" /> 
<add key="key2" value="value2" />
... 
But what if you need some more complex configurations? Something like this:
<MySection>
    <MySettings MyKey="John" MyValue1="Developer" MyValue2="Expert"/>
    <MySettings MyKey="Tomas" MyValue1="Developer" MyValue2="Junior"/>    
    <MySettings MyKey="Robert" MyValue1="Developer" MyValue2="Senior"/>
    <MySettings MyKey="Kurt" MyValue1="IT" MyValue2="Expert"/>
    <MySettings MyKey="Anna" MyValue1="HR" MyValue2="Senior"/>    
</MySection>
Today I'll show how to build this kind of Custom Configuration Settings in C#.

Saturday, October 13, 2012

Speech Synthesizer in WPF

I recently came across with some very interesting feature in C# - Speech Synthesizer! Speech Synthesizer is Microsoft API which allows to build speech enabled applications. Just one row of code and your WPF application will spell any textual data!
All you need is just add a reference to System.Speech.Synthesis and a couple rows of code. I built a simple application just to show how to use Speech Synthesizer in WPF.
Speech Synthesizer in WPF
Here is the XAML code of the GUI:
<TextBox Grid.Column="0" Grid.Row="0"
         HorizontalAlignment="Left"
         TextWrapping="Wrap"
         AcceptsReturn="True"
         VerticalScrollBarVisibility="Visible"
         FontSize="14"
         Height="100"
         Width="270"
         Name="TextBox_Read">Talk to me!</TextBox>

<Button Grid.Column="1" Grid.Row="1"                
        Name="Button_Say"
        Content="Say" Click="Button_Say_Click"></Button>

<Button Grid.Column="1" Grid.Row="2"                
        Name="Button_Who"
        Content="Who's talking?" Click="Button_Who_Click"></Button>

<Slider Grid.Column="0" Grid.Row="1" 
        Name="Slider_Volume"
        Value="50" Minimum="0" Maximum="100"
        TickFrequency="5" ValueChanged="VolumeChanged"
        ToolTip="Volume"/>

<Slider Grid.Column="0" Grid.Row="2" 
        Name="Slider_Rate"
        Value="0" Minimum="-5" Maximum="7" 
        TickFrequency="1" ValueChanged="RateChanged"
        ToolTip="Speech Rate"/>

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);

Tuesday, August 28, 2012

C# DataTable Order By Column


Sometimes when you work with DataSet or DataTable you need to order the data by specific column. The quickest way to sort DataTable by specific column is to convert it to DataView, apply the Sort method and then save back the results to your DataTable. Here is the code sample:
//   Create DataTable and fill out with data
DataTable table = new DataTable();  
table.Columns.Add("EmployeeFirstName", typeof(string));  
table.Columns.Add("EmployeeFamilyName", typeof(string));  
table.Columns.Add("Age", typeof(int));
DataRow row = table.NewRow();
  
row["EmployeeFirstName"] = "Bill";  
row["EmployeeFamilyName"] = "Gates";  
row["Age"] = 56;  
table.Rows.Add(row);  

row = table.NewRow();  
row["EmployeeFirstName"] = "Steve";  
row["EmployeeFamilyName"] = "Ballmer";  
row["Age"] = 57;  
table.Rows.Add(row); 

row = table.NewRow();  
row["EmployeeFirstName"] = "Paul";  
row["EmployeeFamilyName"] = "Allen";  
row["Age"] = 59;  
table.Rows.Add(row); 

//  In real life applications, it is critical 
//  to check if your DataTable is not empty!
if (table.Rows.Count > 0)  
{
    //  Convert DataTable to DataView
   DataView dv = table.DefaultView;
   //   Sort data
   dv.Sort = "Age";
   //   Convert back your sorted DataView to DataTable
   table = dv.ToTable();  
}

Wednesday, August 22, 2012

WPF ScrollViewer Control Example


There are two controls that enables scrolling in WPF: ScrollBar and ScrollViewer. The ScrollViewer encapsulates both vertical and horizontal ScrollBar and a container that contains all the visible elements inside scrollable area. I'll show a ScrollBar example based on code described in my previous post.
WPF ScrollViewer example

Tuesday, August 21, 2012

WPF Expander with DataGrid


WPF has a very useful control called Expander. Expander allows you to hide or show any content that is inside of it. Today I'll show you how to use Expander with DataGrid and how to apply a Style to Expander's Header.
Collapsed WPF Expander with style and DataGrid inside of it
Collapsed state
Expanded WPF Expander with style and DataGrid inside of it
Expanded state

Saturday, August 11, 2012

C# Write to Windows Event Log


As you probably know Windows has its own Event Logging System. You can see the logs in it if you'll run Event Viewer from Administrative Tools. Today I'll show how to write messages into Windows Event Log from your application using C#.
Microsoft Windows Event Viewer

C# LINQ - OrderBy clause

This post is part of a series called LINQ Examples that brings practical examples of using LINQ in C#.

Today we'll see practical examples of using OrderBy, ThenBy clauses in LINQ. This kind of operators in LINQ are called LINQ Ordering Operators.
List<Employee> employees = GetEmployeeList();

var sortedEmployees =
    from e in employees
    orderby e.EmployeeName
    select e;
Console.WriteLine("Employees list ordered by name:");
foreach(var e in sortedEmployees)
    Console.Write(e.EmployeeName + ", ");    /*    Output:    John, Lucas, Marina, Susan, Tomas   */

Saturday, August 4, 2012

C# Entity Framework in Visual Studio 2010

Some time ago I published an article about LINQ to SQL Classes Generation in Visual Studio 2010. Today I'll show how to use a newer version of Microsoft ADO.NET technology called Entity Framework.
ADO.NET Entity Framework enables developers to work directly with object model of a database instead of writing SQL queries. Developers which  already worked with LINQ to SQL will easily switch to Entity Framework, because the overall using of it is pretty similar.

Ok, let's move on to the example. I created a WPF project with a datagrid in the main window and a simple local database with one single table Employees. Now I want to use ADO.NET Entity Framework to fetch data from the database and show it in my datagrid. Final result will look like this:

C# WPF Datagrid with ADO.NET Entity Framework

Monday, July 30, 2012

C# LINQ - Take, Skip, TakeWhile, SkipWhile clauses

This post is part of a series called LINQ Examples that brings practical examples of using LINQ in C#.

Today we'll see practical examples of using Take, TakeWhile, Skip and SkipWhile clauses in LINQ. This kind of operators are called LINQ Partitioning Operators.
int[] numbers = { 1, 3, 9, 8, 6, 7, 2, 0, 5, 10 };

var firstFive = numbers.Take(5);
Console.WriteLine("First five numbers:");
foreach (var x in firstFive)
    Console.Write(x + ", ");    /*    Output:    1, 3, 9, 8, 6    */

var skipFive = numbers.Skip(5);
Console.WriteLine("All but first five numbers:"); 
foreach (var x in skipFive)
    Console.Write(x + ", ");    /*    Output:    7, 2, 0, 5, 10    */

var firstLessThanFive = numbers.TakeWhile(n => n < 5);
Console.WriteLine("First numbers less than five:"); 
foreach (var x in firstLessThanFive)
    Console.Write(x + ", ");    /*    Output:    1, 3    */

var fromFirstEven = numbers.SkipWhile(n => n % 2 != 0);
Console.WriteLine("All elements starting from first even element:");
foreach (var x in fromFirstEven)
    Console.Write(x + ", ");    /*    Output:    8, 6, 7, 2, 0, 5, 10    */

Saturday, July 28, 2012

WPF DataGrid ColumnHeaderStyle (LinearGradientBrush)


This post is part of series called WPF Styles where you can find many different styles for your WPF application.

Due to several requests to share XAML code of the DataGrid style that been used in my examples, today I'm sharing with you a ColumnHeaderStyle. Just to remind, this is how the DataGrid looks like:

WPF DataGrid ColumnHeaderStyle LinearGradientBrush

WPF DataGrid RowStyle (AlternationIndex)


This post is part of series called WPF Styles where you can find many different styles for your WPF application.

Today I will share with you a WPF DataGrid RowStyle that I used recently for my DataGrid. At some point of development I noticed that data inside my DataGrid was really hard to read because of each row had the same color, so I decided to apply a style that will alternate the color for the rows, just like we usually see in excel reports. After applying this style your DataGrid will look like this:

WPF DatagridRow style with AlternationIndex set to 1

Tuesday, July 24, 2012

WPF DataGrid CellStyle (CenterCellStyle)


This post is part of series called WPF Styles where you can find many different styles for your WPF application.

When your DataGrid contains many different controls, the height of a cell in DataGrid increases accordingly. This make your text to look ugly inside the cell.

DataGrid without CellStyle

Sunday, July 22, 2012

C# LINQ - SELECT clause

This post is part of a series called LINQ Examples that brings practical examples of using LINQ in C#.

This time we'll concentrate our attention on SELECT clause. This kind of operators are called LINQ Projection Operators. First example shows use of SELECT with Anonymous Types. We produce a sequence of employees containing employee name and create a new type on the fly called ProjName which indicates the first project that specific employee has participated.
List<Employee> employees = GetEmployeeList();

var emps =
    from e in employees
    select new { e.EmployeeName, ProjName = e.Projects[0].ProjectCode };

foreach (var e in emps)
{
    Console.WriteLine("{0} worked on project {1}.", e.EmployeeName, e.ProjName);
}

/* Output:   
John worked on project Orlando.
Tomas worked on project Orlando.
Marina worked on project Orlando.
Susan worked on project Rocket.
Lucas worked on project Orlando.
*/

Friday, July 20, 2012

C# LINQ - WHERE clause

This post is part of a series called LINQ Examples that brings practical examples of using LINQ in C#.

Today I'll show how to use WHERE clause in LINQ. This kind of operators are called LINQ Restriction Operators. We start from the simplest use of WHERE clause in LINQ - select all numbers from an array less than 10:
int[] numbers = { 15, 42, 14, 3, 9, 83, 64, 76, 23, 0 }; 
      
var lessThanTen = 
    from n in numbers 
    where n < 10 
    select n; 

foreach (var x in lessThanTen) 
{ 
    Console.Write(x + ", ");  // 3, 9, 0
}

Thursday, July 19, 2012

C# Load XML using XLINQ (LINQ to XML)


Today I'll show how to load an XML file into objects using XLINQ (Language Integrated Query for XML).
Imaging that you have an XML file which contains an Employee list with corresponding information about each employee. Now you want to load this list into memory and work with that data. For these purposes we have XLINQ technology which allows you to load the data from XML directly into business objects. 
Let's see how to use XLINQ in C#. First, we need to create our business objects:

Monday, July 16, 2012

Windows Service in C# with Setup


Today I'll show how to build Windows Service in C# using Visual Studio 2010.
First, open Visual Studio and create Windows Service project.

Windows Service Project in Visual Studio 2010

Thursday, July 12, 2012

C# XML Transformation using XSLT


If you have one type of XML and need to transform it to another type, then you can use XSLT for that purposes. For instance in the health care field, there are a lot of XML standards, such as CCD, CCR etc. Sometimes one type of XML need to be transformed to another one. The best way to do it is to use XSLT. You may ask where do you get appropriate XSLT for specific XML transformation? Well, for example I use Altova MapForce. MapForce allows you to do XML transformation manually by simply dragging appropriate attributes. Once you done with that, MapForce will generate an XSLT which you can use then in your code.
Altova MapForce XML Transformation and XSLT Generation
Ok, we got an XSLT file, here is how we use it in C# code in order to transform XML file:

C# Polymorphism Example


How often we use Polymorphism in our programs? Polymorphism is the core of any modern object oriented programming language and we use it daily almost without thinking of it. But do we remember the basics of Polymorphism? Recently I realized that I forgot simple stuff when I was on a job interview. Therefore today I want to remind about Polymorphism basics in C#. Hopefully it will help you to pass your next job interview.
Ok, let's write three simple classes and play with Polymorphism a little bit:

Tuesday, July 3, 2012

WPF DataGrid RowDetailsTemplate

WPF DataGrid provides a Row Details feature. Row details is simply a panel that shown for a selected row. Row Details may contain any thing you want to put there - label, textbox, button, picture...
WPF DataGrid RowDetailsTemplate example

Thursday, June 28, 2012

WPF Menu with Icons

Today I'll show how to build WPF Menu with Icons in XAML. In this example you'll see how to control IsEnabled state of MenuItem from your application. The application looks like this:
WPF Menu with Icons example
Ok, let's see the XAML (MainWindow.xaml):

Thursday, June 21, 2012

WPF TextBox Validation with IDataErrorInfo

There are so many ways for data validation in WPF that sometimes it confuses people. I decided to figure out what's the best way for me to do TextBox validation, which will be enough versatile for different tasks, but also as simple as possible for implementation. I believe a good code must be simple and easy to understand. So today I'll show, for my opinion, the best validation method on TextBox example.

WPF TextBox Validation with IDataErrorInfo

Monday, June 18, 2012

Reversi Game in C# WinForms


Reversi game in C# WinForms

Have you ever played Reversi table game? If not, today you'll play it on your PC!
Check out Reversi game written in C# WinForms using System.Drawing Library.
Today I will not explain the code itself. I don't think it's necessary because the code is pretty simple.
We have a table which is two dimensional array, the rest is logic...
You are welcome to download the source code of this game.

SQL Connection in C# (SqlConnection)

I have a simple SQL script which I need to run on SQL server using C#. The script returns an integer. The best way to do it in C# is to use SqlConnection, SqlCommand and SqlDataReader classes.
Here is the source code how we do it in C#:
using (SqlConnection sqlConnection = 
 new SqlConnection(@"Data Source=SERVER_NAME;Initial Catalog=TABLE_NAME;Integrated Security=True"))
 {
    sqlConnection.Open();
    using (SqlCommand sqlCommand = thisConnection.CreateCommand())
    {
        sqlCommand.CommandText = "SELECT MAX(Salary) Salary FROM STUFF";
    }
    using (SqlDataReader reader = thisCommand.ExecuteReader())
    {
        reader.Read();
        Int32 maxSalary = (Int32)reader["Salary"];
    }
}
As I said before if all you need is to run simple SQL script then this is the best approach for you.
But, If your application will work closely to database, updating and fetching data, then I suggest you to use LINQ to SQL Classes Generation in Visual Studio 2010.

Saturday, June 16, 2012

WPF Binding a Control to Another Control

Today I'll show how to bind a WPF control to another one directly in XAML.
In this example I have a Rectangle control and a Slider.
I want to change Rectangle's width by moving the Slider.
WPF Binding Between Controls Directly in XAML
Let's take a look on XAML:
<Grid>
    <StackPanel>            
        <Rectangle Name="elipse1" 
                   Fill="Black"
                   Margin="10,40"
                   Height="40"
                   Width="{Binding ElementName=slider1, Path=Value}"/>
        <Slider Name="slider1" 
                Minimum="20" 
                Maximum="200"
                Margin="20,0"/>            
    </StackPanel>
</Grid>
The main thing here is actually this string:
    Width="{Binding ElementName=slider1, Path=Value}"
Pretty simple example but I believe it will help to someone.
You are welcome to download the source code (Visual Studio 2010).

Thursday, June 14, 2012

C# Read Excel and Show in WPF DataGrid

In this example I will show how to read data from excel using C# and how to show it in WPF DataGrid.

In order to work with excel in C# you have to add reference to Microsoft.Office.Interop.Excel library.
As I said before I want also show the excel data in WPF DataGrid, so I created ExcelData class which contains Data property. My DataGrid will be bound to this Data property.
Let's see what we got inside of it:

Wednesday, June 13, 2012

WPF Animation (Fifteen Puzzle Game)

I must say WPF is a cool thing! Have you played sometime a Fifteen Puzzle Game?
Check out this Fifteen Puzzle Game as example of WPF Animation.

Fifteen Puzzle Game as example of WPF Animation


LINQ to SQL Classes Generation in Visual Studio 2010

Today I'll explain how to connect to MS-SQL database using LINQ to SQL classes in Visual Studio 2010.
If you building application that will work closely to database, will not only read, but also update the data on SQL server than LINQ to SQL will be extremely comfortable and fast way to work with.
Ok, here is step by step guide how to create LINQ to SQL classes and establish connection with database:

1. Mouse right click on your project in Visual Studio 2010 and choose Add New Item

2. Check LINQ to SQL classes. Visual Studio will generate dbml file for you.

Add New Item - Linq To SQL

Thursday, June 7, 2012

Enum with String (C#)

Sometimes you want to use enum with string values, not exact value of enum, but slightly different.
To achieve this we will create attribute class which will be used for storing string value for each enum.
In addition we need a helper class which will provide possibility to pull out these string values from enum.
OK, here is the attribute class:
public class StringValueAttribute : Attribute
{
    private string _value;
    
    public StringValueAttribute(string value)
    {
        _value = value;
    }
    
    public string Value
    {
        get { return _value; }
    }
}

Sunday, June 3, 2012

WPF Animation (Tower of Hanoi)


A friend of mine implemented well known problem The Tower of Hanoi in WPF.
I think it's a good example of WPF animation, so I decided to share it with you.
Tower Of Hanoi Problem
The Tower of Hanoi Problem
The key of the whole thing is Animate method:

private void Animate(int f, Canvas cn, double x, double y)
{
      Canvas.SetZIndex(cn, Canvas.GetZIndex(cn) * 10);
      DoubleAnimation dax = new DoubleAnimation();
      dax.Duration = new Duration(TimeSpan.FromSeconds(MOVe_SPEED));
      dax.From = cn.RenderTransformOrigin.X;
      dax.To = x;

      DoubleAnimation day = new DoubleAnimation();
      day.Duration = new Duration(TimeSpan.FromSeconds(MOVe_SPEED));
      day.From = cn.RenderTransformOrigin.Y;
      day.To = y;

      TranslateTransform tf = new TranslateTransform();
      cn.RenderTransform = tf;
      tf.SetValue(Canvas.LeftProperty, x);
      tf.SetValue(Canvas.TopProperty, y);
      tf.SetValue(dprop, f);
      tf.SetValue(CanvasProp, cn);

      tf.Changed += new EventHandler(tf_Changed);
      tf.BeginAnimation(TranslateTransform.XProperty, dax);
      tf.BeginAnimation(TranslateTransform.YProperty, day);
}
Please, download the source code here.
Check out another good example of WPF Application which I posted recently - Fifteen Puzzle Game.