Tuesday, September 16, 2014

Sharepoint create custom expiration Formula for retention policy programatically

This amazing blog helped me to create a custom expiration formula programatically

http://www.sharemuch.com/2011/01/10/creation-custom-retention-policies-for-sharepoint-2010-libraries/

http://blog.techperspect.com/2011/11/create-custom-expiration-formula-for.html

As defined in the blog you need to override the "IExpirationFormula" . be careful about the class to make public .

This class will define your custom expiration formula.The method implemented will return a datatype .You can write your logic for string columns as well as I did below

namespace Thi_CustomExp
{
    public class CustThiExpPolicy : IExpirationFormula
    {
       public Nullable<DateTime> ComputeExpireDate(SPListItem item, System.Xml.XmlNode parametersData)
       {
           try
           {
               Nullable<DateTime> dtReturn = null;
               // add your custom custom logic for expiration
              
               if (!String.IsNullOrEmpty(Convert.ToString(item["ThiloshNo"])))
               {
                   string a = Convert.ToString(item["ThiloshNo"]);
                   if (a == "1")
                   {
                       //return current datetime for expire the current item
                       dtReturn = DateTime.Now;
                   }
               }
               
               return dtReturn;
           }
           catch
           {
               return null;
           }
       }
    }
}

the return value will set the expiration date .

As defined in the blog the class will be referenced in a feature receiver.the feature can be deployed at web application or site collection scope.But I seemed to find difficulties in updating the feature once it is deployed.Like the logic in cs files wasnt getting updated.So if any changes I would recommend to create a expiration formula with different name.

Thursday, September 11, 2014

Sharepoint Client Object find if the folder exists in Sharepoint list or library

Below code finds if the Folder is present or not in a SharePoint List or library from client side



public void CheckFolderExists(string siteURL)
        {


            ClientContext clientContext = new ClientContext(siteURL);
            List oList = clientContext.Web.Lists.GetByTitle("ListA");

            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View Scope='RecursiveAll'>"
                                                + "<Query>"
                                                         + "   <Where>"
 + "      <Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq>"
                                                         + "   </Where>"
                                                + "</Query>"
                                + "</View>";
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            clientContext.Load(collListItem);
            clientContext.ExecuteQuery();

            string a = "";
            foreach (ListItem oListItem in collListItem)
            {
               
               a = a + oListItem["Title"];
               
            }
            label1.Text = a;

        }


The code will give you all the folders in the list ,you can play with CAML query or object to get the folder which you need

Sharepoint Client Object model create Folders in Document Library or list programmatically

Below methods will create a Folder or Subfolders in SharePoint library from client side.
Providing the relative path you can create the subfolder e.i  folder inside a folder as well

DDL used are Microsoft.Sharepoint.client and Microsoft.Sharepoint.Client.runtime.


public void CreateListFolder(string siteUrl, string listName, string relativePath, string folderName)
        {
            using (ClientContext clientContext = new ClientContext(siteUrl))
            {
                Web web = clientContext.Web;
                List list = web.Lists.GetByTitle(listName);
                list.EnableFolderCreation = true;
              
                ListItemCreationInformation newItem = new ListItemCreationInformation();
                newItem.UnderlyingObjectType = FileSystemObjectType.Folder;
                newItem.FolderUrl = siteUrl +"/"+ listName;
                if (!relativePath.Equals(string.Empty))
                {
                    newItem.FolderUrl += "/" + relativePath;
                }
                newItem.LeafName = folderName;
                ListItem item = list.AddItem(newItem);
                 //updating the metadata for the folder
                item["Col1"] = "Folder Property-1";
                item.Update();
                clientContext.Load(list);
                clientContext.ExecuteQuery();
            }


You can call the method a below
CreateListFolder(@"http://WebApplication:777", "ListA", "", "FolderA");



Other way of creating it is


  public void CreateLibraryFolder2()
        {
            using (var clientContext = new ClientContext(@"http://WebApplication:777/"))
            {
                var web = clientContext.Web;
                var lst = web.Lists.GetByTitle("Shared Documents");
                var fld1 = lst.RootFolder.Folders.Add("FirstLevel2");
                var fld2 = fld1.Folders.Add("SecondLevel2");      
                fld1.Update();
                fld2.Update();

                var t1 = lst.RootFolder.Folders.Add("FirstLevel7");
                var t2 = t1.Folders.Add("SecondLevel7");
                fld1.Update();
                fld2.Update();
                               

                clientContext.ExecuteQuery();
               
            }
        }

        
Thanks to the references found by googling :)

SharePoint Client object model to upload files into the Document library

Below code uses the managed client object model to upload files to SharePoint library from the client system.
I uploaded the files to SharePoint and my requirement was to upload  into particular folder of the document library through a console application. DDL used are Microsoft.Sharepoint.client and Microsoft.Sharepoint.Client.runtime.
Below method uploads the files like PDF or Excel or word document into particular folder of the SharePoint library

public void UploadDocument(string fileName, string filePath)
        {

            ClientContext ctx = new ClientContext("http://WebApplication:777/");

            Web currentWeb = ctx.Web;
            ctx.Load(currentWeb);
            ctx.ExecuteQuery();

            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {

Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, "/Shared Documents/" + fileName, fs, true);

            }

Microsoft.SharePoint.Client.File getFile = currentWeb.GetFileByServerRelativeUrl("/Shared Documents/" + fileName);
            ctx.Load(getFile);
            ctx.ExecuteQuery();

            //check out to make sure not to create multiple versions
            getFile.CheckOut();

            ListItem item = getFile.ListItemAllFields;
            item["testcol1"] = "T1";
            item["testDateCol2"] = DateTime.Today.ToString("yyyy-MM-ddTHH:mm:ssZ");
            //item["ContentTypeId"] = "0x0101";
            item.Update();
           
            // use OverwriteCheckIn type to make sure not to create multiple versions
            getFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);
            ctx.ExecuteQuery();

        }

You can upload into folder by changing the code as below
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, "/Shared Documents/Folder1" + fileName, fs, true);


You can then call the method in your application as below

UploadDocument("TestDocument.docx", @"E:\Path1\TestDocument.docx");