Wednesday, October 22, 2014

Bulk creation of Sharepoint Site column ,Content types ,list and permission groups



Here is the GitHub Link  where I have upload the CSV and power shell scripts which can be used for bulk creation of Sharepoint Site column,Content types,List and permissions,

All you need to do is enter the values in the respective CSV which already consists of some sample values.


https://gallery.technet.microsoft.com/Create-Sharepoint-81bba042#content

Thursday, October 9, 2014

Sharepoint break role inherentence and add custom permission in sharepoint library/List through Powershell

$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}



function AddGroupsToList($groupName,$permissionLevel)
{
    $Group = $web.SiteGroups[$groupName]
    $GroupAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($Group)
    #Get the permission levels to apply to the new groups
    $RoleDefinition = $web.Site.RootWeb.RoleDefinitions[$permissionLevel]
    #Assign the groups the appropriate permission level
    $GroupAssignment.RoleDefinitionBindings.Add($RoleDefinition)
    #Add the group to the site with the permission level
    $list.RoleAssignments.Add($GroupAssignment)    
    $list.Update()
}


$site = Get-SPSite "http://webapplication/sites/RECMRepository/"
$web = $site.RootWeb



#Break Roleinherentence for "Public Documents" list
Write-Host  -foreground "green" "Breaking Role inherentence for the list - Public Documents"
$list = $web.Lists["Public Documents"]
$list.BreakRoleInheritance($false)
#Add Groups to the list with permission levels assigned
AddGroupsToList "Group1" "Full Control"
AddGroupsToList "Group2" "Contribute"
AddGroupsToList "Group3" "Read"


Note:Breaking role inherentence of either site or library or list with Parameter "False" will give you with clean slate no groups from top level will be copied hence I am adding the groups which I need later,

But if the parameter is "True" it will copy the groups from top level,in the case you may need to delete the unwanted groups from the list
 

Create Sharepoint Site Group and role definition through powershell

Below code to be used in powershell file


function createSiteGroups($groupName,$groupOwner,$groupDescription,$permissionLevel,$users)
{
    Write-Host  -foreground "green"  "Creating Sharepoint group -" $groupName
    $web.SiteGroups.Add($groupName, $groupOwner, $groupOwner, $groupDescription)
    $Group = $web.SiteGroups[$groupName]
    $Group.AllowMembersEditMembership = $true
    $Group.Update()
    Write-Host  -foreground "green"  "Creating role assignment for the group -" $groupName
    $GroupAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($Group)

    #Get the permission levels to apply to the new groups
    $RoleDefinition = $web.Site.RootWeb.RoleDefinitions[$permissionLevel]
    #Assign the groups the appropriate permission level
    $GroupAssignment.RoleDefinitionBindings.Add($RoleDefinition)
    #Add the group to the site with the permission level
    $web.RoleAssignments.Add($GroupAssignment)
    Write-Host  -foreground "green"  "Creation of group and role assignment completed successfully for the group -" $groupName
    #Adding users to the group
    Write-Host  -foreground "green"  "Adding users to the group -" $groupName
    $arrayUsers = $users.split(",")
    foreach($user in $arrayUsers)
        {
           if($user -ne "")
             {
               $adUser = $web.Site.RootWeb.EnsureUser($user)
               $Group.AddUser($adUser)
              }
        }
}


You can call the function as below

#Creating Sharepoint security Groups
#create group "Group1 "
$groupName = "Group1"
$groupOwner = $web.Site.Owner
$groupDescription =  "test Group"
$permissionLevel = "Full Control"
$users = "domain\user1,Domain\user2"
createSiteGroups $groupName  $groupOwner $groupDescription $permissionLevel $users



 

Sharepoint create List and attach Content Type to Library or List through powershell

Below code to be used in Powershell file


$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}

function AddContentTypes($web,$libraryName,$libraryDescription,$libraryTemplate,$customContentTypes)
{
   
    #Adding CT
    Write-Host -foreground "green" "Adding Content Types to the Library - " $libraryName
    $docLib = $web.Lists[$libraryName]
    $docLib.ContentTypesEnabled = "True"
    $docLib.update()
    $customContentTypeArray = $customContentTypes.Split(",")
    foreach($customContentType in $customContentTypeArray)
       {
         $customCT = $web.ContentTypes[$customContentType]
         $docLib.ContentTypes.Add($customCT)
         Write-Host -foreground "green" "Content Type -"$customContentType "Added to the List"
       }
    $docLib.update()

}



$site = Get-SPSite "http://Webapplication:777"
$web = $site.RootWeb

$libraryName = "Config"
$libraryDescription = ""
$libraryTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary;
Write-Host -foreground "green" "Creating Library - " $libraryName "...."
# Adding Library
$web.Lists.Add($libraryName,$libraryDescription,$libraryTemplate);
$web.Update();

$customContentTypes = "CT1,CT2,CT3"
AddContentTypes $web $libraryName $libraryDescription $libraryTemplate $customContentTypes



$web.Dispose()
$site.Dispose()

Read-host "Press Enter key to exit ...."



To create site column and Content type use the Link
 

Create sharepoint Site column and Content Types through powershell

Use the below code in Powershell file




$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}
$site = Get-SPSite http://WebApplication:777
$web = $site.RootWeb 

$fieldXML = '<Field Type="Text" ID="{20152dbc-7793-46cb-bc0d-5dd98b0aa1a4}" StaticName="Col1" Name=" Col1" DisplayName=" Col1"
            Description="A document classification ." Required="TRUE" MaxLength="255"
            Group="RDM Site Columns"  ></Field>'
write-host -foreground "green" "Adding Site Column"
$web.Fields.AddFieldAsXml($fieldXML) 

$fieldXML =  '<Field Type="Note" ID="{2808ba7f-78a9-4930-8840-385a18e85b53}" StaticName="Col2" Name=" Col2" DisplayName=" Col2"
        Description="The type of business conducted at a site." Required="FALSE"  NumLines="6" RichText="TRUE"
        Group="RDM Site Columns"  ></Field>'
write-host -foreground "green" "Adding Site Column"
$web.Fields.AddFieldAsXml($fieldXML) 

$fieldXML = '<Field Type="Choice" ID="{ce7f74d7-fc8c-4844-85a9-903e208e68d2}" StaticName="Col3" Name=" Col3" DisplayName=" Col3"
        Description="The status of a complete location." Required="TRUE" Group="EICM Site Columns" >   
<CHOICES>
      <CHOICE>Active</CHOICE>
      <CHOICE>InActive</CHOICE>
      <CHOICE>Pending</CHOICE>
    </CHOICES>
    <Default>Pending</Default>
  </Field>'
write-host -foreground "green" "Adding Site Column"
$web.Fields.AddFieldAsXml($fieldXML) 
 

Write-Host -foreground "green" "Creating Content Type-CT1 ...."
$ctypeName = “CT1”
$ctypeParent = $web.availablecontenttypes["Document"]
$ctype = new-object Microsoft.SharePoint.SPContentType($ctypeParent, $web.contenttypes, $ctypeName)
$ctype.Group = "CT"
$ctype.Description = ""
$web.contenttypes.add($ctype)
 

$field = $web.fields.getfield(“Col1”)
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.add($fieldLink)
$field = $web.fields.getfield(“Col2”)
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.add($fieldLink)
$field = $web.fields.getfield(“Col3”)
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.add($fieldLink)
$ctype.update()
 

If u need to delete any field in child CT which got inherted from Parent CT then you can use the below code 

 

Write-Host -foreground "green" "Creating Content Type-CT2 ...."
$ctypeName = “CT2”
$ctypeParent = $web.availablecontenttypes["CT1"]
$ctype = new-object Microsoft.SharePoint.SPContentType($ctypeParent, $web.contenttypes, $ctypeName)
$ctype.Group = "EICM Content Types"
$ctype.Description = ""
$web.contenttypes.add($ctype)
 

$field = $web.fields.getfield(“col1”)
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.Delete($fieldLink.Id)
$ctype.update()

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
 
 
 
 

Thursday, May 15, 2014

Modal Popup- close sharepoint page and sharepoint popup page in code behind

Below is the code to close a SharePoint popup window on button click or any event from code behind

// Close if dialog

HttpContext context = HttpContext.Current;

if (HttpContext.Current.Request.QueryString["IsDlg"] != null)



{
 
context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");




}
 
else

SPUtility.Redirect(SPContext.Current.Web.Url, SPRedirectFlags.UseSource, HttpContext.Current);




Source attribute is a Query string which holds the url of the source page from where the page is usually called .This is default behavior of SharePoint. We can use this to navigate when the popup is closed and redirect to same source page as shown above

Eg: http://webpalication:1111?Source=http:wwww.google.com


 

Friday, May 9, 2014

Add Sharepoint Navigation links with audience targeting through powershell

Below is the powershell command to add Navigation links in SharePoint.This was tested in SharePoint 2013 environment.This script will check if the link is present in the site if not it will add the links along with audience targeting



$snapin = Get-PSSnapin | Where-Object { $_.Name -eq "Microsoft.SharePoint.Powershell" }

if ($snapin -eq $null) {

Write-Host "[INIT] Loading SharePoint Powershell Snapin"

Add-PSSnapin "Microsoft.SharePoint.Powershell"


}

 
 
$Web = Get-SPWeb http://testWebapplication:7777

$TopNav = $Web.Navigation.TopNavigationBar

Write-Host -ForegroundColor Green "Creating Navigation links ......................."



$Heading = $TopNav | where { $_.Title -eq "Link1" }

if($Heading -eq $null)



{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @("Link1", "/Lists/CreateNewPublication/DocProjects.aspx");

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Web.Update()





}

 
 
$Heading = $TopNav | where { $_.Title -eq "Search" }

if($Heading -eq $null)


{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @("Search", "/SitePages/Search.aspx");

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Web.Update()


}
 
$Heading = $TopNav | where { $_.Title -eq "Google" }

if($Heading -eq $null)


{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @("Google", http://www.google.com);

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Web.Update()


}
 
$Heading = $TopNav | where { $_.Title -eq "Yahoo" }

if($Heading -eq $null)



{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @("Yahoo", http://yahoo.co.in);

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Heading.Properties["Audience"] = ";;;;" + "IK,IL,R,C"

$Heading.update()

$Web.Update()





}
 
$Heading = $TopNav | where { $_.Title -eq "Reports" }

if($Heading -eq $null)



{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @("Reports", "/SitePages/Reports.aspx");

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Heading.Properties["Audience"] = ";;;;" + "PM,TL,IL,C"

$Heading.update()

$Web.Update() 



}
 
  $Heading = $TopNav | where { $_.Title -eq " Help" }

if($Heading -eq $null)

{
 
$newLink = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode -ArgumentList @(" Help", "/Lists/HelpLibrary ");

$Heading = $Web.Navigation.TopNavigationBar.AddAsLast($newLink)

$Web.Update()


}
 
Write-Host -ForegroundColor Green "Navigation link creation completed"

Pause