Thursday, July 31, 2014

Insert data Into database(SQL SERVER) without page refresh and reload

Today’s challenging environment, we need to very fast running websites or portal. Where we can easily share information and fetch the information.  In simple asp.net when we insert the data into database it take some time, page will be refresh and reload, this is too complex and irritating. Using Ajax and jquery, we can insert data into database without page refresh and reload. Now I will be explain step by step how you can achieve this.
Step-1: create a table where we store information. I am writing code fro create table and store procedure.
For table.
CREATE TABLE [dbo].[testjquery](
      [id] [int] IDENTITY(1,1) NOT NULL,
     
      [name] [nvarchar](50) NULL,
      [cityid] [int] NULL,
     
      [stateid] [int] NULL,
     
      [description] [nvarchar](500) NULL
) ON [PRIMARY]



For store procedure.
CREATE PROCEDURE insertinfo
      -- Add the parameters for the stored procedure here
      @name nvarchar(20),
      @stateid int,
      @cityid int,
      @description nvarchar(100)
      AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

    -- Insert statements for procedure here
insert into dbo.testjquery(name,stateid,cityid,description)values(@name,@stateid,@cityid,@description)
END

Step2- Now we open visual studio and create a new website and add a new page test.aspx. and design a table and write html code for text field.
<table>
    <tr><td>Name :</td><td><asp:TextBox ID="TextBox1" runat="server" CssClass="input_field_contactus" MaxLength="20"></asp:TextBox></td></tr>
     <tr><td>Name :</td><td>  <asp:DropDownList ID="ddlstate" runat="server" 
                            CssClass="input_field_contactus" >
                        </asp:DropDownList>
            </td></tr>
 
    <tr><td>City</td><td>
            <asp:DropDownList ID="ddlcity"   runat="server"  CssClass="input_field_contactus" TextAlign="Left" ></asp:DropDownList>
</td></tr>
<tr><td>Description</td><td><asp:TextBox ID="description" runat="server" CssClass="input_field_contactus" MaxLength="500" TextMode="MultiLine" Height="100px"></asp:TextBox>
</td></tr>
<tr><td><div style="margin:0; padding-top: 10px; float:left;">
<input type="button" value="Submit" class="button"  />


</div></td></tr>
    </table>

Now add a jquery script file and add this code  script code for insert the data .
<script src="http://code.jquery.com/jquery-2.0.0b1.js"></script>
<script src="js/olt.js" type="text/javascript" ></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $('.button').click(function () {

                var name = $('#<%=TextBox1.ClientID%>').val();
                alert(name);
                var state = $('#<%=ddlstate.ClientID%>').val();
                var city = $('#<%=ddlcity.ClientID%>').val();
                var description = $('#<%=description.ClientID%>').val();

                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "test.aspx/InsertMethod",
                    data: "{'name':'" + name + "','state':'" + state + "','city':'" + city + "','description':'" + description + "'}",
                    dataType: "json",
                    success: function (data) {
                        var obj = data.d;
                        if (obj == 'True') {
                            $('#<%=TextBox1.ClientID%>').val('');



                            $('#<%=description.ClientID%>').val('');
                            $('#<%=ddlstate.ClientID%>').val('0');
                            $('#<%=ddlcity.ClientID%>').val('0');

                            alert('Data Submitted Successfully');

                        }
                    },
                    error: function (result) {
                        alert("Error");
                    }

                });


            })
        });
</script>

Step 3- Write this method to code behind in test.aspx.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Text;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

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

    }
    [WebMethod]
    public static string InsertMethod(string name, string state, string city, string description)
    {
        String strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "insertinfo";
        cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = name;
        cmd.Parameters.Add("@description", SqlDbType.VarChar).Value = description;
        cmd.Parameters.Add("@cityid", SqlDbType.VarChar).Value = city;
        cmd.Parameters.Add("@stateid", SqlDbType.VarChar).Value = state;
          cmd.Connection = con;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
           
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }
        return "True";


    }
  
}




Thursday, June 19, 2014

Difference between Store procedure and user defined function in SQL

Difference between Store procedure and function
Store procedure
Function
Store procedure is a pre-compile object which is which are compile for first time and its compile format is saved which executes (compile code) whenever it is called.
Function is compiled every time when it is called.
Procedure allows select as well as DML (INSERT/UPDATE/EDIT) statement.
Function allows only SELECT Statement.
Procedures cannot utilize in SELECT Statement
Function can be embedded in SELECT Statement.
Store procedure cannot be used in SQL statement anywhere in the WHERE/HAVING/SELECT Section.
Function Can be
We can go for transaction Management in Procedure.
We cannot go for transaction in Function
Procedure can return 0 or n values (It is optional).
Function must return a value
Procedure can have input output parameters.
Function can have only input parameters.
Function can be called in procedure.
A store procedure cannot be called in function.
Exception can be handled through catch and try block in procedure.
Exception cannot be handled in function.
Store procedure can be called using execute store procedure name
Function can be called using select statement.

Another point are-
·         Function that returns table can be treated as another row set. That can be used in joins and other table.

·         Inline function  can be tough  of as view that take parameters  and can be used other  row set operations

Friday, June 6, 2014

Difference among ViewData,TempData and View Bag in MVC

Sr.No
Temp Data
View data
View Bag
1
TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
ViewData is a dictionary object that is derived from ViewDataDictionary class.
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
2
TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
ViewData is used to pass data from controller to corresponding view.
Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
3
Its life is very short and lies only till the target view is fully loaded.
Its life lies only during the current request.
Its life also lies only during the current request.
4
It’s required typecasting for getting data and check for null values to avoid error.
If redirection occurs then its value becomes null.
If redirection occurs then its value becomes null.

Error.
It is used to store only one time messages like error messages, validation messages.
It’s required typecasting for getting data and check for null values to avoid error.
It doesn’t required typecasting for getting data.




Difference Between ActionResult() and ViewResult() in MVC


Difference Between ActionResult() and ViewResult()  in MVC are-


Sr.No
ActionResult()
ViewResult()
1
Actionresult() is general result type that can have several subtypes.
Viewresult() renders a specified view to the response stream.
2
ActionResult() is an abstract class.
ViewResult() is a concrete   class.
3
ActionResult() is a base class for ViewResult()
ViewResult() is a derived class for ActionResult()
4
In MVC framework it uses ActionResult() class to the reference the object our action method returns and invoke Execute result method on it
ViewResult() is an implementation for this abstract class (ActionResult class).It will try to find a view page (usually .aspx page) in some predefined  paths by the given name.
5
In ActionResult() class are many subtypes-
·        ViewResult()
·        EmptyResult()
·        RedirectResult()
·        RedirectToRouteResult()
·        JSONResult()
·        JavaScriptResult()
·        ContentResult()
·        FileContentResult()
·         FileStraemResult()
As it is concrete class, so subtypes are not available for the ViewResult() class.

Difference between SQL Server 2002 and SQL Server 2005

Hi Friends, I am explaining differences between sql server 2002 and sql server 2005

Sr.No
2002
2005
1
Query Analyser and Enterprise manager are separate.
Both are combined as SSMS(Sql Server management Studio).
2
No XML data type is used.
XML data type is introduced.
3
We can create maximum of 65,535 databases.
We can create 220-1 databases.
4
Exception Handling mechanism is not available
Exception Handling mechanism is available
5
There is no Varchar(Max) data type is not available
Varchar(Max) data type is introduced.
6
DDL Triggers is not available
DDL Triggers is introduced

RowNumber function for paging is not available
RowNumber function for paging is introduced
7
Table fragmentation facility is not available
Table fragmentation facility is introduced
8
Full Text Search facility is not available
Full Text Search facility is introduced
9
Bulk Copy Update facility is not available
Bulk Copy Update facility is introduced
10
Data Encryption concept is not introduced
.Cannot encrypt the entire database
11
Cannot compress the tables and indexes.
Can Compress tables and indexes.(Introduced in 2005 SP2)
12
No varchar(max) or varbinary(max) is available.
Varchar(max) and varbinary(max) is used.
13
Data Transformation Services(DTS) is used as ETL tool
SQL Server Integration Services(SSIS) is started using from this SQL Server version and which is used as ETL tool

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.


Features
Web Service
WCF
Hosting
It can be hosted in IIS
It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming
[WebService] attribute has to be added to the class
[ServiceContraact] attribute has to be added to the class
Model
[WebMethod] attribute represents the method exposed to client
[OperationContract] attribute represents the method exposed to client
Operation
One-way, Request- Response are the different operations supported in web service
One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML
System.Xml.serialization name space is used for serialization
System.Runtime.Serialization namespace is used for serialization
Encoding
XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom
XML 1.0, MTOM, Binary, Custom
Transports
Can be accessed through HTTP, TCP, Custom
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols
Security
Security, Reliable messaging, Transactions