Tuesday, 15 October 2013

insert,update,delete from gridview

   <table width="100%">
                <tr>
                    <td>
                        <asp:GridView ID="gdvFooter" runat="server" AutoGenerateColumns="false" EmptyDataText="no data..."
                            DataKeyNames="pid" OnRowCommand="gdvFooter_RowCommand" OnRowCancelingEdit="gdvFooter_RowCancelingEdit"
                            OnRowDeleting="gdvFooter_RowDeleting" OnRowEditing="gdvFooter_RowEditing" OnRowUpdating="gdvFooter_RowUpdating" OnRowDataBound="gdvFooter_RowDataBound">
                            <Columns>
                                <asp:BoundField HeaderText="S.No." DataField="Sno" />
                                <asp:TemplateField HeaderText="Product No.">
                                    <ItemTemplate>
                                        <asp:Label ID="lbpnumber" runat="server" Text='<%#bind("pnumber")%>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtpnumberUP" runat="server" Text='<%#bind("pnumber")%>'></asp:TextBox>
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtpnumber" runat="server"></asp:TextBox>
                                    </FooterTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Product Name">
                                    <ItemTemplate>
                                        <asp:Label ID="lbpName" runat="server" Text='<%#bind("pname")%>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtpnameUP" runat="server" Text='<%#bind("pname")%>'></asp:TextBox>
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtpname" runat="server"></asp:TextBox>
                                    </FooterTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Product Price">
                                    <ItemTemplate>
                                        <asp:Label ID="lbpprice" runat="server" Text='<%#bind("pprice")%>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtppriceUP" runat="server" Text='<%#bind("pprice")%>'></asp:TextBox>
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtpprice" runat="server"></asp:TextBox>
                                    </FooterTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Sum">
                                    <ItemTemplate>
                                        <asp:Label ID="blbSum" runat="server"></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:LinkButton ID="lnbtnEdit" runat="server" CommandName="Edit" Text="Edit">
                                        </asp:LinkButton>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update" Text="UpDate">
                                        </asp:LinkButton>
                                        <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete" Text="Delete">
                                        </asp:LinkButton>
                                        <asp:LinkButton ID="btnCancel" runat="server" CommandName="Cancel" Text="Cancel">
                                        </asp:LinkButton>
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                        <asp:Button ID="btnAdd" runat="server" Text="Insert" CommandName="Insert" />
                                    </FooterTemplate>
                                </asp:TemplateField>
                            </Columns>
                        </asp:GridView>
                        <asp:Button ID="btnAddNewRow" runat="server" Text="Add" OnClick="btnAddNewRow_Click" />
                        <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
                    </td>
                </tr>
            </table>
-------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Data.SqlClient;


public partial class UseFooter : System.Web.UI.Page
{
    SqlDataAdapter da;
    SqlDataReader dr;
    DataSet ds;
    SqlCommand cmd;
    SqlConnection con;
    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(@"data source=.\sqlexpress; initial catalog=AdminUse; integrated security=SSPI;");
        if (!IsPostBack == true)
        {
            loadGrid();
        }
    }
    private void loadGrid()
    {
        string sql = "select row_number() over(order by pname) as Sno,* from product order by pname";

        da = new SqlDataAdapter(sql, con);
        ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            gdvFooter.DataSource = ds.Tables[0];
            gdvFooter.DataBind();
        }
        else
        {

            gdvFooter.ShowFooter = true;
            gdvFooter.DataBind();

        }

    }
    protected void gdvFooter_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        double proprice;
        if (e.CommandName.Equals("Insert"))
        {

            TextBox p_number = gdvFooter.FooterRow.FindControl("txtpnumber") as TextBox;
            TextBox p_name = gdvFooter.FooterRow.FindControl("txtpname") as TextBox;
            TextBox p_price = gdvFooter.FooterRow.FindControl("txtpprice") as TextBox;
            if (p_price.Text == "")
            {
                proprice = 0;
            }
            else
            {
                proprice = Convert.ToDouble(p_price.Text);
            }
            SqlCommand cmd = new SqlCommand("insertproduct", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@pnumber", p_number.Text);
            cmd.Parameters.AddWithValue("@pname", p_name.Text);
            cmd.Parameters.AddWithValue("@pprice", proprice);
            cmd.Parameters.AddWithValue("@pid", SqlDbType.Int);
            cmd.Parameters["@pid"].Direction = ParameterDirection.Output;
            con.Open();
            cmd.ExecuteNonQuery();
            loadGrid();
            con.Close();
        }
    }
    protected void btnAddNewRow_Click(object sender, EventArgs e)
    {
        gdvFooter.ShowFooter = true;
        DataBind();
        loadGrid();
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        gdvFooter.ShowFooter = false;
        DataBind();
        loadGrid();
    }
    protected void gdvFooter_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gdvFooter.EditIndex = e.NewEditIndex;
        loadGrid();
    }
    protected void gdvFooter_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string p_id = gdvFooter.DataKeys[e.RowIndex].Value.ToString();
        double proprice;
        //GridViewRow row = gdvFooter.Rows[e.RowIndex];
        TextBox p_numberup = gdvFooter.Rows[e.RowIndex].FindControl("txtpnumberUp") as TextBox;
        TextBox p_nameup = gdvFooter.Rows[e.RowIndex].FindControl("txtpnameUp") as TextBox;
        TextBox p_priceup = gdvFooter.Rows[e.RowIndex].FindControl("txtppriceUP") as TextBox;
        if (p_priceup.Text == "")
        {
            proprice = 0;
        }
        else
        {
            proprice = Convert.ToDouble(p_priceup.Text);
        }
        cmd = new SqlCommand("updateproduct", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@pnumber", p_numberup.Text);
        cmd.Parameters.AddWithValue("@pname", p_nameup.Text);
        cmd.Parameters.AddWithValue("@pprice", proprice);
        cmd.Parameters.AddWithValue("@pid", p_id);
        con.Open();
        cmd.ExecuteNonQuery();
        gdvFooter.EditIndex = -1;
        loadGrid();
        con.Close();
    }
    protected void gdvFooter_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string p_idD = gdvFooter.DataKeys[e.RowIndex].Value.ToString();
        string sql = "delete from product where pid=" + p_idD + "";
        cmd = new SqlCommand(sql, con);
        con.Open();
        cmd.ExecuteNonQuery();
        gdvFooter.EditIndex = -1;
        loadGrid();
        con.Close();

    }
    protected void gdvFooter_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gdvFooter.EditIndex = -1;
        loadGrid();
    }
    protected void gdvFooter_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label Val1 = (Label)e.Row.Cells[1].FindControl("lbpnumber");
            Label Val2 = (Label)e.Row.Cells[3].FindControl("lbpprice");          
            Label lblSum = (Label)e.Row.Cells[4].FindControl("blbSum");

            if (Val1.Text == string.Empty || Val1.Text == "")
            {
                Val1.Text = "0";
            }
            if (Val2.Text == string.Empty || Val2.Text == "")
            {
                Val2.Text = "0";
            }
            int sum = int.Parse(Val1.Text) + int.Parse(Val2.Text);
            lblSum.Text += sum;
        }
    }
}

Monday, 14 October 2013

update delete select and load gridview using linq in asp.net using c#

  protected void btnModify_Click(object sender, EventArgs e)
    {

        DataClassesDataContext dbcontext = new DataClassesDataContext();
        var VideoList = (from vl in dbcontext.VideoTables where vl.VideoID == Convert.ToInt32(ViewState["VideoID"]) select vl).Single();
        if (VideoList != null)
        {
            VideoTable vt = new VideoTable();
            VideoList.VideoHeading = txtVideoHeading.Text;
            VideoList.VideoLink = txtVideoLink.Text;
            VideoList.Remark = txtRemark.Text;
        }
        try
        {
            dbcontext.SubmitChanges();
            loadVideoGrid();
            BAL.Sangram.alert("Record Updateed Successfully.....", "", true);
            return;
        }
        catch
        {
            BAL.Sangram.alert("Some Error Occured.....", "", true);
            return;
        }
    }
----------------------------------------------------------
 protected void gdvVideo_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string videoId = gdvVideo.DataKeys[e.RowIndex]["VideoID"].ToString();
        DataClassesDataContext dbcontext = new DataClassesDataContext();
        var vID = (from VlR in dbcontext.VideoTables where VlR.VideoID == Convert.ToInt32(videoId) select VlR).Single();
        try
        {
            dbcontext.VideoTables.DeleteOnSubmit(vID);
            dbcontext.SubmitChanges();
            loadVideoGrid();
            BAL.Sangram.alert("Record Deleted Successfully.....", "", true);
            return;
        }
        catch
        {
            BAL.Sangram.alert("Some Error Occured.....", "", true);
            return;
        }
    }
-----------------------------------------------------------------
protected void gdvVideo_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        ViewState["VideoID"] = gdvVideo.DataKeys[e.NewSelectedIndex]["VideoID"].ToString();
        DataClassesDataContext dbcontext = new DataClassesDataContext();
        var vidiolist = from vl in dbcontext.VideoTables where vl.VideoID == Convert.ToInt32(ViewState["VideoID"]) select vl;
        if (vidiolist != null)
        {
            txtVideoHeading.Text = vidiolist.FirstOrDefault().VideoHeading.ToString();
            txtVideoLink.Text = vidiolist.FirstOrDefault().VideoLink.ToString();
            txtRemark.Text = vidiolist.FirstOrDefault().Remark.ToString();
            btnModify.Visible = true;
            btnSave.Visible = false;
        }
    }
---------------------------------------------------------------
    private void loadVideoGrid()
    {
        DataClassesDataContext dbcontext = new DataClassesDataContext();
        var vedioList = from vl in dbcontext.VideoTables select vl;
        gdvVideo.DataSource = vedioList;
        gdvVideo.DataBind();
    }

Friday, 13 September 2013

data access layers

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace DataAcessLayer
{
    internal class DataAccess
    {
        public DataAccess()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public static string GetConnection
        {
            get {
                string ConnectionStr = System.Configuration.ConfigurationManager.AppSettings["ConStr"];
            return ConnectionStr;
            }
        }
        public static DataTable GetDataFromTable(string SPName, params SqlParameter[] parameters)
        {
            SqlConnection cn = new SqlConnection(GetConnection);
            SqlCommand cmd = new SqlCommand(SPName,cn);
            IDataReader dr;
            DataTable dt = new DataTable();

            cmd.CommandText = SPName;
            cmd.CommandType = CommandType.StoredProcedure;
            if (parameters != null)
            {
                foreach (SqlParameter item in parameters)
                    cmd.Parameters.Add(item);
            }
            cn.Open();
            try {
                dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                if (dr != null)
                {
                    dt.Load(dr);
                }
           
            }
            catch (SqlException Ex)
            {
                return null;
            }
           
            cn.Close();
            cn.Dispose();
            cn = null;
           
            cmd.Dispose();
            cmd = null;
            return dt;
        }
        public static int Execute(string SPName,params  SqlParameter[] parameters)
        {
            int intERRor = 0;
            SqlConnection cn = new SqlConnection(GetConnection);
            SqlCommand cmd = new SqlCommand(SPName, cn);
            IDataReader dr;
            cmd.CommandText = SPName;
            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter pError = new SqlParameter("@Error",SqlDbType.Int);
            pError.Direction = ParameterDirection.Output;

            if (parameters != null)
            {
                cmd.Parameters.Add(pError);
                foreach (SqlParameter item in parameters)
                {
                    cmd.Parameters.Add(item);
                }
            }
            cn.Open();
            try {
                if (parameters != null)
                {
                    cmd.ExecuteNonQuery();
                }
            }
            catch (SqlException ex)
            {
                intERRor = -1;
            }
            cn.Dispose();
            cn.Close();
            cn = null;
         
            cmd.Dispose();
            cmd = null;
            if (parameters != null)
                intERRor = (int)(pError.Value);
            return intERRor;

        }

    }
}

Monday, 26 August 2013

business logic layer

using System;
using System.Data;
using System.Configuration;
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;
using FileUploadDAL;
/// <summary>
/// Summary description for SAM
/// </summary>
namespace FileUploadSAM
{
    public class SAM
    {
        public SAM()
        {

        }

        public class UploadFile
        {
            public static DataTable CustomTableData(string procedurename, params SqlParameter[] p)
            {
                return DataAccess.GetFromDataTable(procedurename, p);
            }
            //Insert logFile details
            public static int InsertLogFile(LogFile lf)
            {
                SqlParameter[] p = new SqlParameter[5];
                p[0] = new SqlParameter("@UserID", lf.UserID);
                p[1] = new SqlParameter("@UserType", lf.UserType);
                p[2] = new SqlParameter("@UserLog", lf.UserLog);
                p[3] = new SqlParameter("@IPAddress", lf.IPAddress);
                p[4] = new SqlParameter("@EntryDate", lf.EntryDate);
                return DataAccess.Execute("InsertLogFile", p);

            }
            //Insert FileUpload Details from User End
            public static int UserUploadFile(UserUploadFile UF)
            {
                SqlParameter[] p = new SqlParameter[7];
                p[0] = new SqlParameter("@EntryDate", UF.EntryDate );
                p[1] = new SqlParameter("@UserID", UF.UserID );
                p[2] = new SqlParameter("@UIPAddress", UF.UIPAddress );
                p[3] = new SqlParameter("@Titile", UF.Titile );
                p[4] = new SqlParameter("@FilePath", UF.FilePath );
                p[5] = new SqlParameter("@FileSize", UF.FileSize);
                p[6] = new SqlParameter("@Remark", UF.Remark );
                return DataAccess.Execute("InsertUserUploadFile", p);
            }
            public static DataTable GetDownloadFileDetail(string FUPID)
            {
                SqlParameter[] p = new SqlParameter[1];
                p[0] = new SqlParameter("@FUPID", FUPID);
                return  DataAccess.GetFromDataTable("GetDownloadFileDetail", p);
         
            }
            public static DataTable GetDownloadFileDetailbyDate(string FromDate,string ToDate)
            {
                SqlParameter[] p = new SqlParameter[2];
                p[0] = new SqlParameter("@DateFrom", FromDate);
                p[1] = new SqlParameter("@DateTo", ToDate);
                return DataAccess.GetFromDataTable("GetDownloadFileDetailbyDate", p);

            }
        }
        public static string GetIPAddress()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string sIPAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(sIPAddress))
            {
                return context.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                string[] ipArray = sIPAddress.Split(new Char[] { ',' });
                return ipArray[0];
            }
        }
        public static DateTime getDateTime()
        {
            TimeSpan t = new TimeSpan(5, 30, 0);
            DateTime currentDate = DateTime.UtcNow.Add(t);
            return currentDate;
        }
        //Alert massege box
        public static void alert(string customMessage, string redirectPageAbsolutePath, bool redirectAfterShowing)
        {
            Page current_page = (Page)HttpContext.Current.Handler;
            string script_name = "scpt_" + DateTime.Now.Millisecond.ToString();
            string script = "alert('" + customMessage.Replace("'", "\\'") + "');";
            if (redirectAfterShowing == true)
            {
                if (!string.IsNullOrEmpty(redirectPageAbsolutePath))
                {
                    script = script + "window.location.href='" + current_page.ResolveUrl(redirectPageAbsolutePath) + "';";
                }
            }
            if (ScriptManager.GetCurrent(current_page) == null)
            {
                current_page.ClientScript.RegisterStartupScript(current_page.GetType(), script_name, script, true);
            }
            else
            {
                if (ScriptManager.GetCurrent(current_page).IsInAsyncPostBack == true)
                {
                    ScriptManager.RegisterStartupScript(current_page, current_page.GetType(), Guid.NewGuid().ToString(), script, true);
                }
                else
                {
                    current_page.ClientScript.RegisterStartupScript(current_page.GetType(), script_name, script, true);
                }
            }
        }

    }
}
//trim and replace fuction for sqlinjection
public static class StringExtensions
{

    public static string TrimAndReplace(this string s)
    {
        return s.Trim().Replace("'", "").Replace("&quot;", "").Replace("AUX ", "").Replace("CLOCK$", "").Replace("CON ", "").Replace("CONFIG$ ", "").Replace("NUL ", "").Replace(";", "").Replace("--", "").Replace("/*...*/", "").Replace("xp_", "").Replace("DROP ", "");
    }
    public static string TrimAndReplaceText(this string s)
    {
        return s.Trim().Replace(" ", "").Replace("'", "").Replace("&quot;", "").Replace("AUX ", "").Replace("CLOCK$", "").Replace("CON ", "").Replace("CONFIG$ ", "").Replace("NUL ", "").Replace(";", "").Replace("--", "").Replace("/*...*/", "").Replace("xp_", "").Replace("DROP ", "");
    }
}

Wednesday, 17 July 2013

Q.1-Definition of Internet

A.1- A means of connecting a computer to any other computer anywhere in the world via dedicated routers and servers. When two computers are connected over the Internet, they can send and receive all kinds of information such as text, graphics, voice, video, and computer programs.
The Internet is a global network connecting millions of computers. More than 100 countries are linked into exchanges of data, news and opinions. According to Internet World Stats , as of December 31, 2011 there was an estimated 2,267,233,742 Internet users worldwide. This represents 32.7% of the world's population.

Q.2-Evolution of Internet

A.2-The Internet is evolving. The majority of end-users perceive this evolution in the form of changes and updates to the software and networked applications that they are familiar with, or with the arrival of entirely new applications that change the way they communicate, do business, entertain themselves, and so on.
Evolution occurs as a response to a stimulus. In the Internet context, these come in the shape of challenges for which improvements are needed, as well as bright ideas for which implementations are sought. Yet, some very valid critical Internet technologies have had challenged deployment histories because the incentives haven't been aligned with the costs of deployment.

Q.3-What is an internet application.

A.3- Internet applications are programs of sorts that may replicate a program that you have on your computer. Generally, internet applications are less powerful than their software counterparts that run on your computer. Good examples of internet applications include Google Apps, which are less powerful alternatives to Microsoft Office, any web based mail client which can replace the functionality of Outlook or Thunderbird which runs on your computer.

Q.4-what is Internet Technologies.

A.4- Internet Services Technology covers a broad range of technologies used for web development, web production, design, networking, and e-commerce. The field also covers Internet programming, website maintenance, Internet architect, and web master.

Q.5-what are Clients and Servers.

A.5-Client-server is a computing architecture which separates a client from a server, and is almost always implemented over a computer network. Each client or server connected to a network can also be referred to as a node. The most basic type of client-server architecture employs only two types of nodes: clients and servers. This type of architecture is sometimes referred to as two-tier. It allows devices to share files and resources.
Each instance of the client software can send data requests to one or more connected servers. In turn, the servers can accept these requests, process them, and return the requested information to the client. Although this concept can be applied for a variety of reasons to many different kinds of applications, the architecture remains fundamentally the same.

Q.6-What is host and node.

A.6- In networks, a processing  location .  A node can be a computer or some other device, such as a printer. Every node has a unique network address, sometimes called a Data Link Control (DLC) address or Media Access Control (MAC) address.

An Internet host used to be a single machine connected to the Internet (which meant it had a unique IP address). As a host, it made certain services available to other machines on the network. However, virtual hosting now means that one physical host can actually be many virtual hosts.

Q.7-What is Internet Services.

A.7-Internet Service Provider, it refers to a company that provides Internet services, including personal and business access to the Internet. For a monthly fee, the service provider usually provides a software package, username, password and access phone number. Equipped with a modem, you can then log on to the Internet and browse the World Wide Web and USENET, and send and receive e-mail. For broadband access you typically receive the broadband modem hardware or pay a monthly fee for this equipment that is added to your ISP account billing.


Q.9 - Different Type of Connections.

A.9- There is 2 general ways to connect to the Internet:

A) Wired Broadband:

  1. Dial-Up- 
To get a dial-up connection, your computer will dial a phone number using your telephone line.
Dial-up connections need a modem to connect to the internet and you pay for a call each time you dial-up. Dial-up connections are really slow compared to broadband, and are usually too slow for streaming video and making voice or video calls on the internet.
If you want to do more than read web pages and send emails, you'll probably need a broadband connection.

2. DSL (Digital Subscriber Line)

3. Cable

4. T1 Line

5. BPL (Broadband over Power Lines)

6. Fiber Optic Cables

B) Wireless Broadband:

1. Fixed Wireless

2. Wi-Fi

3. Satellite

4. Wi-Max


Leased Line- A leased line is a telephone line that has been leased for private use. In some contexts, it's called a dedicated line. A leased line is usually contrasted with a switched line or dial-up line.