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");

Monday, July 7, 2014

update aspx or any file through Powershell

I had this problem of SharePoint people picker issue, where in the People picker restricted to particular SharePoint group was having UI problem .Problem was that when you try to search users a popup open with the users in that SharePoint group for you to be selected .

Problem is that the Height of the people picker popup in IE10 was very small as below.
It was working fine in IE9,IE11 and IE10 quirks mode


The files in use are picker.aspx and pickerdialog.aspx .

There were two solutions

Solution-1 : Edit the picker.aspx



·         Locate the div with ID = ‘resultcontent ‘and add style property to it. Set the min-height value from inside the style property like below.

<div id='resultcontent' style="min-height:300px" class="ms-pickerresultdiv">
 
 
Solution-2 : Edit the Pickerdialog.master 
·         In the Meta tags section, set the “X-UA-Compatible” to “IE=EmulateIE9” to make it look like below.
 
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />
Here in this option the page is rendered in IE9 mode  

Client chose the solution-2 and they wanted to automate this using the PowerShell ,hence I wrote the below PowerShell command to take backup of the current pickerdialog.aspx and update the tag in the file which is present in 15 hive, this ps1 has to run in all web front-end server
Below is the PowerShell command
 
 
 
 
Write-host -ForegroundColor Green "Updating Pickerdialog.master file started .........!!"
Write-host -ForegroundColor Green "Creating backup of current file ........."
$a =(Get-Date).ToString('MM-dd-yyyy hh-mm-ss')
$filename = "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\pickerdialog-{0}.master" -f $a
copy "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\pickerdialog.master" $filename
Write-host -ForegroundColor Green "Backup of current file completed ........."
(Get-Content "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\pickerdialog.master") |
Foreach-Object {$_ -replace "<meta http-equiv=`"X-UA-Compatible`" content=`"IE=10`"/>", "<meta http-equiv=`"X-UA-Compatible`" content=`"IE=EmulateIE9`"/>"} |
Set-Content "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\pickerdialog.master"
Write-host -ForegroundColor Green "Updating Pickerdialog.master file completed ........."
pause