- Open Visual Studio .NET.
- On the File menu, click New and then click Project. Under Project types click Visual C# Projects, then click ASP.NET Web Service under Templates. Type MathService in the Location text box to change the default name (WebService1) to MathService.
- Change the name of the default Web service that is created from Service1.asmx to MathService.asmx.
- Click Click here to switch to code view in the designer environment to switch to code view.
- Define methods that encapsulate the functionality of your
service. Each method that will be exposed from the service must be flagged with
a WebMethod attribute in front of it. Without this attribute, the method will
not be exposed from the service.
NOTE: Not every method needs to have the WebMethod attribute. It is useful to hide some implementation details called by public Web service methods or for the case in which the WebService class is also used in local applications. A local application can use any public class, but only WebMethod methods will be remotely accessible as Web services.
Add the following method to the MathServices class that you just created:[WebMethod] public int Add(int a, int b) { return(a + b); } [WebMethod] public System.Single Subtract(System.Single A, System.Single B) { return (A - B); } [WebMethod] public System.Single Multiply(System.Single A, System.Single B) { return A * B; } [WebMethod] public System.Single Divide(System.Single A, System.Single B) { if(B == 0) return -1; return Convert.ToSingle(A / B); } - Click Build on the Build menu to build the Web service.
- Browse to the MathService.asmx Web service page to test the
Web service. If you set the local computer to host the page, the URL is
http://localhost/MathService/MathService.asmx.
The ASP.NET runtime returns a Web Service Help Page that describes the Web service. This page also enables you to test different Web service methods.
Tuesday, 4 February 2014
Write a Simple .asmx Web Service
Sql Connections in asp.net
Opening and Closing Connections
Case in point: managing of sql database connection resources. How many of us learned to write something like this:
Sure it’s easy to follow, but if you deploy that on a moderately busy server you are going to make your client very unhappy.
Insert Data into Database-
Case in point: managing of sql database connection resources. How many of us learned to write something like this:
// Create a new SQL Connection object
SqlConnection conn = new SqlConnection( connectionString );
// Open the connection to the database
conn.Open();
// Create a new SQL Command
SqlCommand cmd = new SqlCommand( “DELETE FROM BabyNames;”, conn );
// Execute the command
cmd.ExecuteNonQuery();
// Close the database connection
conn.Close();
Sure it’s easy to follow, but if you deploy that on a moderately busy server you are going to make your client very unhappy.
Insert Data into Database-
Asp.Net-Connection String
ASP.NET Connection String
A connection string provides the information that a
provider needs to communicate with a particular database. The Connection
String includes parameters such as the name of the driver, Server name
and Database name , as well as security information such as user name
and password.
An ADO.NET Data Provider is a class that can
communicate with a specific type of database or data store. Usually Data
Providers use a connection string containing a collection of parameters
to establish the connection with the database through applications. The
.NET Framework provides mainly three data providers, they are
Microsoft SQL Server
OLEDB
ODBC
Here you can see how to make a connection string to the following ADO.NET Data Providers.
Microsoft SQL Server Connection String
connetionString="Data Source=ServerName;Initial Catalog=Databasename;
User ID=UserName;Password=Password";
OLEDB Data Provider Connection String
connetionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourdatabasename.mdb;"
ODBC Connection String
connetionString="Driver={Microsoft Access Driver (*.mdb)};DBQ=yourdatabasename.mdb;"
You have to provide the necessary connection information to the Connection String attributes
Web.config and ConnectionString
You can store connection strings in the Web.config
file and reference the configuration entries in data source controls.
You can create connectionStrings element within the Element element, by create a child element named and place your connection strings there.
<configuration>
<connectionStrings>
<add name="RamaConnectionString"
connectionString="Server=Rama-PC; Database=Test; User Id=sa; password= Admin123"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
You can access the connectionstring value at run time in your ASP.NET application as shown in the following example.
C#
string conn = ConfigurationManager.ConnectionStrings["RamaConnectionString"].ToString();
ASP.NET Sql Server Connection
The SqlConnection Object is Handling the
part of physical communication between the ASP.NET application and the
SQL Server Database . An instance of the SqlConnection class in ASP.NET
is supported the Data Provider for SQL Server Database.
C#
string conn = ConfigurationManager.ConnectionStrings["RamaConnectionString"].ToString();
When the connection
is established , SQL Commands will execute with the help of the Command
Object and retrieve or manipulate the data in the database. Once the
Database activities is over , Connection should be closed and release
the Data Source resources .
The Close() method in SqlConnection Class is used
to close the Database Connection. The Close method rolls back any
pending transactions and releases the Connection from the SQL Server
Database.
The following ASP.NET program connect to a database server and display the message in the Label control.
web.config
<?xml version="1.0"?>
<configuration> <connectionStrings>
<add name="RamaConnectionString"
connectionString="Server=Rama-PC; Database=Test; User Id=sa; password= Admin123"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
You have to fill appropriate web.config database parameters
Default.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
default.aspx.cs
using System;
using System.Data ;
using System.Data.SqlClient ;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["RamaConnectionString"].ToString();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
Label1.Text = "Connected to Database Server !!";
connection.Close();
}
}
Monday, 3 February 2014
Publish Deploy Asp.Net WebSite Application On IIS7 Server
Publish And Deploy Asp.Net Web Site Application On IIS7 Server.
Open Application in Visual Studio, Click on Build > Publish Web Site.
Browse to where you want to save published DLLs,Files and other aspx pages. (TestWebSite)
Copy TestWebSite folder inside C:\inetpub/wwwroot directory.
Click on Start Menu > Run > INETMGR to open IIS manager.
Click on sites > Default Web Site.
Right Click on folder we copied and Select Convert To Application.
Click on Start Menu > Run > INETMGR to open IIS manager.
Click on sites > Default Web Site.
Right Click on folder we copied and Select Convert To Application.
Create new pool by right clicking on Application pools.
Go to Advance settings
Change Identity property to Local System.
Right Click On TestWebSite Application > Manage Application > Advance Settings.
Assign Application Pool we created earlier to this web App.
Open Internet browser and type http://localhost/testwebsite to browse your website application.
OOPS-Objects, object attributes and methods
Object-oriented programming
In this part of the C# tutorial, we will talk about object oriented programming in C#.There are three widely used programming paradigms: procedural programming, functional programming and object-oriented programming. C# supports both procedural and object-oriented programming.
Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs.
There are some basic programming concepts in OOP:
- Abstraction
- Polymorphism
- Encapsulation
- Inheritance
The polymorphism is the process of using an operator or function in different ways for different data input. The encapsulation hides the implementation details of a class from other objects.
The inheritance is a way to form new classes using classes that have already been defined.
Objects
Objects are basic building blocks of a C# OOP program. An object is a combination of data and methods. The data and the methods are called members of an object. In an OOP program, we create objects. These objects communicate together through methods. Each object can receive messages, send messages and process data.There are two steps in creating an object. First, we define a class. A class is a template for an object. It is a blueprint which describes the state and behavior that the objects of the class all share. A class can be used to create many objects. Objects created at runtime from a class are called instances of that particular class.
using System;
public class Being {}
public class Objects
{
static void Main()
{
Being b = new Being();
Console.WriteLine(b);
}
}
In our first example, we create a simple object.
public class Being {}
This is a simple class definition. The body of the template is empty.
It does not have any data or methods. Being b = new Being();
We create a new instance of the Being class. For this we have the
new keyword. The b variable is the handle to
the created object. Console.WriteLine(b);
We print the object to the console to get some basic description
of the object. What does it mean, to print an object? When we print
an object, we in fact call its ToString() method. But
we have not defined any method yet. It is because every object created
inherits from the base object. It has some elementary
functionality which is shared among all objects created. One of this
is the ToString() method. $ ./simpleobject.exe
Being
We get the object class name.
Object attributes
Object attributes is the data bundled in an instance of a class. The object attributes are called instance variables or member fields. An instance variable is a variable defined in a class, for which each object in the class has a separate copy.using System;
public class Person
{
public string name;
}
public class ObjectAttributes
{
static void Main()
{
Person p1 = new Person();
p1.name = "Rama";
Person p2 = new Person();
p2.name = "Devi";
Console.WriteLine(p1.name);
Console.WriteLine(p2.name);
}
}
public class Person
{
public string name;
}
We declare a name member field. The
public
keyword specifies that the member field will be accessible
outside the class block.
Person p1 = new Person();
p1.name = "Rama";
We create an instance of the Person class and set the name variable to "Jane". We use the dot operator to access the attributes of objects.
Person p2 = new Person();
p2.name = "Devi";
We create another instance of the Person class. Here we set the variable to "Beky".
Console.WriteLine(p1.name);
Console.WriteLine(p2.name);
We print the contents of the variables to the console.
$ ./person.exe
Rama
Devi
We see the output of the program. Each instance of the Person class has a separate copy of the name member field.
Methods
Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. Methods bring modularity to our programs.Methods are essential in the encapsulation concept of the OOP paradigm. For example, we might have a Connect() method in our AccessDatabase class. We need not to be informed, how exactly the method Connect() connects to the database. We only have to know, that it is used to connect to a database. This is essential in dividing responsibilities in programming, especially in large applications.
Objects group state and behavior. Methods represent the behavioral part of the objects.
using System;
public class Circle
{
private int radius;
public void SetRadius(int radius)
{
this.radius = radius;
}
public double Area()
{
return this.radius * this.radius * Math.PI;
}
}
public class Methods
{
static void Main()
{
Circle c = new Circle();
c.SetRadius(5);
Console.WriteLine(c.Area());
}
}
In the code example, we have a Circle class. We define two methods.
private int radius;
We have one member field. It is the radius of the circle. The
private keyword is an access specifier. It tells
that the variable is restricted to the outside world. If we
want to modify this variable from the outside, we must use
the publicly available SetRadius() method. This way we protect
our data.
public void SetRadius(int radius)
{
this.radius = radius;
}
This is the
SetRadius() method. The this
variable is a special variable which we use to access the member
fields from methods. The this.radius is an instance variable, while the
radius is a local variable, valid only inside the SetRadius()
method.
Circle c = new Circle();
c.SetRadius(5);
We create an instance of the Circle class and set its radius by calling the
SetRadius() method on the object of the
circle. We use the dot operator to call the method.
public double Area()
{
return this.radius * this.radius * Math.PI;
}
The
Area() method returns the area of a circle. The
Math.PI is a built-in constant.
$ ./circle.exe
78.5398163397448
Running the example gives this outcome.
Basics of C#
Basics
In this part of the C# tutorial, we will cover basic programming concepts
of the C# language. We introduce the very basic programs. We will work with variables,
constants and basic data types. We will read and write to the console; we will mention
variable interpolation.
We start with a very simple code example.
using System;
public class Simple
{
static void Main()
{
Console.WriteLine("This is C#");
}
}
This is our first C# program. It will print "This is C#" message to the console. We will explain it line by line.
using System;
The using keyword imports a specific namespace to
our program. Namespaces are created to group and/or distinguish named entities
from other ones. This prevents name conflicts. This line is a C# statement.
Each statement is ended with a semicolon.
public class Simple
{
...
}
Each C# program is structured. It consists of classes and its members.
A class is a basic building block of a C# program. The
public keyword gives unrestricted access to this
class. The above code is a class definition. The definition has a body,
which starts with a left curly brace ({) and ends with a right curly brace (}).
static void Main()
{
...
}
TheMain()is a method. A method is a piece of code created to do a specific job. Instead of putting all code into one place, we divide it into pieces, called methods. This brings modularity to our application. Each method has a body, in which we place statements. The body of a method is enclosed by curly brackets. The specific job for the Main() method is to start the application. It is the entry point to each console C# program. The method is declared to bestatic. This static method can be called without the need to create an instance of the CSharApp class. First we need start the application and after that, we are able to create instances of classes.
Console.WriteLine("This is C#");
In this code line, we print the "This is C#" string to the console. To print a message to the console, we use the
WriteLine() method of the Console class.
The class represents the standard input, output, and error streams
for console applications. Note that Console class is part of the System namespace.
This line was the reason to import the namespace with the using System;
statement. If we didn't use the statement, we would have to use the fully qualified
name of the WriteLine() method.This would be
System.Console.WriteLine("This is C#");.
$ ./simple.exe
This is C#
Executing the program gives the above output.
Reading values
We can use the Console class to read values as well.using System;
public class ReadLine
{
static void Main()
{
string name;
Console.Write("Enter your name: ");
name = Console.ReadLine();
Console.WriteLine("Hello {0}", name);
}
}
The second program will read a value from a console
and print it.string name;
We declare a variable. The variable is called 'name'. Unlike constants, which store only one value during the life of the program, variables may store various different values of the same type. The
string
keyword defines the data type of the variable. Our variable will hold
string valuesname = Console.ReadLine();
We read a line from the terminal. When we hit the Enter key, the input is assigned to the name variable.
.
Console.WriteLine("Hello {0}", name);
In this code line, we perform variable interpolation. Variable interpolation is replacing variables with their values inside string literals. Another names for variable interpolation are: variable substitution and variable expansion.
$ ./readline.exe Enter your name: Rama devi Hello Rama devi
This is the output of the second program.
Command line arguments
C# programs can receive command line arguments. They follow the name of the program, when we run it.using System;
public class CSharpApp
{
static void Main(string[] args)
{
for (int i=0; i<args.Length; i++)
{
Console.WriteLine("{0}", args[i]);
}
}
}
Command line arguments can be passed to the Main() method.
public static void Main(string[] args)
This
Main() method receives a string array of
command line arguments.
for (int i=0; i<args.Length; i++)
{
Console.WriteLine("{0}", args[i]);
}
We go through the array of these arguments with a for loop and print them to the console. The
Length property gives
the number of elements in the array. Loops and
arrays will be described in more detail later.
$ ./commandargs.exe 1 2 3
1
2
3
We provide three numbers as command line arguments and these are printed to the console.
Variables
A variable is a place to store data. A variable has a name and a data type. A data type determines, what values can be assigned to the variable. Integers, strings, boolean values etc. Over the time of the program, variables can obtain various values of the same data type. Variables are always initialized to the default value of their type before any reference to the variable can be made.using System;
public class CSharpApp
{
static void Main()
{
string city = "Chennai";
string name = "Devi"; int age = 28;
string nationality = "Indian";
Console.WriteLine(city);
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(nationality);
city = "Coimbatore";
Console.WriteLine(city);
}
}
In the above example, we work with four variables.
string city = "Chennai";
We declare a city variable of the string type and initialize it to the "New York" value.
string name = "Devi"; int age = 28;
We declare and initialize two more variables. We can put two statements into one line. But for readability reasons, each statement should be on a separate line.
Console.WriteLine(city);
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(nationality);
We print the values of the variables to the terminal.
city = "Coimbatore";
We assign a new value to the city variable.
$ ./variables.exe
Chennai
Devi
28
Indian
Coimbatore
This is the output of the example.
Constants
Unlike variables, constants retain their values. Once initialized, they cannot be modified. Constants are created with theconst keyword.using System;
public class Constants
{
static void Main()
{
const int WIDTH = 100;
const int HEIGHT= 150;
int var = 40;
var = 50;
// WIDTH = 110;
}
}
In this example, we declare two constants and one variable.
const int WIDTH = 100;
const int HEIGHT= 150;
We use the
const keyword
to inform the compiler, that we declare a constant. It
is a convention to write constants in upper case letters.
int var = 40;
var = 50;
We declare and initialize a variable. Later, we assign a new value to the variable. It is legal.
// WIDTH = 110;
This is not possible with a constant. If we uncomment this line, we will get a compilation error.
String formatting
Building strings from variables is a very common task in programming. C# has the string.Format() method to format strings.Some dynamic languages like Perl, PHP or Ruby support variable interpolation. Variable interpolation is replacing variables with their values inside string literals. C# does not allow this. It has string formatting instead.
using System;
public class StringFormatting
{
static void Main()
{
int age = 28;
string name = "Ramya";
string output;
output = string.Format("{0} is {1} years old.",
name, age);
Console.WriteLine(output);
}
}
Strings are immutable in C#. We cannot modify an existing string. We must create a new string from existing strings and other types. In the code example, we create a new string. We also use values from two variables.
int age = 28; string name = "Ramya"; string output;
Here we declare three variables.
output = string.Format("{0} is {1} years old.",
name, age);
We use the
Format() method of the
built-in string class. The {0}, {1} are the places where
the variables are evaluated. The numbers represent the
position of the variable. The {0} evaluates to the first
supplied variable and the {1} to the second etc.
$ ./stringformatting.exe
Ramya is 28 years old.
This is the output of the stringformatting.exe program.
This chapter covered some basics of the C# language.
IIS-Internet Information Server
What is IIS ?
IIS (Internet Information Server) is one of the most
powerful web servers from Microsoft that is used to host your ASP.NET
Web application. IIS has it’s own ASP.NET Process Engine to handle the
ASP.NET request. So, when a request comes from client to server, IIS
takes that request and process it and send response back to clients.
The Two Main concepts
1.Worker Process
2.Application Pool
Worker Process
- Worker Process (w3wp.exe) runs the ASP.Net application in IIS.
- This process is responsible to manage all the request and response that are coming from client system.
- All the ASP.Net functionality runs under the scope of worker process.
- When a request comes to the server from a client worker process is responsible to generate the request and response.
- In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.
Application Pool
- Application pool is the container of worker process.
- Application pools is used to separate sets of IIS worker processes that share the same configuration.
- Application pools enables a better security, reliability, and availability for any web application.
- The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn’t not impact other web application as they they are configured into different application pools.
- Application Pool with multiple work process is called "WEB GARDEN".
IIS Process
let’s have look how IIS process the request when a new request comes up from client.
If we look into the IIS 6.0 Architecture, we can divided them into Two Layer
If we look into the IIS 6.0 Architecture, we can divided them into Two Layer
1.Kernal Mode
2.User Mode
Now, Kernel mode is introduced with IIS 6.0, which contains the HTTP.SYS. So whenever a request comes from Client to Server, it will hit HTTP.SYS First.
Now, HTTP.SYS is Responsible for pass the request to particular Application pool. Now here is one question, How HTTP.SYS comes to know where to send the request? This is not a random
pickup. Whenever we creates a new Application Pool, the ID of the
Application Pool is being generated and it’s registered with the
HTTP.SYS. So whenever HTTP.SYS Received the request from any web
application, it checks for the Application Pool and based on the
application pool it send the request.
Till now, Client Requested for some information and request came to the Kernel level of IIS means at HTTP.SYS. HTTP.SYS has been identified the name of the application pool where to send. Now, let’s see how this request moves from HTTP.SYS to Application Pool.
In User Level of IIS, we have Web Admin Services (WAS) which takes the request from HTTP.SYS and pass it to the respective application pool.
Note : Sometimes if we install IIS after installing asp.net, we need to register the extension with IIS using aspnet_regiis command.
When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.
After that HttpRuntime load an HttpApplication object with the help of HttpApplicationFactory class.. Each and every request should pass through the corresponding HTTPModule to reach to HTTPHandler, this list of module are configured by the HTTPApplication.
Now, the concept comes called “HTTPPipeline”. It is called a pipeline because it contains a set of HttpModules ( For Both Web.config and Machine.config level) that intercept the request on its way to the HttpHandler. HTTPModules are classes that have access to the incoming request. We can also create our own HTTPModule if we need to handle anything during upcoming request and response.
HTTP Handlers are the endpoints in
the HTTP pipeline. All request that are passing through the HTTPModule
should reached to HTTPHandler. Then HTTP Handler generates the output
for the requested resource. So, when we requesting for any aspx web
pages, it returns the corresponding HTML output.
All the request now passes from httpModule to respective
HTTPHandler then method and the ASP.NET Page life cycle starts. This
ends the IIS Request processing and start the ASP.NET Page Lifecycle.
Conclusion
When client request for some information from a web server, request
first reaches to HTTP.SYS of IIS. HTTP.SYS then send the request to
respective Application Pool. Application Pool then forward the request
to worker process to load the ISAPI Extension which will create an
HTTPRuntime Object to Process the request via HTTPModule and
HTTPHanlder. After that the ASP.NET Page LifeCycle events starts.
Subscribe to:
Posts (Atom)











