Saturday, December 20, 2008

WCFService Library Simple Application

Microsoft.NET framework 3.0 had new features called WCFServiceLibrary template through this you can create the dll for your service.Mostly this will be best option of making business logic for WCF Services.

In this post,I am going to explain how to create the WCFService Libray,how to utilise them in WCFService and then consuming the services.

Step 1



Select the template name "WCFServiceLibrary" and choose the .NET framwork 3.0 as above.

Step 2

Here I just created the function name GetDataLength.This will returns the number of characters in the passing string.
Before I removed the by default text from the source file.




Step 3

An implementation of the function GetDataLength will be



Step 4

After completion of compile,you can see the dll file on your project stored location.
This will be the source for your WCF service.



Step 5

Now open second visual studio 2008 window,and choose the classing WCF Service,here you are going to use the just created WCFServiceLibrary as source.



Step 6

In your WCFService application use AddReference to include the WCFServiceLibrary's dll as below



Step 7

In your code behind,I created the WCFService method name GetDataFromLibrary,this will takes the string as parameter,and then its length will be processed by the WCFServiceLibrary and sent back to your WCFService.



Step -8
Code Implementation for the above method.



Step 9
After this run the application to create the .svc file for generating proxy class for your consumer application.



Step 10

Create the proxy class using svcutil.exe



Step 11
Add the proxy class into your website application in order to consume the WCFService that use the WCFServiceLibrary dll.And place the text box and button for checking the user input's length.




Step 12

You must copy have the endpoint details in your web.config file.Check the output.xml on your generated proxy class location.Pick the servicemodel tag and upto endof servicemodel tag as belows



On your Button click event,Just follow the same code snippet for getting the result from the WCFService.



The result I have got,

Friday, December 05, 2008

Merging the array values

Before writing the actual code I tested this arrays to calculate has to be done on one array and another will be as it is.


double[] Pre = new double[3];
Pre[0] = 1;
Pre[1] = 2;
Pre[2] = 3;
double[] Pre1 = new double[3];
Pre1[0] = 4;
Pre1[1] = 5;
Pre1[2] = 6;
string n1 = "";
string n2 = "";

for (int i = 0; i < Pre.Length; i++)
{
n1 = n1 + "-" + Pre[i].ToString() + ",";

}
for (int a = 0; a < Pre1.Length; a++)
{
n2 = n2 + Pre1[a].ToString() + ",";
}

string result = n1 + n2.TrimEnd(',');

Response.Write(result.ToString());

Wednesday, December 03, 2008

Loding multiple tables in DataSet

How to load multiple tables in DataSet programmatically ?

DataSet ds= new DataSet();
string strConn="Server=(local);dataBase=Northwind;user id=sa;password=;";
SqlConnection cn = new SqlConnection(strConn);
string strSQL="select * from Customers;select * from employees";
cn.Open();
SqlDataAdapter da = new SqlDataAdapter( strSQL,cn);
ds.Tables.Add("Customers");
ds.Tables.Add("Employees");
ds.EnforceConstraints =false;
ds.Tables["Customers"].BeginLoadData();
da.Fill(ds.Tables["Customers"]);
ds.Tables["Customers"].EndLoadData();
ds.Tables["Employees"].BeginLoadData();
da.Fill(ds.Tables["Employees"]);
ds.Tables["Employees"].EndLoadData();
dataGrid1.DataSource=ds.Tables["Customers"];
dataGrid2.DataSource=ds.Tables["Employees"];
cn.Close();

Tuesday, October 21, 2008

Webservice -Basic Authentication

Securing Webservice using IIS - Basic authentication
Once you create a webservice solution using VSS 2008 0r 2009 you MUST host them in IIS server.Please do not use or expect the VSS's built in IIS emulator will take care of authentication for your webservice.

In IIS control panel,choose your webservice directory and set to Basic Authentication checkbox ON.Decheck the Ananoymous authenticate check box.
Supply your computer's user name and password on IIS control for basic authentication.Now you have done 20 percent of secure web service hosting.

Now you need to piece of code in your client application,my code snippet is like

Service s = new Service();
ICredentials cred = new NetworkCredential("murugesa", "pandian", "pp");
s.Credentials = cred;
s.PreAuthenticate = true;
string s1 = s.HelloWorld();
Response.Write(s1);


If you are consuming the webservices from your vendor,please ask them to give their domain name,user name and password which allocated to you.

You can use them on your consume application like above how I used .

Server will check your authentication if fails,it will shows the HTTP 401 status page.

Monday, September 22, 2008

XML Attributes and value reading

System.IO.StreamReader stream = new System.IO.StreamReader(@"D:\MyText.xml");
XmlTextReader reader = null;
reader = new XmlTextReader(stream);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an Element.
Response.Write( reader.Name);

while (reader.MoveToNextAttribute()) // Read attributes.
Response.Write(" " + reader.Name + "='" + reader.Value + "'");

break;
case XmlNodeType.Text: //Display the text in each element.
Response.Write(reader.Value);
break;
case XmlNodeType.EndElement: //Display end of element.
Response.Write(" Response.Write(">");
break;
}
}

Wednesday, September 17, 2008

Difference between two dates

This codesnippet for finding the differences between two given dates.
You can calculate for the months and years also by using this.

DateTime dt1 = Convert.ToDateTime(TextBox1.Text.ToString());
int t1 = dt1.Day;

DateTime dt2 = Convert.ToDateTime(TextBox2.Text.ToString());
int t2 = dt2.Day;


DateTime r1 = new System.DateTime(dt2.Year, dt2.Month, dt2.Day, 12, 0, 0);

DateTime r2 = new System.DateTime(dt1.Year, dt1.Month, dt1.Day, 12, 0, 0);
System.TimeSpan result = r1 - r2;
Response.Write(result.Days);

Thursday, July 31, 2008

Writing XML dynamically

string xmlFile = Server.MapPath("UserControl.xml");
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(xmlFile, null);
writer.WriteStartDocument();
writer.Formatting = Formatting.Indented;
writer.WriteStartElement("InputValue");


for (int i = 0; i < 3; i++)
{

writer.WriteAttributeString(i.ToString(),i.ToString());
//writer.WriteElementString(i.ToString(), i.ToString());
}
writer.WriteEndElement();
writer.Close();

Monday, July 28, 2008

Range value setting in C#

string Source = TextBox2.Text;
string oops1,oops2;
int a1, a2;
string[] First = Source.Split('-');
for (int i = 1; i < First.Length; i++)
{
oops1 = First[0];
oops2 = First[1];
a1 = Convert.ToInt32(oops1);
a2 = Convert.ToInt32(oops2);
for (int ii = a1; ii <= a2; ii++)
{
DropDownList1.Items.Add(ii.ToString());
}

}

Sunday, July 27, 2008

Extracting string through comma separator in C#

Separating the given string into commas and adding them to dropdownlist.


string Months = TextBox1.Text;
string[] ind = Months.Split(new char[]{','});
foreach(string m in ind)
{

DropDownList1.Items.Add(m.ToString());



}

How to Querying XML raw data

This code snippet for loading XML file in to Dataset and then querying particular record as we practising on SQL-Query.

DataSet ds = new DataSet();
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(File.ReadAllText(@"E://Form.xml"));
ds.ReadXml(new XmlNodeReader(xDoc));
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["ID"].Equals(TextBox1.Text))
{
Response.Write(dr["txtControlName"].ToString() + "\t");
Response.Write(dr["lblControlName"].ToString());

}


}

Wednesday, July 23, 2008

DataSet as ArrayList in C#

protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=(local);Database=Test;user id=sa;pwd=####");
con.Open();
SqlDataAdapter sq = new SqlDataAdapter("SELECT *From Employee", con);
DataSet ds = new DataSet();
sq.Fill(ds, "Employee");
ArrayList arrList = new ArrayList();


foreach (DataRow dr in ds.Tables[0].Rows)
{

arrList.Add(dr["Name"]);
GridView1.DataSource = arrList;
GridView1.DataBind();

string[] strArray = arrList.ToArray(typeof(string)) as string[];


}

sq.Dispose();
con.Close();
Response.Write("Done!");

}
}

Tuesday, July 22, 2008

Dynamically showing the TextBox in C#

Its a manual TextBox showing accordingly the requirements.

string[] s1 ={ "TextBox4", "TextBox3","TextBox1" };

TextBox[] _TxtLoop = new TextBox[2];
for (int i = 0;i<_TxtLoop.Length; i++)
{
for(int ii=0;ii {

string t1 =s1[ii].ToString();
TextBox txt=(TextBox)FindControl(t1);
txt.Visible=true;

}


}

Monday, July 21, 2008

dynamically adding TextBox

SqlConnection con = new SqlConnection("Data Source=(local);Database=Test;user id=sa;pwd=***");
con.Open();
SqlDataAdapter sq = new SqlDataAdapter("SELECT *From Employee", con);
DataSet ds = new DataSet();
sq.Fill(ds, "Employee");

foreach (DataRow dr in ds.Tables[0].Rows)
{
string test = "Murugesan";

TextBox txt = (TextBox)this.FindControl(test);

txt.Visible = true;

}


sq.Dispose();
con.Close();


}

Tuesday, July 15, 2008

switch-vb.net

Sub Main()
Dim keyIn As Integer
WriteLine("Enter a number between 1 and 4")
keyIn = Val(ReadLine())

Select Case keyIn
Case 1
WriteLine("You entered 1")
Case 2
WriteLine("You entered 2")
Case 3
WriteLine("You entered 3")
Case 4
WriteLine("You entered 4")
End Select

End Sub

Wednesday, July 02, 2008

Reflection-C#

This part is copied from Gopalan Suresh Raj's article for my reference purpose.

C# Reflection and Dynamic Method Invocation
Gopalan Suresh Raj

The Reflection API allows a C# program to inspect and manipulate itself. It can be used to effectively find all the types in an assembly and/or dynamically invoke methods in an assembly. It can at times even be used to emit Intermediate Language code on the fly so that the generated code can be executed directly.

Reflection is also used to obtain information about a class and its members. Reflection can be used to manipulate other objects on the .NET platform.

The Reflection API uses the System.Reflection namespace, with the Type class to identify the Type of the Class being reflected, and fields of a struct or enum represented by the FieldInfo class, Members of the reflected class represented by the MemberInfo class, Methods of a reflected class represented by the MethodInfo class, and parameters to Methods represented by the ParameterInfo class.

The Activator class's CreateInstance() method is used to dynamically invoke instances on the fly. Dynamic Invocation is very useful in providing a very late-binding architecture, where one component's runtime can be integrated with other component runtimes.

Obtaining All Classes and Their Type Information from an Assembly
using System;
using System.Reflection;

/**
* Develop a class that can Reflect all the Types available in an Assembly
*/
class ReflectTypes {

public static void Main (string[] args) {

// List all the types in the assembly that is passed in as a parameter
Assembly assembly = Assembly.LoadFrom (args[0]);

// Get all Types available in the assembly in an array
Type[] typeArray = assembly.GetTypes ();

Console.WriteLine ("The Different Types of Classes Available in {0} are:", args[0]);
Console.WriteLine ("_____");
// Walk through each Type and list their Information
foreach (Type type in typeArray) {
// Print the Class Name
Console.WriteLine ("Type Name : {0}", type.FullName);
// Print the name space
Console.WriteLine ("Type Namespace : {0}", type.Namespace);
// Print the Base Class Name
Console.WriteLine ("Type Base Class : {0}", (type.BaseType != null)?type.BaseType.FullName:"No Base Class Found...");
Console.WriteLine ("_____");
}
}
}

Sunday, June 29, 2008

TextSearching-Javascript

Simple utilities in javascript for checking user input number in the given numbers.
function ValidTextCheck()
{
var b ="3,5,7,9,10";
var temp = new Array();
temp = b.split(' ');
for(i=0;i < temp.length;i++)
{
var ss=document.getElementById('TextBox1').value;
var sta=temp[i].indexOf(ss);
}
alert(sta);
}

This function will return -1 if the user input doesn't match with pre defined string format variable b.

Thursday, June 26, 2008

onPaste Event handler in JavaScript

This is an simple example for how to user onPaste events in html page
textarea cols=60 onpaste="window.alert('Pasting not allowed!)">
/textarea

Wednesday, June 25, 2008

Javascript validation-ASP.NET

function Murugesan()
{
var d=document.getElementById('TextBox1').value;
if(d=="")
{
alert("cant be blank");
return false;
}
else
{
return true;
}

}
Place above source code on source code window between head tag.Here I simply check the TextBox,wheather it has value or blank.

On code behind file,
Register the control which has to be call this javascript.
Button1.Attributes.Add("onclick", "return Murugesan()");

Thursday, June 12, 2008

webservice part 3

Now how do I use the service?

When Microsoft's Visual Studio.Net ships it will take care of discovering and importing web services for programmatic use, with effort on par with adding a reference in Visual Basic. In the meantime though, the .Net team has created a console application that takes care of requesting the SDL contract of remote web services and generating a proxy to use the service. In order to use a remote web service a few things need to happen.

First you need to know where the web service resides(ex http://www.servername.com/wstest.asmx). Next you need to create a local proxy for the remote service. The proxy allows the developer to work with the remote service as though it were local to the machine. When instantiated, the proxy accepts method calls from your code as though it were the remote service object. Calls are packaged up into SOAP methods and shipped via HTTP to the remote web service. If everything goes correctly, the remote service receives the request, unwraps the envelope, does the work that you asked it to do, then returns the results in a result envelope. Once the proxy receives this returned envelope, it is unwrapped and delivered to your code as a native method call.

The Web Services Utility

The wsdl is a console application that is supplied in Microsoft's .Net SDK. The utility takes care of requesting a SDL contract from a remote web service via HTTP and generating a proxy class for you. Although the Web Services Utility uses C# as its default proxy generation language, any language (including VB and JScript) that implements the ICodeGenerator interface will work. For us to create a proxy class for accessing my web service we use the command below:

wsdl "http://localhost/services/TimeService.asmx" /out:TimeServiceProxy.cs

The /c: parameter informs the utility that I want it to create a proxy for me. The /pa: parameter is the path to the SDL contract; this can be a local path, UNC path or URI. when we run this command a .cs file will be generated. TimeServiceProxy.cs An instance of this object is what takes care of accepting method calls, packaging up calls for SOAP, invoking via HTTP and returning the results if any to the caller. Now that you have a proxy you need to compile it using the appropriate compiler depending on the language you chose. The following command assumes that the C# compiler (csc.exe) is in the system's path and that you are working in the directory where your web service's .asmx file resides.

On my system the TimeService.asmx file is located at C:\inetpub\wwwroot\Services. Since we are working with C#, the command is (this should be on one line):

csc /out:bin\TimeServiceProxy.dll /t:library /r:system.web.services.dll /r:system.xml.serialization.dll TimeServiceProxy.cs

This command creates a DLL (library) named TimeServiceProxy.dll in the C:\inetpub\wwwroot\Services\bin directory importing the resources System.Web.Services.dll and System.xml.serialization.dll. Once we have the DLL in the bin directory of our ASP.NET application we access the methods of the remote web service as though they were running locally. But this remote web service is not limited to being used only by ASP.NET. Any .Net class can now access our time web service

TimeTest Application

To demonstrate that our time web service is usable by any .Net application, I have created a simple console application in C# that prints out the time from the remote service. This application is compiled into an executable (.exe) as opposed to a library (.dll): The TimeTestApp.exe first creates a new instance of our TimeService class that lives in the bin/TimeServiceProxy.dll assembly. Then a call is made to the GetTime method of the TimeService class (ts). The returned value is stored in a local variable named lt. The lt variable is of the type LocalTime. In case it isn't obvious, I want to point out that the LocalTime object that we are now using was originally defined in our remote .asmx file. The WebServiceUtil was able to create a local definition of the LocalTime struct based on the SDL contract that was generated and returned from the Web Service handler. Next in our code, we call GetTime and then begin to simply construct a couple of local strings that contain our formatted time and date. Then we write out the results using Console.WriteLine:

using System;
class MyClass
{
static void Main()
{
TimeService ts = new TimeService();
LocalTime lt = ts.GetTime();
string stime = lt.Hour + ":" + lt.Minute + ":" + lt.Seconds + "." +
lt.Milliseconds + " " + lt.Timezone;
string sdate = lt.Month + "/" + lt.Day + "/" + lt.Year;
Console.WriteLine("The remote date is: " + sdate);
Console.WriteLine("The remote time is: " + stime);
}
}

To compile the TimeTest application use the following command:

csc /r:system.web.services.dll /r:TimeServiceProxy.dll TimeTestApp.cs

This command will create an executable named TimeTestApp.exe in the local directory. We could have been explicit in telling the C# compiler that we wanted an executable, but the compiler creates executables (/target:exe) by default. Another item that should be noted is that although ASP.NET applications look in the bin directory within an ASP.NET application directory to resolve references, non-ASP.NET applications first look in the current directory and then in the system path to resolve assembly references.

Webservice Part 2

First Web Service

The code below is an actual working web service:

<%@ WebService Language="C#" class="GreetingService" %>
using System;
using System.Web.Services;
public class GreetingService
{
[WebMethod]
public string SayHello(string Person)
{
return "Hello, " + Person;
}
}

Returning Complex Types

Our greeting service is only returning a string. Strings as well as most numbers are considered simple types. Web services are not limited to these simple types for return values or inbound parameters. Our next web service will demonstrate how to return a complex type. For this we will create a web service that returns the date and time from the server. We could just return the date and time within a string type and force the caller to parse the string, but this wouldn't be ideal. Instead, we are going to create a LocalTime struct that will be returned to the caller. For those people that may be unfamiliar with structs, they are synonymous with VB's user-defined types (UDT). A walkthrough of the code shows us defining a LocalTime struct that will contain all of the date and time information to be returned to the client. Our LocalTime struct holds seven values; Day, Month, Year, Hour, Minute, Seconds, Milliseconds, and Timezone. The struct's definition is below:

<%@ WebService Language="C#" class="TimeService" %>
using System;
using System.Web.Services;
public struct LocalTime
{
public int Day;
public int Month;
public int Year;
public int Hour;
public int Minute;
public int Seconds;
public int Milliseconds;
public string Timezone;
}
public class TimeService
{
[WebMethod]
public LocalTime GetTime()
{
LocalTime lt = new LocalTime();
DateTime dt = DateTime.Now;
lt.Day = dt.Day;
lt.Month = dt.Month;
lt.Year = dt.Year;
lt.Hour = dt.Hour;
lt.Minute = dt.Minute;
lt.Seconds = dt.Second;
lt.Milliseconds = dt.Millisecond;
lt.Timezone = TimeZone.CurrentTimeZone.StandardName;
return lt;
}
}

Webservices in C#

Introduction

A web service allows a site to expose programmatic functionality via the Internet. Web services can accept messages and optionally return replies to those messages.

More About Web Services

Today's sites already expose functionality that allows you to do things such as query a database, book an airline reservation, check the status of an order, etc, but there is no consistent model for allowing you to program against these sites. Web Services can be invoked via HTTP-POST, HTTP-GET and the Simple Object Access Protocol (SOAP). SOAP is a remote procedure call protocol and specification developed by a group of companies including Microsoft and DevelopMentor. SOAP is based on broadly adopted Internet standards such as XML and typically runs over HTTP

For more information on SOAP please see the SOAP specification on MSDN. Visual Studio.NET will be the formal shipping vehicle for creating rich web services on the .Net platform. With the release of Visual Studio.NET(http://msdn.microsoft.com/vstudio/nextgen/default.asp) you will be able to create web services using ASP.NET and any language that targets the common-language runtime (CLR) or ATL Server and unmanaged C++. ATL Server is a collection of ATL (Active Template Library) classes that aid the C++ developer in writing native, unmanaged ISAPI extensions and filters.

Modules and Handlers

Instead of the .aspx file extension of an ASP.NET Web page, web services are saved in files with the extension of .asmx. Whenever the ASP.NET runtime receives a request for a file with an .asmx extension, the runtime dispatches the call to the web service handler. This mapping is established in the section of the config.web files for the machine and individual applications. Config.web files are human-readable, XML files that are used to configure almost every aspect of your web applications.

Handlers are instances of classes that implement the System.Web.IHTTPHandler interface. The IHTTPHandler interface defines two methods, IsReusable and ProcessRequest. The IsReusable method allows an instance of IHTTPHandler to indicate whether it can be recycled and used for another request. The ProcessRequest method takes an HttpContext object as a parameter and is where the developer of a HTTP handler begins to do his work. A particular handler ultimately services inbound requests that are received by the ASP.NET runtime. After a handler is developed, it is configured in the config.web file of the application. A typical config.web file for a machine will have lines similar to the ones below:

< add verb="*" path="*.asmx" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services" validate="false" />


section states that for all requests (HTTP verbs such as GET, POST, PUT), if the file being requested has the extension of .asmx, create an instance of the WebServiceHandlerFactory, which lives in the System.Web.Services.dll assembly. If the administrator wanted this handler to only accept the GET verb, he would change the verb property to verb="Get".

Handlers accept requests and produce a response. When the HTTP runtime sees a request for a file with the extension of .aspx the handler that is registered to handle .aspx files is called. In the case of the default ASP.NET installation this handler will be System.Web.UI.PageHandlerFactory. This is the same way in which .asmx files are handled. For the default ASP.NET installation, web services are handled by System.Web.Services.Protocols.WebServiceHandlerFactory.

With this custom handler, ASP.NET is able to use reflection and dynamically create an HTML page describing the service's capabilities and methods. The generated HTML page also provides the user with a way in which to test the web methods within the service. Another advantage of ASP.NET is in publishing Web Service Definition Language (WSDL) contracts.

WSDL is an XML-based grammar for describing the capabilities of web services. WSDL allows a web service to be queried by potential consumers of your service - you can think of it as an XML-based type library made available via the web. For output to be generated, one must only make a HTTP request to the web service file passing in sdl in the querystring

SDL is an XML-based grammar for describing the capabilities of web services. SDL allows a web service to be queried by potential consumers of your service-you can think of it as an XML-based type-library made available via the web. For output to be generated, one must only make a HTTP request to the web service file passing in sdl in the querystring

(e.g. http://locahost/services/myservice.asmx ). Another nice aspect of the web service handler is that it creates a simple test web page for your services. This test page allows you to confirm that everything is working with your web service without having to write your own test client.

Continued on Webservice-Part 2

Friday, June 06, 2008

Javascript Validation - ASP.NET

This simple explanation will help you to implement more and pop up logics to work out.

Go to design page of your page and place the script tag between head tag.

I wanted to check my text box had value or not.
I name it txtAmount and then validation starts here,

function CheckValues()
{
if(document.getElementById("<%=txtAmount.ClientID%>")=="")
{
alert("You forgot to mention your deposit amount!");
document.getElementById("<%=txtAmount.ClientID%>").focus();

return false;
}
return true;
}
}

Now I completed the Validation part,Now I need to register this validation accepted by the server,so go to Code behind file

Add this line on OnClick Events of the Button

Button1.attributes.Add("OnClick","return CheckValues()");

Tuesday, June 03, 2008

Excel reading in C#

using System;
using System.Data.OleDb;
using Microsoft.Office.Interop.Excel;

using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class ExcelReader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=F://MuruAjax/Book1.xls;" +
"Extended Properties=Excel 8.0;";
OleDbConnection oc = new OleDbConnection(strConn);
oc.Open();
//You must use the $ after the object you reference in the spreadsheet
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", oc);

DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, "ExcelInfo");
GridView1.DataSource = myDataSet.Tables["ExcelInfo"].DefaultView;
GridView1.DataBind();
myCommand.Dispose();
oc.Close();



}
protected void Button2_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;
Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
ObjExcel.DisplayAlerts = false;
ObjExcel.Visible = false;

ObjWorkBook = ObjExcel.Workbooks.Open(@"F:\MuruAjax\kotak.xls", false, true,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);

ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[2];

ObjWorkSheet = null;
ObjWorkBook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlDoNotSaveChanges, Type.Missing, Type.Missing);
ObjExcel = null;


}
}

Monday, June 02, 2008

WebService in C#

Writing a Web Service in .NET using VS .NET very is easy. However, it is possible to write Web Services using the plain .NET SDK. I struggled a lot to write Web Services without VS .NET and tried to find help on the Net. There are a lot of examples available for writing Web Services using VS.NET, but you will rarely find any examples of writing Web Services using only the .NET SDK. This article is exactly for this purpose. It looks at Web Services development using the .NET SDK alone.

We will write and publish a simple web Service. We will also write two Web Service consumers: one Web-based consumer (ASP.NET application) and another Windows application-based consumer. Let's start writing our first Web Service.

Writing a Web Service
Following is our first Web Service; it exposes two methods (Add and SayHello) as Web Services to be used by applications. This is a standard template for a Web Service. .NET Web Services use the .asmx extension. Note that a method exposed as a Web Service has the WebMethod attribute. Save this file as FirstService.asmx in the IIS virtual directory (as explained in configuring IIS; for example, c:\MyWebSerces).

FirstService.asmx
<%@ WebService language="C" class="FirstService" %>

using System;
using System.Web.Services;
using System.Xml.Serialization;

[WebService(Namespace="http://localhost/MyWebServices/")]
public class FirstService : WebService
{
[WebMethod]
public int Add(int a, int b)
{
return a + b;
}

[WebMethod]
public String SayHello()
{
return "Hello World";
}
}
To test a Web Service, it must be published. A Web Service can be published either on an intranet or the Internet. We will publish this Web Service on IIS running on a local machine. Let's start with configuring the IIS.

Open Start->Settings->Control Panel->Administrative tools->Internet Services Manager.
Expand and right-click on [Default Web Site]; select New ->Virtual Directory.
The Virtual Directory Creation Wizard opens. Click Next.
The "Virtual Directory Alias" screen opens. Type the virtual directory name—for example, MyWebServices—and click Next.
The "Web Site Content Directory" screen opens. Here, enter the directory path name for the virtual directory—for example, c:\MyWebServices—and click Next.
The "Access Permission" screen opens. Change the settings as per your requirements. Let's keep the default settings for this exercise. Click the Next button. It completes the IIS configuration. Click Finish to complete the configuration.
To test that IIS has been configured properly, copy an HTML file (for example, x.html) in the virtual directory (C:\MyWebServices) created above. Now, open Internet Explorer and type http://localhost/MyWebServices/x.html. It should open the x.html file. If it does not work, try replacing localhost with the IP address of your machine. If it still does not work, check whether IIS is running; you may need to reconfigure IIS and Virtual Directory.

To test our Web Service, copy FirstService.asmx in the IIS virtual directory created above (C:\MyWebServices). Open the Web Service in Internet Explorer (http://localhost/MyWebServices/FirstService.asmx). It should open your Web Service page. The page should have links to two methods exposed as Web Services by our application. Congratulations; you have written your first Web Service!!!

Testing the Web Service
As we have just seen, writing Web Services is easy in the .NET Framework. Writing Web Service consumers is also easy in the .NET framework; however, it is a bit more involved. As said earlier, we will write two types of service consumers, one Web- and another Windows application-based consumer. Let's write our first Web Service consumer.

Web-Based Service Consumer
Write a Web-based consumer as given below. Call it WebApp.aspx. Note that it is an ASP.NET application. Save this in the virtual directory of the Web Service (c:\MyWebServices\WebApp.axpx).

This application has two text fields that are used to get numbers from the user to be added. It has one button, Execute, that, when clicked, gets the Add and SayHello Web Services.

WebApp.axpx
HERE create simple asp net page with two textboxes to get the value from the user and a button to execute or call the WebService

After the consumer is created, we need to create a proxy for the Web Service to be consumed. This work is done automatically by Visual Studio .NET for us when referencing a Web Service that has been added. Here are the steps to be followed:
Create a proxy for the Web Service to be consumed. The proxy is created using the wsdl utility supplied with the .NET SDK. This utility extracts information from the Web Service and creates a proxy. Thus, the proxy created is valid only for a particular Web Service. If you need to consume other Web Services, you need to create a proxy for this service as well. VS .NET creates a proxy automatically for you when the reference for the Web Service is added. Create a proxy for the Web Service using the wsdl utility supplied with the .NET SDK. It will create FirstSevice.cs in the current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service.
c:> WSDL http://localhost/MyWebServices/
FirstService.asmx?WSDL
c:> csc /t:library FirstService.cs
Put the compiled proxy in the bin directory of the virtual directory of the Web Service (c:\MyWebServices\bin). IIS looks for the proxy in this directory.
Create the service consumer, which we have already done. Note that I have instantiated an object of the Web Service proxy in the consumer. This proxy takes care of interacting with the service.
Type the URL of the consumer in IE to test it (for example, http://localhost/MyWebServices/WebApp.aspx).

Sunday, June 01, 2008

GridView Row Delete

How do retrieve the DataKey value from the Gridview ?
Please ensure your Gridview had DataKeyName properites setting.
OnRowCommand[ I set DeleMe method] event of the Gridview assign your method name.
This method takes Object and GridViewRowCommand as parameter to perform the task.
Example,If you want to delete a selected row from the Gridview,add the Linkbutton and text the "Remove" and its CommandName must be non than "Delete" and its CommandArgument,you can assign the primary key column value as <%#Eval("ecode")%>.
This LinkButton should be resides under Gridview's TemplateField and ItemTemplate.

My code goes like this..
protected void DeleMe(object sender, GridViewCommandEventArgs g)
{
if (g.CommandName == "Remove")
{
string ecode = g.CommandArgument.ToString();

Response.Write(ecode);
}


}

Friday, May 30, 2008

Class creating in C#

This is simple application for how to create namespace and classes in C#.After how do call them in functional class.

Step #1,

Open VSS 2005 -New->Website-> Add New Item - > add class module

If you give the file name as "DemoClass",then you will see the Class name DemoClass on your file like this,

Public DemoClass
{
If you want constructor go some codes from here..
}

Start to write below of this but under class's curly braces.
Example I create method praise

public string praise()
{
return "Praise the Lord";
}


public string praiseParameter(string s)
{

return s;
}


Now you can call this function on your different

Just initialise the class name with new operator like below
DemoClass Obj=new DemoClass();

Obj.praise();

Oracle - C#

This is my first step to taste the power of C# with Oracle Database.

OracleConnection connection = new OracleConnection(YourConnection)
OracleCommand command = new OracleCommand(SQL, connection);
connection.Open();
OracleDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Response.Write((reader.GetValue(0));
}
}
finally
{
reader.Close();
}
}

Tuesday, May 27, 2008

Excel Sheet data in Gridview

How to retrieve the Excel sheet as Table and display them on Gridview.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.Data.OleDb;
public partial class ExcelGVCS : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection DBConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("~/App_Data/Running.xls") + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes\"");
DBConnection.Open();
string SQLString = "SELECT * FROM [Sheet1$]";
OleDbCommand DBCommand = new OleDbCommand(SQLString, DBConnection);
IDataReader DBReader = DBCommand.ExecuteReader();
GridView1.DataSource = DBReader;
GridView1.DataBind();
DBReader.Close();
DBConnection.Close();
}
}

Tuesday, May 20, 2008

SQL Script for table making

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Employee]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Employee]
GO

CREATE TABLE [dbo].[Employee] (
[EmpCode] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Name] [char] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[DOB] [char] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO

table creation script for below application

Monday, May 19, 2008

Adding records to Gridview

This is an simple application for adding new records on the form and once the record added into GridView,it will show up with newly added record with out regenerating. :-)

Here I used delete option as discard as it wants to my specific requirement.
If possible,I put AJAX version of this same module soon.



protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con;


Cache["code"]=TextBox1.Text;
Cache["Name"]=TextBox2.Text;
Cache["DOB"]=TextBox3.Text;


con = new SqlConnection("Data Source=(local);Initial catalog=Test;user id=sa;pwd=murugesan");
con.Open();
SqlCommand smd = new SqlCommand("INSERT INTO Employee(EmpCode,Name,DOB) Values('" + Cache["code"].ToString() + "','" + Cache["Name"].ToString() + "','" + Cache["DOB"].ToString() + "')", con);

try
{

int a = (int)smd.ExecuteScalar();


}
catch (Exception ex)
{
Response.Write("Already exist !");


}


GridShow();

smd.Dispose();
con.Close();

}
public void GridShow()
{


DataSet ds = new DataSet();
con = new SqlConnection("Data Source=(local);Initial catalog=Test;user id=sa;pwd=murugesan");
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "SELECT *from Employee";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
ada = new SqlDataAdapter();
ada.SelectCommand = cmd;

ada.Fill(ds, "Employee");
GridView1.DataSource = ds;
GridView1.DataBind();
ada.Dispose();
cmd.Dispose();
con.Dispose();


}
public void Murugesan(object sender, GridViewCommandEventArgs er)
{
SqlConnection con;
SqlCommand cmd;


if (er.CommandName == "Discard")
{
string na = Convert.ToString(er.CommandArgument);
con = new SqlConnection("Data Source=(local);Initial catalog=Test;user id=sa;pwd=murugesan");
con.Open();
cmd = new SqlCommand("Delete from Employee where Name='" + na + "'", con);
cmd.ExecuteNonQuery();

GridShow();



}
}

Friday, May 16, 2008

Data Row dynamically adding to DataTable

DataTable tbl = new DataTable();
tbl.Columns.Add("ColumnA");

tbl.Columns.Add("ColumnB");

tbl.Columns.Add("ColumnC");

for(int i = 0; i<10; i++)

{

DataRow nr = tbl.NewRow();

nr["ColumnA"] = "A" + i.ToString();

nr["ColumnB"] = "B" + i.ToString();

nr["ColumnC"] = "C" + i.ToString();

tbl.Rows.Add(nr);

}

PrintRows(tbl);
}


private static void PrintRows(DataTable tbl)
{

for(int i=0; i
{

Console.WriteLine("row: {0}, ColumnA: {1}, ColumnB: {2}", i, tbl.Rows[i]["ColumnA"], tbl.Rows[i]["ColumnB"]);

}

}

Tuesday, May 13, 2008

Multiple file reading in C#

Today I met one situation that I have to read all text files under one general folder.One of My senior Mr.Jignesh hada developed an utility to convert the raw text into DataSet,then it will be taken out as Crystal Report in C#.
I learned many things from him just sitting and watching carefully.Then he suggest me that he have more than 20 files of text file those has to be merged as one as well as create one Database.
He asked me to merge all notepad files.
Simple I read all textfiles then on the fly i created a text files thats going to be serve as Main file for creating DataSet.

Here is the code snippet to read all text files under one folder.
string []files = Directory.GetFiles(@"D:\Murugesan\");
foreach(string sp in files)
{

StreamReader sr = new StreamReader(sp);
string contents = sr.ReadToEnd();
Response.Write(contents);
//use pre tag with contents as concatenation.

sr.Close();

Sunday, May 04, 2008

AJAX -Introduction

Introduction
AJAX stands for Asynchronous JavaScript and XML. Working in ASP.Net with AJAX, developers can develop ASP.Net web applications more user friendly and fast enough to provide data with page postbacks. This programming methodology has removed old fashioned page refreshing method that throws the user back to the page top and lose the context where he was working before clicking the submit button to save data.

ASP.Net Postbacks
ASP.Net methodology based on client server data exchange works as all the data from the client end is sent to the web server then the web server processes the data and sends back to the client. It means AJAX has the ability to make asynchronous calls to a web server. AJAX sends only necessary data to the web server.

AJAX and ASP.Net Framework
ASP.Net framework considers AJAX as a client callback scripts. AJAX enables you to update the page content without posting the page back to the server. Basically AJAX uses XMLHttp ActiveX component or the XMLHttpRequest according to the client’s browser such as Internet Explorer or FireFox.

AJAX allows partial page postbacks that minimize the network usage by not sending the all form data to the server. This method enables the server to perform only limited actions on the data received coz the server does not need to process the whole page elements or images. There is no need to process the viewstate, images or all page elements to send back to the client while processing partial postbacks.

With AJAX there is no full page postback that maintains page location even when user clicks the submit button to perform some action on the page. Hence the use state is maintained and the user doesn’t need to scroll down to the location where he was working before clicking the submit button.

AJAX GridView Databinding























C# code to Load the GridView using AJAX Asynchronous Postback

protected void bindGridView()
{
string connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ToString();
SqlConnection sqlCon = new SqlConnection(connectionString);

try
{
SqlCommand sqlCmd = new SqlCommand("select * from categories", sqlCon);
sqlCmd.CommandType = CommandType.Text;
SqlDataAdapter sqlAdp = new SqlDataAdapter(sqlCmd);
DataSet myDataSet = new DataSet();
sqlAdp.Fill(myDataSet);

// Delay the current Thread to display
// the UpdateProgress status
// Not required in real projects
System.Threading.Thread.Sleep(4000);

GridView1.DataSource = myDataSet;
GridView1.DataBind();
}
catch(Exception ex)
{
lblErrorMsg.Text = ex.Message;
}
}

protected void btnLoadData_Click(object sender, EventArgs e)
{
bindGridView();
}

Sunday, April 27, 2008

salting in Password encryption using C#

Salting means :: creating random string and attach with original password before encrypting.So your password are safe and untraceble to dictionary attack.

public string MuruEncrypt(string paramPass)
{

MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
string salt = Guid.NewGuid().ToString();

byte[] p = UnicodeEncoding.UTF8.GetBytes(text+salt);
byte[] en = md5.ComputeHash(p);
return Convert.ToBase64String(en);
}

MD5 CryptoServiceProvider using C#

This class used to create a function Encrypt the Password.
Just put it this way,Whenever the user login into password protected pages of the website,their password first undergo the MD5 Algorithm based conversion.
Then converted or encrypted password check their identification on the stored data.
If both are matched,we allow the user to navigate the login protected pages.


This password can be crack down once the hacker using the dictionary attack if your database compromised by the hacker.

We can overcome this ,by using salting concept.

Salting means just before generating the hash of a text, we attach a piece of random string – known as a salt - into the original text.

using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Web;
using System.Security.Cryptography;
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 Murugesan
///

public class Murugesan
{
public Murugesan()
{

}

public string MuruDate(DateTime d)
{
d = d.AddDays(2);
string DateAddS = d.ToLongDateString();
return DateAddS;

}


public string Encrypt(string text)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] p = UnicodeEncoding.UTF8.GetBytes(text);
byte[] en = md5.ComputeHash(p);
return Convert.ToBase64String(en);


}



}

Sunday, April 20, 2008

How to use SQLBulkCopy in C#

This is code implementation for alternative bcp command prompt of SQL Server for copying the Table records among Local server Databases or Server Databases.

SqlConnection Con = new SqlConnection("Data Source=(Local);Initial Catalog=Pack;user id=sa;pwd=*****");
Con.Open();
SqlCommand Com = new SqlCommand("Select *from TrackDetails", Con);
SqlDataReader Dr = Com.ExecuteReader();


//Destination Database Connection Opening..
SqlConnection DCon = new SqlConnection("Data Source=(Local);Initial Catalog=Muru;user id=sa;pwd=*****");
DCon.Open();

SqlBulkCopy bc = new SqlBulkCopy(DCon);
bc.DestinationTableName = "SQLBulk";
bc.WriteToServer(Dr);
Dr.Close();
Response.Write("Copied successfully");


Just for a demo purpose.you can use the WriteServer method of SQLBulkCopy Class in try,catch and finally to close the stream SQLDataReader and destination connection as well as source connection.

Friday, April 04, 2008

Extracting a month from String - C#

How do extract the month from the user entered string?

DateTime dt=Request.Form["DropDownList1"];
string spdate=dt.Month;

Then simply use this string on your query like to see the result on monthly based
Select *from Sales where Month(salesdate)='"+spdate+"' ;

Friday, March 28, 2008

CheckBox in GridView


Add Gridview Control from the ToolBox
once its placed,click on source tab from VSS,there you can see the rendered html tags for the control.
Between closed Gridview tag,add these tags.In itemtemplate portion,you can add anything like button,image,hyperlink etc..each control will be tie-up with record which binded on Gridview.
Actually,this gridview its quite useful for reporting view.Simply we can call the minimal crystalreport for web application.
example,
if you want to view the individual invoice detail on the Bill listing report.you can add hyper link control to GridView,then you make some piece of codeto retrieve the details for corresponding invoice number.
secondly,If there is situation where user has to select multiple choices from the GridviewReport.we go for checkbox option.
Added checkboxes bind with GridViews.
If you wish to select the each row in gridview and find the selected row's value.then code will be,

foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chb = (CheckBox)row.FindControl("friend");
//You need to identify the control which fired on GridView
if(chb.Checked = true)
{
selValue= (row.Cells[1].Text) + ',';
Response.Write(selValue);
}
}
I hope this simple explanation will help you to go further up on this !







Saturday, March 01, 2008

C# - Types of function and Enumeration

Enumeration
It allows you to create your own data types.You can't declare the enum in the main block because it cant execute,its only a definition so youmust place it out of main.each value in enumeration can accept a storage type which is int by default.
enum days
{sunday,monday,tuesday,wednesday,thursday,friday,saturday}
using the enum value in main method.
days d;
d=days.friday;
Response.Write(d); // friday
Function call by Ref:
Compiler doesnt want to create temprory variable for the parameters of the function.So less overhead and tremendous functionality available while using this function.It uses the same value in the calling function.
out parameter function.
An function can return only one value at the time of execution.If you require more than on value return by the function,you can pass the out parameter to your function.out varialble must be unassigned declared.
Example

public int MuruOutParameter(out int x)
{
int y=5;
int x=6;
x=x+1;
return(y+1);
}
Call the function in the main
int p;
Console.WriteLine(MuruOutParameter(out p)
output : 6

Friday, February 29, 2008

.NET-interview question

What is the base class of .NET?
Base class provides a base set of methods that all derived classes can use

Explain assemblies.
Answer 1:
Assemblies are similar to dll files. Both has the reusable pieces of code in the form of classes/ functions. Dll needs to be registered but assemblies have its own metadata.

Answer 2:
Assembly is a single deployable unit that contains information about the implementation of classes, structures and interfaces. it also stores the information about itself called metadata and includes name and verison of the assembly, security information, information about the dependencies and the list of files that constitute the assembly.
Assembly also contains namespaces. In the .Net Framework, applications are deployed in the form of assemblies.

Answer 3:
An assembly is a single deployable unit that contains all the information about the implementation of :
- classes
- structures and
- interfaces

An assembly stores all the information about itself. This information is called METADATA and include the name and the verison number of the assembly, security information, information about the dependencies and a lost of files that constitute the assembly.
All the application developed using the .NET framework are made up of assemblies.
Namespaces are also stored in assemblies

Answer 4:
In the Microsoft .NET framework an assembly is a partially compiled code library for use in deployment, versioning and security. In the Microsoft Windows implementation of .NET, an assembly is a PE (portable executable) file. There are two types, process assemblies (EXE) and library assemblies (DLL). A process assembly represents a process which will use classes defined in library assemblies. In version 1.1 of the CLR classes can only be exported from library assemblies; in version 2.0 this restriction is relaxed. The compiler will have a switch to determine if the assembly is a process or library and will set a flag in the PE file. .NET does not use the extension to determine if the file is a process or library. This means that a library may have either .dll or .exe as its extension.

The code in an assembly is partially compiled into CIL, which is then fully compiled into machine language at runtime by the CLR.

An assembly can consist of one or more files. Code files are called modules. An assembly can contain more than one code module and since it is possible to use different languages to create code modules this means that it is technically possible to use several different languages to create an assembly. In practice this rarely happens, principally because Visual Studio only allows developers to create assemblies that consist of a single code module.

Name some of the languages .NET support?
Some of the languages that are supported by .NET
1. Visual Basic.NET
2. Visual C#
3. Visual C++

ADO.NET features? Benefits? Drawbacks?
Answer 1:
1. Data will be retrieved through Datasets
2. Scalability

Answer 2:
1. Disconnected Data Architecture
2. Data cached in Datasets
3. Data transfer in XML format
4. Interaction with the database is done through data commands

How many types of exception handlers are there in .NET?
Answer 1:
From
MSDN>gt; “How the Runtime Manages Exceptions”
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconexceptionsoverview.asp
The exception information table represents four types of exception handlers for protected blocks:
A finally handler that executes whenever the block exits, whether that occurs by normal control flow or by an unhandled exception.
A fault handler that must execute if an exception occurs, but does not execute on completion of normal control flow.
A type-filtered handler that handles any exception of a specified class or any of its derived classes.
A user-filtered handler that runs user-specified code to determine whether the exception should be handled by the associated handler or should be passed to the next protected block.

Answer 2:
1. Unstructured Exception Handling
2. Structured Exception Handling

Difference between Panel and GroupBox classes?

Security Tip

Use Firefox instead of Internet Explorer and PREVENT Spyware !


Firefox is free and is considered the best free, safe web browser available today
Get Firefox with Google Toolbar for better browsing

Answer 1:
Panel and Group box both can used as container for other controls like radio buttons and check box.
the difference in panel and group box are Panel
1) In case of panel captions cannot be displayed
2) Can have scroll bars.

Group box
1) Captions can be displayed.
2) Cannot have a scroll bar

Answer 2:
Panel is scrollable. In panel you can’t set caption like Group box.

What is the base class of Button control?
Listing from visual studio .net > Button Class
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ButtonBase
System.Windows.Forms.Button

What is Response object? How is it related to ASP’s Response object?
Response object allows the server to communicate with the client(browser). It is useful for displaying information to the user (or) redirecting the client.
Eg: Response.Write(”Hello World”)


hat is IIS? Have you used it?
IIS - Internet Information Server
IIS is used to access the ASP.Net web applications
Yes, I used in ASP.NET web applications.

Main differences between ASP and ASP.NET.
Answer 1:
1. ASP: Code is Interpreted
ASP.NET: Code is Compiled

2. ASP: Business Logic and Presentation Logic are in a single file
ASP.NET: Business Logic and Presentation Logic are in separate files (.cs or .vb) and (.aspx) respectively.
3. ASP: No Web Server Controls
ASP.NET: Web Server Controls supported by strong .NET Framework
4. ASP: No RAD in Classic ASP
ASP.NET: Supports RAD

Answer 2:
1.Asp is interpreted
Asp.net is compiled which is faster than asp.
2 Asp.net maintains its own CLR and is managed as it runs by CLR
Where as asp is unmanaged
3 We can mainatin sessions in state server and sql server which is Outproc,
where in asp sessions will be last if we restart webserver or make changes.
4 In asp.net we can configure each application using web.config file which is availble in application itself and we have machine.config wherer we can configure all applications.
In asp we cannot configure single aplication
5 Asp.net we have autopostback event which is not in asp
6 In asp.net we have global.asax where can hadle some global things which is not in asp.
7 We have well built GUI to work in asp.net
8 We have ado.net and as well as disconnected architecture in asp.net
9 We have Xcopy deployment in asp.net
10. We can work with any language as code behind technique in asp.net that supports .net frame work

Answer 3:
a) asp.net is compiled but ASP is a interpretor or script only.
b) asp.net is supported more control then the asp.
c) asp.net is more supported even control then the asp.
d) In asp.net if update any component then no need to shutdown the computer but in asp if loaded any component then need tobe shutdown the computer.
d) So lastly an asp.net is faster then asp .

C# - interview questions

How many classes can a single.NET DLL contain?
Answer2:
One or more

What are good ADO.NET object(s) to replace the ADO Recordset object?
The differences includes
In ADO, the in-memory representation of data is the Recordset.
In ADO.net, it is the dataset

A recordset looks like a single table in ADO
In contrast, a dataset is a collection of one or more tables in ADO.net

ADO is designed primarily for connected access
ADO.net the disconnected access to the database is used

In ADO you communicate with the database by making calls to an OLE DB provider.
In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source.

In ADO you cant update the database from the recordset. ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database.


On order to get assembly info which namespace we should import?
System.Reflection Namespace

How do you declare a static variable and what is its lifetime? Give an example.

The static modifier is used to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types. In C#, the static keyword indicates a class variable. In VB, the equivalent keyword is Shared. Its scoped to the class in which it occurs.

Example
a. Static int var //in c#.net
b. static void Time( ) //in c#.net

How do you get records number from 5 to 15 in a dataset of 100 records? Write code.
Answer1
DataSet ds1=new DataSet();
String strCon=”data source=IBM-6BC8A0DACEF;initial catalog=pubs;integrated security=SSPI;persist” +” security info=False;user
id=sa;workstation id=IBM-6BC8A0DACEF;packet size=4096?;

String strCom1=”SELECT * FROM employee”;
SqlDataAdapter sqlDa1=new SqlDataAdapter(strCom1,strCon);
ds1.Tables.Add(”employee”);
sqlDa1.Fill(ds1,40,50,ds1.Tables[”employee”].TableName);
DataGrid dg1.DataSource=ds1.Tables[”employee”].DefaultView;
dg1.DataBind();


Answer2
OleDbConnection1.Open()
OleDbDataAdapter1.Fill(DataSet21, 5, 15, “tab”)
This will fill the dataset with the records starting at 5 to 15

How do you call and execute a Stored Procedure in .NET? Give an example.
Answer1
ds1=new DataSet();

sqlCon1=new SqlConnection(connectionstring);

String strCom1=”byroyalty”;

sqlCom1=new SqlCommand(strCom1,sqlCon1);
sqlCom1.CommandType=CommandType.StoredProcedure;
sqlDa1=new SqlDataAdapter(sqlCom1);
SqlParameter myPar=new SqlParameter(”@percentage”,SqlDbType.Int);
sqlCom1.Parameters.Add (myPar);
myPar.Value=40;
sqlDa1.Fill(ds1);
dg1.DataSource=ds1;
dg1.DataBind();

Answer2
Yes

Dim cn as new OleDbConnection ( “Provider=Microsoft.Jet.OLEDB.4.0;”+ _
“Data Source=C:\Documents and Settings\User\My Documents\Visual Studio Projects\1209\db1.mdb”+ _
“User ID=Admin;”+ _
“Password=;”);
Dim cmd As New OleDbCommand(”Products”, cn)
cmd.CommandType = CommandType.StoredProcedure

Dim da As New OleDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds, “Products”)
DataGrid1.DataSource = ds.Tables(”Products”)

What is the maximum length of a varchar in SQL Server?
Answer1
VARCHAR[(n)]
Null-terminated Unicode character string of length n,
with a maximum of 255 characters. If n is not supplied, then 1 is assumed.

Answer2
8000

Answer3
The business logic is the aspx.cs or the aspx.vb where the code is being written. The presentation logic is done with .aspx extention.

How do you define an integer in SQL Server?
We define integer in Sql server as
var_name int

How do you separate business logic while creating an ASP.NET application?
There are two level of asp.net debugging
1. Page level debugging
For this we have to edit the page level debugging enable the trace to true in the line in the html format of the page.

%@ Page Language=”vb” trace=”true”AutoEventWireup=”false” Codebehind=”WebForm1.aspx.vb” Inherits=”WebApplication2.WebForm1?>

2. You can enable the debugging in the application level for this
Edit the following trace value in web.config file

Enable trace enabled=true.

If there is a calendar control to be included in each page of your application, and and we do not intend to use the Microsoft-provided calendar control, how do you develop it? Do you copy and paste the code into each and every page of your application?
Create the Calendar User Control
The control we will create will contain a calendar control and a label which has the corresponding date and time written
Steps are:-

Creating a CalenderControl
1) To begin, open Visual Studio .NET and begin a new C# Windows Control Library.
2) You may name it whatever you like, for this sample the project name will be CalenderControl

Using the Calender Control in a Windows Application
It’s just like adding any other control like a button or a label.
1) First, create a new Windows Application project named: CustomControl.
2) Add a reference to the Calender Control DLL named: CalenderControl.dll.
3) Now you a can customize the Toolbox:
Right-Click the Toolbox> .NET Framework Components> Browse> select the CalenderControl.dll.
4)The Calender Control is now added to the Toolbox and can be inserted in Windows Form as any other control. The control itself will take care of the date display

Insert Stored Procedure using C#

If you are fresher to C# coding and SQL Procedure,this article will be a great useful for you to enchance your knowledge and getting ideas on how a simple application being developed.Source code for this application available for Code behind method as well as straight forward method.

Step #1,

Start your SQL SERVER on your local computer.
Goto -> Enterprise Manager - Locate your desired database or create new database

Create New Table and give the name "Secure "
add columns username and password.make it username as primary key.
Now you need to create StoredProcedure for this table for inserting record through C#.
Click on Database node,it will expand and shows its object,right click on 4th Object,storedprocedure - > New StoredProcedure -it will open up the Pop up window,type it exactly like this below

CREATE PROCEDURE InsertSP
@username varchar(12),
@password varchar(10)
AS
Begin
Insert into Secure values(@username,@password)
End
GO

and make sure all syntax are spelled correctly by clicking"Check syntax " button.

Step # 2,
In visual studio open your existing website or create new one.
Add a new form and make sure the language for the page will be "C#"

Add 2 textboxes and naming them user_name and pass_word and a button
Double click on this button,on click event handler write these code in order to execute the StoredProcedure for inserting the user input in to your database.

protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection("Data Source=(Local);Initial Catalog=Login;user id=sa;pwd=yourpassword");
sc.Open();
//Response.Write(sc.State);
SqlCommand smd = new SqlCommand("InsertSP", sc);
smd.CommandType = CommandType.StoredProcedure;
smd.Parameters.Add("@username", SqlDbType.VarChar).Value = Request.Form["user_name"];
smd.Parameters.Add("@password", SqlDbType.VarChar).Value = Request.Form["pass_word"];
try
{
int r = smd.ExecuteNonQuery();
if (r == 1)
{
Literal1.Visible = true;
Literal1.Text = "Successfully added!!";
}
}
catch
{
Literal1.Visible = true;
Literal1.Text = "user name already exist !";
}
smd.Dispose();
sc.Close();
}
}






Thursday, February 28, 2008

You Tube on your Smart Phone

When i am digging my Nokia E61i for new features,I found Flash player.But when I am trying to run the website http://www.thedesignzone.in/ where I made a simple flash work but i cant achieve it.
My Nokia E61i doesnt support the flash website on my browser or might be I dont know how do setting them.
Recently I came across Google's mobile blog and how do run the Youtube.com on your mobile.Amazing and unbelievable to see them on Nokia's smart phone series.
Soon I am going to make my mobile blog.
Watch this Video,Mr.Desai explain how do use mobile blog on Nokia Phones.

MSSQL - Do's and Don'ts

SQL Server DO's and DON'TsSo, you are now the leader of a SQL Server based project and this is your first one, perhaps migrating from Access. Or maybe you have performance problems with your SQL Server and don't know what to do next. Or maybe you simply want to know of some design guidelines for solutions using SQL Server and designing Database Access Layers (DAL): this article is for you.
Even if you are not using SQL Server, most of these design guidelines apply to other DBMS, too: Sybase is a very similar environment for the programmer, and Oracle designs may benefit from this too. I won't show here how to use specific T-SQL tricks, nor won't give you miracle solutions for your SQL Server problem. This is by no means a complete, closed issue. What I intend to do is give you some advices for a sound design, with lessons learned through the last years of my life, seeing the same design errors being done again and again.
DO know your tools.Please, don't underestimate this tip. This is the best of all of those you'll see in this article. You'd be surprised of how many SQL Server programmers don't even know all T-SQL commands and all of those effective tools SQL Server has.
"What? I need to spend a month learning all those SQL commands I'll never use???" you might say. No, you don't need to. But spend a weekend at MSDN and browse through all T-SQL commands: the mission here is to learn a lot of what can and what can't be done. And, in the future, when designing a query, you'll remember "Hey, there's this command that does exactly what I need", and then you'll refer again to MSDN to see its exact syntax.
In this article I'll assume that you already know the T-SQL syntax or can find about it on MSDN.
DON'T use cursorsLet me say it again: DON'T use cursors. They should be your preferred way of killing the performance of an entire system. Most beginners use cursors and don't realize the performance hit they have. They use memory; they lock tables in weird ways, and they are slow. Worst of all, they defeat most of the performance optimization your DBA can do. Did you know that every FETCH being executed has about the same performance of executing a SELECT? This means that if your cursor has 10,000 records, it will execute about 10,000 SELECTs! If you can do this in a couple of SELECT, UPDATE or DELETE, it will be much faster.
Beginner SQL programmers find in cursors a comfortable and familiar way of coding. Well, unfortunately this lead to bad performance. The whole purpose of SQL is specifying what you want, not how it should be done.
I've once rewritten a cursor-based stored procedure and substituted some code for a pair of traditional SQL queries. The table had only 100,000 records and the stored procedure used to take 40 minutes to process. You should see the face of the poor programmer when the new stored procedure took 10 seconds to run!
Sometimes it's even faster to create a small application that gets all the data, proccess it and update the server. T-SQL was not done with loop performance in mind.
If you are reading this article, I need to mention: there is no good use for cursors; I have never seen cursors being well used, except for DBA work. And good DBAs, most of the time, know what they are doing. But, if you are reading this, you are not a DBA, right?
DO normalize your tablesThere are two common excuses for not normalizing databases: performance and pure laziness. You'll pay for the second one sooner or later; and, about performance, don't optimize what's not slow. Often I see programmers de-normalizing databases because "this will be slow". And, more frequent than the inverse, the resulting design is slower. DBMSs were designed to be used with normalized databases, so design with normalization in mind.
DON'T SELECT *This is hard to get used, I know. And I confess: often I use it; but try to specify only the columns you'll need. This will:
Reduce memory consumption and network bandwidth Ease security design Gives the query optimizer a chance to read all the needed columns from the indexesDO know how your data will be/is being acessedA robust index design is one of the good things you can do for your database. And doing this is almost an art form. Everytime you add an index to a table, things get faster on SELECT, but INSERT and DELETE will be much slower. There's a lot of work in building and mantaining indexes. If you add several indexes to a table to speed your SELECT, you'll soon notice locks being held for a long time while updating indexes. So, the question is: what is being done with this table? Reading or Updating data? This question is tricky, specially with the DELETE and UPDATE, because they often involve a SELECT for the WHERE part and after this they update the table.
DON'T create an index on the "Sex" columnThis is useless. First, let's understand how indexes speed up table access. You can see indexes as a way of quickly partitioning a table based on a criteria. If you create an index with a column like "Sex", you'll have only two partitions: Male and Female. What optimization will you have on a table with 1,000,000 rows? Remember, mantaining an index is slow. Always design your indexes with the most sparse columns first and the least sparse columns last, e.g, Name + Province + Sex.
DO use transactionsSpecially on long-running queries. This will save you when things get wrong. Working with data for some time you'll soon discover some unexpected situation which will make your stored procured crash.
DO beware of deadlocksAlways access your tables on the same order. When working with stored procedures and transactions, you may find this soon. If you lock the table A then table B, always lock them in this very same order in all stored procedures. If you, by accident, lock the table B and then table A in another procedure some day you'll have a deadlock. Deadlocks can be tricky to find if the lock sequence is not carefully designed.
DON'T open large recordsetsA common request on programming forums is: "How can I quickly fill this combo with 100,00 items?". Well, this is an error. You can't and you shouldn't. First, your user will hate browsing through 100,000 records to find the right one. A better UI is needed here, because you should ideally show no more that 100 or 200 records to your users.
DON'T use server side cursorsUnless you know what your are doing. Client side cursors often (not always) put less overhead on the network and on the server, and reduce locking time.
DO use parametrized queriesSometimes I see in programming forums, questions like: "My queries are failing with some chars, e.g. quotes. How can I avoid it?". And a common answer is: "Replace it by double quotes". Wrong. This is only a workaround and will still fail with other chars, and will introduce serious security bugs. Besides this, it will trash the SQL Server caching system, which will cache several similar queries, instead of caching only one. Learn how to use parameterized queries (in ADO, through the use of the Command Object, or in ADO.NET the SqlCommand) and never have these problems again.
DO always test with large databasesIt's a common pattern programmers developing with a small test database, and the end user using large databases. This is an error: disk is cheap, and performance problems will only be noticed when it's too late.
DON'T import bulk data with INSERTUnless strictly necessary. Use DTS or the BCP utility and you'll have both a flexible and fast solution.
DO beware of timeoutsWhen querying a database, the default timeout is often low, like 15 seconds or 30 seconds. Remember that report queries may run longer than this, specially when your database grows.
DON'T ignore simultaneous editingSometimes two users will edit the same record at the same time. When writing, the last writer wins and some of the updates will be lost. It's easy to detect this situation: create a timestamp column and check it before you write. If possible, merge changes. If there is a conflict, prompt the user for some action.
DON'T do SELECT max(ID) from Master when inserting in a Detail table.This is another common mistake, and will fail when two users are inserting data at the same time. Use one of SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY. Avoid @@IDENTITY if possible because it can introduce some nasty bugs with triggers.
DO Avoid NULLable columnsWhen possible. They consume an extra byte on each NULLable column in each row and have more overhead associated when querying data. The DAL will be harder to code, too, because everytime you access this column you'll need to check
I'm not saying that NULLs are the evil incarnation, like some people say. I believe they can have good uses and simplify coding when "missing data" is part of your business rules. But sometimes NULLable columns are used in situations like this:
CustomerName1CustomerAddress1CustomerEmail1CustomerName2CustomerAddress2CustomerEmail3CustomerName1CustomerAddress2CustomerEmail3
This is horrible. Please, don't do this, normalize your table. It will be more flexible and faster, and will reduce the NULLable columns.
DON'T use the TEXT datatypeUnless you are using it for really large data. The TEXT datatype is not flexible to query, is slow and wastes a lot of space if used incorrectly. Sometimes a VARCHAR will handle your data better.
DON'T use temporary tablesUnless strictly necessary. Often a subquery can substitute a temporary table. They induce overhead and will give you a big headache when programming under COM+ because it uses a database connection pool and temporary tables will last forever. In SQL Server 2000, there are alternatives like the TABLE data type which can provide in-memory solutions for small tables inside stored procedures too.
DO learn how to read a query execution planThe SQL Server query analyzer is your friend, and you'll learn a lot of how it works and how the query and index design can affect performance through it.
DO use referential integrity

This can be a great time saver. Define all your keys, unique constraints and foreign keys. Every validation you create on the server will save you time in the future.

Monday, February 18, 2008

Benefits of procedures and triggers

Benefits of procedures and triggers
--------------------------------------------------------------------------------
Definitions for procedures and triggers appear in the database, separately from any one database application. This separation provides a number of advantages.
Standardisation

Procedures and triggers standardize actions performed by more than one application program. By coding the action once and storing it in the database for future use, applications need only call the procedure or fire the trigger to achieve the desired result repeatedly. And since changes occur in only one place, all applications using the action automatically acquire the new functionality if the implementation of the action changes.

Efficiency
Procedures and triggers used in a network database server environment can access data in the database without requiring network communication. This means they execute faster and with less impact on network performance than if they had been implemented in an application on one of the client machines.

When you create a procedure or trigger, it is automatically checked for correct syntax, and then stored in the system tables. The first time any application calls or fires a procedure or trigger, it is compiled from the system tables into the server's virtual memory and executed from there. Since one copy of the procedure or trigger remains in memory after the first execution, repeated executions of the same procedure or trigger happen instantly. As well, several applications can use a procedure or trigger concurrently, or one application can use it recursively.
Procedures are less efficient if they contain simple queries and have many arguments. For complex queries, procedures are more efficient.
Security
Procedures and triggers provide security by allowing users limited access to data in tables that they cannot directly examine or modify.

Triggers, for example, execute under the table permissions of the owner of the associated table, but any user with permissions to insert, update or delete rows in the table can fire them. Similarly, procedures (including user-defined functions) execute with permissions of the procedure owner, but any user granted permissions can call them. This means that procedures and triggers can (and usually do) have different permissions than the user ID that invoked them.