Friday, January 22, 2010

Using Microsoft Application Block for interacting with Database

Example below shows how can we use Application Block for DAL layer.

//This method inserts values to DB by using a stored procedure
public void DBInsert(string[] points)
        {           
            SqlParameter[] param = SqlHelperParameterCache.GetSpParameterSet(_connection, "sp_CIP_insert");

            if (param == null)
            {
                param = new SqlParameter[7];
                param[0] = new SqlParameter("@appcode", SqlDbType.VarChar);
                param[1] = new SqlParameter("@Realistic", SqlDbType.Int);
                param[2] = new SqlParameter("@Investigative", SqlDbType.Int);
                param[3] = new SqlParameter("@Artistic", SqlDbType.Int);
                param[4] = new SqlParameter("@Social", SqlDbType.Int);
                param[5] = new SqlParameter("@Enterprising", SqlDbType.Int);
                param[6] = new SqlParameter("@Conventional", SqlDbType.Int);
                SqlHelperParameterCache.CacheParameterSet(_connection, "sp_CIP_insert", param);
            }
            param[0].Value = points[0];
            param[1].Value = points[1];
            param[2].Value = points[2];
            param[3].Value = points[3];
            param[4].Value = points[4];
            param[5].Value = points[5];
            param[6].Value = points[6];

            SqlHelper.ExecuteNonQuery(_connection, CommandType.StoredProcedure, "sp_CIP_insert",param);

        }

//This method gets the values from DB, it uses ExecuteReader class



public int[] Uscores(string appcode)
        {
            int[] Uscr = new int[6];

            SqlParameter[] spm = SqlHelperParameterCache.GetCachedParameterSet(_connection, "sp_CIP_getScore");

            if (spm == null)
            {
                spm = new SqlParameter[1];
                spm[0] = new SqlParameter("@appcode", SqlDbType.VarChar);
                SqlHelperParameterCache.CacheParameterSet(_connection, "sp_CIP_getScore", spm);
            }

            spm[0].Value = appcode.Trim();           

            SqlDataReader dr = SqlHelper.ExecuteReader(_connection, CommandType.StoredProcedure, "sp_CIP_getScore",spm);

            if (dr.Read())
            {
                Uscr[0] = Convert.ToInt32(dr["Realistic"].ToString());
                Uscr[1] = Convert.ToInt32(dr["Investigative"].ToString());
                Uscr[2] = Convert.ToInt32(dr["Artistic"].ToString());
                Uscr[3] = Convert.ToInt32(dr["Social"].ToString());
                Uscr[4] = Convert.ToInt32(dr["Enterprising"].ToString());
                Uscr[5] = Convert.ToInt32(dr["Conventional"].ToString());
                dr.Close();
            }

            return Uscr;
        }

No comments:

Post a Comment