jump to navigation

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

Posted by fofo in Sql Server, Visual Studio 2008, asp.net, c# 3.0.
Tags:
1 comment so far

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 “country” 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

Viewstate management and ASP.Net 4.0 June 27, 2009

Posted by fofo in ASP.NET 4.0, VS 2010.
Tags: ,
1 comment so far

For people who have been following this blog for some time, they know my favourite subject is ASP.NET.

I think this is the best platform for building web applications nowadays. In ASP.NET 4.0 we have some very interesting new enhancements and new features.

I will try to talk about all of them in separate posts since some people have been complaining that my posts are too long.

In this post I will talk about Viewstate management in ASP.NET 4.0.

Let’s have a look first what really Viewstate is and what it really does.Unless you move to a new paradigm for building web applications like ASP.NET MVC you must have a good knowledge of Viewstate.

Viewstate represents the state of the page when it was last processed on the server. We use it to retain values across two successive requests for the same page. It is a hidden field added to the page and is restored on the server before the page request is processed. The Viewstate information travels back and forth with the page itself, but contains no visual elements that need to be rendered. So you must be thinking that this is fantastic news for the web developer. But (there is always a but), the extra information in the Viewstate adds to the size of the page and the information that travels down the wire. I have seen web pages that have an additional 20Kbytes of Viewstate information.

Every .aspx page derives from the Page class or Page control and extends it. The default value for the EnableViewState property for the page is True. Through that property we can get or set(enable-disable)  the view state of the control. However, EnableViewState property is ignored for child controls. So if we have EnableViewState=True for the page, which is True by default, all the child elements on that page will have EnableViewState=True for their viewstate property. So if we type this  txtname.EnableViewState = false , this will have no effect, since the textbox is the child of the .aspx page we are designing.

In ASP.NET 4.0 we have the ViewState property. There are 3 values for this property:enabled, disabled, inherit .

We can use this property to enable Viewstate for an individual control even if Viewstate is disabled for the page. We can disable the Viewstate for a control even if it is enabled on a page level.

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

VB 10.0 new features and Visual Studio 2010 IDE enhancements June 27, 2009

Posted by fofo in Visual Basic 10.0.
Tags: ,
add a comment

I have downloaded the .Net 4.0 version of the framework and VS 2010 beta version 1 from the microsoft site and I started looking at the new features, IDE e.t.c. Visual studio 2010 has some exciting features.

In this post I will try with a step by step example to highlight the new features of VB 10.0. I will also highlight some of the new enhancements on VS 2010 IDE. There are many new things in .net 4.0 and VS 2010 and certainly I will not cover everything in this post.

The first thing we must do is to create a sample application. I will create a console application. So just fire VS 2010 and from the available templates select a Console application.

Consume first mode

There is a new enhancement in the IntelliSense functionality. We have two alternatives for IntelliSense statement completion: standard mode and consume-first mode. This basically means that we consume classes,types,methods before we actually define them. Have a look at the picture below. In the Main() method I start to use this method without even declaring it first.

Sub Main()

addtwonums(3, 5)

End Sub

consume

When I type the new method I receive a curly line from the compiler and I can realise that there is not a method with such a name.

If I hit CTRL + . a simple method structure is created for me.

Private Sub addtwonums(ByVal p1 As Integer, ByVal p2 As Integer)
Throw New NotImplementedException
End Sub

Now I can go on and finish my method.

This works equally well with classes I have not implemented yet. I have the declaration below in my Main() method.

Dim myperson As New Person

With the same mechanism, CTRL+. we can have a new Person.vb file created in the Solutions window.

Auto-Implemented Properties

Auto-implemented properties, which is a feature that was available with C# 3.0, provides us with a way to specify a property of a class without having to write code to Get and Set the property.If I start setting values to the myperson object, like the code below

Dim myperson As New Person

myperson.name = “Michael”
myperson.surname = “Owen”

myperson.Walk()

I can create properties (without Get and Set)for the name,surname and a method stub for the Walk() method.So in my Person.vb file I have:

Class Person

Property name As String
Property surname As String
Sub Walk()
Throw New NotImplementedException
End Sub
End Class

Also note that you can With auto-implemented properties, a property, including a default value, can be declared in a single line. For example

Public Property Name As String = “John”

It is great seeing that Microsoft has decided to bring VB to the same level as C#. For the future of VB you can listen to this fantastic podcast where Joe Stagner talks with Lisa Feigenbaum from the .NET Managed Languages Group. Another great thing is that Αnders Hejlsberg is going to be in charge of the VB language as well. We know Anders is probably the most suitable person for driving VB to the future.

Collection Initialisers

Collection initialisers was a feature of C# 3.0 and basically it is a new syntax we can create a collection and populate it with an initial set of values. Let’s create a collection of List(Person). Each value that is supplied in the collection initializer is passed to the appropriate Add method of the collection.Inside my Main() method I can create

Dim people As New List(Of Person) From {
{New Person With {.name = “michael”, .surname = “owen”}},
{New Person With {.name = “kenny”, .surname = “daglish”}},
{New Person With {.name = “robbie”, .surname = “fowler”}}}

Please note that there is no “_”, underscore anymore.For more information on this topic see this video and this site.

Multiline Lambdas

In order to demonstrate this, let’s add another console application to our solution. Until VB 9.0 we had only inline lambda expressions. In VB 10.0 we have multiline lambdas. Consider the code below, we just have an array of temperatures and we want to find values greater than 30 degrees.

Dim temperatures(4) As String

temperatures(0) = 12
temperatures(1) = 23
temperatures(2) = 34
temperatures(3) = 45

Dim heightemperatures = temperatures.Where(

Function(temperature)
Return (temperature > 30)

End Function).ToList()

heightemperatures.ForEach(Sub(temperature)
Console.WriteLine(temperature)

End Sub)
Console.ReadLine()

As you can see in this line bit of the code,

Dim heightemperatures = temperatures.Where(Function(temperature)
Return (temperature > 30)

End Function).ToList()

I am using a multiline lambda expression where I pass into the temperature.

In this part of the code I just display the temperatures on the console by using  Lambda statements (a new feature in vb 10.0) by using the Sub keyword.

heightemperatures.ForEach(Sub(temperature)
Console.WriteLine(temperature)

End Sub)

For our array declaration we could use .Instead of typing this

Dim temperatures(4) As String

temperatures(0) = 12
temperatures(1) = 23
temperatures(2) = 34
temperatures(3) = 45

we could type this equivalent chunk of code

Dim temperatures = {12, 23, 34, 45}

This is a another new feature called array literals.

Parallel Support

We can execute parts of our program asynchronously-not in sequence using the Parallel object of the.Net 4.0 framework.

The first thing is to import the relevant namespace at the beginning of our code.

Imports System.Threading

To give you a simple example , we can write the following bit of code to output two strings in parallel on the console.Place the code inside the Main () routine.

Parallel.Invoke(
Sub()
Console.WriteLine(”My name”)
Thread.Sleep(4200)
End Sub,
Sub()
Console.WriteLine(”My surname”)
Thread.Sleep(1000)
End Sub
)

We use the Invoke method to execute the tasks in parallel.

Run the code and see that the two strings outputted  simultaneously on the screen.For more information on Parallel computing have a look here.

Call Hierarchies

This is a brand new feature of the IDE in VS 2010. If you select a method and right click on it and select View Call Hierarchy so we can see in a niew window that appears titled “Call Hierarchy” which method calls (Calls to) this particular method and what methods this method calls(Calls from). See the picture below.

call hierarchies

Quick Symbol Search

In the code editor if you type CTRL + , the Navigate To window appears. You can enter the name of the type,variable you want and it will find all instances and by clicking on them you will navigate easily to them. Have a look at the picture below.

quick search

Highlighting References

We can highlight all instances of a particular of property , method e.t.c by simply clicking on it.

We can navigate between instances with CTRL+SHIFT+DOWN ARROW or CTRL+SHIFT+UP ARROW.

Enhancements to ASP.NET Multi-Targeting

In Visual Studio 2008, when we targeted a project for an earlier version of the .NET Framework most features of the development environment adapted to the targeted version. However, IntelliSense displayed language features that are available in the current version, and property windows displayed properties available in the current version. In Visual Studio 2010 only language features and properties available in the targeted version of the .NET Framework are shown.

Code Editor

The new Code Editor makes code easier to read. You can zoom in on text by pressing CTRL and scrolling with the mouse wheel.

Visual Studio Debugger

There are Breakpoint enhancements in VS 2010 such as

  • Searching in the Breakpoints window
  • Label breakpoints
  • Import and export breakpoints
  • String comparison for breakpoint conditions in native debugging

See the picture below.

breakpoints

Components

The Chart Control

This control sports various chart types, including point, column, bar, area, doughnut and many more.It can be rendered in a 3D mode. For more information click here and here .

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

Lambda Expressions with VB.Net June 25, 2009

Posted by fofo in VB 9.0, Visual Studio 2005, Visual Studio 2008.
Tags:
1 comment so far

Another idea-concept that is tightly linked with LINQ is LAMBDA expressions.

Lambda expressions are shorthand for anonymous delegates . Basically delegates allow you to create a variable that “points” to a method. We can use this variable at any time to invoke the method.

Lambdas are used extensively in LINQ queries, which are by nature pretty functional.

I will start talking a little bit about delegates and giving a short example on delegates before moving into lambda expressions.

You can start a Console application project with Visual Studio 2008/2010 (Express editions will also do) . Give your project a name and make sure VB is selected as the language of choice.

The first step when using a delegate is to define its signature. I am going to define a method signature for a function which is basically: its return type, the number of parameters it has, and the data type of each parameter.

Public Delegate Function FunctionForString(ByVal s As String) As Boolean

Now we can define a method that uses our new delegate as an input parameter.  This particular method will accept a string array, and accept an instance of the delegate (some algorithm to perform on a string), then  for each string in the array, it will apply the algorithm to it the return the array of strings back.

Public Function OperateStringArray(ByVal theStrings As String(), ByVal myFunction As FunctionForString) As String()

Dim myList As New List(Of String)
Dim mystring As String

For Each mystring In theStrings

If myFunction(mystring) = True Then
myList.Add(mystring)
End If

Next

Return myList.ToArray()

End Function

The code above is very easy to understand. I just loop through the string array that has been passed in and I am going to perform myFunction(whatever has been passed in to the input parameter of type delagate) and perform it on each item in the string array, and if that is True, I will add it to a list. It is not confusing as it sounds. When you will run the code step by step it will make sense. Now I need to create a method that matches the delegation declaration.When this method will be passed as an argument to the OperateStringArray it becomes an instance of the delegate.

Public Function StringsFinishingWithS(ByVal s As String) As Boolean
Return s.EndsWith(”s”)
End Function

The method above matches the delegate declaration since it takes a string parameter and returns a Boolean result.

Basically it returns True if the string passed in, finishes with an “s”.

Now let’s write the code in our Main routine.

Sub Main()

Dim myStrings As String() = {”Davis”, “Jones”, “Beckett”, “Jordan”, “Kennt”}

Dim stringsA As String() = OperateStringArray(myStrings, AddressOf StringsFinishingWithS)

For Each s In stringsA
Console.WriteLine(s)
Next

Console.WriteLine(”Press enter to continue …”)
Console.ReadLine()

End Sub

In this routine, I use our OperateStringArray, which knows how to loop through an array of strings (passed in as the the first parameter) and apply an algorithm to it (the method that encapsulates the algorithm is passed in as the second parameter).

Run you application. I suggest you use breakpoints and use F11 to execute step by step and see what is really happening.

The whole code in my Module1.vb module is

Module Module1

Public Delegate Function FunctionForString(ByVal s As String) As Boolean

Public Function OperateStringArray(ByVal theStrings As String(), ByVal myFunction As FunctionForString) As String()

Dim myList As New List(Of String)
Dim mystring As String

For Each mystring In theStrings

If myFunction(mystring) = True Then
myList.Add(mystring)
End If

Next

Return myList.ToArray()

End Function

Public Function StringsFinishingWithS(ByVal s As String) As Boolean
Return s.EndsWith(”s”)
End Function

Sub Main()

Dim myStrings As String() = {”Davis”, “Jones”, “Beckett”, “Jordan”, “Kennt”}

Dim stringsA As String() = OperateStringArray(myStrings, AddressOf StringsFinishingWithS)

For Each s In stringsA
Console.WriteLine(s)
Next

Console.WriteLine(”Press enter to continue …”)
Console.ReadLine()

End Sub

End Module

Let’s make some alterations in our code to incorporate the concept of Lambda expressions in it. By doing that we hope to have less and more elegant code. The purpose of Lambda expression is to be a shorthand for an anonymous delegate.

What I will do inside the Main() routine, is to remove the delagate and replace this  bit of code

Dim stringsA As String() = OperateStringArray(myStrings, Function(s As String) s.StringsFinishingWithS(”s”))

with this

Dim stringsA As String() = OperateStringArray(myStrings, Function(s As String) s.EndsWith(”s”))

Our StringsFinishingWithS is gone now because we can use a lambda expression instead to perform the simple algorithm. I took the body of the StringsFinishingWithS method and in-lined it as the input parameter to OperateStringArray.  I define the delegate’s method signature as:

Function (string S)

to match the OperateStringArray function type definition.

We could easily change our code above to work with generics and not just strings.

In order to change the delagate declaration to use generics we do this

Public Delegate Function FunctionGeneric(Of T)(ByVal s As T)

Our OperateStringArray becomes

Public Function OperateStringArray(ByVal theStrings As String(), ByVal myFunction As FunctionGeneric(Of String)) As String()

Dim myList As New List(Of String)
Dim mystring As String

For Each mystring In theStrings

If myFunction(mystring) = True Then
myList.Add(mystring)
End If

Next

Return myList.ToArray()

End Function

We can use the Func instead of  the delegate we defined. Func is a generic delegate which can be used by anyone.
Our function join given string and string, it returns a “string”.Now, I will dynamically assign the parameters and body of the function and name it join.

So If I comment everything out and just leave my Main() declaration, I have this chunk of code.

Dim join As Func(Of String, String, String) = Function(a, b) a  &  “  “  & b

Dim value As String = join(”nik”, “fofo”)

Console.WriteLine(value.ToString())
Console.ReadLine()

If you would like the source code just leave a comment and I will email it to you shortly afterwards.

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 C#, Visual Studio 2008, asp.net, c# 3.0.
Tags: , ,
2 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