Thursday, August 1, 2019

CRUD Operations Using SPServices (Update Operation)

SPServices is a jQuery library which abstracts SharePoint’s Web Services and makes them easier to use. It also includes functions which use the various Web Service operations to provide more useful capabilities. It works entirely client side and requires no server install.
SPServices can be used with SharePoint 2007, 2010, and 2013, whether on premises or hosted with Office365 or others. SPServices is primarily hosted on Codeplex, with this repository mirroring most of the downloads there. With Codeplex shutting down, any new activity will happen on the NEW Github-backed site. Check out the newer location (http://sympmarc.github.io/SPServices/) for SPServices information on Github pages.
We can perform Create, Read, Update, Delete operations easily using SPServices. Let us go through one by one.
In my earlier post, we have discussed about Create Operation. Now, we will discuss about Update operation.

Basic Preparations

List Creation

We have created a custom list name "EmployeeMaster" in Sharepoint having Columns "Title", "First Name", "Last Name", "Employee ID", "Date of Joining".


Now on page we have added references of jquery and spservices files.

<script type="text/javascript" src="../Scripts/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="../Scripts/jquery.SPServices-2014.02.min.js"></script>


Next, we have added some CSS.

<style type="text/css">
 table thead th,
 table tbody tr td
 {
  border:thin gray dotted;
 }
</style>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">


1. UPDATE (Update existing record of list)
For this, first we create a page having a table showing existing records and 5 boxes for load the value of record that needs to update and a button to submit the data.








For this we have added html as below-




<div id="dvResult">
 <table id="tblResult">
 </table>
</div>
<div>
 <table>
  <tr style="display:none">
   <td>
    ID
   </td>
   <td>
    <input type="text" id="txtID" title="ID">
   </td>
  </tr>
  <tr>
   <td>
    Title
   </td>
   <td>
    <input type="text" id="txtTitle" title="Title">
   </td>
  </tr>
  <tr>
   <td>
    First Name
   </td>
   <td>
    <input type="text" id="txtFirstName" title="First Name">
   </td>
  </tr>
  <tr>
   <td>
    Last Name
   </td>
   <td>
    <input type="text" id="txtLastName" title="Last Name">
   </td>
  </tr>
  <tr>
   <td>
    Employee ID
   </td>
   <td>
    <input type="text" id="txtEmployeeID" title="Employee ID">
   </td>
  </tr>
  <tr>
   <td>
    Date of Joining
   </td>
   <td>
    <input type="text" id="txtDOJ" title="Date of Joining">
   </td>
  </tr>
  <tr>
   <td colspan="2" align="center">
    <input type="button" id="btnSubmit" title="Submit" value="Submit" onclick="UpdateRecord();">
   </td>
  </tr>
 </table>
</div>


Now we have added 3 functions
1. GetRecords - To get and display all the records of list
2. LoadSingleRecord - To load single record in boxes when clicked on Edit button
3. UpdateRecord - To update the edited record back in list


<script type="text/javascript">
 $(document).ready(function()
 {
  $("#txtDOJ").datepicker();
 });

 $(document).ready(function()
 {
  GetRecords();
 });

 function GetRecords()
 {
  $().SPServices(
  {
   operation: "GetListItems",
   webURL: $(this).attr('location').origin,
   async: false,
   listName: "EmployeeMaster",
   completefunc: function (xData, Status)
   {
    if(Status == 'success')
    {
     var vrTableHTML = '';

     vrTableHTML += '<thead>' + 
          '<th>' + 'First Name' + '</th>' + 
          '<th>' + 'Last Name' + '</th>' + 
          '<th>' + 'Employee ID' + '</th>' + 
          '<th>' + 'Date Of Joining' + '</th>' + 
          '<th>' + 'Edit' + '</th>' + 
         '</thead>';

     vrTableHTML += '<tbody>';
     $(xData.responseXML).SPFilterNode("z:row").each(function()
     {debugger;
      vrTableHTML += '<tr>' + 
           '<td>' + $(this).attr("ows_First_x0020_Name") + '</td>' + 
           '<td>' + $(this).attr("ows_Last_x0020_Name") + '</td>' + 
           '<td>' + $(this).attr("ows_Employee_x0020_ID") + '</td>' + 
           '<td>' + ($(this).attr("ows_Date_x0020_Of_x0020_Joining")).split(' ')[0] + '</td>' + 
           '<td>' + '<input type="button" id="btnEdit" title="Edit" value="Edit" onclick="LoadSingleRecord(' + $(this).attr("ows_ID") + ');">' + '</td>' + 
          '</tr>';
     });
     vrTableHTML += '</tbody>';
     $('#tblResult').html(vrTableHTML);
    }
    else
    {
    }
   }
  });
 }

 function LoadSingleRecord(itemID)
 {
  $().SPServices(
  {
   operation: "GetListItems",
   webURL: $(this).attr('location').origin,
   async: false,
   listName: "EmployeeMaster",
   CAMLQuery: "<Query>" +
       "<Where>" +
        "<Eq>" +
         "<FieldRef Name=\"ID\" />" +
         "<Value Type=\"Counter\">" + itemID + "</Value>" +
        "</Eq>" +
       "</Where>" +
      "</Query>",
   completefunc: function (xData, Status)
   {
    if(Status == 'success')
    {
     $(xData.responseXML).SPFilterNode("z:row").each(function()
     {
      $('#txtID').val($(this).attr("ows_ID"));
      $('#txtTitle').val($(this).attr("ows_Title"));
      $('#txtFirstName').val($(this).attr("ows_First_x0020_Name"));
      $('#txtLastName').val($(this).attr("ows_Last_x0020_Name"));
      $('#txtEmployeeID').val($(this).attr("ows_Employee_x0020_ID"));
      $('#txtDOJ').val(formatDateMMDDYYYY($(this).attr("ows_Date_x0020_Of_x0020_Joining")));
     });
    }
    else
    {
    }
   }
  });
 }

 function UpdateRecord()
 {
  var vrID = $('#txtID').val();
  var vrTitle = $('#txtTitle').val();
  var vrFirstName = $('#txtFirstName').val();
  var vrLastName = $('#txtLastName').val();
  var vrEmployeeID = $('#txtEmployeeID').val();
  var vrDOJ = formatDate(new Date($('#txtDOJ').val()));

  $().SPServices(
  {
   operation: "UpdateListItems",
   webURL: $(this).attr('location').origin,
   async: false,
   batchCmd: "Update",
   listName: "EmployeeMaster",
   ID: vrID,
   valuepairs: [
       ["Title", vrTitle],
       ["First_x0020_Name", vrFirstName],
       ["Last_x0020_Name", vrLastName],
       ["Employee_x0020_ID", vrEmployeeID],
       ["Date_x0020_Of_x0020_Joining", vrDOJ]
      ],

   completefunc: function (xData, Status)
   {
    if(Status == "success")
    {
     alert("Record Updated Successfully");
     GetRecords();
    }
    else
    {
     alert("Error");
    }
   }
  });
 }
 
 function formatDate(date)
 {
  var d = new Date(date),
  month = '' + (d.getMonth() + 1),
  day = '' + d.getDate(),
  year = d.getFullYear();
  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;
  return [year, month, day].join('-');
 }
 
 function formatDateMMDDYYYY(date)
 {
  var d = new Date(date),
  month = '' + (d.getMonth() + 1),
  day = '' + d.getDate(),
  year = d.getFullYear();
  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;
  return [month, day, year].join('/');
 }
</script>

Let's start the process. Load the page and click on Edit button displaying ahead of any record.






We had updated Employee ID of this record.




Now click on Submit button. The record will get updated in list and the list will be refreshed on UI.




Update Database Table Using Temp Table & MERGE Operation

Sometimes, we have a situation where we have to update the data in SQL table with following conditions:-


1. If existing table record matches with new table record, update it.
2. If existing table record doesn't available in new table, inactivate it.
3. If new table record doesn't available in existing table, insert in existing table.


For this, we have written below process.

We have a service which will provide list of user groups having Group ID & Group Name. The service also provide list of user (User Id, User Email ID...) for each group on Group ID basis.

The scenario is:-

We have a table [post_groupvisibilty_Groupdtls] with columns as-

  • [Groupdtls_Id]
  • [Groupdtls_Name]
  • [Groupdtls_IsActive]
  • [Groupdtls_dt]
  • [Easy_Group_Id]


We have another table [post_groupvisibilty_GroupUserdtls] with columns as-

  • [GroupUserdtls_Id]
  • [Groupdtls_Id]
  • [domain]
  • [user_id]
  • [user_display_nm]
  • [user_email]
  • [GroupUserdtls_IsActive]
  • [Easy_Group_Id]
  • [Easy_User_Id]
  • [GroupUserdtls_dt]


We have to udpate both tables on daily basis.
The process is as below.



using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using UserGroupsSyncFromEasy.Classes;

namespace UserGroupsSyncFromEasy
{
    class Program
    {
        static void Main(string[] args)
        {

            string strLogFolderPath = System.Configuration.ConfigurationManager.AppSettings.Get("LogFolder");
            string strCurrentDateStringForLOGFile = DateTime.Now.ToString("yyyy-MM-dd").Replace('/', '-');
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "------------------ PROCESS START (DATE:- " + DateTime.Now.ToString() + ") ------------------");

            /// CREATE DATATABLE TO STORE EASY GROUP DETAILS (FETCHED FROM EASY SERVICE)
            DataTable dtEASYGroups = new DataTable();
            dtEASYGroups.Columns.Add("Groupdtls_Name", typeof(string));
            dtEASYGroups.Columns.Add("Groupdtls_IsActive", typeof(bool));
            dtEASYGroups.Columns.Add("Groupdtls_dt", typeof(DateTime));
            dtEASYGroups.Columns.Add("Easy_Group_Id", typeof(Int32));
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "Datatable created for EASY Groups (Fetched from Easy Service)");
            /// CREATE DATATABLE TO STORE EASY GROUP DETAILS (FETCHED FROM DATABASE AFTER INSERTING DATA FROM SERVICE)
            DataTable dtUpdatedEASYGroupsFromDB = new DataTable();
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "Datatable created for EASY Groups (Fetched from Database)");
            /// CREATE DATATABLE TO STORE EASY GROUP USERS DETAILS (FETCHED FROM EASY SERVICE)
            DataTable dtEASYGroupUsers = new DataTable();
            dtEASYGroupUsers.Columns.Add("Groupdtls_Id", typeof(Int32));
            dtEASYGroupUsers.Columns.Add("domain", typeof(string));
            dtEASYGroupUsers.Columns.Add("user_email", typeof(string));
            dtEASYGroupUsers.Columns.Add("GroupUserdtls_IsActive", typeof(bool));
            dtEASYGroupUsers.Columns.Add("Easy_Group_Id", typeof(int));
            dtEASYGroupUsers.Columns.Add("Easy_User_Id", typeof(int));
            dtEASYGroupUsers.Columns.Add("GroupUserdtls_dt", typeof(DateTime));
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "Datatable created for EASY Group Users (Fetched from Easy Service)");

            EasyIntegrationWSEasyGroupIDsService.EasyIntegrationWS objEasyIntegrationWS = new EasyIntegrationWSEasyGroupIDsService.EasyIntegrationWS();
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "Easy Service instance created");

            EasyIntegrationWSEasyGroupIDsService.groupMailResponseBean objGroupMailResponseBean = objEasyIntegrationWS.getGroupMailDetails("");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "Easy Groups Details fetched from Service (Total Groups Count:- " + objGroupMailResponseBean.groupMailMstList.Count()+")");

            for (int inGroupIndex = 0; inGroupIndex < objGroupMailResponseBean.groupMailMstList.Count(); inGroupIndex++)
            {
                //Console.WriteLine(objGroupMailResponseBean.groupMailMstList[inGroupIndex].groupMailId + "\t" + objGroupMailResponseBean.groupMailMstList[inGroupIndex].groupMailName);
                Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "GroupID:- " + objGroupMailResponseBean.groupMailMstList[inGroupIndex].groupMailId + "\t" + "GroupName:- " + objGroupMailResponseBean.groupMailMstList[inGroupIndex].groupMailName);
                DataRow drGroup = dtEASYGroups.NewRow();
                drGroup["Groupdtls_Name"] = objGroupMailResponseBean.groupMailMstList[inGroupIndex].groupMailName;
                drGroup["Groupdtls_IsActive"] = true;
                drGroup["Groupdtls_dt"] = DateTime.Now.Date.ToShortDateString();
                drGroup["Easy_Group_Id"] = objGroupMailResponseBean.groupMailMstList[inGroupIndex].groupMailId;
                dtEASYGroups.Rows.Add(drGroup);

                EasyIntegrationWSEasyGroupIDsService.groupMailResponseBean objGroupMailResponseBeanUsers = objEasyIntegrationWS.getGroupMailDetails(objGroupMailResponseBean.groupMailMstList[inGroupIndex].groupMailId);
                if (objGroupMailResponseBeanUsers.userList != null)
                {
                    for (int inUserIndex = 0; inUserIndex < objGroupMailResponseBeanUsers.userList.Count(); inUserIndex++)
                    {
                        //Console.WriteLine("\t" + objGroupMailResponseBeanUsers.userList[inUserIndex].userId + "\t" + objGroupMailResponseBeanUsers.userList[inUserIndex].displayName);
                        Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "UserDomain:- " + objGroupMailResponseBeanUsers.userList[inUserIndex].domain + "\t" + "UserEmail:- " + objGroupMailResponseBeanUsers.userList[inUserIndex].email + "\t" + "GroupID:- " + objGroupMailResponseBean.groupMailMstList[inGroupIndex].groupMailId);
                        DataRow drUser = dtEASYGroupUsers.NewRow();
                        drUser["Groupdtls_Id"] = 0;
                        drUser["domain"] = objGroupMailResponseBeanUsers.userList[inUserIndex].domain;
                        drUser["user_email"] = objGroupMailResponseBeanUsers.userList[inUserIndex].email;
                        drUser["GroupUserdtls_IsActive"] = !objGroupMailResponseBeanUsers.userList[inUserIndex].isDeleted;
                        drUser["Easy_Group_Id"] = objGroupMailResponseBean.groupMailMstList[inGroupIndex].groupMailId;
                        drUser["Easy_User_Id"] = objGroupMailResponseBeanUsers.userList[inUserIndex].userId;
                        drUser["GroupUserdtls_dt"] = DateTime.Now.Date.ToShortDateString();
                        dtEASYGroupUsers.Rows.Add(drUser);
                    }
                }
            }

            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "Total Groups Received:- " + dtEASYGroups.Rows.Count);
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "Total Users Received:- " + dtEASYGroupUsers.Rows.Count);

            var UniqueGroupRows = dtEASYGroups.AsEnumerable().Distinct(DataRowComparer.Default);
            dtEASYGroups = UniqueGroupRows.CopyToDataTable();
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "Total Groups After Applying DISTINCT:- " + dtEASYGroups.Rows.Count);

            var UniqueUserRows = dtEASYGroupUsers.AsEnumerable().Distinct(DataRowComparer.Default);
            dtEASYGroupUsers = UniqueUserRows.CopyToDataTable();
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "Total Users After Applying DISTINCT:- " + dtEASYGroupUsers.Rows.Count);

            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "MERGE START For EASY Groups");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "MERGE PROCESS For EASY Groups-");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "1.0- Create TEMP Table for Easy Groups in Database");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "2.0- BULK Insert data from DataTable to TEMP Table");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "3.0- MERGE DATA FROM TEMP Table to Permanent Table in Database");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "3.1- IF Record Match, Update group name & isActive");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "3.2- IF Record Not available in Permanent Table, Insert the record");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "3.3- IF Record Not available in Easy (but available in Permanent Table), Update group isActive to FALSE");
            #region EASY GROUPS
            // MERGE GROUP DATA TO DATABASE
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["M1LogConnectionString"].ConnectionString))
            {
                using (SqlCommand command = new SqlCommand("", conn))
                {
                    try
                    {

                        conn.Open();
                        try
                        {
                            //Creating temp table on database
                            command.CommandText = "CREATE TABLE #post_groupvisibilty_Groupdtls_TEMP" +
                                                    "(" +
                                                        "[Groupdtls_Name] [nvarchar](200) NOT NULL," +
                                                        "[Groupdtls_IsActive] [bit] NOT NULL," +
                                                        "[Groupdtls_dt] [datetime] NOT NULL," +
                                                        "[Easy_Group_Id] [int] NOT NULL," +
                                                        "[LastUpdated] DATETIME" +
                                                    ")";
                            command.ExecuteNonQuery();
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "TEMP TABLE CREATED FOR EASY GROUPS IN DATABASE DONE");
                        }
                        catch (Exception ex)
                        {
                            //Console.Write(ex.Message);
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "ERROR (Process of TEMP TABLE Creation for EASY GROUPS in Database):- " + ex.Message);
                            throw new Exception(ex.Message);
                        }

                        try
                        {
                            //Bulk insert into temp table EASY GROUPS
                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(conn))
                            {
                                bulkcopy.BulkCopyTimeout = 660;
                                bulkcopy.DestinationTableName = "#post_groupvisibilty_Groupdtls_TEMP";
                                bulkcopy.WriteToServer(dtEASYGroups);
                                bulkcopy.Close();
                            }
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "BULK INSERT OF EASY GROUPS IN DATABASE TEMP TABLE DONE");
                        }
                        catch (Exception ex)
                        {
                            //Console.Write(ex.Message);
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "ERROR (Process of BULK INSERT of EASY GROUPS in Database TEMP Table):- " + ex.Message);
                            throw new Exception(ex.Message);
                        }

                        //Updating GROUP table, and dropping temp table
                        try
                        {
                            command.CommandTimeout = 300;

                            command.CommandText = "MERGE [post_groupvisibilty_Groupdtls] AS TARGETTBL " +
                                                    "USING #post_groupvisibilty_Groupdtls_TEMP  AS SOURCETBL " +
                                                    "ON " +
                                                    "TARGETTBL.[Easy_Group_Id] = SOURCETBL.[Easy_Group_Id] " +
                                                    "WHEN MATCHED " +
                                                    "THEN " +
                                                    "    UPDATE " +
                                                    "    SET TARGETTBL.[Groupdtls_Name] = SOURCETBL.[Groupdtls_Name], TARGETTBL.[Groupdtls_IsActive] = SOURCETBL.[Groupdtls_IsActive] " +
                                                    "WHEN NOT MATCHED BY TARGET " +
                                                    "THEN " +
                                                    "    INSERT ([Groupdtls_Name] ,[Groupdtls_IsActive] ,[Groupdtls_dt] ,[Easy_Group_Id]) VALUES ([Groupdtls_Name] ,[Groupdtls_IsActive] ,GETDATE() ,[Easy_Group_Id]) " +
                                                    "WHEN NOT MATCHED BY SOURCE " +
                                                    "THEN " +
                                                    "    UPDATE " +
                                                    "    SET [Groupdtls_IsActive] = 0, [Groupdtls_dt] = GETDATE(); ";
                            //"GO " +
                            //"DROP TABLE #post_groupvisibilty_Groupdtls_TEMP;";
                            command.ExecuteNonQuery();
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "MERGE OF EASY GROUPS FROM TEMP TABLE TO PERMANENT TABLE IN DATABASE DONE");
                        }
                        catch (Exception ex)
                        {
                            //Console.Write(ex.Message);
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "ERROR (Process of MERGE Operation for EASY GROUPS in Database):- " + ex.Message);
                            throw new Exception(ex.Message);
                        }
                        Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "MERGE END For EASY Groups");

                        try
                        {
                            //  GET UPDATED EASY GROUPS FROM DATABASE
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "GET updated EASY Groups from Database");
                            SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM [post_groupvisibilty_Groupdtls]", conn);
                            dataAdapter.Fill(dtUpdatedEASYGroupsFromDB);
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "GET Updated EASY GROUPS from DATABASE Done");
                        }
                        catch (Exception ex)
                        {
                            //Console.Write(ex.Message);
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "ERROR (Process of FETCH Operation of EASY GROUPS from Database):- " + ex.Message);
                            throw new Exception(ex.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        // Handle exception properly
                        Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "ERROR (MERGE GROUP DATA TO DATABASE):- " + ex.Message);
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            #endregion

            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "MERGE START For EASY Group Users");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "MERGE PROCESS For EASY Group Users-");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "1.0- Create TEMP Table for Easy Group Users in Database");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "2.0- Update Group Id in Easy Users DataTable from Easy Group DB DataTable");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "3.0- BULK Insert data from DataTable to TEMP Table");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "4.0- MERGE DATA FROM TEMP Table to Permanent Table in Database");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "4.1- IF Record Match, Update GroupId of Database Table, UserID(Blank), DisplayName(Blank), isActive, GroupId of EASY");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "4.2- IF Record Not available in Permanent Table, Insert the record");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "4.3- IF Record Not available in Easy (but available in Permanent Table), Update user isActive to FALSE");
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "\t" + "5.0- Update Permanent Table with User Windows ID, Display Name (mapping with DB MONE Database)");

            #region EASY GROUP USERS
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["M1LogConnectionString"].ConnectionString))
            {
                using (SqlCommand command = new SqlCommand("", conn))
                {
                    try
                    {

                        conn.Open();
                        try
                        {
                            command.CommandText = "CREATE TABLE #post_groupvisibilty_GroupUserdtls_TEMP" +
                                                    "(" +
                                                        "[Groupdtls_Id] [int]," +
                                                        "[domain] [nvarchar](50)," +
                                                        "[user_email] [nvarchar](200)," +
                                                        "[GroupUserdtls_IsActive] [bit]," +
                                                        "[Easy_Group_Id] [int]," +
                                                        "[Easy_User_Id] [int]," +
                                                        "[GroupUserdtls_dt] [datetime]" +
                                                    ")";
                            command.ExecuteNonQuery();
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "TEMP TABLE CREATED FOR EASY GROUP USERS IN DATABASE DONE");
                        }
                        catch (Exception ex)
                        {
                            //Console.Write(ex.Message);
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "ERROR (Process of TEMP TABLE Creation for EASY GROUP USERS in Database):- " + ex.Message);
                            throw new Exception(ex.Message);
                        }

                        
                        try
                        {
                            foreach (DataRow row in dtEASYGroupUsers.Rows)
                            {
                                DataRow rowsToUpdate = dtUpdatedEASYGroupsFromDB.AsEnumerable().FirstOrDefault(r => r.Field<int>("Easy_Group_Id") == row.Field<int>("Easy_Group_Id"));
                                row.SetField("Groupdtls_Id", rowsToUpdate.Field<int>("Groupdtls_Id"));
                            }
                            dtEASYGroupUsers.AcceptChanges();
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "UPDATE FOR EASY GROUP ID IN DATATABLE DONE");
                        }
                        catch (Exception ex)
                        {
                            //Console.Write(ex.Message);
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "ERROR (Process of UPDATE FOR EASY GROUP ID in DataTable):- " + ex.Message);
                            throw new Exception(ex.Message);
                        }

                        try
                        {
                            //Bulk insert into temp table EASY GROUP USERS
                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(conn))
                            {
                                bulkcopy.BulkCopyTimeout = 660;
                                bulkcopy.DestinationTableName = "#post_groupvisibilty_GroupUserdtls_TEMP";
                                bulkcopy.WriteToServer(dtEASYGroupUsers);
                                bulkcopy.Close();
                            }
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "BULK INSERT OF EASY GROUP USERS IN DATABASE TEMP TABLE DONE");
                        }
                        catch (Exception ex)
                        {
                            //Console.Write(ex.Message);
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "ERROR (Process of BULK INSERT of EASY GROUP USERS in Database TEMP Table):- " + ex.Message);
                            throw new Exception(ex.Message);
                        }

                        try
                        {
                            command.CommandTimeout = 300;

                            command.CommandText = "MERGE post_groupvisibilty_GroupUserdtls AS TARGETTBL " +
                                                    "USING #post_groupvisibilty_GroupUserdtls_TEMP  AS SOURCETBL " +
                                                    "ON " +
                                                    "TARGETTBL.[domain] = SOURCETBL.[domain] AND TARGETTBL.[user_email] = SOURCETBL.[user_email] AND TARGETTBL.[Easy_Group_Id] = SOURCETBL.[Easy_Group_Id] " +
                                                    "WHEN MATCHED " +
                                                    "THEN " +
                                                    "    UPDATE " +
                                                    "    SET TARGETTBL.[Groupdtls_id] = SOURCETBL.[Groupdtls_id], TARGETTBL.[user_id] = '', TARGETTBL.[user_display_nm] = '', TARGETTBL.[GroupUserdtls_IsActive] = 1, TARGETTBL.[Easy_Group_Id] = SOURCETBL.[Easy_Group_Id], TARGETTBL.[GroupUserdtls_dt] = GETDATE() " +
                                                    "WHEN NOT MATCHED BY TARGET " +
                                                    "THEN " +
                                                    "    INSERT ([Groupdtls_Id] ,[domain] ,[user_id] ,[user_display_nm] ,[user_email] ,[GroupUserdtls_IsActive] ,[Easy_Group_Id] ,[Easy_User_Id] ,[GroupUserdtls_dt]) VALUES ([Groupdtls_Id] ,[domain] ,'' ,'' ,[user_email] ,1 ,[Easy_Group_Id] ,[Easy_User_Id] ,GETDATE()) " +
                                                    "WHEN NOT MATCHED BY SOURCE " +
                                                    "THEN " +
                                                    "    UPDATE " +
                                                    "    SET [GroupUserdtls_IsActive] = 0, [GroupUserdtls_dt] = GETDATE(); ";
                            //"GO " +
                            //"DROP TABLE #post_groupvisibilty_GroupUserdtls_TEMP;";

                            command.ExecuteNonQuery();
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "MERGE OF EASY GROUP USERS FROM TEMP TABLE TO PERMANENT TABLE IN DATABASE DONE");
                        }
                        catch (Exception ex)
                        {
                            //Console.Write(ex.Message);
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "ERROR (Process of MERGE Operation for EASY GROUP USERS in Database):- " + ex.Message);
                            throw new Exception(ex.Message);
                        }

                        //Updating GROUP USERS table with Display Name & User Windows ID
                        try
                        {
                            command.CommandTimeout = 300;

                            command.CommandText = "UPDATE TARGETTBL " +
                                                    "   SET TARGETTBL.[user_id] = [SOURCETBL].[User_Id] " +
                                                    "       ,TARGETTBL.[user_display_nm] = [SOURCETBL].[Display_Nm] " +
                                                    "       ,TARGETTBL.[GroupUserdtls_IsActive] = 1 " +
                                                    "   FROM [MONE_LOG]..[post_groupvisibilty_GroupUserdtls]  AS TARGETTBL " +
                                                    "   JOIN [DB_ADMS_MONE]..[tbl_user_detail]  AS SOURCETBL " +
                                                    "   ON TARGETTBL.[domain] = [SOURCETBL].[Domain] " +
                                                    "   AND TARGETTBL.[user_email] = [SOURCETBL].[User_Email] " +
                                                    "   WHERE[TARGETTBL].[GroupUserdtls_IsActive] = 1";
                            command.ExecuteNonQuery();
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "UPDATE Operation of WindowsId, Display Name (FROM USERS MASTER DATA [DB MONE]) for EASY GROUP USERS in Database DONE");
                        }
                        catch (Exception ex)
                        {
                            //Console.Write(ex.Message);
                            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "ERROR (Process of UPDATE Operation of WindowsId, Display Name (FROM USERS MASTER DATA [DB MONE]) for EASY GROUP USERS in Database):- " + ex.Message);
                            throw new Exception(ex.Message);
                        }
                        Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "MERGE END For EASY Group Users");
                    }
                    catch (Exception ex)
                    {
                        //Console.Write(ex.Message);
                        Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "ERROR (MERGE GROUP USERS DATA TO DATABASE):- " + ex.Message);
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }

            #endregion
            //Console.ReadLine();
            Utilities.MakeLogEntry(strLogFolderPath, "", strCurrentDateStringForLOGFile, "------------------ PROCESS END (DATE:- " + DateTime.Now.ToString() + ") ------------------");
        }
    }
}