Wednesday, 16 September 2015

Efficiently Inserting Data into Multiple Tables Using Primary and Foreign Keys

Efficiently Inserting Data into Multiple Tables Using Primary and Foreign Keys.
this is a very short online invoice genration project i hope u enjoy this.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;

namespace InvoiceDemo
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string strConnString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
        SqlCommand cmd;
        int count;
        SqlDataAdapter da = new SqlDataAdapter();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {


                autogenerateid();
                SetInitialRow();
            }
        }
        private void autogenerateid()
        {
            SqlConnection con = new SqlConnection(strConnString);
            string str = "Select Count(*) from tblInvoiceDetails";
            cmd = new SqlCommand(str, con);
            con.Open();
            cmd.ExecuteNonQuery();

            count = Convert.ToInt32(cmd.ExecuteScalar()) + 1;
            txt_invoiceno.Text = count.ToString();
            txt_invoiceno.Enabled = false;
            con.Close();
            ViewState["invoiceid"] = txt_invoiceno.Text;

        }

        protected void ddl_companyname_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void SetInitialRow()
        {
            int quant = 0;
            int pri = 0;
            DataTable dt = new DataTable();
            DataRow dr = null;

            dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));

            dt.Columns.Add(new DataColumn("ProductName", typeof(string)));
            dt.Columns.Add(new DataColumn("Description", typeof(string)));
            dt.Columns.Add(new DataColumn("Quantity", typeof(string)));
            dt.Columns.Add(new DataColumn("Price", typeof(string)));
            dt.Columns.Add(new DataColumn("invoiceid", typeof(int)));
            dr = dt.NewRow();
            dr["RowNumber"] = 1;

            dr["ProductName"] = string.Empty;
            dr["Description"] = string.Empty;
            dr["Quantity"] = string.Empty;
            dr["Price"] = string.Empty;
            dr["invoiceid"] = Convert.ToInt32(ViewState["invoiceid"]);
            dt.Rows.Add(dr);


            //Store the DataTable in ViewState
            ViewState["CurrentTable"] = dt;
            gridviewproduct.DataSource = dt;
            gridviewproduct.DataBind();
        }

        protected void btn_save_Click(object sender, EventArgs e)
        {
            int lastid;
            SqlConnection con = new SqlConnection(strConnString);
            SqlCommand cmd = new SqlCommand(strConnString, con);

            cmd.CommandText = "sp_insertinvoice";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();


            //cmd.Parameters
            cmd.Parameters.AddWithValue("@invoice_date", txtDate.Text);
            cmd.Parameters.AddWithValue("@Firm_name", txt_frmname.Text.Trim());
            cmd.Parameters.AddWithValue("@Regis_id", txt_regno.Text.Trim());
            cmd.Parameters.Add("@idcategory", SqlDbType.Int).Direction = ParameterDirection.Output;
            con.Open();
            cmd.ExecuteNonQuery();
            lastid = Convert.ToInt32(cmd.Parameters["@idcategory"].Value.ToString());
            con.Close();

            insertProductdetails();
            BulkInsertToDatabase();
            txtDate.Text = string.Empty;
            txt_frmname.Text = string.Empty;
            txt_regno.Text = string.Empty;

        }
        private void BulkInsertToDatabase()
        {
            //int lastinvoiceid = Convert.ToInt32(ViewState["id"]);
            DataTable dtProductDetails = (DataTable)ViewState["CurrentTable1"];
            //int index = Convert.ToInt32(dtProductDetails.Rows[4]);
            SqlConnection con = new SqlConnection(strConnString);
            SqlBulkCopy objBulk = new SqlBulkCopy(con);
            con.Open();
            objBulk.DestinationTableName = "tbl_ProductDetails";
            objBulk.ColumnMappings.Add("ProductName", "Product_Name");
            objBulk.ColumnMappings.Add("Description", "Product_Description");
            objBulk.ColumnMappings.Add("Quantity", "Qty");
            objBulk.ColumnMappings.Add("Price", "Price");
            objBulk.ColumnMappings.Add("invoiceid", "Invoice_id");
            objBulk.WriteToServer(dtProductDetails);
            con.Close();
        }


        private void insertProductdetails()
        {
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtcurrentTable = new DataTable();// = (DataTable)ViewState["CurrentTable"];
                DataRow dtCurrentRow = null;

                if (gridviewproduct.Rows.Count > 0)
                {

                    dtcurrentTable.Columns.Add(new DataColumn("ProductName", typeof(string)));
                    dtcurrentTable.Columns.Add(new DataColumn("Description", typeof(string)));
                    dtcurrentTable.Columns.Add(new DataColumn("Quantity", typeof(int)));
                    dtcurrentTable.Columns.Add(new DataColumn("Price", typeof(int)));
                    dtcurrentTable.Columns.Add(new DataColumn("invoiceid", typeof(int)));


                    for (int i = 0; i < gridviewproduct.Rows.Count; i++)
                    {
                        dtCurrentRow = dtcurrentTable.NewRow();

                        dtCurrentRow["ProductName"] = ((TextBox)gridviewproduct.Rows[i].FindControl("grd_txt_productname")).Text;
                        dtCurrentRow["Description"] = ((TextBox)gridviewproduct.Rows[i].FindControl("grd_txt_description")).Text;
                        dtCurrentRow["Quantity"] = ((TextBox)gridviewproduct.Rows[i].FindControl("grd_txt_qty")).Text;
                        dtCurrentRow["Price"] = ((TextBox)gridviewproduct.Rows[i].FindControl("grd_txt_price")).Text;
                        dtCurrentRow["Invoiceid"] = Convert.ToInt32(ViewState["invoiceid"]);




                        dtcurrentTable.Rows.Add(dtCurrentRow);
                    }


                    ViewState["CurrentTable1"] = dtcurrentTable;
                }



            }

        }


        protected void ButtonAdd_Click1(object sender, EventArgs e)
        {
            AddNewRowToGrid();

        }
        private void AddNewRowToGrid()
        {
            int rowIndex = 0;

            if (ViewState["CurrentTable"] != null)
            {

                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                   {
                       //extract the TextBox values
                       // TextBox box1 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[1].FindControl("grd_txt_productid");
                       TextBox box1 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[1].FindControl("grd_txt_productname");
                       TextBox box2 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[2].FindControl("grd_txt_description");
                       TextBox box3 = ((TextBox)gridviewproduct.Rows[rowIndex].Cells[3].FindControl("grd_txt_qty"));
                       TextBox box4 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[4].FindControl("grd_txt_price");

                       drCurrentRow = dtCurrentTable.NewRow();
                       drCurrentRow["RowNumber"] = i + 1;

                       // dtCurrentTable.Rows[i - 1]["ProductId"] = box1.Text;
                       dtCurrentTable.Rows[i - 1]["ProductName"] = box1.Text;
                       dtCurrentTable.Rows[i - 1]["Description"] = box2.Text;
                       dtCurrentTable.Rows[i - 1]["Quantity"] = box3.Text;
                       dtCurrentTable.Rows[i - 1]["Price"] = box4.Text;
                       dtCurrentTable.Rows[i - 1]["invoiceid"] = Convert.ToInt32(ViewState["id"]);

                       rowIndex++;
                   }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;

                    gridviewproduct.DataSource = dtCurrentTable;
                    gridviewproduct.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }

            //Set Previous Data on Postbacks
            SetPreviousData();
        }
        private void SetPreviousData()
        {
            int rowIndex = 0;
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dt = (DataTable)ViewState["CurrentTable"];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        //TextBox box1 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[1].FindControl("grd_txt_productid");
                        TextBox box1 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[1].FindControl("grd_txt_productname");
                        TextBox box2 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[2].FindControl("grd_txt_description");
                        TextBox box3 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[3].FindControl("grd_txt_qty");
                        TextBox box4 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[4].FindControl("grd_txt_price");

                        // box1.Text = dt.Rows[i]["ProductId"].ToString();
                        box1.Text = dt.Rows[i]["ProductName"].ToString();
                        box2.Text = dt.Rows[i]["Description"].ToString();
                        box3.Text = dt.Rows[i]["Quantity"].ToString();
                        box4.Text = dt.Rows[i]["Price"].ToString();
                        rowIndex++;
                    }
                }
            }
        }

        protected void btnupload_Click(object sender, EventArgs e)
        {
            if (fileupload1.HasFile)
            {
                string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
                fileupload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + filename);
                lblstatus.Text = "Success";
            }
            else
            {
                lblstatus.Text = "Unsuccessful";
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Button clickedButton = sender as Button;
            GridViewRow row = (GridViewRow)clickedButton.Parent.Parent;
            int rowID = Convert.ToInt16(row.RowIndex);

            gridviewproduct.DeleteRow(rowID);
        }

        protected void gridviewproduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            setRowData();
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dt = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                int rowIndex = Convert.ToInt32(e.RowIndex);
                if (dt.Rows.Count > 1)
                {
                    dt.Rows.Remove(dt.Rows[rowIndex]);
                    drCurrentRow = dt.NewRow();
                    ViewState["CurrentTable"] = dt;
                    gridviewproduct.DataSource = dt;
                    gridviewproduct.DataBind();
                    for (int i = 0; i < gridviewproduct.Rows.Count - 1; i++)
                    {
                        gridviewproduct.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                    }
                    SetPreviousData();
                }
            }
        }
        private void setRowData()
        {
            int rowIndex = 0;
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        TextBox box1 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[1].FindControl("grd_txt_productname");
                        TextBox box2 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[2].FindControl("grd_txt_description");
                        TextBox box3 = ((TextBox)gridviewproduct.Rows[rowIndex].Cells[3].FindControl("grd_txt_qty"));
                        TextBox box4 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[4].FindControl("grd_txt_price");
                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;

                        dtCurrentTable.Rows[i-1]["ProductName"] = box1.Text;
                        dtCurrentTable.Rows[i-1]["Description"] = box2.Text;
                        dtCurrentTable.Rows[i-1]["Quantity"] = box3.Text;
                        dtCurrentTable.Rows[i-1]["Price"] = box4.Text;

                        rowIndex++;
                    }
                    ViewState["CurrentTable"] = dtCurrentTable;


                }
            }
            else
            {
                lbl_msg.Text = "View State is null";
            }
        }

    }



We have use sql Bulk copy here to insert more than one row in database using single statement 

Tuesday, 28 October 2014

Demystifying Polymorphism: Understanding Its Concept and Implementation in Object-Oriented Programming.

Demystifying Polymorphism: Understanding Its Concept and Implementation in Object-Oriented Programming.

Polymorphism

Polymorphism is a word which is created by a combination of two word Poly and morphism means that a thing which is created by one or more thing
In the polymorphism we create a one object and associated with many name which name is same
means that


Polymorphism means one object behaving as multiple forms. One function behaves in different forms. In other words, Many forms of a single object is called Polymorphism.


there are two type of polymorphism 
1. Compile time poly morphism that is also known as function overloading or operator overloading

or 2. Run time polymorphism that is also known as virtual function 

in function or operator overloding we create on object and associated with same name function
and in virtual function we must override the function

Partial Classes in C#: Understanding Their Purpose and Implementation

What is a Partial Class.

Partial class is one of the most important thing when we work on larger project we can break the concept of interface,class into one or more thing and use partial keyword with each of this so that many of the person can work on them at same time

"To split the definition of a class or a struct, an interface or a method over two or more source files is known as Partial Class."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UsingPartialClass
{
    public partial class book
    {
        public void study()
        {
            Console.WriteLine("Reading..........");
        }
    }

    public partial class book
    {
        public void watch()
        {
            Console.WriteLine("watch movie........");
        }
    } 
}

class Program
    {
        static void Main(string[] args)
        {
            book obj = new book();
            obj.study();
            obj.watch();

            Console.ReadKey();
        }
    }
it is very necessary to use partial keyword with each portion of the partial class 
access specifier is also attach with each part of partial class




we can create partial interface,struct and method.
we can create partial delegate and enumrator.
Different parts of a partial class can inherit from different interfaces.
nested classes can be specified as partial classes even if the containing class is not partial. An example is shown below.

Understanding ASP.NET, IIS Web Server, and Request Processing

Exploring ASP.NET and IIS Web Server: Understanding Request Handling and Web Gardening

Question :--what is ASP .net IIS web server how this work? how it handle request ? what is web gardening?

Answer :When a request comes from client to the server a lot of operations is performed before sending the response to client browser. This is all about how IIS process the request from client to server. So in this article I will explain about IIS Request Processing and concept of ASP.Net Worker Process and IIS Application Pool. When we run our asp.net web application from Visual Studio IDE, there visual studio integrated asp.net engine is responsible to execute all kind of asp.net requests and responses. The "WebDev.WebServer.Exe" process take care of all request and response of an web application which is running from Visual Studio IDE. So when we want to host the application on a centralized location and wanted to access from many locations. Web server is responsible for handle all the requests that are coming from clients, process them and provide the responses. IIS (Internet Information Server) is one of the most powerful web server from Microsoft that is used to host your ASP.NET Web application. IIS has it's own ASP.NET Process Engine to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and process it and send response back to clients. There are two main major concepts available in IIS Process Request:- Worker Process (w3wp.exe) Application Pool Worker Process (w3wp.exe) Worker process is responsible to manage all the request and response that are coming from client system. All the asp.net functionality runs under the scope of worker process. In a single word we can say "Worker process is the heart of asp.net web application which runs on IIS" How to run Worker Process If you are debugging a ASP.NET web application which is hosted on IIS7, you need to attach the particular worker process in Visual Studio to start debugging. To Attach a process we can go to Tools -> Attach Process or use shortcut key Ctrl +P. The process window will show the worker process (w3wp.exe) which is currently running on IIS7. You need to select the process and click on attach button to start the debugging. Application Pool Application pool is the container of worker process. Application pools is used to separate sets of IIS worker processes that share the same configuration. Application pools enables a better security, reliability, and availability for any web application. Application pools allow you to isolate your applications from one another, even if they are running on the same server. This way, if there is an error in one app, it won't take down other applications. Application Pool with multiple worker process is called "Web Garden" Summary : When client request for some information from a web server, request first reaches to HTTP.SYS of IIS. HTTP.SYS then send the request to respective Application Pool. Application Pool then forward the request to worker process to load the ISAPI Extension which will create an HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder. After that the ASP.NET Page LifeCycle events starts.

AdSense

The Ultimate Guide to Interceptors: Understanding Their Power and Functionality

  The Ultimate Guide to Interceptors: Understanding Their Power and Functionality An interceptor is a service that can intercept HTTP reques...

Follow