Wednesday, July 31, 2019

CRUD Operations Using SPServices (Delete 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 Update Operation. Now, we will discuss about Delete 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 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>

1. DELETE (Delete existing record of list)

For this, first we create a page having a table showing existing records and a button to delete the record.
For this we have added html as below-

<div id="dvResult">
 <table id="tblResult">
 </table>
</div>

Now we have added 2 functions-
1. GetRecords - To get and display all the records of list
3. DeleteRecord - To delete the record

<script type="text/javascript">
 $(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="Delete" value="Delete" onclick="DeleteRecord(' + $(this).attr("ows_ID") + ');">' + '</td>' + 
          '</tr>';
     });
     vrTableHTML += '</tbody>';
     $('#tblResult').html(vrTableHTML);
    }
    else
    {
    }
   }
  });
 }


 function DeleteRecord(vrID)
 {

  $().SPServices(
  {
   operation: "UpdateListItems",
   webURL: $(this).attr('location').origin,
   async: false,
   batchCmd: "Delete",
   listName: "EmployeeMaster",
   ID: vrID,
   valuepairs: [],

   completefunc: function (xData, Status)
   {
    if(Status == "success")
    {
     alert("Record Deleted Successfully");
     GetRecords();
    }
    else
    {
     alert("Error");
    }
   }
  });
 }
</script>

Let's start the process. Load the page.


Now click on Delete button ahead of the record you wish to delete. It will delete the record.

Now click on OK. It will reload the list.

Here we can see that the record has been deleted.

Recursive Deletion of Folders & Files (C#)

Sometimes, there is situation when we have to delete nested folders and files through code. Here is an example to achieve the functionality.




        public static void RecursiveDelete(DirectoryInfo baseDir)
        {
            if (!baseDir.Exists)
                return;

            foreach (var dir in baseDir.EnumerateDirectories())
            {
                RecursiveDelete(dir);
            }
            var files = baseDir.GetFiles();
            foreach (var file in files)
            {
                file.IsReadOnly = false;
                file.Delete();
            }
            baseDir.Delete();
        }


Implementation:- Below is the implementation of the method.Here I had created another method, which takes the root folder path and the no. of months. The no. of months are used here to delete the folders which the older than these no. from today. For example:- if today is 30 July, 2019, and the no. of months passed is 2, then the new date is 27 May, 2019. It means this method will delete all the folders (and it's contents) for May 2019 month.



        public static bool DeleteFolder(string LogFolder, int months)
        {
            bool bSuccess = false;

            try
            {
                DirectoryInfo ObjDirectoryInWhichToSearch = new DirectoryInfo(LogFolder);
                DirectoryInfo[] ObjDirectoriesToDelete = ObjDirectoryInWhichToSearch.GetDirectories(DateTime.Now.AddMonths((-1) * months).ToString("yyyy-MM") + "*");

                foreach (DirectoryInfo ObjSingleDirectory in ObjDirectoriesToDelete)
                {
                    try
                    {
                        RecursiveDelete(ObjSingleDirectory);
                    }
                    catch (Exception ex) { }
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine("ERROR In DeleteFolder:- " + ex.Message);
            }
            finally
            {
            }
            return bSuccess;
        }

Tuesday, July 16, 2019

CRUD Operations Using SPServices (Create 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 Read Operation. Now, we will discuss about Create 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. CREATE (Add record to list)
For this, first we create a page having 5 boxes for input the value and a button to submit the data.

The HTML code is as below.

<div>
 <table>
  <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="AddRecord();">
   </td>
  </tr>
 </table> 
</div> 

Image View:-



Now add code for submitting the data to list as below.


<script type="text/javascript">
 function AddRecord()
 {
  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: "New",
   listName: "EmployeeMaster",
   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 Added 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('-');
 }
</script>


Now add below script to make Date Of Joining box as DatePicker control.

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

Lastly, add function to get records from list after saving the data.


<script type="text/javascript">
 function GetRecords()
 {
  $().SPServices(
  {
   operation: "GetListItems",
   webURL: $(this).attr('location').origin,
   async: false,
   listName: "EmployeeMaster",
   CAMLQuery: "<Query>" +
       "<Where>" +
        "<Gt>" +
         "<FieldRef Name=\"Date_x0020_Of_x0020_Joining\" />" +
         "<Value IncludeTimeValue=\"TRUE\" Type=\"DateTime\">2014-01-01</Value>" +
        "</Gt>" +
       "</Where>" +
      "</Query>",
   CAMLViewFields: "<ViewFields>" +
        "<FieldRef Name=\"Employee_x0020_ID\" />" +
        "<FieldRef Name=\"First_x0020_Name\" />" +
        "<FieldRef Name=\"Last_x0020_Name\" />" +
        "<FieldRef Name=\"Date_x0020_Of_x0020_Joining\" />" +
       "</ViewFields>",
   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>' + 
         '</thead>';

     vrTableHTML += '<tbody>';
     $(xData.responseXML).SPFilterNode("z:row").each(function()
     {
      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>' + 
          '</tr>';
     });
     vrTableHTML += '</tbody>';
     $('#tblResult').html(vrTableHTML);
     $('#dvResult').show();
    }
    else
    {
    }
   }
  });
 }
</script>

Now start filling the data.
Below are two images-
1. All fields except Date of Joining

2. Date of Joining




Now click on Submit button. If everything goes fine, record will be added to list and a message will be prompted on screen.



Now check the list. If the inserted record is available there.

This way, we can add records to SharePoint list using client side code.