Wednesday, 18 February 2009

ADO.NET Entity Framework Model

ADO.net entity framework model represents an object model that contains classes (LINQ To SQL ) entities, and association between objects.These objects are based & mapped to the datasource we provide.

Object relational designer is used to create entities.Lets create a Northwind database Object Model and query it through LINQ.I am using ADO.net Entity framework wizard for quick start.
On solution right click, Add new item.
Go to Template and select ADO.net Entity Framework Model.

Name it with Nortwindsamplemodel.In th wizard Generate from database.

in next step , choose connection to datasource and datasource.
  • click on new Connection
select server name from dropdown list.
choose authentication options.
select database from dropdownlist.(In example i have used Northwindump database which is a replicated database of northwind)
Test connection and press OK
for th System administrator password (sa) i am keeping password in .config file for simpilicty of this tutorial therefore i have select the option in the step given
->Yes include the sensitive data ine connection string.
Now select the database objects you want to include as entities.

Designer creates .edmx file with database entities(tables,views,stored procedure) as object on designer surface and also creates association based on Primary key,Foreign key relationship between tables in database.Every object is mapped exactly to one matching table in database.There is no option to map one object to joined table in ADO.net entity framework.

Below figure shows Created Entities(Objects based on tables) and associations.

Now our model is complete and we just need to query the data via the model.

We will use LINQ for this purpose.(Note that DataContext is the main class to send and receive the data from database however we dont code it by our self as wizard has done it)
Lets create store and query category object through LINQ.

using (NorthWindDumpEntities NorthwindStore=new NorthWindDumpEntities())
{
var _categorylist = from _catlist in NorthwindStore.Categories
select _catlist;
foreach (Categories c in _categorylist)
{
listBox1.Items.Add(c.CategoryName);
}

}

Conclusion. ADO.net entity together with LINQ saves greater time to do same thing by creating objects manually and doing a lot of coding.

Friday, 13 February 2009

Anonymous methods & Lambda expressions

When we declare a Delegate we usually write this code,

public delegate string aDelagateFunc(string name);

Now create a function with same signature
string otherfunc(string n)
{
return "hello " + n;
}

call this function through delegate

aDelagateFunc del = new aDelagateFunc(otherfunc);
stringstrreturnval = del("World");

MessageBox.Show(strreturnval);


To reduce this amount of code , to make the called function as Inline function , C# 2.0 introduced new feature with called " anonymous Methods".

Lets declare another delegate
public string string aDelagateFunc2(string name);

associate delegate with anonymous method
aDelagateFunc2 del2 = delegate(string s) { return "hello " + s; };
Now call anonymous method
MessageBox.Show(del2("anonymous method"));

In C# latest version ( with .Net 3.0 installed) same amount of code can be done even more shorter as anonymous methods which is called lambda expression.

in Lambda expression => operator is used to indicate the parameters on left side as input parameters(similiar to a function input parameters) and right side contain statement block(function body).

let define another delegate
public delegate string LambdaDelegate(string name);

on a button click event , write this code

LambdaDelegate _lamdadel = strname => "hello " + strname;

string strResult = _lamdadel("Lamda Expression Example");
MessageBox.Show(strResult);

As we see here , lambda expression code makes coding styles even more simplier.

strname as input parameters is not given explicit type,it is implicitly converted to type string by complilor , however type can be defined explicitly as

LambdaDelegate _lamdadel = ( string strname) => "hello " + strname;

It is called Type Inference as C# compiler infer the type of input parameters from function body( determine how paarmeters are used in function body.)



There can be more than one input parameters seperated by commas.
LambdaDelegate _lamdadel = ( string strname,string strlastname) => "hello " + strname;
It is not necessary to always providea input parameters , you can leave it black if no input parametrs are required like LambdaDelegate _lamdadel= ()=>"hello ";

Query operators for example count can also be used with lambda expression.

int[] numb=new int[]{1,2,3,4,5,6,7,8,9};
int _inttotal = numb.Count(n => n % 2 != 0);
MessageBox.Show(_inttotal.ToString());


This lambda expression is used in LINQ as in given sample Zenab's Tech Blog.Net: LINQ Basics

Next topic will be on ADO.net Entity framework MODEL and LINQ to SQL.

Wednesday, 11 February 2009

LINQ Basics

Language Integrated Query is .net 3.0 new features for querying data source where data source is in the form collection of objects. It can be simple array, classes or sql databases.You can say simple "It is general type query language in .net World that can be applied to a variety of data sources."
Advantage of LINQ over conventional query languages(like SQL for databases) has one pattern of coding querying data source. For example Oracle or SQl server, posgres has different syntax of SQL and if one has to query that data sources in their relative syntax, one has to learn the syntax of each data source sql syntax.Other Advantage is of course is highly scalable object oriented code in n- tier Architecture.


LINQ query is executed through foreach statement and foreach statement requires that object that is quried should implement IEnumerable Interface.That is mandatory.so if you query a simple array , it can be queried easily with LINQ as it by default implments IEnumerable interface.All types that implments this interface are called queryable types.


Let start with simple string of array as datasource and execute it through LINQ.I will use Visual studio 2008 for example and i see

using System.Linq; namespace by default in windows forms application.


Open Windows form application. drag & drop Listbox & a button control on form. write this code on button click event.


private void button1_Click(object sender, EventArgs e)

{

String[] MoviesList = new String[] {"Dantes peak","Twister","Shashank redemption","Trueman show","National Treasure" };

var moviesn = from greatmovies in MoviesList

select greatmovies;

foreach (String favMovies in moviesn)

{

listBox1.Items.Add(favMovies);

}

}









Result is shown in screen shot below.




















I will discuss LINQ in depth with LINQ to SQL features later.

Sunday, 1 February 2009

Step by Step Guide to Integrate windows Workflow Foundation Business Process flow in Asp.net 3.5

Here is a guide to Integrate windows Workflow Foundation Business Process flow in Asp.net 3.5 C#

Windows workflow foundation is rather a programming model for creating business process workflows. before Jumping on development , you must need to know three things about windows workflow foundation

1. It has a Process Model Designer
2.Runtime Engine & Runtime Services(such as Tracking services of workflow,persistence services to store workflow execution detail in sql database.)
3.Hosting( to host a workflow in some application like Asp.net,Windows Form Application)

As i described earlier windows workflow foundation is a programming model and to integrate a workflow in Asp.net , one might think using workflow's base Libraries .yes, but the most exciting thing is to use that specific process's web service.

How?

Let expose the whole Workflow as a webservice and call that webservice from a Asp.net.
Now it seems interesting. Here is step by step guide to expose a workflow as webservice and calling webservice methods from Asp.net.

1.Open Visual studio 2008( or Visual studio 2005 with .Net 3.0 Installed).
2.Select sequential Workflow Library Template





To expose workflow as webservice , drag & drop two activities on designer
1. WebserviceInputActivity which enable workflow to receive input parameters from webservice(of course we will pass parameters from asp.net)
2. For a WebserviceInputActivity,we need WebserviceOutputActivity as well which returns a value from workflow to the calling method.Its is placed only on designer if there is a return value of the method that is activated in WebserviceinputActivity.

To expose Methods(that contains our workflow logic) as Web Method
Create an Interfacein the current project

To expose workflow as webservice , you need to drag & drop two activities on designer
1. WebserviceInputActivity which enable workflow to receive input parameters from webservice(of course we will pass parameters from asp.net)
2. For a WebserviceInputActivity,we need WebserviceOutputActivity as well which returns a value from workflow to the calling method.Its is placed only on designer if there is a return value of the method that is activated in WebserviceinputActivity.
To Expose workflow methods as Web methods,you need to create interface nad define each method.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NewUserCreationWorkflow
{
interface INewUserRequest
{
string processNewUser(string strfirstName, string strlastName);
}
}
Now in the workflow designer ,open the properties of the webserviceinput activity as it is marked with red icon (it means you to set some properties of it).


  1. Interfacetype-->NewUserCreationWorkflow.INewUserRequest(click next to interfacetype property and dialog window is opened)



2.MethodName->processNewUser
3.IsActiviting->True


4.click next to strfirstname and strlastname, adialog window is opened , click on "Bind to New Member" (to bind new member. these are input parameters and by binding to these parameters designer will create code for these properties).
Normal 0 false false false MicrosoftInternetExplorer4

   1:   public static 
 DependencyProperty webServiceInputActivity1_strfirstName1Property =
   2:   DependencyProperty.Register
   3:  ("webServiceInputActivity1_strfirstName1", typeof(System.String),
 typeof(NewUserCreationWorkflow.Workflow1));
   4:   
   5:  [DesignerSerializationVisibilityAttribute
   6:  (DesignerSerializationVisibility.Visible)]
   7:   
   8:  [BrowsableAttribute(true)]
   9:   
  10:  [CategoryAttribute("Parameters")]
  11:   
  12:  public String webServiceInputActivity1_strfirstName1
  13:   
  14:  {
  15:   
  16:  get
  17:   
  18:  {
  19:   
  20:  return 
((string)
(base.GetValue
(NewUserCreationWorkflow.Workflow1.webServiceInputActivity1_strfirstName1Property)));
  21:   
  22:  }
  23:   
  24:  set
  25:   
  26:  {
  27:   
  28:  base.SetValue
(NewUserCreationWorkflow.Workflow1.webServiceInputActivity1_strfirstName1Property, value);
  29:   
  30:  }
  31:   
  32:  }
  33:   
  34:  public static DependencyProperty
 webServiceInputActivity1_strlastName1Property = DependencyProperty.Register
("webServiceInputActivity1_strlastName1", typeof(System.String), 
typeof(NewUserCreationWorkflow.Workflow1));
  35:   
  36:  [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
  37:   
  38:  [BrowsableAttribute(true)]
  39:   
  40:  [CategoryAttribute("Parameters")]
  41:   
  42:  public String webServiceInputActivity1_strlastName1
  43:   
  44:  {
  45:   
  46:  get
  47:   
  48:  {
  49:   
  50:  return 
 ((string)
(base.GetValue
(NewUserCreationWorkflow.Workflow1.webServiceInputActivity1_strlastName1Property)));
  51:   
  52:  }
  53:   
  54:  set
  55:   
  56:  {
  57:   
  58:  base.SetValue
(NewUserCreationWorkflow.Workflow1.webServiceInputActivity1_strlastName1Property, value);
  59:   
  60:  }
  61:   
  62:  }
  63:   
  64:  private void processNewUser(object sender, EventArgs e)
  65:   
  66:  {
  67:   
  68:  Random r = new Random();
  69:   
  70:  NewUserIDTicket = webServiceInputActivity1_strlastName1 + r.Next(999).ToString();
  71:   
  72:  }
  73:   
  74:  public static DependencyProperty NewUserIDTicketProperty = 
DependencyProperty.Register("NewUserIDTicket", typeof(System.String),  
typeof(NewUserCreationWorkflow.Workflow1));
  75:   
  76:  [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
  77:   
  78:  [BrowsableAttribute(true)]
  79:   
  80:  [CategoryAttribute("Parameters")]
  81:   
  82:  public String NewUserIDTicket
  83:   
  84:  {
  85:   
  86:  get
  87:   
  88:  {
  89:   
  90:  return ((string)(base.GetValue(NewUserCreationWorkflow.Workflow1.NewUserIDTicketProperty)));
  91:   
  92:  }
  93:   
  94:  set
  95:   
  96:  {
  97:   
  98:  base.SetValue
  99:  (NewUserCreationWorkflow.Workflow1.NewUserIDTicketProperty, value);
 100:   
 101:  }
 102:   
 103:  }
 104:   
 105:  }
 106:   
 107:  }
 108:   
 109:   
 110:   
As NewUserIDTicket is return value , we need to place WebServiceOutputActivity.
After Placing, Set properties of WebServiceOutputActivity.




  • InputActivityName->webServiceInputActivity1
  • Sendingoutput->processNewUser
  • ReturnValue->(click next to the property, a dialog box opened click on 'Bind to new member' , enter NewUserIDTicket. )

Now Publish the workflow as webservice.
In solution explorer, Right click on project and select 'Publish as Webservice'.
VS will create web.config,.asmx,.dll files.

Now open asp.net application or create new asp.net application.
here in this case i will integrate this webservice in my e-commerce Asp.net web example.

Add webservice
Create a User interface form.
Add Webform
Place two textboxes , tree labels and a button


On a button click event write this code:

protected void Button1_Click(object sender, EventArgs e)
{
string newid;
NewUserWebservice.Workflow1_WebService _userwebservice = new NewUserWebservice.Workflow1_WebService();
newid= _userwebservice.processNewUser(TextBox1.Text.Trim(),TextBox2.Text.Trim());
Lbluserid.Text =newid;
}

Build the solution and run.


Thursday, 2 August 2007

Where is Global.asax file in ASP.NET 2.0

I just figure out how to add Global.asax file in Microsoft Visual Studio.Net 2005.
Here is step by step guide.



First of all you need to Add Global.asax fle from



-->right click project-->Add New Item-->Add Global.asax



change script top tag to




@ Application Language="C#" CodeBehind ="Global.asax.cs" Inherits="NEWSU.Global" %>

where NewsU is namespace in my case \.

comment all script bellow this tag.



Now add normal class file to APP_Code folder in solution.

Right click->Add New Item->Class.



Name it as Global.asax.cs

and then inherit it from System.Web.HttpApplication.

Copy code (events handlers) from Global.asax file to new Global.asax.cs file

aha now you can add your code inside and this class will always execute upon intantiation of application from web server.


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
///
/// Summary description for Global
///

///
namespace NEWSU
{
public partial class Global : System.Web.HttpApplication
{
public static int usercnt = 0;
public Global()
{
//
// TODO: Add constructor logic here
//
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}