Sunday, November 26, 2006

.Net Layered Design (Automated) with LLBL Gen. Pro.

Exploring LLBL Gen. Pro.

Want to know what is LLBL Gen. Pro. ??? than click here.

Using LLBL Gen. Pro. tool is divided into Three parts
Part 1: Discuss All about Generating Files from LLBL Tool.
Part 2: Execute StoredProcedure in Database.
Part 3: Discussion about using files generated from LLBL Tool.

Part1
Step1: Enter DB Server., user-id and password.


Step2: Select Table.


Step3: Select Language option and namespace. Select DBNull value support and property option rather than web.config file option.


Step4: Select the field names


Step5: Start Generation : It will generate three files clsCustomer.cs, clsDBInteractionBase.cs and Northwind_LLBL_StoredProcedures.txt

clsCustomer.cs - It consist of functions for SelectOne, SelectAll, Update, Delete, Insert, Update.

clsDBInteractionBase.cs - It is a abstract class which needs to be included once for all the tables, it consist of functions such as BeginTransaction, CommitTransaction, RollbackTransaction, and so on which are require for DBInteraction.

Northwind_LLBL_StoredProcedures.txt - It consist of stored procedure to be executed on database.


Part2
Step1: Open QueryAnalyzer, and select the database. (here choose Northwind).

Step2: Copy all the content from "Northwind_LLBL_StoredProcedures" file and execute it in query analyser.


Part3
Step1: Create New Web Project (you can use it with window project, but for this example i am going to explain with Web Project).

Step2: Add New Class Library project. (you can make individual class library project outside main project and add its .dll file as reference)




Step3: Add Files to Class Library Project.
Files to be add as existing items are:
- clsCustomer.cs and
- clsDBInteractionBase.cs (Note: clsDBInteractionBase class needs to be added only 1 time for N no. of classes (associated with tables))

After Files are added.


Step4: Make changes in clsDBInteractionBase.cs file.
In InitClass() method, change m_ScoMainConnection.ConnectionString = ConfigurationSettings.AppSettings["connStr"].ToString();
where "connStr" is a key for connection string define in web.config file.
This change will help you to use connection string from web.config file.

Also, if required, In clsCustomer.cs file replace Int32 with SqlInt32.

Step5: Add the reference of class project within your web project to use its functionality. Right click on web project and click on add reference and add choose project tab., add the Northwind Class.

Step6: For testing the functionality take a datagrid on form.

Step7: Switch to Code view and add namespace of generated file.
eg: using NorthwindLLBL;

Step8: Add code to display all the data of customer in datagrid.
eg:
if(!Page.IsPostBack)
{
clsCustomers objCust = new clsCustomers();
DataGrid1.DataSource = objCust.SelectAll();
DataGrid1.DataBind();
}

That it, you are done with it, so now Depend on your need you can perform different operations as everything is ready for your use.

Friday, November 24, 2006

.Net Layered Design (Manually)

.Net Layered design

ADO.net Programming article which focus on both how to write efficient code and how to represent the information which take advantage of layered design of .net framework. Articles describes how you can write code efficiently and improve performance of application and avoids errors due to poor coding style.



Target Audience

Programmers having basic ADO.net Knowledge and who are interested to write efficient industry based ADO.net programming.

Advantage / Why use of Layered Design???
This article focus on how to efficiently write database programming so that we can take following advantage and prepared a layered code which is followed by industry standards.

i) Opening of connection for a short time and Closing it as soon as database task is completed, it thus help in improving performance of application.

ii) Better usage of Error-Handling, to make sure that connection is closed even if the exception occurs.

iii) Follow Stateless design, taking all needed information as parameter and return all the data through return value. It helps in load balancing and it would be easy while implementing web-service.

iv) Storing connection string in app.config file allow us to made a single change, to change a connection string. It helps in connection pooling.


Preparing Code

Now, that you ready to learn how to write ADO.net Programming efficiently lets execute the preliminary steps to make code ready for your demo.

Open DemoCode Application
Change Server Name in "app.Config" File if your database is located on Remote Server. Also modifies connection string if it requires user id and password.

Open and Login to MS SQL SERVER, open query analyzer and execute following stored procedure

Select "NORTHWIND" Database

1) Adding Employee Record
create proc procInsertEmployee
@EmployeeId int OUTPUT,
@FirstName varchar(20),
@LastName varchar(20)
as
Insert into employees
(FirstName,LastName)
values
(@FirstName,@LastName)
set @EmployeeId = @@Identity

2) Updating Emplyee Record
create proc procUpdateEmployee
@EmployeeId int,
@FirstName varchar(20),
@LastName varchar(20)
as
Update Employees
set
FirstName = @FirstName,
LastName = @LastName
where EmployeeId = @EmployeeId

3) Delete Employee Record
create proc procDeleteEmployee
@EmployeeId int
as
Delete from Employees
where EmployeeId = @EmployeeId

4) Get Specific Employee
create proc procGetEmployeeRec
@EmployeeId int
as
select EmployeeId,FirstName,LastName
from employees
where EmployeeId = @EmployeeId

5) Get All Employees
Create proc procGetAllEmployee
as
select EmployeeId,FirstName,LastName
from employees

How it works!!!
ADO.net Programming Style consist of Layered design which describes as bellow:

1. User Interface Layer

User Interface consist of Forms which are been designed to interact with User.

Screen Shot


2. Stub for Accessing Database Layer

Stub for accessing database layer is been prepared by creating classes which contains a specific details related to access data and task such as adding, editing and deleting functionality..

Note: Connection string is retrieved from section of the app.config file, rather than hard-coded. This is beneficial for connection pooling, which ultimately improves performance of application.



Stub consist of two class files:

1) A data details class and

2) A database utility class.

1) Data Details Class: It consist of details of record which is manipulated.

public class EmpDetails
{
/* Declaring Property for each field. */
private int employeeId;
public int EmployeeId
{
get{return employeeId;}
set{employeeId = value;}
}

private string firstName;
public string FirstName
{
get{return firstName;}
set{firstName = value;}
}

private string lastName;
public string LastName
{
get{return lastName;}
set{lastName = value;}
}

/* Constructor definition */
public EmpDetails(int employeeId,
string firstName,string lastName)
{
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
}
}


2) Database Utility Class: It consist of different data manipulation operation (such as add, delete, update, select) which is performed to the actual database.

public class EmpDB

{

string connStr;

/* Retrieving Connection String in Constructor*/
public EmpDB()
{

connStr = ConfigurationSettings.AppSettings["connStr"];

}



/* Insertion of employee details*/
public int InsertEmployee(EmpDetails emp)
{



// Opening Connection
SqlConnection conn = new SqlConnection(connStr);

// Creating Command

SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;

cmd.CommandText = "procInsertEmployee";



// Adding required parameter
cmd.Parameters.Add(new SqlParameter("@EmployeeId",SqlDbType.Int));
cmd.Parameters["@EmployeeId"].Direction = ParameterDirection.Output;

cmd.Parameters.Add(new SqlParameter("@FirstName",SqlDbType.NVarChar,20));

cmd.Parameters["@FirstName"].Value = emp.FirstName;

cmd.Parameters.Add(new SqlParameter("@LastName",SqlDbType.NVarChar,20));

cmd.Parameters["@LastName"].Value = emp.LastName;

try

{

conn.Open();


// Executing Command and retrieving result.

int RecordsAffected = cmd.ExecuteNonQuery();
int EmpId;

if(RecordsAffected != 0)

EmpId = (int)cmd.Parameters["@EmployeeId"].Value;

else

EmpId = -1;

return EmpId;

}

catch(SqlException ex)

{

throw new ApplicationException("Data Error");

}

finally

{

// Ensuring that Connection is closed even if exception occurs.
conn.Close();
}

}


// Similarly Perform different database opperation
// Check out "EmpDB.cs" for demo code.
public int UpdateEmployee(EmpDetails emp)
{...}

public int DeleteEmployee(int EmployeeId)

{...}

public EmpDetails GetEmployee(int EmployeeId)

{...}

public EmpDetails[] GetAllEmployee()

{...}

}

3. Database Layer
Database layer is server where MS SQL Server is installed, or where the database is actually stored. This code design is independent of database layer.

Conclusion
Thus by end of this article, you have understand how to write efficient code and how to represent the information which take advantage of layered design of .net framework. You must also now aware about how you can write code efficiently and improve performance of application and avoids errors due to poor coding style.

Hope to hear your useful comments so that together we can make programming easy and efficient.

Wednesday, November 22, 2006

null and its related problem

null and its related problem
I have recieved many queries stating that my ViewState is null than to (ViewState["Test"] != null) doesn't satisfies, what could be the problem why i am recieving such a abnormal output.

Identifying the cause of problem and its resolution

Case 1: When assigning unassigned value to ViewState or Session.
Example:
int iFlag;

ViewState["Test"] = iFlag;

if (ViewState["Test"] != null)
{
Response.Write("I am In");
}
else
{
Response.Write("I am Out");
}
Thanks to the compiler that it identifies such errors at compile time and so it wouldn't be headache for yours.

//Output of above code.
Error : Use of unassigned local variable 'iFlag'


Case 2: When assigning unassigned value of class variable to ViewState or Session.
Example:
ViewState["Test"] = clsGlobal.iFlag; //Definition in clsGlobal: public static int iFlag;

if (ViewState["Test"] != null)
{
Response.Write("I am In");
}
else
{
Response.Write("I am Out");
}

//Output of above code.
I am In
Note: whenever you are assigning integer value to ViewState or Session, unassigned int value is not equals to null and so the output.

Same code with unassigned string variable of class would have work perfectly as per your desire as unassigned string variable is null.
Example:
ViewState["Test"] = clsGlobal.striFlag; //Definition in clsGlobal: public static string striFlag;

if (ViewState["Test"] != null)
{
Response.Write("I am In");
}
else
{
Response.Write("I am Out");
}
//Output of above code.
I am Out

So the moral of disscusion is to avoid such errors it is better to take precaution before assigning integer value to ViewState or Session.
Example:
if(clsGlobal.iFlag != 0)
ViewState["Test"] = clsGlobal.iFlag;

if (ViewState["Test"] != null)
{
Response.Write("I am In");
}
else
{
Response.Write("I am Out");
}
This code will work perfectly
//Output of above code.
I am Out

Saturday, November 18, 2006

Understanding Globalization and Localization Concept

Understanding Globalization: Globalization is process of identifying all the localizable resources in the application, that will support multiple cultures. Ideally it is perform during design phase of an application, so that the resources always remains separate from the code.

Understanding Localization: In Localization you customize the application for new locales. This consist of translating resources that you identified during the globalization phase.

Difference between Localization and Globalization: Globalization is process of identifying how many resources needs to be localized to adopt a multiple culture support, while Localization is actual process of translating resource to a specific culture.

Understanding concept with Example
Step1: Create a Web Project.

Step2: Design your form.
For this example : Take 4 label controls, 4 textbox controls and 1 drop-down list control.
Place the control on form as shown in figure.


Step3: Identifying Resources that needs to be localized (Globalization Phase).
We want the output as shown in figure:

So here Resource that needs localization are

Language Name Label
Long Date Label
currency Label
Amount Label


Now, Applying Localization to resources which needs to be localized and globalization phase. (Localization Phase begin).

Step5: Creating Resource File.
For this example i am creating resource file for French and German culture and other culture would get value from default resource file. Right click the Project in Solution Explorer and add a folder and name it. here i have named it to "MyLocalResources" you can name accordingly.

Now, Right click the Project in Solution Explorer and add a Resource File and add the content as shown in figure.

Creating Default Resource File "MyRes.resx"
(content of this resource file would be applied to resource in case resource content for language selected by user is not available.)


Creating French Resource File


Creating German Resource File


Step6: Adding code in .CS file to make it work

Adding Namespace
using System.Globalization;
using System.Threading;
using System.Resources;
using System.Reflection;

Filling Dropdown with set of languages for user-choice.
Code in Page Load Event.

if(!Page.IsPostBack)
{
//CultureInfo Class GetCultures gives collection of language.
foreach(CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
//Filling the language collection into drop-downlistbox for user choice.
ddlLanguage.Items.Add(new ListItem(ci.EnglishName,ci.Name));
}
//Calling the Event when page loads for the first time.
ddlLanguage_SelectedIndexChanged(sender,e);
}

Assigning selected language value to current thread, to reflect changes.
private void ddlLanguage_SelectedIndexChanged(object sender, System.EventArgs e)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlLanguage.SelectedValue);
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlLanguage.SelectedValue);

//Applying Localization
ApplyLocalization();
ApplyUILocalization();
}

Code which requires localization value.
private void ApplyUILocalization()
{
ResourceManager rm = new ResourceManager("LocalizationPrac6.MyLocalResources.myRes",Assembly.GetExecutingAssembly(),null);
if(rm != null)
{
lblLanguageName.Text = rm.GetString("webform1.lblLanguageName");
lblLongDate.Text = rm.GetString("webform1.lblLongDate");
lblCurrency.Text = rm.GetString("webform1.lblCurrency");
lblAmount.Text = rm.GetString("webform1.lblAmount");
}
}

Code which does not requires localization.
private void ApplyLocalization()
{
//Lets Assume currency and amount to keep example simple.
double dblCurrency = 500.50;
double dblAmount = 9580000.75;

//No extra effort for localization as you see here.
txtLangName.Text = ddlLanguage.SelectedItem.Text;
txtLongDate.Text = DateTime.Now.ToLongDateString();
txtCurrency.Text = dblCurrency.ToString("c");
txtAmount.Text = dblAmount.ToString("n");
}


Now, run the application and select the different culture and based on selection you will get the localized display as shown in figure:

When associated resource file not available culture from Default Resource File would be shown.



Selecting French Culture

Selecting German Culture

Wednesday, November 15, 2006

Pirated Versions Of Vista Won't Last Long

Microsoft on Wednesday said that pirated copies of Windows Vista "will be of limited value" because the operating system's integrated anti-counterfeit technology would disable the fakes in short order.

The Redmond, Wash. developer's response was an answer to earlier reports that final code of both Windows Vista and Office 2007 had been posted to BitTorrent download sites, peer-to-peer networks, and Usenet groups. On some message forums, pirates gloated that they could side-step Vista's product activation process with "cracked" keys.

"The copies of Vista available for download are not final code and users should avoid unauthorized copies which could be incomplete or tampered," a Microsoft spokesperson said.

"These unauthorized downloads rely on the use of pre-RTM [released to manufacturing] activation keys that will be blocked using Microsoft's Software Protection Platform. Consequently, these downloads will be of limited value," the spokesperson added.

The new authentication scheme for Vista -- which Microsoft dubs "Software Protection Platform" -- is supposed to render the operating system inoperative if it suspects a product key is bogus. Copies of the OS whose product keys have been blocked eventually drop into a barely-usable state where only the Internet Explorer browser works, and then only for an hour before its user is automatically logged off. Office 2007, meanwhile, will use a less robust anti-piracy scheme based on Windows XP's already-deployed Windows Genuine Advantage technology.

Windows Vista and Office 2007 are scheduled to launch to businesses at the end of November, and will land in retail on Jan. 30 2007.

Read More...

Tuesday, November 14, 2006

Microsoft released .NET 3.0

Microsoft released the .NET Framework 3.0, which contains the final release of the Windows Presentation Foundation. The main code base has remained the same at its core .NET 3.0 is the same framework as .NET 2.0. The addition of new features such Windows Communication Foundation (WCF), Windows Presentations Foundation (WPF), Windows Workflow Foundation (WWF), and Windows Cardspace caused the version update.A list of available download is stored on the .NET Framework blog.

Sunday, November 12, 2006

Response.Redirect(url,true) Vs Response.Redirect(url,false)

To avoid ThreadAbortException while Redirect

You don't need to put the redirect in a try-catch block. Just replace all calls to Response.Redirect(url) with the following two lines:

Response.Redirect(url, false);

That will avoid the exception being thrown and gracefully end execution of the thread and event chain. See http://www.c6software.com/CodeSolutions/dotnet/ThreadAbortException.aspx for a full solution explanation.

Thursday, November 09, 2006

BlogStars Contest Winner

Its a good news from microsoft team that they found my blog among 20 top bloggers list.




Check out the URL for more details : http://www.microsoft.com/india/blogstars/winners.aspx

Monday, November 06, 2006

Error: Cannot interpret token

Cannot interpret token '!'

This error will occur when you try to pass an Invalid Token specifier.
eg:drCheck = dsSaveTemplate.Tables[0].Select("isExists = 'true' and template_code != '6'");

You will recieve error similar to this...Cannot interpret token '!' at position 37.

Solution
Make use of proper token specifier in search field.
eg: != is replaced with <>drCheck = dsSaveTemplate.Tables[0].Select("isExists = 'true' and template_code <> '6'");

So whenever this error occurs try to find out help on available valid token specifier for a given argument.

Microsoft Zune

iPod Owners Willing To Switch To Microsoft Zune

Many prospective buyers of digital music players, including those who currently use Apple's iPod, would be likely to choose Microsoft's upcoming Zune player, a market research firm said Wednesday.

A survey of 1,725 U.S. teenagers and adults found that of those who planned to buy a digital music player in the next 12 months, 58% who owned iPods and 59% who owned some other brand were either "somewhat likely" or "extremely likely" to choose a Zune, ABI Research said.

Read More...

Saturday, November 04, 2006

Gmail for Mobile webpage

Users can download the free application directly to their mobile device from the Gmail for Mobile webpage. The software requires users to provide their own wireless data connection.

Users can currently access Gmail messages through mobile browsers or built-in email clients, but the new Gmail for Mobile claims to offer a better user experience.

Thursday, November 02, 2006

Microsoft .NET Micro Framework


The Microsoft .NET Micro Framework brings a full-featured managed code environment to smaller, less expensive, and more resource-constrained devices than could previously be served by such cutting-edge technology. Using only a few hundred kilobytes of RAM and an inexpensive processor, the Microsoft .NET Micro Framework platform gives you the means to build applications by using the same unsurpassed development tools and advanced languages that you use to build desktop applications. Currently, this framework supplies the software platform for all Smart Watches for MSN® Direct. There are also plans to include it in Windows Vista™ SideShow displays and in an upcoming version of Microsoft TV Foundation Edition.

The .NET Micro Framework grew out of the Smart Personal Objects Technology (SPOT) initiative, which Microsoft first publicly announced more than three years ago when it introduced the MSN Direct Smart Watch. Developing SPOT devices required support for rich graphical applications on very inexpensive and power-efficient hardware. However, it did not require all of the features that were available in Windows CE. As a result, Microsoft created the .NET Micro Framework.

Won a Monthly C# Book @ DotNetSpider.com

Hello Friends,

Won a Monthly C# Book @ DotNetSpider.com


Check out my profile @ DotNetSpider.com

Wednesday, November 01, 2006

Won a 3rd Prize Prize @ Community-Credit

Hello Friends,


Again Won a Prize @ Community-Credit






I have won 3rd Prize : BendiBoard


Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape