Saturday, November 18, 2006

Working with global variable in c#

There are lots of questions about the way to declare the global level variable in C#.
If you are true VB programmer, you might have declared public variable in module.bas.
This variable is accessed through out the project. But what about in c#?
Does it support global variable to retain the value in app life time?
Eventhough the answer is Yes, many people does not know to declare global level variable.
Common scenario is global level database variable.
In c#, it is very easy. There is something called static variable. You can use the help of static variable as follows:
In your Program.cs, declare the following variable

public static OdbcConnection myConn= new OdbcConnection();

There should be a function to open the database as follows:
public int DatabaseConnect()
{
try
{
myConn.ConnectionString = strDBConnectionString;
myConn.Open();
if (myConn.State.ToString().Trim() !="Open")//if database connection failed then {
return 0;
}
else
{ return 1;
}
}
catch (OdbcException odbcex)
{
MessageBox.Show(odbcex.Message.ToString());
return -1;
}
}

Since there should be only one datbase instance, you can delcare it as static. To access the static variable, you don't have to create the class instance. In your login screen or MDI screen, you can access the function using the following syntax:
Program.DatabaseConnect();
and you can use the myConn object variable in all windows forms just by calling the myConn variable.


Write me if you have any doubt: soshekar@gmail.com

Database Insert statement Made easy

Writing Database insert, update statement is allways tedious task especially if you have large number of table fields. Even if you have a database stored procedure, you will be passing huge string as an input parameter. I bet, you may end up by debugging the code to findout the errors in sql statement. Either there is no coma, no single quots, passed values are lesser than the actual numbers etc are common problems.How do I comeout from the mess? There is no inbuilt function you can use. I will help you to have a better framework.
  • I assume that you are using SQL Server and ODBC connection.
    Create a stored procedure in your SQL server database as follows:

CREATE PROCEDURE [dbo].[InsertRecord]@tablename varchar(25) , @statement varchar(5000), @ReturnValue int OUTPUT
AS

BEGIN execute(@statement);

if @@error<>0 begin return 0; end else begin SET @ReturnValue= IDENT_CURRENT(@tablename); return @ReturnValue; end
END

GO
//The above sql code will create a storede procedure named "InsertRecord". This has two

//input parameters and one output parameter. The first parameter will

//accept the table name. Second parameter will accept the insert statement

//(I will explain about generating the insert statement) and the third paramete will


//return the next auto generated id. So make sure that, your target table name should

//have an auto generated field.Now, this much is enough in database.


//Letus go to c# code and write a function as follows:you should have the following lines of

//code in bigining:

using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

using System.Data.Odbc;

using System.Collections.Specialized;

using System.Windows.Forms;
//In you class, declare a global bariable as follows:
NameValueCollection FieldValue=new NameValueCollection();
public void Add(string p_fieldName, string p_fieldValue, string p_dataType)

{

p_fieldValue = p_fieldValue.Replace("'", "''");

if (p_dataType == "I")

{

FieldValue.Add(p_fieldName, p_fieldValue);

}

if (p_dataType == "S" p_dataType == "D")

{

FieldValue.Add(p_fieldName,"'" +p_fieldValue +"'");

}

}

//Our next step is to prepare the sql statement from the values we have passed into

//FieldValue using Add function

private string PrepareInsertSQLStatement(string tablename)

{

string FieldNames = "INSERT INTO " + tablename +" (", FieldValues = "(";

for (int i = 0; i <= FieldValue.Count - 1; i++)

{

FieldNames += FieldValue.GetKey(i).ToString() +",";

FieldValues += (FieldValue.GetValues(FieldValue.Keys[i])[0]).ToString() + ",";

}

FieldNames = FieldNames.Remove(FieldNames.Length - 1);

FieldNames += ") VALUES";

FieldValues = FieldValues.Remove(FieldValues.Length - 1);

FieldValues += ")";
FieldValue.Clear();

return FieldNames + FieldValues;

}
public int InsertRecordStatement(string tablename)

{

try

{

string strSQLStatement = PrepareInsertSQLStatement(tablename); OdbcCommand p_Command = new OdbcCommand("{ call InsertRecord (?, ?,?)}", mydatabaseConnectionObject);

p_Command.CommandType = CommandType.StoredProcedure;

OdbcParameter prm = p_Command.Parameters.Add("@tablename", OdbcType.VarChar);

prm.Direction = ParameterDirection.Input;

prm.Value=tablename;

OdbcParameter prm1 = p_Command.Parameters.Add("@statement", OdbcType.VarChar); prm1.Direction = ParameterDirection.Input;

prm1.Value = strSQLStatement;
OdbcParameter prm2 = p_Command.Parameters.Add("@ReturnValue", OdbcType.Int);

prm2.Direction = ParameterDirection.ReturnValue;
p_Command.ExecuteNonQuery();

if (p_Command.Parameters[2].Value.ToString() != "")

{

return (int)p_Command.Parameters[2].Value;

}

else

return 0;

}

catch (OdbcException odbcexp)

{

MessageBox.Show(odbcexp.Message.ToString());

return 0;

}

}
//we are through with the code!!.//In your window form, on click of a command button, create an instance of the class you have as follows:
DataBaseClass dbclass=new DataBaseClass();
//we will use the Add function to add the fields and value
dbClass.Add("field1","value1","S");

dbClass.Add("field2","value2","S");

dbClass.Add("field3","value3","S");

dbClass.Add("field4","value4","D");

dbClass.Add("field5","value5","I");

dbClass.Add("field6","value6","S");

dbClass.Add("field7","value7","S");
//you can add as much as you want.

//Once you are through, call InsertStament function as follows:

int intReturnID=dbClass.InsertStatement("tablename");

//If the insert is successfull, then intReturnID will hold its auto generated value.

***

Friday, November 17, 2006

Windows Workflow Foundation (WWF)-Base Activity

Windows Workflow Foundation (WWF)-Base Activity
In this session, we will explore the concept of Base activity in WWF. This is in continuation of my previous post which deals with Custom Activity.

  • Create a new project in Visual Studio 2005 by selecting Sequential Workflow Console Application template. Name the project as "swcaCustomPropertySample".
    Your designer will have graphical representation of the workflow .
  • In Program.cs, you can see few auto generated code lines, which includes WorkflowCompleted and WorkflowTerminated events. Do not change the code. Compile the project and make sure that it is successful.
  • Our next step is to add an activity project to the solution. Then we will add two code activities in to the activity project.
  • Create a new project in Visual Studio 2005 by selecting Workflow Activity Library template. Name the project as "swcaBaseActivityLibrary".
    You can see the designer with "Drop Activities Here".
  • Right click on the item "Activity1" and select the Properties. You can see the properties of Activity1 in property window.
    We will concentrate on "Base Class" property now.
  • Click on "..." button and go to "Browse and select a .NET type" window.
    Under Type tab, select System.Workflow.ComponentModel. This will display "Activity" and "CompositActivity".
    Select "Activity".Click on Ok button.
  • View the change that happend to the designer window.
  • Right click on Activity1 and select "View Code" menu. This will take you to the code behind file.
    You can see the following code by default:
    public Activity1()
    {
    InitializeComponent();
    }
  • Place the cursor bellow the last bracket and right click and select "Insert Sniplet". From the context menu, double click on "Workflow".
  • Select "DependencyProperty-Property"
    This will add few lines of code. We need to customize this as bellow:
    public static DependencyProperty FirstNameProperty =
    System.Workflow.ComponentModel.DependencyProperty.Register("FirstName", typeof( string), typeof(Activity1));
    [Description("First Name")]
    [Category("NameActivity")]
    [Browsable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public string FirstName
    {
    get
    {
    return ((string)(base.GetValue(Activity1.FirstNameProperty)));
    }
    set
    {
    base.SetValue(Activity1.FirstNameProperty, value);
    }
    }
    protected override ActivityExecutionStatus Execute(ActivityExecutionContext
    executionContext)
    {
    Console.WriteLine(FirstName);
    Console.ReadKey();
    return ActivityExecutionStatus.Closed;
    }
    Your activity has 1 custom property. You can add more properties as per your interest.
  • Rebuild the solution and make sure that it is successful. After rebuild, you can see your activity in the ToolBox.
  • Double click on the designer in swcaCustomPropertySample project you created.
  • Add the activity you have created into "Drop Activities to create a Sequential Workflow".
    Right click on the added activity and select "Properties" menu. You can see the property window. Specify the value for "FirstName" property. Type "karada". You MUST enclose the value in "quots".
    Run the application and watch the output!!!

    Note: This is the very basic behaviour of a workflow. We can create very complex system later.
    write me if you have any doubts: soshekar@gmail.com



Windows Workflow Foundation (WWF)-Base Activity

Windows Workflow Foundation (WWF)-Base Activity
In this session, we will explore the concept of Base activity in WWF. This is in continuation of my previous post which deals with Custom Activity.

Create a new project in Visual Studio 2005 by selecting Sequential Workflow Console Application template. Name the project as "swcaCustomPropertySample".
Your designer will have graphical representation of the workflow .
In Program.cs, you can see few auto generated code lines, which includes WorkflowCompleted and WorkflowTerminated events. Do not change the code. Compile the project and make sure that it is successful.
Our next step is to add an activity project to the solution. Then we will add two code activities in to the activity project.
Create a new project in Visual Studio 2005 by selecting Workflow Activity Library template. Name the project as "swcaBaseActivityLibrary".
You can see the designer with "Drop Activities Here".
Right click on the item "Activity1" and select the Properties. You can see the properties of Activity1 in property window.
We will concentrate on "Base Class" property now.
Click on "..." button and go to "Browse and select a .NET type" window.
Under Type tab, select System.Workflow.ComponentModel. This will display "Activity" and "CompositActivity".
Select "Activity".Click on Ok button.
View the change that happend to the designer window.
Right click on Activity1 and select "View Code" menu. This will take you to the code behind file.
You can see the following code by default:
public Activity1()
{
InitializeComponent();
}
Place the cursor bellow the last bracket and right click and select "Insert Sniplet". From the context menu, double click on "Workflow". Select "DependencyProperty-Property"
This will add few lines of code. We need to customize this as bellow:
public static DependencyProperty FirstNameProperty =
System.Workflow.ComponentModel.DependencyProperty.Register("FirstName", typeof( string), typeof(Activity1));
[Description("First Name")]
[Category("NameActivity")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string FirstName
{
get
{
return ((string)(base.GetValue(Activity1.FirstNameProperty)));
}
set
{
base.SetValue(Activity1.FirstNameProperty, value);
}
}
protected override ActivityExecutionStatus Execute(ActivityExecutionContext
executionContext)
{
Console.WriteLine(FirstName);
Console.ReadKey();
return ActivityExecutionStatus.Closed;
}
Your activity has 1 custom property. You can add more properties as per your interest.
Rebuild the solution and make sure that it is successful. After rebuild, you can see your activity in the ToolBox.
Double click on the designer in swcaCustomPropertySample project you created.
Add the activity you have created into "Drop Activities to create a Sequential Workflow".
Right click on the added activity and select "Properties" menu. You can see the property window. Specify the value for "FirstName" property. Type "karada". You MUST enclose the value in "quots".
Run the application and watch the output!!!

Note: This is the very basic behaviour of a workflow. We can create very complex system later.
write me if you have any doubts: soshekar@gmail.com

Windows Workflow Foundation (WWF)-Composite Activity

I was searching for a good article with step by step example for WWF activity. I wondered, i could not find a good article. I am always interested in sharing my knowledge to the world. So thought to write a small white paper which talks about Composite Activity in WWF.
***
Activities are the primary unit of execution and can be reused in different ways.
In this lession, I will teach you to create Composite Activity using WWF.
A composite activity is the one created by the user and is available in Visual Studio 2005 ToolBox.
You can drag and place to your designer the way you do with Base activity. A Base activity is the one you are seeing in ToolBox by default.
Activity is nothing but a class.
This class will have the methods to execute.

  • Create a new project in Visual Studio 2005 by selecting Sequential Workflow Console Application template.
  • Name the project as "swcaCompositeActivity".
    Your designer will have graphical representation of the workflow .
  • In Program.cs, you can see few auto generated code lines, which includes WorkflowCompleted and WorkflowTerminated events. Do not change the code. Compile the project and make sure that it is successful.
  • Our next step is to add an activity project to the solution. Then we will add two code activities in to the activity project.
  • Create a new project in Visual Studio 2005 by selecting Workflow Activity Library template. Name the project as "swcaCompositeActivityLibrary".
    You can see the designer with "Drop Activities Here".
  • Drag a code activity from the tool box and drop it on "Drop Activities Here".
    Now you can see a code activity in the work area.
  • Double click on this code activity. You can see a new event named codeActivity1_ExecuteCode automatically generated.
    Write a greeting message inside the event.
  • Your code should look like this:
    private void codeActivity1_ExecuteCode(object sender, EventArgs e)
    {
    Console.Write("hello ,");
    }
    Now, go back to the designer by selecting the menu View->Designer
    Drag one more code activity. Double click on this activity to see its ExecuteCode.Modify the ExecuteCode as follows:
    private void codeActivity2_ExecuteCode(object sender, EventArgs e)
    {
    Console.Write("where are you?");
    Console.ReadLine();
    }
  • Compile the project and make sure that it is successful.
    Double click on swcaCompositeActivity design template. You can see "Drop Activities to create a Sequential Workflow"
  • In ToolBox, you should see the activity you have created in swcaCompositeActivityLibrary.
  • Drag this activity into to Drop Activity place.
    The code activities we have created will execute sequentially.
    Run the application and you should see "Hello ,where are you?" message in console window.
    To terminate the application just press enter key.
    Note: This is the very basic behaviour of a workflow. We can create very complex system later.
    write me if you have any doubts: soshekar@gmail.com