Tuesday, May 21, 2019

Export Import Content Types in SharePoint using Powershell CSOM


In SharePoint, we have lists and libraries for collaboration purposes. The lists and libraries contain a huge number of columns.
For better understanding and reusability, these are grouped in content types.
Content types are, hence, reusable collections of metadata which can be attached to any list or library. They help us to organize and handle the data in a better and more efficient way.
There are 2 types of content types.
  • Site Content typesThis is present in the root level of the site which can be used by subsequent subsites and lists/ libraries.
  • List Content types
    These are associated with lists and libraries and are a subset of site content types.
Let's take an example where content types are required.
Suppose, we have an Employee site which contains list like EmployeeData, HREmployeeData, FinanceEmployeeData, EmployeeDocuments, HRDocuments.
In this case, as we can see for EmployeeData and HR EmployeeData, we can have similar columns related to employees (For example, Firstname, Lastname, Ph Number, Address). So, here there are 2 possibilities.
  • We can either create a parent content type as Employee(which contains basic Employee details). Then, create HREMPContenttype and EMPContentype which will inherit from Employee.
  • Or, we can create a content type Employee and add that in the 2 lists. Then, add additional columns for the respective list.
Same goes for documents as well.
Now comes a situation where we need the same content types or a few of them in a separate site.
In on-premise, we have a content type hub for publishing the content type to be used across multiple locations. But, in SP Online we do not have the feature.
There is an option to export and import content type.
In the below PowerShell CSOM code, we can export the content type in XML file and use in the respective sites as required.
  1. //We need to refer to the DLLs first,  
  2. Add - Type - Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"  
  3. Add - Type - Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"  
  4. $URL = Read - Host - Prompt "Enter URL"– - URL of your online site.  
  5. $User = Read - Host - Prompt "Enter User"– - YOUR inline username  
  6. $siteURL = $URL  
  7. $userId = $User  
  8. $pwd = Read - Host - Prompt "Enter password" - AsSecureString--password  
  9. $creds = New - Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  
  10. //Read the SharePoint site content  
  11. $ctx = New - Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
  12. $ctx.credentials = $creds  
  13. try {  
  14.     $OutPutLocation = "C:\Powershell"–  
  15.     Give your respective file location to store xml files  
  16.     $web = $ctx.Web  
  17.     $contenttypes = $web.ContentTypes;  
  18.     --This line gives the content types presemt in the site.  
  19.     $fileName = [System.IO.Path]::Combine($OutPutLocation, "content-types.xml")  
  20.     Write - Host "Starting content type export to $fileName" - ForegroundColor Green  
  21.     $ctx.load($contenttypes)  
  22.     $ctx.executeQuery()  
  23.     $GroupName = "Discussion"  
  24.     //Here it iterates through all content types and store the data in xml file  
  25.     $contenttypes | ForEach - Object {  
  26.         #if ($_.Group - eq $GroupName) {  
  27.             Write - Host - ForegroundColor Blue $_.Name  
  28.             Add - Content $fileName $_.SchemaXml  
  29.             #  
  30.         }  
  31.     }  
  32.     Add - Content $fileName "
"  
  • catch {  
  •     write - host "$($_.Exception.Message)" - foregroundcolor red  
  • }  

  • Please store the DLLs in respective ISAPI folder before proceeding with the code.
    Similarly, we can import the respective content types to a destination site collection using the below script.
    1. Add - Type - Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"  
    2. Add - Type - Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"  
    3. $xmlFilePath = "C:\powershell\content-types.xml"  
    4. $URL = Read - Host - Prompt "Enter URL"  
    5. $User = Read - Host - Prompt "Enter User"  
    6. $siteURL = $URL  
    7. $userId = $User  
    8. $pwd = Read - Host - Prompt "Enter password" - AsSecureString  
    9. $creds = New - Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  
    10. $ctx = New - Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
    11. $ctx.credentials = $creds  
    12. $destWeb = $ctx.Web  
    13. $ctx.executeQuery()  
    14. $ctsXML = [xml](Get - Content($xmlFilePath))  
    15. # get content types from xml path  
    16. $ctsXML.ContentTypes.ContentType | ForEach - Object {  
    17.     $SPContentType = New - Object Microsoft.SharePoint.SPContentType($_.ID, $destWeb.ContentTypes, $_.Name)  
    18.     $SPContentType.Group = $_.Group  
    19.     # loop through each content type and add them.  
    20.     $_.Fields.Field | ForEach - Object {  
    21.         if (!$spContentType.FieldLinks[$_.DisplayName]) {  
    22.             #Create a field link  
    23.             for the Content Type by getting an existing column  
    24.             $spFieldLink = New - Object Microsoft.SharePoint.SPFieldLink($destWeb.Fields[$_.DisplayName])  
    25.             # Check to see  
    26.             if column should be Optional, Required or Hidden  
    27.             if ($_.Required - eq "TRUE") {  
    28.                 $spFieldLink.Required = $true  
    29.             }  
    30.             if ($_.Hidden - eq "TRUE") {  
    31.                 $spFieldLink.Hidden = $true  
    32.             }  
    33.           #Add column to Content Type  
    34.             $spContentType.FieldLinks.Add($spFieldLink)  
    35.         }  
    36.     }  
    37.     #Create Content Type on the site and update Content Type object  
    38.     $ct = $destWeb.ContentTypes.Add($spContentType)  
    39.     $spContentType.Update()  
    40.     write - host "Content type"  
    41.     $ct.Name "has been created"  
    42. }  
    43. $destWeb.Dispose()  

    Friday, December 2, 2016

    Claims based Authentication in SharePoint

    SharePoint 2013 has 2 authentication mechanisms:
    • ·         Windows classis mode Authentication
    • ·         Claims based Authentication
    • ·         SAML token based authentication

    Windows authentication validates the user thorough windows credentials. It uses the windows user account to validate the user to SharePoint resources.
    Here I will describe the Claims based authentication with membership provider
    • This authentication mechanism authenticates credentials through a membership provider. The authentication providers can be:
    • ·         LDAP
    • ·         AD DS
    • ·         SQL  Databases



    1.       Configure FBA in SharePoint
    2.       Open the Central Admin and click on Application ManagementàManage Web Applications
    3.       Select the “New Web Application” tab from the ribbon
    4.       Under Claims authentication type
           àCheck “Enable form based authentication”
    5.       Give the provider name and role manager name.(This will be used in config files and also authenticating with SQL DB
    6.       Open the 3 web.config files from IIS:
    (Central Admin,Web Application,Security Token service Appication)


    Locate the web.config file

    Add the Membership Provider and role manager
    Replace the section with the name provides while configuring the application
    The membership provider includes the names that we will be using to connect to SQL DB.

    Same configuration needs to be done to other 2 files mentioned above.

    The next step will be authenticating the user through code.
    1.       The aspnet membership provider creates the default tables and stored procedures which can be used to validate the user.
    2.       A user enters the credentials in the site .The following code will be required to authenticate user.
    SPClaimsUtility.AuthenticateFormsUser(Context.Request.UrlReferrer, userName, this.txtPassword.Text)
    3.       In the next step we authorize user with the user claims as below:
    string userRole = Project1.GetUserRole(claimsIdentity);
           string personId = Project1.GetPersonId(claimsIdentity);
           string email = Project1.GetUserEmail(claimsIdentity);
           string displayName = Project1.GetDisplayName(claimsIdentity, ants.USLocaleInUrl);
           string arabicDisplayName Project1.GetDisplayName(claimsIdentity, Constants.UAELocaleInUrl);
              string mobileNumber = Project1.GetMobileNumber(claimsIdentity);

    if (claimsIdentity != null)
                    {
                        Claim mobileClaim = claimsIdentity.Claims.SingleOrDefault(obj => obj.ClaimType == Constants.MobilePhoneClaimType);
                        if (mobileClaim != null)
                        {
                            return mobileClaim.Value;
                        }

    4.       If the user authentication fails,we validate from SQL DB using aspnet membership provider.
    The method used is (provider.ValidateUser) which validates whether a user with specified credentials are present in DB and returns value as true or false.

            







    Tuesday, September 9, 2014

    Central Admin content DB in Suspect Mode

    Central Admin content DB in Suspect Mode


    There are a few times when the central admin content DB gets into suspect mode for no reason.However,there is no reason to panic. we need to run a few set of commands to get our central admin back to running status.
    In my case the WSS_Content DB went in suspect mode which was giving error in Central Admin page.
    Open the SQL server and perform the following steps as below:

    It is recommended to take a backup of the databases the .mdf and .ldf files before performing the below actions.

    EXEC sp_resetstatus "WSSContentDB"

    ALTER DATABASE "WSSContentDB" SET EMERGENCY
    DBCC checkdb('"WSSContentDB"')

    ALTER DATABASE ""WSSContentDB"" SET SINGLE_USER WITH ROLLBACK IMMEDIATE

    DBCC CheckDB('"WSSContentDB"',REPAIR_ALLOW_DATA_LOSS)

    ALTER DATABASE "WSSContentDB" SET MULTI_USER

    EXEC sp_resetstatus 'WSSContentDB'

    Now, we can go back and check the SQL server ,the suspect mode gets removed and the Central admin page opens successfully.
    No data loss has occured.

    Wednesday, January 13, 2010

    Deploy solutions in Sharepoint


    We need to deploy solutions in SharePoint through wsps.
    There are generally 2 commands :
    First is to Add the solution ,then to install solution .
    Using the below msdn link the solution can be updated

    https://technet.microsoft.com/en-us/library/ff607534.aspx
    https://technet.microsoft.com/en-us/library/ff607552.aspx

    However,if the deployment still shows error we can use -FulltrustBinDeployment with -Force.

    Incase any code modification is done,we need to upgrade wsp. and not deploy the entire solution.





    Export Import Content Types in SharePoint using Powershell CSOM In SharePoint, we have lists and libraries for collaboration purposes....