Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Sunday, September 11, 2011

Method Overloading Best Practise – Do’s and Don’t

In this article i will explain what to do and what to avoid while going for method overloading.


Let's breifly understand what is Method Overloading, it is method with same name but with different arguments is called method overloading.


Example of Method Overloading

//SendEmail without Header and Footer
bool SendEmail(string Subject, string Body, string ToEmail) {}


//SendEmail with only Footer
bool SendEmail(string Subject, string Body, string ToEmail, string Footer) {}


//SendEmail with both Header and Footer
bool SendEmail(string Subject, string Body, string ToEmail, string Footer, string Header) {}

Must follow rules while doing method overloading

1 Method Body should not be repeated in every method,   don’t write same code in every method, instead, call the method by passing default parameter.



//SendEmail without Header and Footer
bool SendEmail(string Subject, string Body, string ToEmail) {
   //Since we don’t have footer, call method by passing empty string
   return SendEmail(Subject, Body, ToEmail, string.Empty);
}

//SendEmail with only Footer
bool SendEmail(string Subject, string Body, string ToEmail, string Footer) {
   //Since we don’t have header, call method by passing empty string
   return SendEmail(Subject, Body, ToEmail, Footer, string.Empty);
}

//SendEmail with both Header and Footer
bool SendEmail(string Subject, string Body, string ToEmail, string Footer, string Header) {           
    bool IsEmailSendSuccessfully = false;
   string WebsiteName = ConfigurationManager.AppSettings["WebsiteName"].ToString();
   string EmailServer = ConfigurationManager.AppSettings["EmailServer"].ToString();
   string FromEmail = ConfigurationManager.AppSettings["EmailDoNotReply"].ToString();
   string FromEmailPassword = ConfigurationManager.AppSettings["EmailPassword"].ToString();
   Body = Header + Body + Footer;
   try
  {
       MailMessage MyMailMessage = new MailMessage(FromEmail, ToEmail, Subject, Body);
       MyMailMessage.IsBodyHtml = true;
       MailAddress objMailAddr = new MailAddress(FromEmail, WebsiteName);
       MyMailMessage.From = objMailAddr;
       SmtpClient mailClient = new SmtpClient(EmailServer);
       mailClient.Credentials = new NetworkCredential(FromEmail, FromEmailPassword);
       mailClient.Send(MyMailMessage);
       IsEmailSendSuccessfully = true;
    }
    catch (Exception ex)
   {
     IsEmailSendSuccessfully = false;
     ErrorMessages.ErrorReporting(ex);
    }
    return IsEmailSendSuccessfully;
}


2 Avoid changing name of parameters for Overloaded Methods 

Bad Example:

bool SendEmail(string Subject, string Body, string ToEmail) {}


bool SendEmail(string Title, string Message, string ToEmail, string Footer) {}


bool SendEmail(string SubjectTitle, string BodyMessage, string ToEmail, string Footer, string Header) {}



In above method  you might have notice that we are using different parameter name for Subject and Body, across different method overload function, try to avoid that.

Good Example:

bool SendEmail(string Subject, string Body, string ToEmail) {}


bool SendEmail(string Subject, string Body, string ToEmail, string Footer) {}


bool SendEmail(string Subject, string Body, string ToEmail, string Footer, string Header) {}




3 Avoid changing sequence of parameters for Overloaded Methods, Ordering of overloaded method should be consistent.

Bad Example:

bool SendEmail(string Subject, string Body, string ToEmail) {}


bool SendEmail(string Body, string Subject, string Footer, string ToEmail) {}


bool SendEmail(string Footer, string Header, string Subject, string Body, string ToEmail) {}

In above examples sequence of overloaded method are not consistent.  Try to avoid that to avoid confusion and making things complex.

Good Example:
bool SendEmail(string Subject, string Body, string ToEmail) {}


bool SendEmail(string Subject, string Body, string ToEmail, string Footer) {}


bool SendEmail(string Subject, string Body, string ToEmail, string Footer, string Header) {}

Saturday, September 10, 2011

Programming Best Practise consideration

Here are some of programming best practise, a quick reference.

For Events
Consider placing the code where the event is raised in a try-catch block to prevent program termination due to unhandled exceptions thrown from the event handlers.

For Fields
1) Do not use public field, rather declare private field, and expose them through properties.
2) Use constant fields for fields which are not going to change.

For more details visit
http://msdn.microsoft.com/en-us/library/ms229042.aspx

Thursday, September 08, 2011

Naming Convention for Code and DB

First let’s understand different types of casing styles.

  • 1)    UpperCase – All letters in uppercase. Example: ISITEMREQUIRED
  • 2)     LowerCase – All letters in lowercase. Example: isitemrequired
  • 3)     CamelCase – first letter in identifier is lowercase and each subsequent concatenated word is capitalized.  Example: isItemRequired
  • 4)     PascalCase – first letter in identifier and each subsequent concatenated word is capitalized.  Example: IsItemRequired

Naming Convention for Coding

Identifier

Casing Style to use

Example

Local variable declarations

Camel casing

userName

Private variables

Camel casing

statusMessage

Property declaration

Pascal casing

ForeColor

Public variables

Pascal casing

ErrorCode

Const, Static or Readonly fields

Pascal casing

IsMembershipRequired

Method Name

Pascal casing

ProcessApplication()

Enum

Pascal casing

MembershipLevels

Class Name

Pascal casing

MemberDetails

Interface

Pascal casing

IDisposable, *Using “I” in front of interface name to avoid confusion between other class, while inheriting.

Events

Pascal casing

SubmitButtonClick, use “Functionality name” + “Event name”

Namespace

Pascal casing

CompanyName.ProjectName


To summarize it easily, anything which is public in nature then use pascal casing.  Avoid using underscore “_” or hyphen “-“ while naming identifier.




Naming Convention for Database

Table name convention.
·         It should be in UpperCase
·         It should not have Spaces
·         Multiple words should be split with Underscore, since some of DB Client always shows DB name in uppercase, using case will not be good choice.
·         It should be Plural (more than one in number) - Example: EMPLOYEES Table, rather than EMPLOYEE.  If it contains multiple words only last word should be plural.  Example: EMPLOYEE_PHOTOS


Field name convention.
·         It should not have Spaces
·         Multiple words should be split with Underscore.
·         It should be Singular - Example: EMPLOYEE_ID column name, rather than EMPLOYEES_ID or EMPLOYEE_IDS.

For Datatype consideration, refer my article.

Procedure name convention
·         Procedure name should be defined as TableName_ProcedureFunctionalityName.  Example: Employees_SelectAll,  Employees_Insert, Employees_Update, Employees_Delete.  If table name is too long, it is also better to use short name of table rather than full tablename prefix, Example: Emp_SelectAll, Emp_Insert.  If table name contains multiple words like Employee_Locations then it is better to give name like EL_SelectAll, EL_Insert.  If short name are getting duplicate, then you can change of one of short name to avoid duplication or confusion.
·         If you are creating procedure which is general in nature or combines 2 or more tables or mainly business logic which cannot be associated with any table, then it is better to use as BusinessLogicName_ProcedureFunctionalityName.  Example:  procedure for employees quarterly sales report should be named something like Reports_Emp_Quaterly_Sales.  That way you can combine all reports procedure together to easily find them in a complex database structure.
·         Remember, naming convention is to help finding things easily and a standard which can be easily explain to anyone joining a development team.  So always name considering this scenario in mind.

Function name convention
·         Function name are mostly generic utilities, but incase if they are associated with table, then follow procedure naming convention approach, else use meaningful name.  Example:  AgeFromDOB  - If you pass a valid date, this function will return age, no. of years between current date and DOB.

Primary Key convention
·         Primary key should be name as PK_TableName.  Example:  PK_Employees.   If you are using SQL Server, whenever you are creating primary key in table designer, it will automatically follows above naming convention.

Foreign Key convention
·         Foreign key should be name as FK_PrimaryTableName_ForeignTableName.  Example:  PK_Employees_Departments.   If you are using SQL Server, whenever you are creating foreign key in table designer, it will automatically follows above naming convention.

Constraint name convention
·         Constraint name should be name as ConstraintShort_ConstraintColumnName.  Example: 
Default value constraint for IsActive column field in employe table should be 1 (or true).  DF_IsActive.  Here DF stands for Default value constraint and IsActive is column field in Employees Table.

Index name convention
·         Index name should be name with prefix idx_ColumnName.  Example: 
Idx_Employee_ID

Wednesday, December 10, 2008

Reflection in C# - List of Class Name, Method Name

Reflection is way through which we can identify metadata about assembly runtime.
Example: We have a .Net Assembly file (.dll file), which consist of 2 Class Definition and 10 Method Names, We can get information about classes and method name list through reflection.

Few Examples of Reflection

Loading Assembly FileAssembly assem = Assembly.LoadFrom(sAssemblyFileName);

Get List of Class Name.
Type[] types = assem.GetTypes();

Get List of Method Name


foreach (Type cls in types)
{
try
{
//Add Namespace Name
arrl.Add(cls.FullName);

//Add Class Name
if(cls.IsAbstract)
arrl.Add("Abstract Class:" + cls.Name.ToString());
else if(cls.IsPublic)
arrl.Add("Public Class:" + cls.Name.ToString());
else if(cls.IsSealed)
arrl.Add("Sealed Class:" + cls.Name.ToString());


MemberInfo[] methodName = cls.GetMethods();
foreach (MemberInfo method in methodName)
{
if (method.ReflectedType.IsPublic)
arrl.Add("\tPublic - " + method.Name.ToString());
else
arrl.Add("\tNon-Public - " + method.Name.ToString());
}
}
catch (System.NullReferenceException)
{
Console.WriteLine("Error msg");
}
}


A Sample Application Showing Good Usage of Reflection in .Net
Following application shows how to identify list of Classes and Method in any .Net Assembly file with the help of .Net Reflection. For an example I am using Ajax Assembly filename to list all its classname and method name.



Step 1: Design a web form consisting of following controls.
Label – Shows text “Assembly File Name”
Textbox – Taking Input Assembly File Name.
Listbox – For displaying list of Class Names and Method Names
Button – On Button Click Event Display List of Class Name and Method Name

Step 2: Write following code on Button_Click Event.


private void btnListMethodName_Click(object sender, EventArgs e)
{
string sAssemblyFileName = txtAssemblyFileName.Text;

if (sAssemblyFileName.Length != 0)
{
Assembly assem = Assembly.LoadFrom(sAssemblyFileName);
Type[] types = assem.GetTypes();
ArrayList arrl = new ArrayList();
foreach (Type cls in types)
{
try
{
//Add Class Name
arrl.Add(cls.FullName);
if(cls.IsAbstract)
arrl.Add("Abstract Class:" + cls.Name.ToString());
else if(cls.IsPublic)
arrl.Add("Public Class:" + cls.Name.ToString());
else if(cls.IsSealed)
arrl.Add("Sealed Class:" + cls.Name.ToString());

MemberInfo[] methodName = cls.GetMethods();
foreach (MemberInfo method in methodName)
{
//arrl.Add("\t" + method.Name.ToString());
if (method.ReflectedType.IsPublic)
arrl.Add("\tPublic - " + method.Name.ToString());
else
arrl.Add("\tNon-Public - " + method.Name.ToString());
}
}
catch (System.NullReferenceException)
{
Console.WriteLine("Error msg");
}
}

//Dump Data to NotePad File
FileStream fs = new FileStream(@"c:\myData.txt", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
for (int i = 0; i < arrl.Count; i++)
{
lstInfo.Items.Add(arrl[i].ToString());
sw.WriteLine(arrl[i].ToString());
}
sw.Flush();
sw.Close();
}
}

Monday, September 08, 2008

C++ to C# Converter Utility

C++ to C# Converter Utility

For migration project from C++ to C# Converter, a online utility might be helpful for getting startup stuff ready.

Check out C++ to C# Converter

Wednesday, June 11, 2008

Random Password Generation

I have previously written article on how to Generate Registration Image on Fly

Enhancing the same password generation logic so that it would be useful for generating random password using C# code.



public static string GetRandomPassword(int length)
{
char[] chars = "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();
string password = string.Empty;
Random random = new Random();

for (int i = 0; i < length; i++)
{
int x = random.Next(1,chars.Length);
//Don't Allow Repetation of Characters
if (!password.Contains(chars.GetValue(x).ToString()))
password += chars.GetValue(x);
else
i--;
}
return password;
}

Its a simple logic instead by generating a random number between 1 and Length of characters. It also checks that same character is not repeated in generated password and finally return the randomly generated password string of desired length.

Thursday, May 22, 2008

Disable Multiple Button Click in Asp.net

This post is a step enhance version of my previous post: Preventing Multiple Button Click on Asp.net Page

Problem: How to disable button immediately on user click in asp.net so that user cannot click multiple time.

Solution: To solve this problem use regular html button, including runat=”server” attribute and write the disable client-side click event which disable button immediately and server-side event which runs the actual code for click event.


To perform this task add javascript function.

Client-Side Event to disable button immediately.




Note: Replace “Button1” with object name of button control

And following button code in body.


Button Control – HTML Button instead of Asp button.
onclick="DisableClick();" type="button"
value="Submit Payment" name="Button1"
runat="server" onserverclick="Button1_Click">

Note: onclick event is calling javascript client-side function and onserverclick event is calling server-side function which performs actual task.


Server-Side Event to perform actual task
This task can be any as per your logic, for an example I am performing some heavy time consuming task, you can even make use of Threading concept to minimize code…

protected void Button1_Click(object sender, EventArgs e)
{
ArrayList a = new ArrayList();
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 1000; j++)
{
a.Add(i.ToString() + j.ToString());
}
}
Response.Write("I am done: " +
DateTime.Now.ToLongTimeString());
}



Before Button Click








During Button Click







After Task is done





Related Links:

Thursday, February 28, 2008

MSDN Code Galledry - Download and Upload .Net SourceCode

MSDN Code Galledry - Download and Upload .Net SourceCode

MSDN Code Gallery is your destination for downloading sample applications and code snippets , as well as sharing your own resources.

http://code.msdn.microsoft.com/

Wednesday, February 06, 2008

Namespace Chart in .Net Framework 3.5

Namespace Chart in .Net Framework 3.5 Available for Download

Monday, December 10, 2007

Numeric String Format in .Net

Must Know Issue: Basics of String Format in .Net


Numeric Format

double dValue = 55000.54987D;

//displaying number in different formats

Response.Write("Currency Format: " + dValue.ToString("C") + "
"
);

Response.Write("Scientific Format: " + dValue.ToString("E") + "
"
);

Response.Write("Percentage Format: " + dValue.ToString("P") + "
"
);

/* OUTPUT */

Currency Format: $55,000.55
Scientific Format: 5.500055E+004
Percentage Format: 5,500,054.99 %

Getting Culture Specific String

double dValue = 55000.54987D;

//You can Remove this line

Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");

//This line will automatically detect client culture

//and display data accordingly

//Here culture has forcefully changed to german to

//view difference in output

CultureInfo ci = Thread.CurrentThread.CurrentCulture;

//displaying number in different formats

Response.Write("Currency Format: " + dValue.ToString("C",ci) + "
"
);

Response.Write("Scientific Format: " + dValue.ToString("E",ci) + "
"
);

Response.Write("Percentage Format: " + dValue.ToString("P",ci) + "
"
);

/* OUTPUT */

Currency Format: 55.000,55 €
Scientific Format: 5,500055E+004
Percentage Format: 5.500.054,99%

Tuesday, September 25, 2007

Creating Component in .Net

Creating Component in .Net

What is Component?
It is a set pre-compiled class, which is reusable. For now, just stick to it at the end of article you will practically understand how it is reusable piece of code.

Advantages of Component

  • Improving Application Performance
  • Better Code Management and Maintenance

How Component can Improve Application Performance?
CLR is place where .Net Application codes gets compiled. Whenever you made an request to ASP.NET page, the page gets compiled first and then is transferred to the user. The compilation process is also completed in two steps.
  • 1. An IL (Intermediate Language) is generated and then this is handed over for JIT
  • 2. JIT (Just In Time) compilation which produces the machine code and our pages get displayed with their dynamic content.

The performance of our web application can be improved by creating pre-compiled libraries of IL which can then be handed over to JIT directly without having the inclusion of an extra process to make the conversion. This method is called componentization. Components are pre-compiled set of classes that have been developed in the form of DLL files and can then be included within our projects. This is also known as an assembly.


How Component can be used for Better Code Management and Maintenance
As we use Componentization(refer above description), if a code change require you need to change the component code compile it, so you do not require to change all the reference of code for minor change. For better understanding understand the example of component given below.


Example of Creating Component in .Net

Creating a simple demo of famous Class Shape Example, wherein simple functionality is added.

Step1:
Create a Asp.net web application

Step2: Right click the solution explorer and add New Project "class library project"
For example, Delete the .CS File and Add Component using Project > Add New Component and Name it as csShape.cs

Note: By creating component you are actually creating assembly file and it has all the benefits that assembly has. You can edit all the assembly details by right clicking "Class Library Project" and Selecting Properties from popup window.

Step3: Created a Four Class as shown in Class Diagram



For better understanding download the Shape.CS File

Step4: Compile the Class Library Project

Step5: Add Reference to Project




Step6: Test the component.

Add namespace
using Shape;

protected void Page_Load(object sender, EventArgs e)
{
csShape objShape = new csShape();
Response.Write("
" + "I am " + objShape.ShapeName
+ " Object and my color is " + objShape.Color);

csCircle objCircle = new csCircle();
objCircle.Color = "Blue";
Response.Write("
" + "I am " + objCircle.ShapeName
+ " Object and my color is " + objCircle.Color);

csSquare objSquare = new csSquare();
objSquare.Color = "Green";
Response.Write("
" + "I am " + objSquare.ShapeName
+ " Object and my color is " + objSquare.Color);

csRectangle objRectangle = new csRectangle();
objRectangle.Color = "Orange";
Response.Write("
" + "I am " + objRectangle.ShapeName
+ " Object and my color is " + objRectangle.Color);
}


Output of Application



So now if you want to change the functionality of Shape class you can do it independently you just need to rebuild the class library application and all changes are reference without any extra effort.

Saturday, September 22, 2007

All About Web Service in .Net

This article will explain you everything about Web Services in .Net, so lets get started with Web Service

What is Web Service?

  • Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet.
  • Web Service is
    • Language Independent
    • Protocol Independent
    • Platform Independent
    • It assumes a stateless service architecture.
  • We will discuss more on web service as the article proceed. Before that lets understand bit on how web service comes into picture.

History of Web Service or How Web Service comes into existence?
  • As i have mention before that Web Service is nothing but means for Interacting with objects over the Internet.
  • 1. Initially Object - Oriented Language comes which allow us to interact with two object within same application.
  • 2. Than comes Component Object Model (COM) which allows to interact two objects on the same computer, but in different applications.
  • 3. Than comes Distributed Component Object Model (DCOM) which allows to interact two objects on different computers, but within same local network.
  • 4. And finally the web services, which allows two object to interact internet. That is it allows to interact between two object on different computers and even not within same local network.
Example of Web Service
  • Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
  • Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
  • News Headline: You can display latest news update by using News Headline Web Service in your website.
  • In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your companies advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.

Web Service Communication
Web Services communicate by using standard web protocols and data formats, such as
  • HTTP
  • XML
  • SOAP
Advantages of Web Service Communication
Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.

Terms which are frequently used with web services
  • What is SOAP?
    • SOAP are remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.
  • What is WSDL?
    • WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
    • WSDL contains every details regarding using web service
      • Method and Properties provided by web service
      • URLs from which those method can be accessed.
      • Data Types used.
      • Communication Protocol used.
  • What is UDDI?
    • UDDI allows you to find web services by connecting to a directory.
  • What is Discovery or .Disco Files?
    • Discovery files are used to group common services together on a web server.
    • Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service.
    • .Disco File (static)
      • .Disco File contains
        • URL for the WSDL
        • URL for the documentation
        • URL to which SOAP messages should be sent.
      • A static discovery file is an XML document that contains links to other resources that describe web services.
    • .VsDisco File (dynamic)
      • A dynamic discovery files are dynamic discovery document that are automatically generated by VS.Net during the development phase of a web service.
  • What is difference between Disco and UDDI?
    • Disco is Microsoft's Standard format for discovery documents which contains information about Web Services, while UDDI is a multi-vendor standard for discovery documents which contains information about Web Services.
  • What is Web Service Discovery Tool (disco.exe) ?
    • The Web Services Discovery Tool (disco.exe) can retrieve discovery information from a server that exposes a web service.
  • What is Proxy Class?
    • A proxy class is code that looks exactly like the class it meant to represent; however the proxy class doesn't contain any of the application logic. Instead, the proxy class contains marshalling and transport logic.
    • A proxy class object allows a client to access a web service as if it were a local COM object.
    • The Proxy must be on the computer that has the web application.
  • What is Web Service Description Language Tool (wsdl.exe)?
    • This tool can take a WSDL file and generate a corresponding proxy class that you can use to invoke the web service.
    • Alternate of generating Proxy class through WSDL.exe is you can use web reference. Web Reference automatically generate a proxy classes for a web service by setting a web reference to point to the web service.
    • Advantage of using Web Reference as compare to using WSDL.exe Tool is you can update changes done in web service class easily by updating web reference, which is more tedious task with WSDL.exe tool.
  • Testing a Web Service?
    • You can test web service without building an entire client application.
      • With Asp.net you can simply run the application and test the method by entering valid input paramters.
      • You can also use .Net Web Service Studio Tool comes from Microsoft.

Example of Creating Web Service in .Net

This Web Service will retrieve CustomerList Country Wise and return as dataset to client application for display.

Step1: Create a Web Service Application by File > New > Web Site > Asp.net Web Services
Named the web service, for example here i have choosen name "WSGetCustomerCountryWise"

Step2: Rename the default Service.asmx file to proper name, you also need to switch design view and change the class name with the same name you use to rename the service.asmx.
For example, "WSGetCustomerCountryWise.asmx" and switch to design view and change the class="Service" to class="WSGetCustomerCountryWise"

Step3: Rename the Service.CS File to proper name, you need to change the class name and constructor name too.
For example, "WSGetCustomerCountryWise.CS" and switch to code view and change the class and constructor name to "WSGetCustomerCountryWise"

After three steps your solution explorer looks as shown in figure




Step4: Create a Logic for Web Service
  • Create a Method "GetCustomerCountryWise"
  • Note: You need to specify [WebMethod] before method definition, if you want it to be accessible public, otherwise the method would not be accessible remotely.
  • Specify proper argument and return type for method in web service.
  • It is also good practise to specify the use "Description" attribute to tell what method is meant for.
For example, here i need to access data of northwind customers and want to return customer list country wise, so add namespace for

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

[WebMethod(Description="It will generate Customer List, Country Wise")] public System.Xml.XmlElement GetCustomerCountryWise(string sCountry)
{
string sConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();

string sSQL = "select CustomerId, CompanyName, ContactTitle, City " +
" from Customers where country = '" + sCountry + "'";

SqlConnection connCustomer = new SqlConnection(sConn);

DataSet dsCustomer = new DataSet();

SqlDataAdapter daCustomer = new SqlDataAdapter(sSQL, sConn);

daCustomer.Fill(dsCustomer,"Customers");

//Known bug while return "DataSet" is "Data source is an invalid type.
It must be either an IListSource, IEnumerable, or IDataSource."
//For more details on Error: http://support.microsoft.com/kb/317340

//So to access data we need to make use of XmlElement.

// Return the DataSet as an XmlElement.
System.Xml.XmlDataDocument xdd = new System.Xml.XmlDataDocument(dsCustomer);
System.Xml.XmlElement docElem = xdd.DocumentElement;
return docElem;
}


Step5: Build Web Service and Run the Web Service for testing by pressing F5 function key.






By pressing "Invoke" button will generate XML File.

So you are done creating web service application.

Example of Testing Web Service in .Net

This Web Service will display the information which had been retrieved from Remote computer by accessing public method "GetCustomerCountryWise".

Step1: Create a Test Web Site by File > New > Web Site > Asp.net Web Site
Named the web site, for example here i have choosen name "TestGetCustomerCountryWise"

Step2: Displaying data in gridview, so drag the gridview on to the form.

Step3: Right Click Solution Explorer and Choose "Add Web Reference"



Step4: Choose the option Web Service on the local machine or you can enter the .WSDL File address directly in URL space and press Go button.




Step5: Press "Add Reference button"


Step6: Writing Code for Displaying data in GridView
Here note: I have Pass "USA" as parameter in Country Field.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Create object of WSGetCustomerCountryWise Object
localhost.WSGetCustomerCountryWise objGetCustomerCountryWise
= new localhost.WSGetCustomerCountryWise();

DataSet dsCustomer = new DataSet();

// Get the data from Webservice.
XmlElement elem = objGetCustomerCountryWise.GetCustomerCountryWise("USA");

// Load the XML to the Typed DataSet that you want.
XmlNodeReader nodeReader = new XmlNodeReader(elem);
dsCustomer.ReadXml(nodeReader, XmlReadMode.Auto);

GridView1.DataSource = dsCustomer;

GridView1.DataBind();
}
}


Step7: Output as data displayed in GridView.




Few Facts about Web Service in .Net
  • Each Response from web service is a new object, with a new state.
  • Web Service are asynchronous because the request object from the client application and the response object from the web service are unique SOAP envelopes that do not require shared connection.
  • This allow client application and the web service to continue processing while the interaction is ongoing.
  • Instead of a user interface, it provides a standard defined interface called a contract.

Thursday, August 23, 2007

Displaying Google Map in your asp.net web application

Displaying Google Map in asp.net web application

Found 2 useful link which will help to display google map in asp.net web application within few minutes.


Saturday, August 18, 2007

How to send email from localhost

How to send email from local machine

Found an article on Sending Email from Localhost

Click here


Alternate way when you don't have your own SMTP server you can use third party email service to send email.

To know How to send email using Free Email Service. i.e. How to send email from gmail, yahoo, hotmail, rediffmail, etc

Click here

Friday, August 17, 2007

Best Practices for SQL Server 2000

Article on SQL Server 2000 Best Practices

It contain 35 useful tips, check out

Thursday, August 16, 2007

SQL Server Keyboard Shortcuts

SQL Server Keyboard Shortcuts

Complete list of SQL Server Keyboard Shortcuts

Click here

Wednesday, August 08, 2007

Regular Expression Patterns and Examples in .Net

Regular Expression Patterns and Examples in .Net

Quick Reference for Regular Expression Patterns and Examples

  • List of MetaCharacters used in Regular Expression, its Pattern and Example
  • List of Escape Characters

Regular Expression Cheat Sheet

Escape Character and Character Classes

Wednesday, August 01, 2007

Inspiration for Developers

Jawed, who is the Co-Founder YouTube , which is the 4th most-popular website in the world and one of the fastest-growing websites in the history of the Internet. Amazing to know how the idea of YouTube originated. This was the best way for me to see how things got started with YouTube. - From Ali Raza Shaikh Blog






I found it inspiring one for all developers, specially within a small span of time two gaint google and youtube has prove that "Anything is possible"

If you don't find this post inspiring one than check out the latest clip from chak de India, it is really inspiring one, well SRK is back after so long with some good movie lets hope best from this one

Cheers and Enjoy!

Saturday, July 07, 2007

What is Nullable Type in .Net 2.0?

What is Nullable Type in .Net 2.0?
Nullable in .Net 2.0, helps to determine whether variable has been assigned a value or not. Example: Quiz application having option yes/no, but it should displayed “Not Attempted” when user does not make any choice.

Declaring a variable as nullable enables the HasValue and Value members.

Nullable b = null; -OR-

// Shorthand notation for declaring nullable type, only for C#
bool? b = null;


Example of Nullable Type
Use HasValue to detect whether or not a value has been set:
if (b.HasValue)
Console.WriteLine("User has Attempted Given Question");
else
Console.WriteLine("User has not Attempted Given Question");

//Output
User has not Attempted Given Question

The Nullable type is a new feature in .NET 2.0.

Improving Performance with Connection Pooling

Improving Performance with Connection Pooling

Opening a connection is a database-intensive task. It can be one of the slowest operations that you perform in an ASP.NET page. Furthermore, a database has a limited supply of connections, and each connection requires a certain amount of memory overhead (approximately 40 kilobytes per connection).

If you plan to have hundreds of users hitting your Web site simultaneously, the process of opening a database connection for each user can have a severe impact on the performance of your Web site.

Fortunately, you can safely ignore these bad warnings if you take advantage of connection pooling. When database connections are pooled, a set of connections is kept open so that they can be shared among multiple users. When you request a new connection, an active connection is removed from the pool. When you close the connection, the connection is placed back in the pool.

Connection pooling is enabled for both OleDb and SqlClient connections by default.

To take advantage of connection pooling, you must be careful to do two things in your ASP.NET pages.

First
, you must be careful to use the same exact connection string whenever you open a database connection. Only those connections opened with the same connection string can be placed in the same connection pool. For this reason you should place your connection string in the web.config file and retrieve it from this file whenever you need to open a connection

Second, you must also be careful to explicitly close whatever connection you open as quickly as possible. If you do not explicitly close a connection with the Close() method, the connection is never added back to the connection pool.

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