Asp.Net

Friday 22 August 2014

Web Services in Asp.net

In this article ,I will Explain you how to create a simple web service in Asp.Net:

First Create a Employee Table and Insert some records in your database:(Table Name:TB_Employee)
ID Int (Set Identity=true and don't allow null values)
Name varchar(50)
City varchar(50)
Mob varchar(50)

Asp.Net Web Service Application:
Now In the Microsoft Visual Studio

Open visual studio -> Select File -> New -> Web Site -> select ASP.NET Web Service
 
Now open  Service.cs file in App_Code folder to write the code to get the user details from the database
Before writing the WebMethod in Service.cs first add following namespaces
 

using System.Xml;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
 
Now Add below Method in the Service.cs File 

 [WebMethod]
  public XmlElement GetEmployeeDetails(string name)
   {
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dbconnection"].ToString());con.Open();
 string query = "select * from [Tb_Employee] where Name like @name+'%'";
 SqlCommand cmd = new SqlCommand(query, con);
 cmd.Parameters.AddWithValue("@name", name);
 SqlDataAdapter da = new SqlDataAdapter();
 da.SelectCommand = cmd;
 DataSet ds = new DataSet();
 da.Fill(ds);
 con.Close();
 XmlDataDocument xmldata = new XmlDataDocument(ds);
  XmlElement xmlele = xmldata.DocumentElement;
  return xmlele;
   }
 
Here we need to remember one point that is adding [WebMethod] before method definition because we need to access web method pulically otherwise it’s not possible to access method publically. If you observe above code I converted dataset to XmlElement t because sometimes we will get error like return type dataset invalid type it must be either an IListSource, IEnumerable, or IDataSource to avoid this error I converted dataset to XmlElement.
Here we need to set the database connection in web.config because here I am getting database connection from web.config 
 
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=USER\SQLEXPRESS; Integrated Security=True; Initial Catalog=Practice"/>
  </connectionStrings>
 
 
Now our Web Service Application is ready to use and Lets See how to use web service in an web application.
 
Open visual studio -> Select File -> New -> Web Site -> select ASP.NET Web Site
 
 Asp.Net Web Site :
 
After creation of new website right click on solution explorer and choose “Add web reference” 
then give our URL of the web service in the search text box And Click the Add Reference.
 
Now our Default.aspx should be like this: 
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Getting Data from WebService</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<b>Enter UserName:</b>
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gvUserDetails" runat="server" EmptyDataText="No Record Found">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
 
Default.aspx.cs 
 
 
using System;
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;
using System.Xml;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bindemployee("");
        }

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        bindemployee(txtUserName.Text);
    }

    protected void bindemployee(string username)
    {
        localhost.Service objectemp = new localhost.Service();
        DataSet ds = new DataSet();
        XmlElement xmlele = objectemp.GetEmployeeDetails(username);
        if (xmlele != null)
        {
            XmlNodeReader xmln = new XmlNodeReader(xmlele);
            ds.ReadXml(xmln, XmlReadMode.Auto);
            gvUserDetails.DataSource = ds;
            gvUserDetails.DataBind();

        }
        else
        {
            gvUserDetails.DataSource = null;
            gvUserDetails.DataBind();
        }
       
      
    }
}

 


 
 



 
 
 
 






Thursday 21 August 2014

jQuery Adding two numbes by getting value from Asp.Net Textboxes

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>jQuery</title>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
        $('#Submit').click(function ()
                {
                    var a =parseInt($('#txtno1').val());
                    var b =parseInt($('#txtno2').val());
                    $('#txtresult').val(a+b);
                });
         });
       </script>
    <body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:TextBox ID="txtno1" runat="server"></asp:TextBox>
    <asp:TextBox ID="txtno2" runat="server"></asp:TextBox>
    <asp:TextBox ID="txtresult" runat="server"></asp:TextBox>
    <asp:button ID="Submit" runat="server" text="Button" />
    </form>
</body>
</html>

Wednesday 13 August 2014

Exporting Data from Form to Excel,Word and PDF in Asp.Net

--Export to Excel:--

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
protected void btnexporttoexcel_click(object sender, EventArgs e)
    {
        string attachment = "attachment; filename=ContractorDetails.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        gvclientcontractordetails.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gvclientcontractordetails);
        frm.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
 public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
--Export to Word:---



     Response.AddHeader("content-disposition", "attachment;filename=Export.doc");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.word";
 
            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
 
            HtmlForm frm = new HtmlForm();
            gv.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(gv);
            frm.RenderControl(htmlWrite);
      
            Response.Write(stringWrite.ToString());
            Response.End();
--Export to PDF--

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            HtmlForm frm = new HtmlForm();
            gv.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(gv);
            frm.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
 

Tuesday 12 August 2014

MVC3 Application Using Code First Approach

Model:Student.cs



using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.ComponentModel.DataAnnotations;

using System.Data.Entity;

namespace MVC_C.Models

{

    public class Student

    {

        [Key]

        public int S_Id { get; set; }

        [Required]

        [StringLength(30)]

        public string S_Name { get; set; }

        [Required]

        [StringLength(30)]

        public string S_Class { get; set; }

        [Required]

        [StringLength(30)]

        public string S_Grade { get; set; }

        [Required]

        [StringLength(10)]

        public string S_Mob { get; set; }

    }

    public class Studentcontext : DbContext

    {

        public DbSet<Student> Students { get; set; }

    }

}


Controller:StudentController.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using MVC_C.Models;

using System.Data.Entity;

namespace MVC_C.Controllers

{

    public class StudentController : Controller

    {

        Studentcontext db = new Studentcontext();

        //

        // GET: /Student/

        public ActionResult Index()

        {

            return View(db.Students.ToList());

        }

        //

        // GET: /Student/Details/5

        public ActionResult Details(int id)

        {

        

           return View(db.Students.Find(id));

        }

        //

        // GET: /Student/Create

        public ActionResult Create()

        {

            return View();

        }

        //

        // POST: /Student/Create

        [HttpPost]

        public ActionResult Create(Student student)

        {

            try

            {

                // TODO: Add insert logic here

                db.Students.Add(student);

                db.SaveChanges();

                return RedirectToAction("Index");

            }

            catch

            {

                return View();

            }

        }

      

        //

        // GET: /Student/Edit/5

        public ActionResult Edit(int id)

        {

          

            return View(db.Students.Find(id));

        }

        //

        // POST: /Student/Edit/5

        [HttpPost]

        public ActionResult Edit(Student student)

        {

            try

            {

                db.Entry(student).State= System.Data.EntityState.Modified;

                db.SaveChanges();

          

            return RedirectToAction("Index");

            }

            catch

            {

                return View();

            }

        }

        //

        // GET: /Student/Delete/5

        public ActionResult Delete(int id)

        {

            return View(db.Students.Find(id));

        }

        //

        // POST: /Student/Delete/5

        [HttpPost]

        public ActionResult Delete(Student student)

        {

            try

            {

                db.Entry(student).State = System.Data.EntityState.Deleted;

                db.SaveChanges();

                return RedirectToAction("Index");

            }

            catch

            {

                return View();

            }

        }

    }

}


View:Student/Index.cshtml(while adding view you should select list template)


@model IEnumerable<MVC_C.Models.Student>

@{

    ViewBag.Title = "Index";

}

<h2>Index</h2>

<p>

    @Html.ActionLink("Create New", "Create")

</p>

<table>

    <tr>

        <th>

            S_Name

        </th>

        <th>

            S_Class

        </th>

        <th>

            S_Grade

        </th>

        <th>

            S_Mob

        </th>

        <th></th>

    </tr>

@foreach (var item in Model) {

    <tr>

        <td>

            @Html.DisplayFor(modelItem => item.S_Name)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.S_Class)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.S_Grade)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.S_Mob)

        </td>

        <td>

            @Html.ActionLink("Edit", "Edit", new { id=item.S_Id }) |

            @Html.ActionLink("Details", "Details", new { id=item.S_Id }) |

            @Html.ActionLink("Delete", "Delete", new { id=item.S_Id })

        </td>

    </tr>

}

</table>



GridView Edit,Delete.Update and Add New Row in ASP.NET

Aspx Page Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="grid.aspx.cs" Inherits="Practice.grid" %>

<!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>Untitled Page</title>
</head>
<script type="text/javascript" language="javascript"></script>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvdetails" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
            OnRowEditing="OnRowEditing_gvdetails" ShowFooter="true" OnRowUpdating="OnRowUpdating_gvdetails"
            OnRowDeleting="OnRowDeleting_gvdetails" OnRowCancelingEdit="OnRowCancelingEdit_gvdetails"
            DataKeyNames="Id" AutoGenerateColumns="false" OnRowCommand="OnRowCommand_gvdetails">
            <Columns>
                <asp:TemplateField HeaderText="Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtname" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblname" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Id">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtid" runat="server" Text='<%#Eval("Id") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblid" runat="server" Text='<%#Eval("Id") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtfid" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtfcity" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Mob">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtmob" runat="server" Text='<%#Eval("Mob") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblmob" runat="server" Text='<%#Eval("Mob") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtfmob" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="true" CausesValidation="false" ShowDeleteButton="true"
                    ButtonType="Button" EditText="Edit" />
                <asp:TemplateField>
                    <FooterTemplate>
                        <asp:Button ID="btnadd" runat="server" CommandName="Add" Text="Add" Width="60px" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
            <RowStyle BackColor="#EFF3FB" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
    </div>
    <asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClick="btnsubmit_Click" OnClientClick="javascript: return confirm('Do you want to Save this invoice as PDF?')" />
    </form>
</body>
</html>

Code Behind File i e, .cs File

using System;
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;
using System.Data.SqlClient;

namespace Practice
{
    public partial class grid : System.Web.UI.Page
    {
        //Connection to Database
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ToString());

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                gridvalues();
            }

        }
        //Gridview binding
        private void gridvalues()
        {
            DataTable dt = new DataTable();
            con.Open();
            string selquery = "select * from Tb_Employee";
            SqlCommand cmd = new SqlCommand(selquery,con);
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            gvdetails.DataSource = dt;
            gvdetails.DataBind();
            con.Close();
       }

        //on row Gridview Editing
        protected void OnRowEditing_gvdetails(object sender, GridViewEditEventArgs e)
        {
            gvdetails.EditIndex = e.NewEditIndex;
            gridvalues();
        }
        //on row Gridview Deleting
        protected void OnRowDeleting_gvdetails(object sender, GridViewDeleteEventArgs e)
        {
            int index = e.RowIndex;
            string id = gvdetails.DataKeys[index].Values["Id"].ToString();

            string selquery = "delete from Tb_Employee where Id='"+id+"'";
            con.Open();
            SqlCommand cmd = new SqlCommand(selquery, con);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            con.Close();
            gridvalues();
        }
        //on row Gridview Canceling Edit
        protected void OnRowCancelingEdit_gvdetails(object sender, GridViewCancelEditEventArgs e)
        {
            gvdetails.EditIndex = -1;
            gridvalues();
           
        }
        //on row Gridview Updating
        protected void OnRowUpdating_gvdetails(object sender, GridViewUpdateEventArgs e)
        {
          int index = e.RowIndex;
         
          string id = gvdetails.DataKeys[index].Values["Id"].ToString();
          TextBox txtname =((TextBox)gvdetails.Rows[e.RowIndex].FindControl("txtname"));
          TextBox txtcity = ((TextBox)gvdetails.Rows[e.RowIndex].FindControl("txtcity"));
          TextBox txtmob = ((TextBox)gvdetails.Rows[e.RowIndex].FindControl("txtmob"));

          string selquery = "update Tb_Employee set Name='" + txtname.Text + "',City='" + txtcity.Text + "',Mob='" + txtmob.Text + "' where Id='" + id + "'";
          con.Open();
          SqlCommand cmd = new SqlCommand(selquery, con);
          cmd.CommandType = CommandType.Text;
          cmd.ExecuteNonQuery();
          con.Close();
          gvdetails.EditIndex = -1;
          gridvalues();
        }
        //on row Gridview Adding Rows
        protected void OnRowCommand_gvdetails(object sender, GridViewCommandEventArgs e)
        {


            TextBox txtfname = (TextBox)gvdetails.FooterRow.FindControl("txtfname");
            TextBox txtfcity = (TextBox)gvdetails.FooterRow.FindControl("txtfcity");
            TextBox txtfmob = (TextBox)gvdetails.FooterRow.FindControl("txtfmob");
            TextBox txtfid = (TextBox)gvdetails.FooterRow.FindControl("txtfid");
          
            string selquery ="insert into Tb_Employee values('"+txtfname.Text+"','"+txtfid.Text+"','"+txtfcity.Text+"','"+txtfmob.Text+"')";
            con.Open();
            SqlCommand cmd = new SqlCommand(selquery, con);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            con.Close();
            gvdetails.EditIndex = -1;
            gridvalues();
           

        }
        private void FnAlert(string msg)
        {
            string strMsg = "alert('" + msg + "')";
            string popupScript = "<script language='javascript'> {" + strMsg + "}</script>";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", popupScript);
        }
        protected void btnsubmit_Click(object sender, EventArgs e)
        {
            int a = 1;
            if (a == 1)
            {
                FnAlert("Hello Naveen");
              
             
            }
        }
     
    }

  
}