jump to navigation

Using Type Converters in WPF July 31, 2011

Posted by fofo in C#, c# 3.0, c# 4.0, general .net, Visual Studio 2008, Visual Studio 2010, VS 2010, WPF, XAML.
Tags:
3 comments

In this post I would like to talk/show you how to implement type conversions in WPF.

We must talk a little bit for Binding in WPF before we move on to explain why we use type converters and show a hands on example.

So what is Binding in WPF? In WPF we can bind any property of any object to any other property of some other object.

Binding is typically done in XAML by using the Binding markup extensions.For example

<TextBox Text=”{Binding Path=Property}” />

The syntax above implies that we do not set the value of the Target to some literal value.

When we use binding in XAML , what really happens is that in runtime we create an instance of the Binding class, setting various properties that affect its behaviour.

We can create bindings in code as well. Basically in WPF it is entirely up to the developer if he will write any XAML code to implement the application.

I strongly recommend to use the XAML approach.

In binding we have a Target object/element. In order for binding to be possible, that object/element must inherit from (be an object of type) FrameworkElement.

In the previous small example, TextBox is a Control and inherits from FrameworkElement class. All controls inherit from that class. So all the WPF controls and their properties/attributes can be part of a Binding situation.

Speaking of properties/attibutes the Target property must be a DepenencyProperty. So the “Text” property in the previous example is a Dependency property.

Obviously we need to have some sort of source to bind to.Any .Net object can be a binding source.We can display customers from a customer object in a ListBox control.

We can bind to datasets and entity classes. We can bind to properties of other elements. For example we can bind the value of a Slider control to a TextBlock.

So we can bind from various sources. Basically any CLR object can play the role of the Binding source.

We can specify the mode of how data flows between the data and the source. So we have

  • TwoWay – Data flows both directions
  • OneWay – Data flows only from the source to the target
  • OneTime – Data flows only from the source to the target but we bind only once to the source. It is a useful only if we do not expect the source to change.
  • OneWayToSource – Data flows from the target to the source, for example, we have a textbox that we tell it not to bother read the initial value from the source but update the source with any value the user types in

In order to have a better idea how binding works have a look at the picture below

So where value converters figure in the above scenario? In many cases the binding source is of a type that needs to be converted so that the target property can bind to.

Value converters are instances of classes that implement the IValueConverter interface.

I will create a hands on example to demonstrate how to use type converters in WPF.

1) Launch Visual Studio 2010/2008. From the available templates, choose a WPF application template.Choose an appropriate name for your application. I have named it WpfApplicationConverters. I will use C# as the development language.

2) We will create a simple WPF application , with a button, 2 comboboxes and a border. The first combobox will load with various font families.Every time the user will select a different font from the combobox the FontFamily attribute of the Button element will reflect those changes.

3) The second combobox will load with integer values ( 1-10). Every time the user selects a different value from this combobox then the BorderThickness property of the Border element will change to reflect this change.

In both cases we need to need some sort of value conversions. The values in the FontFamily Combobox are of type String and we need to convert it to FontFamily type.

The values of the second combobox has integer values.These values need to be mapped to another type, the BorderThickness property.The BorderThickness property has four values.

We need to have some sort of classes where we make the conversion.

4) We need to write the UI first. The XAML for the UI follows

<Window x:Class="WpfApplicationConverters.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">

<StackPanel>

<Border BorderBrush="DarkCyan" >

<StackPanel>

<Grid Height="210">

<Button FontSize="16"  Content="I am a button"  Height="34"  Name="button1" Width="164"   Margin="166,41,161,135" />

<ComboBox Height="32" Name="BorderThicknessComboBox" Width="120" Margin="82,128,289,50"   />

<ComboBox Name="FontFamilyComboBox" Width="136" Height="34"  Margin="243,128,112,48"></ComboBox>

</Grid>

</StackPanel>

</Border>

</StackPanel>

</Window>

5) Run your application and make sure it works.

Now I need to populate the comboxoxes with the initial values. I will use the Loaded event of each control.

I will write the code in the MainWindow.xaml.cs file.

using System.Windows;
using System.Linq;
using System.Collections.Generic;

namespace WpfApplicationConverters
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{

InitializeComponent();
}

private void ThicknessComboBoxSetUp()
{
BorderThicknessComboBox.ItemsSource = Enumerable.Range(1, 10);
BorderThicknessComboBox.SelectedIndex = 0;
}

private void FillComboBoxWithFontFamilies()
{

FontFamilyComboBox.ItemsSource = new List<string>() { "Arial", "Arial Black", "Comic Sans MS", "Courier New", "Georgia",
            "Lucida Sans Unicode", "Times New Roman", "Trebuchet MS", "Verdana" };
FontFamilyComboBox.SelectedIndex = 0;
}

private void FontFamilyComboBox_Loaded(object sender, RoutedEventArgs e)
{
FillComboBoxWithFontFamilies();
}

private void BorderThicknessComboBox_Loaded(object sender, RoutedEventArgs e)
{
ThicknessComboBoxSetUp();
}

6) The code above is very easy to follow and understand.I create two methods ThicknessComboBoxSetup() and FillComboBoxWithFontFamilies() and then use these methods in the BorderThicknessComboBox_Loaded and FontFamilyComboBox_Loaded event handling routines.

Obviously you need to change the XAML code as well.


<ComboBox Height="32" Name="BorderThicknessComboBox" Width="120" Margin="82,128,289,50" Loaded="BorderThicknessComboBox_Loaded"/>

<ComboBox Name="FontFamilyComboBox" Width="136" Height="34"  Margin="243,128,112,48" Loaded="FontFamilyComboBox_Loaded" />

7) Run your application and make sure everything works as expected. Now we will implement the type value converters.

Add a new item to the project, a class file. Name it FontFamilyConversions.cs. The code for the class follows

using System.Windows.Media;
using System.Windows.Data;

namespace WpfApplicationConverters
{
class FontFamilyConversions: IValueConverter
{

public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
FontFamily fontfamily = new FontFamily("Verdana");
if (value != null)
{
fontfamily = new FontFamily(value.ToString());
}
return fontfamily;
}

public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
}

8) The code above is easy to understand. I implement the IValueConverter interface and the to methods, Convert and ConvertBack methods.

I actually implement only the Convert method.I convert the string value to a new value of type FontFamily.

9) Add a new class to the project so you can perform the second conversion.Name it IntergerToThicknessConversions.cs

The conversion in this case will be from a type integer to a type Thickness.The code for the class follows


using System;
using System.Windows.Data;
using System.Windows;

namespace WpfApplicationConverters
{
class IntergerToThicknessConversions:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Thickness thicknessValue = new Thickness(0);

if (value != null)
{
thicknessValue =
new Thickness(System.Convert.ToInt32(value));
}
return thicknessValue;

}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

10) Now we need to hook these classes with the XAML.The first thing I do is to add the namespace of all the classes in our project.

 xmlns:local="clr-namespace:WpfApplicationConverters"

Then I need to define the classes that implement the type conversions. I do that inside a Window.Resources element.

<Window.Resources>
    <local:FontFamilyConversions x:Key="FontFamilyConversions" />
    <local:IntergerToThicknessConversions x:Key="IntergerToThicknessConversions" />
</Window.Resources>

The last thing is to bind the target properties to the Comboboxes selected values and the Conversion classes.  I use markup extensions in XAML. I bind to the appropriate combobox for each case, then set the Path property to the SelectedValue. For the conversions I use the Converter attribute to bind to the appropriate conversion classes.

<Border BorderBrush="DarkCyan"  BorderThickness="{Binding ElementName=BorderThicknessComboBox, 
Path=SelectedValue, Converter={StaticResource IntergerToThicknessConversions}}">

<Button FontSize="16"  Content="I am a button"  Height="34"  Name="button1" Width="164" 
FontFamily="{Binding SelectedValue,ElementName=FontFamilyComboBox, Mode=OneWay,  
 Converter={StaticResource FontFamilyConversions}}" Margin="166,41,161,135" />

The whole code for the UI is this


<Window x:Class="WpfApplicationConverters.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:WpfApplicationConverters"
>
<Window.Resources>
<local:FontFamilyConversions x:Key="FontFamilyConversions" />
<local:IntergerToThicknessConversions x:Key="IntergerToThicknessConversions" />
</Window.Resources>
<StackPanel>

<Border BorderBrush="DarkCyan"  BorderThickness="{Binding ElementName=BorderThicknessComboBox, Path=SelectedValue,
Converter={StaticResource IntergerToThicknessConversions}}">

<StackPanel>

<Grid Height="210">

<Button FontSize="16"  Content="I am a button"  Height="34"  Name="button1" Width="164"  FontFamily="{Binding SelectedValue, ElementName=FontFamilyComboBox, Mode=OneWay, Converter={StaticResource FontFamilyConversions}}" Margin="166,41,161,135" />

<ComboBox Height="32" Name="BorderThicknessComboBox" Width="120" Margin="82,128,289,50"  Loaded="BorderThicknessComboBox_Loaded"  />

<ComboBox Name="FontFamilyComboBox" Width="136" Height="34"  Loaded="FontFamilyComboBox_Loaded" Margin="243,128,112,48"></ComboBox>
</Grid>
</StackPanel>
</Border>
</StackPanel>
</Window></pre>

Run your application and change the Font Family for the button and the Thickness of the border. Make sure everything works as expected.

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

Building an ASP.Net application with C# and Entity Framework June 27, 2009

Posted by fofo in asp.net, c# 3.0, Sql Server, Visual Studio 2008.
Tags:
11 comments

In this post I will show you a step by step example on how to build an ASP.NET application with C# and Entity Framework. 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.

ADO.NET Entity Framework (EF) is included with .NET Framework 3.5 Service Pack 1 and Visual Studio 2008 Service Pack 1

So you must donwload and have this software installed if you want to follow along.

It is not going to be a very difficult example. I will just bring data from a entity model to a gridview control and then give the user a way to filter that data.

There are many new enhancements regarding EF in VS 2010 and .Net .4.0 framework. I will not be talking about that since these enhancements are brand new and I am currently looking into them. I will just mention model-first development. This feature allows you to create your entity data model from scratch and then generate a database from it!!! We will do the opposite in this example.

Obviously for this example we will need a database. I will use the Pubs database. This is a well known database and many people are familiar with its schema.You can download the Pubs database from this link. If you need some help on how to install the database have a look here .

I have installed SQL Server 2008 Standard edition in my PC. SQL Server 2008/2005 Express editions will work just fine.You can download SQL Server 2008 Express edition from this link. I have attached the Pubs database in my local instance of the SQL Server.

Let’s start out project.

1) Launch Visual studio 2008

2) Create a new Project and from the available templates choose “ASP.Net web application”

3) Choose C# as your language of development and save your project in your hard drive with a name e.g “EFWebApplication” and click “OK”.

4) Click on the Solutions Explorer and open the Default.aspx page.

5) From the Toolbox drag and drop on the page , a Gridview control, a Textbox control and Button control. Leave the default names.

6) From the Toolbox drag and drop a EntityDatasource control on the page.

7) Choose the data source of the gridview control to be the EntityDatasource1 object.

8) Now we are ready to create our entity model. Right – click on your project from the Solutions Explorer window and Add a new Item. From the availble templates choose ADO.NET Entity data model. Give it the name Pubs.edmx and click the Add button.

9) In the Entity data model wizard window choose Generate from database and click Next .

10) Click New Connection, choose the Server name and from the databases your Pubs database is attached and then connect to the Pubs database and test your connection and click OK

11) If you notice you will see that there is something called Entity connection string and looks like this

metadata=res://*/Pubs.csdl|res://*/Pubs.ssdl|res://*/Pubs.msl;provider=System.Data.SqlClient;provider connection string=”Data Source=FOFO-PC;Initial Catalog=pubs;Integrated Security=True”

The connection string used by the Entity Framework contains not only the database connection string, but a metadata parameter with pointers to three mapping files separated by a pipe character.These mapping files will be generated when we finish this wizard.

12) Click Next on your wizard window and from the databases objects available choose Tables and more specifically the Titles, Authors and TitleAuthor tables. Leave the Model namespace as pubsModel and click Finish.

13) Our new Pubs.edmx file called is created and all the entities are generated which are basically classes derived from the data model . Have a look at the picture below to see the Entity model in the Designer window. You can zoom in and zoom out using the appropriate buttons.

pubsedmx

14) Have a look at the Mapping details of each entity type (Authors, Titles,  TitleAuthor). You can change if you want the property names for a particular entity type. For example you can change au_lname to lastname of the Authors entity type. You can also change the names of the entity types and singularise them in a way so they resemble more like a class name. Change Authors to Author and Titles to Title from the Designer.

15) Go to your default.aspx page and click on the EntityDatasource object and hit the option Configure Data Source. In the window that appears choose Named Connection and select the PubsEntities that will apear in the drop-down and hit the Next button.

pubsef-1

16) In the next step from the EntitySetName select authors. Select all fields and and enable automatic inserts,updates,deletes and hit the Finish button.

pubsef-2

17) In your gridview control enable paging,sorting,editing,deleting and selection.

pubsef-3

18) Build and run your application and see the records in your web page. Try to sort,edit, delete records. Well done!!!!

19) Let’s give the ability to the user to apply a filter to the data by typing something to the textbox and return only the relevant data.Choose your EntityDatasource object and from the Properties window select  Where. Click on the “…” to launch the Expression editor window.

20) We will create an expression to use it as a filter(e.g filter the records by city name). The expression could be something like this

it.city=@city OR @city IS NULL

This expression above is written in Entity SQL which is T-SQL like syntax.

Click the Add Parameter button and under name write “city” and the value will be a control, so from the Parameter Source select Control and from the ControlID your textbox control (e.g TextBox1)

Go to show advanced properties and in the “Type” field choose String.  Your settings should be like this:

pubsef-4jpg

21) Hit the OK button to close the Expression Editor window. Hit F5 to run your application. In the textbox type

“Oakland” and hit the button control. See the filtered results. That is all!!!! We did that without writing a single line of code.

If you need the source code for this example, just leave a comment and I will email it to you as soon as possible.

Hope it helps!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Object Oriented Programming Concepts with C#3.0 June 21, 2009

Posted by fofo in asp.net, C#, c# 3.0, Visual Studio 2008.
Tags: , ,
126 comments

In this blog I try to write about all the latest issues regarding the .Net platform.

But in this post I will try to explain thoroughly the Object Oriented programming model-paradigm.

Speaking from my experience so far, I have identified that the lack of knowledge of basic-advanced OOP concepts is the main reason that people fail to grasp how to design and implement a .Net application.

Dragging and dropping controls from the Toolbox to an .aspx page and connecting to a database does not mean we know OOP.

Unless you do have a good knowledge of OOP concepts , there is a pretty good chance you will fail in your projects.

In this very long post I will try to explain in details the OOP concepts using C# 3.0 in an ASP.NET application.

Many good people have created very good tutorials which are available on the internet about OOP , but I thought I will have a go myself.Along the way I will show you tips and tricks with do’s and dont’s.

Well, some people think, “I do not need classes and object oriented programming to develop my applications”.

That is a true. However if you want to create .NET applications you must use objects. Even if you fail to realise it, everything in .Net is an object. When you open a connection to a database that “connection” is an object. To put it in one line:

Each class in C# is automatically (implicitly) inherited from the Object class.

I have been posting about C# 3.0 new features in other posts and there will be links where required.

Some of the topics-concepts, I will try to cover are:

  • Classes
  • Properties
  • Methods
  • Fields
  • Members
  • Enums
  • Casting
  • Structures
  • Abstraction
  • Encapsulation
  • Interfaces
  • Static classes
  • Constructors
  • Method overloading
  • Inheritance
  • Overriding methods
  • Virtual methods
  • Abstract classes
  • Polymorphism
  • Delegates
  • Events
  • Assemblies
  • Namespaces

and many more…

Before jumping into bits of code and create our step by step example, I must explain some basic concepts regarding  OOP.

  • What is a class?

A class is an abstract concept. It is a blueprint. Try to think of a class as e.g  the blueprints of a car in the real world.

The designers of auto mobiles sit in front of their computer (or use paper and pencil) and describe exactly the parts of the auto mobile. They describe how these parts interact, the colour of the car, the height of the car, the size of the engine, the acceleration of the car, if the car has air-conditioning system installed.

Then the mechanics that observe the production line, make sure that the cars built (the actual cars) follow the blueprints outlined in the design stage of building a car.

So a class is a way of describing real world entities. It is the code definition for objects.

The class is the fundamental building block of code when creating object-oriented software. A class describes in abstract (in theory) all of the characteristics and behaviour of an object.

The object on the other hand is the instance of a class. The real thing, if you excuse my slang…

So we must start thinking about modelling our applications in terms of objects.

When someone, who has hired us to implement a web site-commerce site for his business, he could outline his view of the web site in plain words…

” I would like to have a site where I can keep track of the sales-orders that were placed through the site. I also would like to be able to see the customer details and manage my employees details”,

Then you must think in terms of Orders,Customer,Employee classes-objects for this particular scenario.

This is a first attempt of Abstraction for the scenario above.

Abstraction is the process of representing simplified versions of real-world objects in your classes and objects.

Programming with the OOP paradigm is to decide what a class should represent and breaking down your code into a group of interrelated classes.

Members of a class

The first thing after finalising the class names is to identify the members of a class.

I will talk about Properties, methods and events. As we go on I will talk in greater detail about class members.

  • What is a property ?

A Property allows you to access an object’s data. Properties can be read-only, so they cannot be modified, while others can be changed. A Property defines the state of an object.It describes its individual data or unique configuration.

  • What is a method ?

A method allows you to perform an action with an object. Unlike properties, methods are used for actions that perform a distinct task and may  change the object’s state-property.

  • What is an event ?

An event provides notification that something has happened. Objects can fire events to trigger the code we have placed in the event-handling routines-methods. For example, if a user clicks on a button,the button object fires a Click event, which our code can react to.

Methods, properties and events can be considered as the public interface of a class.

Now we are ready to move on and practice what we have been saying so far.

I assume that people who will read this post, have some experience with C# and Visual studio as a development platform.

I will use Visual Studio 2008 Professional edition. People who have downloaded and installed Visual web developer 2008 can also follow these examples. You can download Visual Web Developer by clicking here .

I will create an ASP.NET application. I will create a base class and then take it from there and try to highlight all the concepts mentioned above. The point of this example is not create super sophisticated classes and methods but to create a simple class with plain properties and methods.

1) Launch VS 2008

2) Go to File->New->Project

3) From the templates, choose ASP.NET web application. Make sure you select C# as the language of development

4) Give a name for your project. I name it “LearnCLass”. Click OK on the Templates window.

5) You will have 2 main files, Default.aspx and Default.aspx.cs

Building a basic class

The class I will construct regards a Person class.This class can represent any person, e.g the customer of an e-commerce shop.The Person class will store the person’s data, and it will include the built-in functionality needed to generate a block of HTML that displays the person details on a web page. We will test this class with an ASP.NET page.
Once you’ve defined a class, the first step is to add some basic data. The next example defines five member variables that store information about the person, namely, its name, surname, age, height,weight .

In your default.aspx.cs (code behind file) you have something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LearnCLass
{
public partial class _Default : System.Web.UI.Page
{

Then add the class definition

public class Person
{
public string name;
public string surname;
public int age;
public decimal height;
public decimal weight;
}

Now we have the class definition we need to creating an object. We must use new keyword to do that. The new keyword instantiates the object, which means it creates a copy of the class in memory. If you define an object but don’t instantiate it, you’ll receive an error from the compiler.The members of a class (methods and properties) are accessed using dot ‘.’ operator against the reference of the object.

In the Page _Load event handling routine type

protected void Page_Load(object sender, EventArgs e)
{
Person mynewperson;
mynewperson=new Person();
mynewperson.name = “nikos”;
mynewperson.surname = “kantzelis”;
mynewperson.age = 31;
mynewperson.weight = 88;
mynewperson.height = 1.78M;
Response.Write(mynewperson.name);
}

Run your application by hitting F5 from the keyboard and see the results.

What I am trying to highlight here, is how to create an object from a class.The bit that does it is this:

Person mynewperson;
mynewperson=new Person();

One could write it in a single line

Person mynewperson=new Person();

But the snippet of code inside the Page_Load method is not very well thought.

One could write mynewperson.age = -2;

We would not like to have the code above. The reason the code above works is that the properties of the Person class,

are all public. That is the visibility of the properties is public. Another more technical word for visibility is scope.

This is very important concept and one must understand.

The main accessibility keywords are

public -Members defined as public can be accessed by any other class
private – Members defined as private can be accessed only by code procedures inside the current class
internal – Members defined as internal can be accessed by code procedures in any of the classes in the current assembly (the compiled file)
protected Members defined as protected can be accessed by code procedures in the current class or by any class
that inherits from this class

So by having in our example the variables defined as public, this means that any other class or method of another class has direct access to those variables-properties.

We must not design classes like that. In order to have useful classes we must have a way to protect the data within them. This is called, Encapsulation. Encapsulation is is the hiding of the internal mechanisms and data of a class behind a defined interface.Other classes , if they need to “talk” – interact with a specific class, they can do so by just knowing its interface. Let me try to explain this better with my car analogy example. When you try to change the gear in your car, imagine the gear system as class or a component, the gear system interacts with another system that commands the car to slow down or accelerate. The gear system does not have to know how it is done, just how to interacts with it.

So let’s change public to private.

private string name;
private string surname;
private int age;
private decimal height;
private decimal weight;

Let’s run the code again. We get the following error. I am sure you get what is going on here. There is no variable name still “alive-visible” when we call it in the Page_Load event handling routine.

Error    1    ‘LearnCLass._Default.Person.name’ is inaccessible due to its protection level    C:\Users\fofo\Desktop\webapps\LearnCLass\LearnCLass\Default.aspx.cs    24    25    LearnCLass

In general objects are automatically released when the appropriate variable goes out of scope. Objects are also released when your application ends. That means that their memory is reclaimed. In the managed applications, the CLR uses a service (garbage collector) that periodically scans for released objects and reclaims the memory they hold.

So , you must be thinking that we have not accomplished anything yet. The truth is that we have not finished yet.

We must write property accessors for the member variables.

For the name member variable we have

public string Name
{
get
{
return name;
}

set
{
name = value;
}

}

With C# 3.0 we had a new feature that is called Auto-implemented properties. Have a look here in one of my past posts to find out more about that.Basically with auto implemented properties,  there is no need to implement a private field to store the value.

So we could write the code above like this

public string Name { get; set; }

much easier isn’t it?

We can do that for all property accessors if no no additional logic is required.

So we have

public string Name { get; set; }
public string Surname { get; set; }

that means that we can comment out the following lines from our class declaration.

//private string name;
//private string surname;

but for the Age,Height,Weight member variables we require some additional logic for the property accessors.

Just for this example let’s just assume that a person’s age must between 1 and 100, his height from 1 to 2.40 and his weight from 30 to 240.

public int Age
{
get
{
return age;
}

set
{
if (value < 1 || value > 100)
{
throw new Exception(“Invalid age”);
}

age = value;
}

}

public decimal Height
{
get
{
return height;
}

set
{
if (value < 1.00M || value > 2.40M )
{
throw new Exception(“Invalid height”);
}

height = value;
}

}

public decimal Weight
{
get
{
return weight;
}

set
{
if (value < 30 || value > 240)
{
throw new Exception(“Invalid weight”);
}

weight = value;
}

}

When trying to assign an invalidvalue, an exception is thrown by the class code.

Now let’s create a method for our Person Class.

We can create a very simple method like:

public void Talk()

{

// add logic later

}

or we can add a method that returns something (it is not void) and can do something useful.

So we can have a method that calculates the age of the person in years. The method follows:

public int CalculateAge(DateTime birthDate)
{DateTime now = DateTime.Today;int years = now.Year – birthDate.Year;if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
–years;return years;
}

It is not something difficult.  We should not focus on how the method does it, right now. Basically I am just using

DateTime Class in the System namespace.

In your Page_Load event you can add to the code already there, the following bit

string myDateTimeString;int res;myDateTimeString = “17 Feb,1977”;DateTime dt;
dt = Convert.ToDateTime(myDateTimeString);
res=mynewperson.CalculateAge(dt);Response.Write(res.ToString());

Run your application and see the results.

The Person class so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LearnCLass
{
public partial class _Default : System.Web.UI.Page
{

public class Person
{
//private string name;
//private string surname;
private int age;
private decimal height;
private decimal weight;

public int Age
{
get
{
return age;
}

set
{
if (value < 1 || value > 100)
{
throw new Exception(“Invalid age”);
}

age = value;
}

}

public decimal Height
{
get
{
return height;
}

set
{
if (value < 1.00M || value > 2.40M )
{
throw new Exception(“Invalid height”);
}

height = value;
}

}

public decimal Weight
{
get
{
return weight;
}

set
{
if (value < 30 || value > 240)
{
throw new Exception(“Invalid weight”);
}

weight = value;
}

}

public string Name { get; set; }
public string Surname { get; set; }

public int CalculateAge(DateTime birthDate)
{

DateTime now = DateTime.Today;

int years = now.Year – birthDate.Year;

if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
–years;

return years;
}

public void Talk()
{
//add logic later
}

}

protected void Page_Load(object sender, EventArgs e)
{
Person mynewperson=new Person();
mynewperson.Name = “nikos”;
mynewperson.Surname = “kantzelis”;
mynewperson.Age = 22;
mynewperson.Weight = 88;
mynewperson.Height = 1.78M;
Response.Write(mynewperson.Name);
Response.Write(“</br>”);
Response.Write(mynewperson.Surname);
Response.Write(“</br>”);
Response.Write(mynewperson.Age);
Response.Write(“</br>”);
Response.Write(mynewperson.Height);
Response.Write(“</br>”);
Response.Write(mynewperson.Weight);
Response.Write(“</br>”);
mynewperson.Talk();

string myDateTimeString;

int res;

myDateTimeString = “17 Feb,1977”;

DateTime dt;
dt = Convert.ToDateTime(myDateTimeString);
res=mynewperson.CalculateAge(dt);

Response.Write(res.ToString());

mynewperson.Talk();

}
}
}

When we create our Person object,

Person mynewperson=new Person();

you might think that we have here is a method call.When an instance of a class is created the C# system makes a call to a constructor method in that class. A constructor is a function with the same name as that of the class. Every single class must have a constructor method.It is called when we write the new keyword. Even If we do not provide a constructor method, the compiler creates a default one,without any parameters.

So in our case is:

public Person()

{

}

We often need to overload our default constructors. Let me explain what overload is.

It is possible to have more than one method with the same name and return type but with a different number and type of arguments-parameters. The compiler knows every time which method to call by looking at the number of the arguments. I will explain more about overloading later on.

Sometimes it is better to send some information to the class upfront so it is available as soon as it is constructed. So let’s overload the default constructor.

public Person( string thename, string thesurname, int theage)
{
Name = thename;
Surname=thesurname;
Age = theage;
}

We can also have a destructor.Destructors are just the opposite of constructors.

It has the same name as the containing class but prefixes it with the ~ (tilde) sign.

It is called automatically when the object is about to be destructed (when garbage collector is about to destroy your object).

It has no return type just as the constructor does not have one as well.
We declare the destructor in our case like

~Person()
{
// place our e.g resource freeing code here
}

What really happens is that the C# compiler internally converts the destructor to the Finalize() method.

The Object class is the parent of all objects in .Net.It contains a method called Finalize().
This method is  be called when your object is garbage collected . One can override this method and put here code for freeing resources that you reserved when using the object.

protected override void Finalize()
{
try
{

// put some code here
}
finally
{
base.Finalize();
}
}

Do not worry about the override keyword. I will explain it later on.

Many people ask me about enums and structures and what they are and how we can use them.

What is enum?

An enumeration is a group of related constants. Each constant is given a descriptive name.
Every enumerated value corresponds to a preset integer.

Sometimes we want to hold a range of particular values or states. This is a perfect place to use enums.

In our example we could have something like

public enum PersonState
{
Married = 1,
Widoewed = 2,
Single = 3,
Divorced = 4
}

And then call it from our Page_load event

PersonState personstate;

personstate =PersonState.Married;
Response.Write(“</br>”);
Response.Write(personstate);

C# compiler will  represent these states as particular numeric values . But it will do so behind the curtains.

So I can use the enum name values and have more readable code. The concept of enumerated values is extremely important, because the .NET class library uses it extensively.

What is a structure ?

Structures are lightweight objects. Structures are very similar to classes in C#.

Basically they can hold a collection of different things about a particular item.

They are denoted in C# by the struct keyword. In our example we could have a structure like this

struct NewPerson
{
public string name;
public string surname;
public int age;
public decimal height;
public decimal weight;

}

In the Page_Load event routine we can have

NewPerson myperson;

myperson.name = “John”;

Response.Write(myperson.name);

As you notice there is no need for the new keyword.

There is a key difference between objects and structures. Structures are managed in terms of value while objects are managed in terms of reference.

A reference holds the physical address of where the data is stored in memory. So it points to the data. It is not the actual data. On the other hand structure variables hold the actual data.

There are some limitations with structures and even if they have their place when we design a software component, they can never be used to replace a class type.

A structure  for example can neither inherit another class, nor can they be inherited. A structure can implement interfaces.

A common place where we find structures  are Net framework types like System.Int32, System.Double , System.Boolean.If you want to check it out yourselves just place the pointer of your mouse on an int declaration and right click. From the right-menu click on the “Go To Definition “. Then you will see the definitions. See the picture below.

go to def

Inheritance

I know a lot people who use Inheritance in their applications without even realizing.

If you look at the Default.aspx.cs you can see

public partial class _Default : System.Web.UI.Page

In plain English , this means that every web page we create is a child of the Page class. Inheritance is a form of code reuse. It allows one class to acquire and extend the functionality of another class. There is no need to reinvent the wheel when other people have done this for you. Instead of that you have only to think about the peculiarities of the project at hand.

Let’s assume that we need to create another class,called Student.

In this class we want to inherit the functionality of the Person class or base class.

class  Student : Person

Then we want to extend the Parent class. We want to create a new simple method to calculate the total marks achieved by the student.

The whole Student class follows. I have explained in detail properties and methods in previous paragraphs.

class  Student : Person
{
private int _marksEnglish;
private int _marksLiterature;
private int _marksIT;
private int _marksMaths;
private int marksTotal;

public int marksEnglish
{
get
{
return _marksEnglish;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}

_marksEnglish = value;
}
}
public int marksLiterature
{
get
{
return _marksLiterature;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksLiterature = value;
}
}

public int marksMaths
{
get
{
return _marksMaths;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksMaths = value;
}
}

public int marksIT
{
get
{
return _marksIT;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksIT = value;
}
}

public int CalculateTotalMarks()
{

marksTotal = marksEnglish + marksLiterature + marksIT + marksMaths;

return marksTotal;
}
}



In our Page_Load event , we can create a new object of type Student.

Student mystudent = new Student();
Response.Write(“</br>”);
mystudent.Name=”fofo”;
Response.Write(mystudent.Name);
mystudent.marksEnglish = 12;
mystudent.marksLiterature = 13;
mystudent.marksIT = 18;

mystudent.marksMaths = 17;

mystudent.CalculateTotalMarks();


Response.Write(mystudent.CalculateTotalMarks());

If you pay attention even though we did not define the Name and Surname properties for the Student class, they are available to the class, since they are inherited. The same applies for the CalculateAge method.

Some things worth mentioning regarding inheritance are:

  • C# allows only single class inheritance
  • Multiple inheritance of classes is not allowed in C#
  • The Object class defined in the System namespace is implicitly the ultimate base class of all the classes in C# and the .NET framework
  • A class may implement multiple interfaces. We may also declare objects of different classes in a class. This way, the encapsulated class may be instantiated in other classes.

Now, we know how to make a new class based on an existing one and extend it.If we want to change the behavior of a method in the base class in the child class we must override it.

Let’s create a new method in the base class (Person) that we want to override it later on the child class. It is just a method that calculates the pay of a person.

public double CalculatePay(double hoursWorked, double wageperhour,double tax)
{

return (hoursWorked * wageperhour * tax);
}

This method is inherited in the Student class. Let’s assume that we live in a fantastic world where student’s money is not taxed if the student worked less than 100 hours.

The first thing to do is to add the word virtual to the CalculatePay method.So we have:

public virtual double CalculatePay(double hoursWorked, double wageperhour,double tax)
{

return (hoursWorked * wageperhour * tax);
}

and then to use the word override in Student class CalculatePay method

public override double CalculatePay(double hoursWorked, double wageperhour,double tax)
{
if (hoursWorked > 100)
{

return (hoursWorked * wageperhour * tax);
}
else
{
return (hoursWorked * wageperhour);

}
}

From our Page_Load event we can call this

Response.Write(mystudent.CalculatePay(45, 4, 0.45));

By calling the line above the CalculatePay method of the student class will be invoked.This relationship between virtual  methods and the derived class methods that override them enables polymorphism.

If we want to stop overriding a class we can use the special word sealed. This means that this class cannot be used as the basis for another class.

if you change the

public class Person to public sealed class Person

and run your application you will receive an error

cannot derive from sealed type ‘LearnCLass._Default.Person

Now it is time to see in greater detail method overloading.

In our Person class we can define a new method

public string JoinNames(string name, string surname)
{
return name + ” ” + surname;
}

Now we could have a different implementation of the method above.

public string JoinNames(string prefix, string name, string surname)
{
return prefix + ” ” + name + ” ” + surname;
}

In our Page_ Load event if we write the line:

mynewperson.JoinNames(“Mr”,”nikos”, “kantzelis”)

The compiler will not complain. It will know which method to invoke depending on the number of the parameters-arguments it “sees”.

Polymorphism (from the Greek meaning “having multiple forms” – “Poly” means many and “morphy” means “shape”) can be achieved by overloading a method.

What is a static class?

In .NET we can  use some class members without creating an object first. These are called static members, and they’re accessed by class name. So far in the previous examples we have seen the static property DateTime.Now to retrieve a DateTime object that represents the current date and time. We didn’ create a DateTime object first.

If we wanted to have a method that determines whether a person can hold a valid driving licence, the method would look like this.

public bool AllowedToDrive(int age)
{
if (age >= 18 || age <= 80)
{
return true;
}
else
{
return false;
}

}

The method above is a good candidate to become a static method.In order to do that, we just add the word static

public static bool AllowedToDrive(int age)
{
if (age >= 18 || age <= 80)
{
return true;
}
else
{
return false;
}

}

In our Page_Load event routine,we can write

Person.AllowedToDrive(22)

As you see we do not need an object to invoke our method, just the class name.

So a static member is a member of the class and not a member of an instance of the class.

It takes some experience to determine which methods or classes. One common place where we find static classes and methods is the creation of libraries that provide general functionality, e.g find the square root of a number, find the perimeter of a circle.

The next thing to review is Interfaces. I will not cover Interfaces in detail because you can find another post of mine on Interfaces on this blog.

The Interface is basically a contract between a the Interface and a class. In the Interface we do not have implementation of properties of methods.

The class that implements the Interface or inherits from the Interface must implement the methods defined in the Interface.

A .NET interface is similar to an abstract class in the sense that it’s a kind of a template. More on abstract classes later.

If we define an interface like this

interface IPerson
{
double DaysVacation(int yearsOfWork);
}

and if we say that the Person class implements the IPerson Interface

class Person : IPerson

the Person class must in its body implement the DaysVacation(int yearsOfWork) method.

public double DaysVacation(int yearsOfWork)
{

if (yearsOfWork > 25)
{
return 25;
}
else if (yearsOfWork < 25 && yearsOfWork > 20)
{
return 20;
}
else
{
return 10;
}

}

What is an abstact class?

If we need to provide common fields and members to all subclasses, we create an Abstract class. We can create an abstract class, with the use of the abstract keyword. Abstract classes cannot be instantiated. In our example if we decide that there are some things that an object of type Person must do, then we can make the class Person abstract and then get the clild classes to provide the implementation. I will create another class to demonstrate abstract classes, because we need to change los of code in the Person class  and I do not want to do that.

In abstract classes we can have abstract members and virtual members. An abstract member is not implemented in the base class and must be implemented in derived classes in order for the class to compile. A virtual member must be implemented in the base class, and if need be (optionally) overriden in the derived class if want the child method to do something different.

Let’s define our abstract Vehicle class.

public abstract class Vehicle
{

public string Model { get; set; }
public string Color { get; set; }
public int NumOfDoors { get; set; }
public int NumoOfWheels { get; set; }

public Vehicle(string model, string color)
{
this.Color = color;
this.Model = model;

}
public abstract string Accelarate(int speed);

public virtual double CalculatePetrolCostPerDistance( double distance)

{
double costperkilometer=0.25;
double res;

res = distance * costperkilometer;

return res;
}

}

Now we can have another class Car that can inherit from the Vehicle class. The method Accelerate in the Vehicle class must be implemented in the child class.

public class Car : Vehicle
{

public Car(string model, string color): base(model,color)
{
//code to be added
}

public override string Accelarate(int speed)
{
return “I can accelerate. My speed is right now:”+speed.ToString();
}

public override double CalculatePetrolCostPerDistance(double distance)
{
double costperkilometer = 0.45;
double res;

res = distance * costperkilometer;

return res;
}

}

We can create and use an object type Car in our Page_Load event handling routine

Car mycar = new Car( “bmw”, “silver”);
Response.Write(mycar.Accelarate(134));
Response.Write(“</br>”);
Response.Write(“The cost is: ” + mycar.CalculatePetrolCostPerDistance(125.5).ToString() +” euros”);

In the child class I have implemented a simple version of the Accelarate method by using the override keyword and I chose to ovveride CalculatePetrolCostPerDistance. But If i did not need any different behaviour for the CalculatePetrolCostPerDistance then that would be ok, my class would compile just fine.

Abstract classes are a lot like interfaces, however abstract classes are different in that they contain fully implemented methods alongside the abstract ones.So we do not have to implement the same methods in each of the components that implement a particular interface. An abstract class can contain fields, constructors, or destructors and implement properties while an interface cannot.
An abstract class cannot support multiple inheritance, but an interface can support multiple inheritance. Thus a class may inherit several interfaces but only one abstract class.

What is a delegate?

For more information on this topic have a look at this post of mine.

What is Generics ?

Same applies here. I have another single post on Generics and I do not see any point repeating myself.

What is a namespace?

In my solution in the Default.aspx.cs , I have the namespace LearnCLass namespace. All my classes and code is included in this namespace.

Namespaces are a logical way to group classes. Let me give you an example of what it means. It is a way that we can identify a class beyond doubt.

Imagine that you want to phone an old friend that you have lost track, so you can invite him to your wedding. So you phone the phone directory service.

Your friend’s name is George Patouxas. The operator lets you know that there are 100 people with this name coming up. Then you tell the operator that his mother’s name and father’s name are Maria and John respectively. BINGO!! The operator tells you there is only match. So in our example the LearnCLass.Person class resides in this specific namespace and if someone wants to use it, he can use the using LearnCLass.Person declaration.

That is exactly why namespaces are for in .NET.  We try to group related classes in namespaces and all of them that reside in this particular namespace will be uniquely identified.

If I have a class called Calculate in my LearnClass namespace, then there will be no conflict if need be to use another component from a third party that has also a Calculate Class.

That Calculate class will reside in the AnotherNameSpace so there will be no conflict.

Please note that in the beginning of the Default.aspx.cs we import namespaces that we need to using System.Web.UI;

Assemblies

All .NET classes (built-in or custom made) are contained in assemblies. Assemblies are the physical files that contain compiled code. Assembly files have the extension .exe if they are stand-alone applications or .dll if they’re reusable components. Assemblies are a physical package for distributing code. Often, assemblies and namespaces have the same names. For example, you’ll find the namespace System.Web in the assembly file System.Web.dll.

But in many cases there is no direct mapping between assemblies and namespaces.

What is Casting?

When we talk about casting, we can think of this concept in terms of narrowing and widening. If you move a value from one type to another that narrows the value, it will ask you to explicitly do it yourself. When you move a value from one type to another by widening it, it does not complain.

By widening I mean that if I have the declaration:

int mynum=5;

float anothernum=mynum;

This will be fine because the floating point type can hold all the values supported by the integer type.

If I have this statement (narrowing)

double mynum = 3.5;
float thenum = mynum;

the compiler will complain.

Cannot implicitly convert type ‘double’ to ‘float’. An explicit conversion exists (are you missing a cast?)

The compiler is basically saying “Is there any chance you are discarding information?”

But you can cast the value by using this statement.

double mynum = 3.5;
float thenum = (float)mynum;

This is an explicit conversion and I say in simple words to the compiler, that I take the responsibility for the possible data loss.

For reference types, if we have a situation like this, where the derived type (Student) is converted to base type (Person), we have imlicit conversion which is safe.

Student thestudent = new Student();

while if we type this:

Person theperson=new Person();

this will fail and we must explicitly cast it to the Student type, like this.

Person theperson=new Person();
Student thestudent = (Student)theperson;

Hope it helps. If you need the source code, leave a comment and I will email it to you.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

LINQ TO SQL and Stored procedures December 13, 2008

Posted by fofo in c# 3.0, LINQ, SQL Server 2008, Visual Studio 2008.
Tags: , , ,
8 comments

In this post, I will go back to the issue of LINQ. I am going to show with an example how to use LINQ and stored procedures to insert,update and delete records from a particular table.

I will use visual studio 2008 to create an asp.net application (c# version) that demonstrates how to use stored procs with LINQ.

If you want to see how LINQ treats stored procedures , have a look here

I am going to use the Pubs datatabase and in particular the Authors table.

I am pretty sure, because I have used the Pubs database in almost all my examples that you have installed it and attached it in your local instance of Sql Server.

You can use Visual Studio 2008 express edition and Sql Server express edition for this example.

We often need to use stored procs to talk with our database because there have many benefits

for example

  • They allow modular programming.
  • They allow faster execution.
  • They can reduce network traffic.
  • They can be used as a security mechanism.

First we need to create the 3 stored procedures that will insert,update and delete records from the Authors table

This is not a post on how to create stored procedures, so i am just going to paste here the complete stored procs.

  • DeleteAuthor

USE [pubs]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[DeleteAuthor]

@AuthorID nvarchar(20)

AS
BEGIN

DELETE FROM authors
WHERE au_id = @AuthorID

END
GO

  • UpdateAuthor

USE [pubs]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[UpdateAuthor]

@authorID varchar(11),
@lname nvarchar(50),
@fname nvarchar(50),
@phone char(12),
@address nvarchar(40),
@city nvarchar(40),
@state char(2),
@zip char(5),
@contract bit

AS
BEGIN

UPDATE authors
SET

au_lname=@lname,
au_fname=@fname,
phone=@phone,
address=@address,
city=@city,
state=@state,
zip=@zip,
contract=@contract
WHERE au_id  = @authorID

END
GO

  • InsertAuthor

USE [pubs]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[InsertAuthor]
@id varchar(11),
@lName nvarchar(50),
@fname nvarchar(50),
@phone char(12),
@address nvarchar(40),
@city nvarchar(40),
@state char(2),
@zip char(5),
@contract bit

AS
BEGIN

INSERT INTO pubs.dbo.authors(
au_id,
au_lname,
au_fname,
phone,
address,
city,
state,
zip,
contract)
VALUES (
@id,
@lname,
@fname,
@phone,
@address,
@city,
@state,
@zip,
@contract)

END

GO

1) Launch Visual Studio 2008

2) Create an ASP.net web application. Use C# a your language of development

3) Name your project – solution as you want.

4) Open the Server Explorer and connect to the Pubs database.

5) Add a new item in your project, a Linq to SQL classes, a .dbml file. name it authors.dbml

6) Drag and drop from the Server explorer window the authors table into the designer area (on the .dbml file)

7) Right-Click on the designer area and show the “Show methods Pane”

8) Drag and drop the stored procedures from the Server explorer to the designer area

9) Select the author entity from the deisgner area and select the Properties window. In the Default methods we need to assign the correct stored procs and not to leave the default option which is “use Runtime”. So please assign the different methods to their respective stored procs. Have a look at the picture below

sql-linq

10) We will use these stored procs that are methods now as far as LINQ is concerned to update,insert and delete records from the database.

11) Add a button in the Default.aspx file. Name it “Update”.Double click on this button. In the event handling routine type:

using (authorsDataContext authdata = new authorsDataContext())
{
var author = (from a in authdata.authors
where a.au_id == “238-95-7766”
select a).Single();
Response.Write(author.au_fname);
author.au_fname = “nikolaos”;

authdata.SubmitChanges();

}

12) Add another button in the default.aspx page. Name it “After Update”.In this routine we try to see the updated value in the database.Double click on this button. In the event handling routine type:

using (authorsDataContext authdata = new authorsDataContext())
{
var author = (from a in authdata.authors
where a.au_id == “238-95-7766”
select a).Single();
Response.Write(author.au_fname);

}
12) Add another button in the default.aspx page and name it “Insert”.Double click on this button. In the event handling routine type:

using (authorsDataContext authdata = new authorsDataContext())
{

authdata.InsertAuthor(“216-49-8915”, “Jones”, “Michael”, “432423424”, “james street 123”, “New york”, “NY”, “94618”, true);

authdata.SubmitChanges();
}

13) Add another button in the default.aspx page and name it “Delete”. Double click on this button. In the event handling routine type:

using (authorsDataContext authdata = new authorsDataContext())
{
var author = (from a in authdata.authors
where a.au_id == “216-49-8915”
select a).Single();
authdata.DeleteAuthor(author.au_id);
authdata.SubmitChanges();
}

if you named you .dbml file “authors”, then there is a file “authors.designer.cs”. Inside there you will find this code

private void Insertauthor(author obj)
{
this.InsertAuthor(default(string), default(string), default(string), obj.phone, obj.address, obj.city, obj.state, obj.zip, ((System.Nullable<bool>)(obj.contract)));
}
private void Updateauthor(author obj)
{
this.UpdateAuthor(obj.au_id, obj.au_lname, obj.au_fname, obj.phone, obj.address, obj.city, obj.state, obj.zip, ((System.Nullable<bool>)(obj.contract)));
}
private void Deleteauthor(author obj)
{
this.DeleteAuthor(default(string));
}

The methods above, are our stored procedures , which are called whenever we insert,update,delete

Hope it helps!!!

If you need the source code just email me.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

How to monitor and debug LINQ to SQL queries November 19, 2008

Posted by fofo in c# 3.0, LINQ, Visual Studio 2008.
Tags:
1 comment so far

In one of my previous posts where I tried to explain how to query an Sql Server database with LINQ to SQL, I said that LINQ to SQL queries get translated into commands that SQL Server understands. The LINQ runtime knows how to translate LINQ to SQL queries to T-SQL, the only language SQL Server knows!

We can see the communication between the Runtime and SQL Server using several tools.

Some tools are built into the Visual Studio 2008 sp1 for looking into the results of a LINQ query.

If you follow the exact same steps of my previous post until step 8 (the first example), then

you can put a breakpoint in this line

var tauthors = from ta in db.titleauthors
select ta;

run your application now and then press F11 to move one step forward from the above statement

Then place your cursor in the tauthors variable and select the Results View.

It has all the instances of author entity that has been retrieved from the database and populated in the titleauthors class.

You can go throuch each one of them and their respective private fields.

see the picture below and consider it as a visual aid

resultsview

That is one approach viewing-debugging the results before they actually executes

There is another tool available.

Fire the browser of your choice and type the following url from Scott’s Gu website

http://www.scottgu.com/blogposts/linqquery/sqlserverqueryvisualiser.zip

Scott includes this tool as an add-on on his website.

Download this tool to your desktop and then unzip it.

Go then to the Debug/bin folder , copy the SqlServerQueryVisualizer.dll and place it in the following folder

C:\Program Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers

Save all your work. Close your project and exit Visual Studio

Fire up Visual Studio 2008 again and open your project again.

If you put a breakpoint in the same line,  run your application, press F11 and place your cursor above the

tauthors variable. You will see a magnifier icon. Click on it. You will see a screen that looks like the one below

scottvisualiser1

When you click on the magnifier icon, you will see the SQL Server Query Visualiser which shows the query that is going to be executed.

You can hit the “Execute” button to preview the results before they executed.If you want to see when commands are executed you can use a different tool called LINQ to SQL Debug Writer.

LINQ to SQL Debug Writer is basically just a class that you add to your applications that outputs the generated T-SQL to the Debug window.

So you need to add another class to your project. Name it “class1.cs”

clear all the code in the class file and go to the following url

http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?List=4a6d97a9-b3b0-45a7-88a0-1a7f4819a678&ID=11&Source=http%3A%2F%2Fwww.u2u.info%2FBlogs%2FKris%2FLists%2FPosts%2FAllPosts.aspx

You will need to copy all the contents from this line

Here’s the code:

until the end…

and place it in the class1.cs file.

make sure you change this line inside the above file

namespace Vandermotten.Diagnostics

with whatever you named your project.

Then you need to add this line

db.Log = new DebuggerWriter();

immediately after this line

pubsDataContext db = new pubsDataContext();

Save and run your application by placing the breakpoint in the same place.

Clear all windows (like watch,locals) and just make sure you have the “Output” window open.

Step into your code. You can see in the output window, LINQ to SQL runtime, generates the T-SQL and sends the statement to the SQL SERVER.With this tool we can see both what is executed and what is executed.

We can also use the SQL Server Profiler to watch the traffic between LINQ to SQL and SQL Server.

Select Sql Profiler from the Performance Tools, start a new trace,connect to your SQL SERVER ,accept all the defaults and hit the Run button.

If you run the application again and have this break point and run the code step by step,you can see the entire T-SQL statement that has been executed in the SQL profiler window.

Hope it helps…..

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl