Understand tiered architecture in SharePoint - C#

In this post we will learn to implement tiered architecture in a CSharp application. tiered architecture is a very famous and well known buzzword in the world of software development. 

Basic Layers
  1. Presentation Layer
  2. Data Access Layer 
  3. Entity Layer 

Code for Entity Layer 


 public class ITDRITCoordinatorsEntity
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public SPFieldUserValueCollection Users { get; set; }

        public ITDRITCoordinatorsEntity() { }

        public ITDRITCoordinatorsEntity(int ID, string Title, SPFieldUserValueCollection Users) 
        {
            this.ID = ID;
            this.Title = Title;
            this.Users = Users;
        }
    }


Code for Data Access Layer 

        public ITDRITCoordinatorsEntity GetItCoordinators()
        {
            try
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
                {
                    spSite.AllowUnsafeUpdates = true;
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;
                        ITDRITCoordinatorsEntity iTDRITCoordinatorsEntity = new ITDRITCoordinatorsEntity();
                        SPList list = spWeb.Lists.TryGetList("ITDR_ITCoordinators");

                        SPQuery qryEmp = new SPQuery();

                        qryEmp.Query = "<Where>" +
                                       "<Eq><FieldRef Name='LinkTitle' />  <Value Type='Text'>IT Codinator</Value></Eq>" +
                                 "</Where>"; ;

                        SPListItemCollection oSpListCln = list.GetItems(qryEmp);

                        foreach (SPListItem item in oSpListCln)
                        {
                            iTDRITCoordinatorsEntity = new ITDRITCoordinatorsEntity();
                            iTDRITCoordinatorsEntity.ID = Convert.ToInt32(item["ID"]);

                            if (item["LinkTitle"] != null)
                                iTDRITCoordinatorsEntity.Title = item["LinkTitle"].ToString();

                            if (item["Users"] != null)
                            {
                                SPFieldUserValueCollection sPFieldUserValue1 = new SPFieldUserValueCollection(spWeb, item["Users"].ToString());
                                iTDRITCoordinatorsEntity.Users = sPFieldUserValue1;  
                            }
                        }
                        spWeb.AllowUnsafeUpdates = false;
                        return iTDRITCoordinatorsEntity;
                    }
                }
            }
            catch (Exception)
            {               
                throw;
            }            
        }

Code for Presentation Layer 

ITDRITCoordinatorsDataAccess iTDRITCoordinatorsDataAccess = new ITDRITCoordinatorsDataAccess();
                
ITDRITCoordinatorsEntity iTDRITCoordinatorsEntity = ITDRITCoordinatorsDataAccess.GetItCoordinators();








========================================================

==================== Data Connection =================

    public class DataConnection
    {
        public int ScopeIdentity = 0;
        public static string sqlConnectionstring;

        public DataConnection()
        {

        }

        public DataConnection(string sqlConString)
        {
            sqlConnectionstring = sqlConString;
        }

        public SqlConnection GetConnection()
        {
            SqlConnection sqlConnection = null;
            try
            {
             
       //sqlConnectionstring = "Data Source=SHASHIKAPROBOOK;Initial Catalog=VTAAdminWebApp_db;Persist Security Info=True;User ID=sa;Password=123";
                
                sqlConnectionstring= "Server=tcp:icgdev.database.windows.net,1433;Initial Catalog=VTAAdminWebApp_db;Persist Security Info=False;User ID=icgadmin;Password=Admin@123;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30";

                sqlConnection = new SqlConnection(sqlConnectionstring);
                sqlConnection.Open();
            }
            catch (Exception ex)
            {

            }
            return sqlConnection;
        }

        public bool InsertCommand(string CommandText, SqlParameter[] parameters, SqlConnection con, SqlTransaction trans)
        {
            SqlCommand com = new SqlCommand(CommandText, con, trans);

            try
            {
                com.Connection = con;
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddRange(parameters);
                ScopeIdentity = Convert.ToInt32(com.ExecuteScalar());
            }
            catch (Exception ex)
            {
                if (trans != null) trans.Rollback();
                return false;
            }
            return true;
        }
    }


============================================================================================================

=================================== Data Access Layer ======================================================

 public class StudentMasterDataAccess : DataConnection
    {
        public StudentMasterDataAccess() { }

        public bool Save(StudentMaster studentMaster, SqlConnection sqlConnection, SqlTransaction sqlTransaction)
        {
            bool status = false;
            string commandText = "";
            try
            {
                if (studentMaster.Id == 0)
                {
                    SqlParameter[] parameters ={
new SqlParameter("@FirstName", studentMaster.FirstName),
new SqlParameter("@MiddleName", studentMaster.MiddleName),
new SqlParameter("@LastName", studentMaster.LastName),
new SqlParameter("@NIC", studentMaster.NIC),
};
                    commandText = studentMaster.CommandText;
                    status = InsertCommand(commandText, parameters, sqlConnection, sqlTransaction);
                    studentMaster.Id = this.ScopeIdentity;
                }
                else
                {
                    SqlParameter[] parameters ={
new SqlParameter("@Id", studentMaster.Id),
new SqlParameter("@FirstName", studentMaster.FirstName),
new SqlParameter("@MiddleName", studentMaster.MiddleName),
};
                    commandText = studentMaster.CommandText;
                    status = InsertCommand(commandText, parameters, sqlConnection, sqlTransaction);
                }
            }
            catch (Exception ex)
            {
                status = false;
            }
            return status;
        }

        public List<StudentMaster> GetAllStudentMaster()
        {
            List<StudentMaster> studentMasterList = new List<StudentMaster>();
            try
            {
                using (SqlConnection sqlConnection = this.GetConnection())
                {
                    using (SqlCommand sqlCommand = new SqlCommand())
                    {
                        sqlCommand.Connection = sqlConnection;
                        sqlCommand.CommandText = "GetAllStudentMaster";
                        sqlCommand.CommandType = CommandType.StoredProcedure;

                        using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                        {
                            if (sqlDataReader.HasRows)
                            {
                                while (sqlDataReader.Read())
                                {
                                    object Id = sqlDataReader["Id"];

                                    object FirstName = sqlDataReader["FirstName"];
                                    if (FirstName == DBNull.Value)
                                        FirstName = string.Empty;
                                    object Age = sqlDataReader["Age"];
                                    if (Age == DBNull.Value)
                                        Age = 0;                                  
                                    object Email = sqlDataReader["Email"];
                                    if (Email == DBNull.Value)
                                        Email = string.Empty;

                                    StudentMaster studentMaster = new StudentMaster(
                                    Convert.ToInt32(Id),
                                    FirstName.ToString(),
                                    MiddleName.ToString(),
                                    Email.ToString()
                                    );

                                    studentMasterList.Add(studentMaster);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return studentMasterList;
        }

        public StudentMaster GetStudentMasterById(int id)
        {
            StudentMaster studentMaster = new StudentMaster();
            try
            {
                using (SqlConnection sqlConnection = this.GetConnection())
                {
                    using (SqlCommand sqlCommand = new SqlCommand())
                    {
                        sqlCommand.Connection = sqlConnection;
                        sqlCommand.CommandText = "GetStudentMasterById";
                        sqlCommand.CommandType = CommandType.StoredProcedure;
                        sqlCommand.Parameters.AddWithValue("@Id", id);

                        using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                        {
                            if (sqlDataReader.HasRows)
                            {
                                while (sqlDataReader.Read())
                                {
                                    object Id = sqlDataReader["Id"];

                                    object FirstName = sqlDataReader["FirstName"];
                                    if (FirstName == DBNull.Value)
                                        FirstName = string.Empty;


                                    studentMaster = new StudentMaster(
                                    Convert.ToInt32(Id),
                                    Email.ToString()
                                    );
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return studentMaster;
        }
    }

===========================================================================================================================

================================== Data Entity Layer =====================================================================

 [Serializable]
    public class ContactUsEntity
    {
        public int Id { get; set; }
        public string CreatedBy { get; set; }
        public string CommandText { get; set; }

        public ContactUsEntity() { }
        public ContactUsEntity(int id, string name, string contactNumber, string reason, bool isActive, DateTime modifiedDateTime, string modifiedBy, DateTime createdDateTime, string createdBy)
        {
            this.Id = id;
            this.Name = name;
            this.ContactNumber = contactNumber;
            this.CreatedBy = createdBy;

            if (Id == 0)
            {
                this.CommandText = "InsertContactUs";
            }
            else
            {
                this.CommandText = "UpdateContactUs";
            }
        }
    }
===========================================================================================================================

========================================= Logic Layer ====================================================================
 CommanClass 
- SharedClass ========================================

 public static class SharedClass
    {
        public static StudentMasterDataAccess studentMasterDataAccess = new StudentMasterDataAccess();
        public static StudentOLResultsDataAccess studentOLResultsDataAccess = new StudentOLResultsDataAccess();
        public static ContactUsDataAccess contactUsDataAccess = new ContactUsDataAccess();
    }
=============================================

UILogics
- UILogics ========================================

public class VTALogicClass
    {
        public static class StudentMasterBase
        {
            public static bool save(StudentMaster studentMaster, SqlConnection connection, SqlTransaction transaction)
            {
                return SharedClass.studentMasterDataAccess.Save(studentMaster, connection, transaction);
            }
            public static List<StudentMaster> GetEntire()
            {
                return SharedClass.studentMasterDataAccess.GetAllStudentMaster();
            }
            public static StudentMaster GetSingleById(int id)
            {
                return SharedClass.studentMasterDataAccess.GetStudentMasterById(id);
            }
        }
   }
====================================================================================================================================

=========================== Methods ================================================================================================

  DataConnection dataConnection = new DataConnection();
        SqlConnection connection = null;
        SqlTransaction transaction = null;

================== Save Method ===========================================================

private void SaveStudentMaster()
        {
            try
            {

                Label lbluserType = new Label();
                lbluserType = (Label)Page.Master.FindControl("LoggedUserLabel");
                string UserName = lbluserType.Text.ToString();

                bool isWorkExp = false;
                if (WorkExperienceDropDownList.SelectedItem.Text == "Yes")
                {
                    isWorkExp = true;
                }

                StudentMaster studentMaster = new StudentMaster(0, FirstNameTextBox.Value
                                                                , MobileTextBox.Text
                                                                , EmailTextBox.Text);

                this.connection = dataConnection.GetConnection();
                this.transaction = this.connection.BeginTransaction();


                if (VTALogicClass.StudentMasterBase.save(studentMaster, connection, transaction))
                {
                    if (this.transaction != null)
                    {
                        this.transaction.Commit();
                        this.SaveOLResults(studentMaster.Id);

                        MainRegisterStudentDiv.Visible = false;
                        FinalMessageDiv.Visible = true;
                        RegisterNoLabel.Text = "Student Register No is : " + studentMaster.JOBSRegNo;
                    }
                    else
                    {
                        this.transaction.Rollback();
                        SuccessLabelPanel.Visible = false;
                        ErrorLabelPanel.Visible = true;
                        FormErrorLabel.Text = "Error occured while saving.!";
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
========================================================================================================


=================== Bind DropDown =========================================================

private void GetDistrictAccordingToProvince(string provinceName)
        {
            try
            {
                List<SriLankaProvince> SriLankaProvinceList = new List<SriLankaProvince>();
                SriLankaProvinceList = SharedClass.sriLankaProvinceDataAccess.GetAllSriLankaProvinceByProvinceName("Western");
                if (SriLankaProvinceList != null)
                {
                    SriLankaProvinceList.Insert(0, new SriLankaProvince { Id = 0, DistrictName = "-- Select District --" });
                    DistrictDropdownList.DataSource = SriLankaProvinceList;
                    DistrictDropdownList.DataTextField = "DistrictName";
                    DistrictDropdownList.DataValueField = "DistrictName";
                    DistrictDropdownList.DataBind();
                }
            }
            catch (Exception ex)
            {
                //  log.EventLogWriter("System : BrandixTPMS || Method : LoadVehicleType || Page : RefVehicleTypePage || ERROR : " + ex.Message);
            }
        }
====================================================================================
  Response.Redirect("~/");
===================================================================================

========================= Bind Grid ===============================================
[Serializable]
        public struct MyPendingExamStruct
        {
            public string Link { get; set; }
            public string ExamRefNo { get; set; }
            public string ExaminerName { get; set; }
            public string StudentName { get; set; }
            public string JOBSCenter { get; set; }
            public string ExamDate { get; set; }

        }

==========

private void BindPendingExamGrid(string examinerName)
        {
            try
            {

                string host = HttpContext.Current.Request.Url.Host;
                List<AptitudeTestMaster> aptitudeTestMasterList = new List<AptitudeTestMaster>();
                MyPendingExamStruct myPendingExamStruct = new MyPendingExamStruct();
                List<MyPendingExamStruct> myPendingExamStructList = new List<MyPendingExamStruct>();

                aptitudeTestMasterList = VTALogicClass.AptitudeTestMasterBase.GetNotmarkedByExaminerName(examinerName);

                foreach (var item in aptitudeTestMasterList)
                {
                    myPendingExamStruct.Link = "/ExamMarking.aspx?ReqId=" + item.ExamRefNo;
                    myPendingExamStruct.ExamRefNo = item.ExamRefNo;
                    myPendingExamStruct.ExaminerName = item.ExaminerName;
                    myPendingExamStruct.StudentName = item.StudentName;
                    myPendingExamStruct.JOBSCenter = item.JOBSCenter;
                    myPendingExamStruct.ExamDate = item.ExamDate;

                    myPendingExamStructList.Add(myPendingExamStruct);
                }
                ExamReviewGridView.DataSource = myPendingExamStructList;
                ExamReviewGridView.DataBind();


                ExamResultCountShowLabel.Text = aptitudeTestMasterList.Count.ToString() + " result (s) found !!";
            }
            catch (Exception ex)
            {

            }
        }

=================

 <asp:GridView runat="server" CssClass="grid-view" ID="ExamReviewGridView" AutoGenerateColumns="false">
                                                    <Columns>
                                                        <asp:TemplateField HeaderText="Ref No" ShowHeader="False" HeaderStyle-HorizontalAlign="Left">
                                                            <ItemTemplate>
                                                                <asp:HyperLink ID="Link" Target="_blank" runat="server" Text='<%# Eval("ExamRefNo") %>' NavigateUrl='<%# Eval("Link") %>'></asp:HyperLink>
                                                            </ItemTemplate>
                                                        </asp:TemplateField>
                                                        <asp:BoundField DataField="ExaminerName" HeaderText="Examiner Name" ReadOnly="True" />
                                                        <asp:BoundField DataField="StudentName" HeaderText="Student Name" ReadOnly="True" />
                                                        <asp:BoundField DataField="JOBSCenter" HeaderText="JOBS Center" ReadOnly="True" />
                                                        <asp:BoundField DataField="ExamDate" HeaderText="Exam Date" ReadOnly="True" />
                                                    </Columns>
                                                </asp:GridView>

==========================
=================================================================================================================================










































Comments

Popular posts from this blog

[SOLVED] The SharePoint Timer Service service terminated unexpectedly. Event ID : 7031

FIX : The password supplied with the username Domain\Username was not correct. Verify that it was entered correctly and try again.

FIX : stsadm is not recognized as an internal command