Asp.Net

Sunday 5 October 2014

Inserting Data to Database using jQuery

User.aspx:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Jquery Data Insertion</title>
</head>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
        $("[id*=btnSave]").bind("click", function () {
            var user = {};
            user.Username = $("[id*=txtusername]").val();
            user.Password = $("[id*=txtpassword]").val();
            $.ajax({
                type: "POST",
                url: "User.aspx/SaveUser",
                data: '{user: ' + JSON.stringify(user) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                alert("User has been added successfully.");
                window.location.reload();
                }
            });
            return false;
        });
    });
</script>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
    <tr>
    <td>
    Username:<asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    Password:<asp:TextBox ID="txtpassword" runat="server"></asp:TextBox>
    </td>
   
    </tr>
    <tr>
    <td>
    <asp:Button ID="btnSave" runat="server" Text="Save"/>
   
    </td>
   
    </tr>
   
    </table>
     <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" HeaderStyle-        BackColor="#3AC0F2"
    HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2">
    <Columns>
        <asp:BoundField DataField="Username" HeaderText="Username" />
        <asp:BoundField DataField="Password" HeaderText="Password" />
    </Columns>
</asp:GridView>
   
    </div>
    </form>
</body>
</html>

User.aspx.cs:

public partial class User : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users"))
                    {
                        using (SqlDataAdapter sda = new SqlDataAdapter())
                        {
                            DataTable dt = new DataTable();
                            cmd.CommandType = CommandType.Text;
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            sda.Fill(dt);
                            gvUsers.DataSource = dt;
                            gvUsers.DataBind();
                        }
                    }
                }
            }
        }

        public string Username { get; set; }
        public string Password { get; set; }


        [WebMethod]
        [ScriptMethod]
        public static void SaveUser(User user)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO Users VALUES(@Username, @Password)"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@Username", user.Username);
                    cmd.Parameters.AddWithValue("@Password", user.Password);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

    }

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>