Tuesday, 27 March 2012

Creating a WebService in ASP.NET

What is a Web Service?
Web Services can convert your applications into Web-applications.

A. Create a Web Service class and method
 
Step 1: Creating Web Project
 Open Visual Studio and create a new Web Site. Name it whatever you want.


 Step 2: Adding New Item
 

This will open the 'Add New Item' Dialoge box. Select template 'Web Service' and name it WS.asmx.


 You will notice that two new files has been added: WS.aspx and WS.cs under App_Code

Adding a web service file will add WS.asmx file. If you open the WS.cs file, you will notice lot of pre-coded lines there. 
A class must inherit System.Web.Services.WebService in order to behave like a web service.

Also, a HelloWorld method is added by default. The normal method can be converted to a webmethod by adding the following line on top of that method:
<WebMethod()> _

Step 3: Adding Custom Code:
My objective is to write a webmethod that will accept two parameters and return the sum and multiplication of those two numbers. So, I removed the HelloWorld method and added my own Add and mul method as shown below.

<WebMethod()> _
Public Function Add(ByVal a As Integer, ByVal b As Integer) As Integer

        Return (a + b)

    End Function


    <WebMethod()> _
Public Function Mul(ByVal a As Integer, ByVal b As Integer) As Integer

        Return (a * b)

    End Function

At this point, your webservice clas is ready.

In order to test whether web service is created successfully or not, build the website and right click the WS.asmx and click 'View in Browser'. This action will open the webservice in browser and display the webmethod as a link.

Clicking on the WebMethod will ask for the input parameters that we defined (a, b) and submitting the form will show the result in a xml file.

B. Add Web-Reference to the project

Now when the web service has been developed, we need to add the web reference to the project. In order to do so , follow these steps:

Step 1: Click Add WebReference

Right click the project and select 'Add Web Reference'

Step 2: Browse for the web service
This action will open the 'Add Web Reference' wizard. It will ask use rto select the location where the web service is their. Since for our purpose, web service is in the solution, click 'Web Service in the solution'
Step 3: Selecting the web service:

Select the web service 'WS'. This will check the webservice 'WS' and list out all the WebMethods. During this process, you will see a progress bar liek this:
Step 4: Defining namespace and adding the reference:

After the internal process, wizard will list out the webmethods found in that webservice. If you chek the image below, there are few things to notice:

i. URL : That is the url fo the webservice. You can access the webservice WS directly from browser also.

ii. Webmethod Name: 'Add' is the name of our web method.

iii. Web Reference Name: This will be the namespace of the webservice.You can change it to your desired name. For demo purpose, I have kept it the default 'localhost'.

Clicking 'Add Reference' will add the web reference to the project and add the following files:


 
Here 'localhost' is the namespace. There are discovery file and WSDL file. I will explain the file types in next post..This means web-reference has been added.

C. Consume the created web service in the ASP.NET code.
Now after creating and adding reference, we need to consume the web service.

Step 1: Modify the ASP.NET page:

In the default.aspx, add the following code:





<body>
    <form id="form1" runat="server">
<div>
Enter value 1:<asp:TextBox ID="A" runat="server"/>
Enter value 2:<asp:TextBox ID="B" runat="server"/>
<asp:Button id="btnSubmit" runat="server" Text="Add" onclick="btnSubmit_Click" />
&nbsp;&nbsp;
    <asp:Button ID="Button1" runat="server" Text="Mul" />
<hr />
Sub Result: <asp:Label id="lbl" runat="server"/>
</div>
</form>
</body>





Now we need to access the webservice from code. That we do by referring the namespace 'localhost'.

In the btnSubit and mul Click event , add the following code:

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Dim s1 As New localhost.WebService()
        lbl.Text = s1.Add(Int32.Parse(A.Text), Int32.Parse(B.Text)).ToString()
    End Sub

    Protected Sub mul_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim s1 As New localhost.WebService()
        lbl.Text = s1.Mul(Int32.Parse(A.Text), Int32.Parse(B.Text)).ToString()
    End Sub


Finally, build the website and run the application, default.aspx will open .Enter two values and click 'Add' and Mul button.The result will be shown in the label.



Please feel free to contact me if you have any query..

Sunday, 25 March 2012

java script code to display photos that changes after few seconds.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="AdRedirect.aspx.vb" Inherits="AdRedirect" %>

<!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 runat="server"> 
        <title>Image</title>
        <script type="text/javascript">
            var picPaths = ['pic1.jpg','pic2.jpg','pic3.jpg','pic4.jpg','pic5.jpg'];
            var curPic = -1;
            //preload the images for smooth animation
            var imgO = new Array();
            for(i=0; i < picPaths.length; i++) {
                imgO[i] = new Image();
                imgO[i].src = picPaths[i];
            }
 
            function swapImage() {
                curPic = (++curPic > picPaths.length-1)? 0 : curPic;
                imgCont.src = imgO[curPic].src;
                setTimeout(swapImage,2000);
            }
 
            window.onload=function() {
                imgCont = document.getElementById('Image1');
                swapImage();
            }
        </script>
 
    </head>
    <body>
 
        <div>
            <asp:Image ID="Image1" runat="server" Width="147px" />
        </div>
 
    </body>
</html> 

Thursday, 15 March 2012

What is difference between ExecuteReader ,ExecuteNonQuery and ExecuteScalar?

 1)ExecuteReader : Use for accessing data. It provides a forward-only, read-only, connected recordset.  

2)ExecuteNonQuery : Use for data manipulation, such as Insert, Update, Delete.  

3)ExecuteScalar : Use for retriving 1 row 1 col. value., i.e. Single value. eg: for retriving aggregate function. It is faster than other ways of retriving a single value from DB. 

Saturday, 10 March 2012

Asp.net control tutorial

Friends following link gives detail information about asp.net all types of control. If you have any doubt in using any control, how to set properties of control ,how to perform validation etc.plz refer given link:
click here for Asp.net control tutorial

Select query operation

Till now we have seen how to perform insert,delete and update operation now next and last operation is select query.

Till now we have seen only one page project here i will tell you how to redirect from one page to another page in asp.net using two page project.In this section i will create two page project on first page user will submit his detail and on next page he will display all his detail.

1)Create form as shown below for submitting data to database.
 In above screen shot submit button is used for inserting data to database which we already have seen.If you forgot how to insert data in database please go to this link Insert data into database.
Redirect to display page button will redirect you to next page ie. page where you will display data using select query.


2)Now our first page is ready which is shown above but how to insert one more webform in your project?just refer following screenshot:




After clicking Add new item following window opens,select webform from given list and give name to this form as submit.aspx .
Now click on Add button now you will see in your solution explorer one more page submit.aspx as shown below:


3)Code use for redirecting from one page to another page is given below:
Response.Redirect("*.aspx")
 in our case it will be  Response.Redirect("submit.aspx").

So now double click Redirect to display page button and type this code in click button event:
Response.Redirect("submit.aspx")
4)Now open submit.aspx page from solution explorer and create form as shown below:

Here we will take help of roll no to retrieve remaining data from database:

4)Now double click Show data button present on submit .aspx page. and type following code in submit.aspx.vb page.

 See this is your new page so first include following imort statement on top of sumbit.aspx.vb page:
Imports System.Data
Imports System.Data.SqlClient


Now type following code in button click event of Show data:
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("a").ToString())
        Dim sqlqry As String = "select Name,Gender,City from Table1 where Rollno=' " & TextBox1.Text & " '"
        Dim cmd As New SqlCommand
        Dim dr As SqlDataReader
        Try
            connection.Open()
            cmd = New SqlCommand(sqlqry, connection)
            dr = cmd.ExecuteReader()
            If dr.HasRows Then
                dr.Read()
                TextBox2.Text = dr("Name").ToString()
                TextBox3.Text = dr("Gender").ToString()
                TextBox4.Text = dr("City").ToString()
            End If
        Catch ex As Exception
            'Label2.Text = ex.Message
        Finally
            connection.Close()
        End Try


5)Now save and run your website:

Database after submitting above data is shown below:

Now click on Redirect to display page button on webbrowser enter roll no of which details you want to retrieve as shown below:
 Click on Show data button:
This completes your select operation.

Thursday, 8 March 2012

Update query operation

Here we will see how to update your database.In this section we will update name of student using Roll no attribute.Use same form just replace delete button with update button and add one more textbox where you will enter name of student which you want to save in database.


Now double click update button.Type following code in button click event of update button.
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("a").ToString())
        Dim sqlqry As String = "update Table1 set Name=' " & txt4.Text & " 'where Rollno=' " & txt5.Text & " '"
        Dim cmd As SqlCommand
        Try
            connection.Open()
            cmd = New SqlCommand(sqlqry, connection)
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            lblmsg.Text = ex.Message
        Finally
            connection.Close()
        End Try


Initially consider following entry were there in database.


Now save and run your website.

Now see following screenshot shows you updated database.



Wednesday, 7 March 2012

Delete query opeartion.

Now we have seen how to insert data in database.Now will see how to delete data from database.
consider following entries are there in database.


Here we will perform delete opeartion using roll no. attribute.Now modify your .aspx page by adding two control textbox and delete button as shown below:



Now open .aspx.vb page by double clicking delete button now add following code to .aspx.vb page.
Code to be written in button click event of delete button:
 Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("a").ToString())
        Dim sqlqry As String = "delete from Table1 where Rollno=' " & txt4.Text & " ' "
        Dim cmd As SqlCommand
        Try
            connection.Open()
            cmd = New SqlCommand(sqlqry, connection)
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            lblmsg.Text = ex.Message
        Finally
            connection.Close()
        End Try








In above code "a" is your connection string.txt4 is ID of your control which takes roll no of  student whose entry you want to delete..
        
Now save and run your website:Enter roll no of which entry you want to delete.

Now view whether this entry is deleted or not.Go to database explorer right click on table and click show table data.Now you can see Suresh's entry is deleted from table as shown below:



Database connection and perform insert query operation on database in .net 3.5


Now we have seen how to generate connection string in .net.Now will see how to use that connection string to connect to database.Here we will see insert query database operation:

1)Submitting data to database

    1. Go to file menu create new website.Go to design page as shown below:



2.Create  form as shown below using toolbox:

Now go to source code by clicking Source tab as shown below and type code highlighted below in between dropdown tag.Following highlighted code is used to insert value to dropdown control:

Now another way of inserting value to dropdown box is given below .just follow the screnshot given below:
    a)Click on smart tag of dropdown button:

    b)Now click on Edit Items which opens a following window:

c)Now click on Add button.
 d)Now move to Text and type please select as shown below:

e)Now click on Add button this will add "Please select" to your dropdown button.You can check it in left side of window as shown below:

 Repeat above steps d) and e) to enter male and female value to dropdown button.

 Remove button is used to remove element from dropdown button.
3)Now add sql datasource control to your page as shown below:
Now we have seen the steps for creating connection string.If you forgot please go to Given link.Steps to generate connection string
 Follow the steps given in above link,create one database then create table with attribute name Name ,Roll no.,Gender and City.Keep datatype for all attribute as nvarchar(50). Here you will get connection string which will be used to connect to your database.



After creating table ,databse and  generating connection string double click on Submit button present on .aspx page.This will open .aspx.vb page as shown below:



Now whenever we will do any code related with database  we need to type following two import statement at top of your .aspx.vb page.
Imports System.Data
Imports System.Data.SqlClient

Then type following insert query code into your submit button click event:
 Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("a").ToString())
        Dim sqlqry As String = "insert into Table1(Name,Rollno,Gender,City) values(' " & txt1.Text & " ',' " & txt2.Text & " ',' " & dd1.SelectedValue & " ',' " & txt3.Text & " ')"
        Dim cmd As SqlCommand
        Try
            connection.Open()
            cmd = New SqlCommand(sqlqry, connection)
            cmd.ExecuteNonQuery()
        Catch ex As Exception
           lblmsg.Text = ex.Message
        Finally
            connection.Close()
        End Try
 In above code "a" is your connection string.txt1,txt2,txt3 and dd1 are ID of your control.Table1 is name of your table.



In above code we have used try catch so it will throw exception if something wrong happens.In order to display or to know which types of exception you are getting take one label control on .apsx page and set prperties as shown below:

Now save and run your website:


 Now how to view data in database?Go to view click on database explorer and follow the given screenshot: