Friday, 5 April 2013

Insert Data Code with Return Boolean and Int Result in three tier arch.


Insert Data Code with Return Boolean and Int Result
Step by Step: 
1. Create Property Class for This Section and create members as inserted data required.
2. Set Property to appropriate data taken by Control.
3. After taking data in property class just call Logic layer Class with this Property Class’s obj .
4. For Step 3 just create Logic Layer Class and create method which take Property Class’s obj and call        DataLayer’s Mehod with Property Class’s obj as a parameter.
5. For Step 4 just create DataLayer Class with method which take Property Class’s obj and by this obj create SqlParameter[] and set SqlParameter with the help of Properties Value.
6. After that call the method of Main Data Class, this class is vary on Company by Company.
7. This Main Data Class takes two parameter (a).Procedure Name (b). Sqlparameter[]
8. Return Type of All Methods will be same as return type of Main Data Class.
Code…
On Submit Button:::
  protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
    {
        /*******************************Insertion***************************************/
        try
        {
            if (!Page.IsValid)
                return;
            objProp.EventDate = Convert.ToDateTime(txtEventDate.Text);
            objProp.ClientID = Convert.ToInt32(Session["clientId"]);

            ClsEvent objEvent=new ClsEvent(); //Logic Class
            bool IsDone=objEvent.AddEvent (objProp );

                if (IsDone)
                    Response.Redirect("message.aspx?EventIsOpen=true&id=72");
               
                /*******************************End***************************************/
            }   
        catch (Exception ex)
        {
            lblError.Text = "<b>Following Error Found<p>" + ex + "</p></b>";
        }

    }


//Logic Class (ClsEvent)


public bool AddEvent(ClsEventProp objProp)
    {
        ClsEventDB objDB = new ClsEventDB(); //Data Class
        bool IsDone;
        IsDone = objDB.AddEvent(objProp);
        return IsDone;
    }



//Data Class (ClsEventDB)


internal bool AddEvent(ClsEventProp objProp)
    {
        SqlParameter[] param ={
                         
                                 new SqlParameter ("@EventDate",objProp .EventDate ),
                                 new SqlParameter ("@ClientId",objProp .ClientID )
                             };

//Call Main Data Layer Class Method.

        return ClsDataLayer.GetScaler("sp_Add_Event", param);
    }



Main Data Class’ Method.
(Always create mehod as Static)
1…[Mehod which return int Value for get value which return by Stored procedure]

public static int InsertUpdate(String p, SqlParameter[] param)
    {
        int id;
        SqlConnection conn = GetConnection();
        SqlCommand cmd = new SqlCommand(p, conn);
        try
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandTimeout = 0;
            conn.Open();
            SqlParameter returnvalue = new SqlParameter("returnvalue", SqlDbType.Int);
            returnvalue.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(returnvalue);
            foreach (SqlParameter para in param)
            {
                cmd.Parameters.Add(para);

            }
            cmd.ExecuteNonQuery();
            id = Convert.ToInt32(returnvalue.Value);
            return id;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            cmd.Dispose();
            conn.Close();
        }
    }

2…[Mehod which return Bool Value for inspect operaton success or not.]

public static bool InsertUpdate(String p, SqlParameter[] param)
    {
        bool isDone;
        SqlConnection conn = GetConnection();
        SqlCommand cmd = new SqlCommand(p, conn);
        try
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandTimeout = 0;
            conn.Open();
            SqlParameter returnvalue = new SqlParameter("returnvalue", SqlDbType.Int);
            returnvalue.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(returnvalue);
            foreach (SqlParameter para in param)
            {
                cmd.Parameters.Add(para);

            }
            cmd.ExecuteNonQuery();
            isDone = Convert.ToBoolean(returnvalue.Value);
            return isDone;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            cmd.Dispose();
            conn.Close();
        }
    }

Help

Select or Get Data Code



Simple with sorting, Select or Get Data Code
 Step by Step:
1.  Call logic layer with appropriate parameter
(a). ClientId or other if required by logic.
(b). ViewState["SortBy"] ,which set before For Column name for Sorting.
(c). ViewState["SortAs"],which set before for Sorting as  asc(ascending) or desc(descending) order for column sorting.
(d). ViewState["SearchExprBy"], which set before for value ,which is takeb by search text box means search date by inserting name.
2.  First thing is that I am not using property here due to some search sort.
3. Take these value in Logic Layer method and send them to Data Class’s Mehod.
4. In DataClass take these value in assign to SqlParameter[] as before.
5. Send this SqlParameter[] and Store Procedure name to Mail DataClass for taking Dataset.
6. All method from first step has returen type will be Dataset.

//BindGrid for taking Dataset and Formating GridView such as total records etc.

public void BindGrid(string orderby, string strVal)  //BingGrid
    {
       
        try
        {
ClsEvent objEvent = new ClsEvent(); //Logic layer

            DataSet ds = objEvent.GetEvent
(Convert.ToInt32(Session["clientId"]),
ViewState["SortBy"].ToString(),
ViewState["SortAs"].ToString(),
ViewState["SearchExprBy"].ToString());
          
            Int32 intCnt;
            intCnt = ds.Tables[0].Rows.Count;
            if (ds.Tables[0].Rows.Count > 0)
            {
               
                lblTotalRecords.Text = "Total Records : " + intCnt;

                DataView dv = (DataView)ds.Tables[0].DefaultView;
                GVUSer.DataSource = ds;
                GVUSer.DataBind();
                lblGoto.Visible = true;
                txtPage.Visible = true;
                imgbtnGo.Visible = true;
            }
            else
            {
                lblTotalRecords.Text = "";
                GVUSer.DataBind();
                lblGoto.Visible = false;
                txtPage.Visible = false;
                imgbtnGo.Visible = false;

            }
        }
        catch (Exception ex)
        {

            lblError.Text = "<b>Following Error Found<p>" + ex + "</p></b>";
        }
    }



//Logic Layer

public DataSet GetEvent(int ClientId, string SortBy, string SortAs, string SearchExprBy)
    {
        DataSet ds = new DataSet();
       ClsEventDB objDB = new ClsEventDB();

        ds = objDB.GetEvent(ClientId, SortBy, SortAs, SearchExprBy);
        return ds;
    }

//Data Layer
internal DataSet GetEvent(int ClientId, string SortBy, string SortAs, string SearchExprBy)
    {
        SqlParameter[] param ={
                                new SqlParameter ("@SortBy", SortBy),
                                new SqlParameter ("@SortAs", SortAs),
                                new SqlParameter ("@Search", SearchExprBy),
                                new SqlParameter ("@ClientID", ClientId),

                           };

        DataSet ds = new DataSet();
        ds = ClsDataLayer.GetDataSet("[sp_Get_Event]", param);
        return ds;
    }

//Main Data Class
public static DataSet GetDataSet(string ProcName, SqlParameter[] param)
    {
        SqlConnection cn = GetConnection();
        DataSet Ds = new DataSet();
        SqlDataAdapter ObjAdapter = new SqlDataAdapter(ProcName, cn);       
        ObjAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
        ObjAdapter.SelectCommand.CommandTimeout = 0;
             
              try
        {
                     cn.Open();
                     foreach (SqlParameter par in param)
                     {
                           ObjAdapter.SelectCommand.Parameters.Add(par);
                     }
                     ObjAdapter.Fill(Ds);
            cn.Close();
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
        finally
        {            
                     cn.Close();
              cn.Dispose();
        }

        return Ds;
    }
When you don’t send parameter and just take value :
Step by Step:
<![if !supportLists]>1.       <![endif]>Don’t Send anything in Mehod
<![if !supportLists]>2.       <![endif]>In DataClass send Only Procedure Name.
<![if !supportLists]>3.       <![endif]>Best Example take value of Country and Regions.

Code For Main DataLayer.
public static DataSet GetDS(string ProcName)
    {       
        DataSet ds = new DataSet();
        SqlConnection cn = GetConnection();
        using (cn)
        {
                  try
                  {
                        SqlDataAdapter da = new SqlDataAdapter(ProcName, cn);
                        da.SelectCommand.CommandType = CommandType.StoredProcedure;
                        da.SelectCommand.CommandTimeout = 0;
                        da.Fill(ds);
                cn.Close();
                cn.Dispose();
                  }
                  catch (Exception Ex)
                  {
                        throw Ex;
                  }
                  finally
                  {
                        cn.Close();
                        cn.Dispose();
                  }          

            return ds;
        }

    }