SharePoint Tips

Wednesday, November 22, 2017

SharePoint Online : CSOM : PowerShell : Update List Item

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

$siteURL = ""
$userId = ""
$pwd = Read-Host -Prompt "Enter password" -AsSecureString
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$ctx.credentials = $creds
try{
    $lists = $ctx.web.Lists
    $list = $lists.GetByTitle("TestList")
    $listItem = $list.GetItemById(1)
    $listItem["Title"] = "aa"
    $listItem.Update()
    $ctx.load($listItem)   
    $ctx.executeQuery()
}
catch{
    write-host "$($_.Exception.Message)" -foregroundcolor red

SharePoint Online : CSOM : PowerShell : Delete List Item

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

$siteURL = ""
$userId = ""
$pwd = Read-Host -Prompt "Enter password" -AsSecureString
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$ctx.credentials = $creds
try{
    $lists = $ctx.web.Lists
    $list = $lists.GetByTitle("TestList")
    $listItem = $list.GetItemById(1)
    $listItem.DeleteObject()
    $ctx.executeQuery()   
}
catch{
    write-host "$($_.Exception.Message)" -foregroundcolor red
}  

SharePoint Online : CSOM : PowerShell : Create List Item

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

$siteURL = ""
$userId = ""
$pwd = Read-Host -Prompt "Enter password" -AsSecureString
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$ctx.credentials = $creds
try{
    $lists = $ctx.web.Lists
    $list = $lists.GetByTitle("TestList")
    $listItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
    $listItem = $list.AddItem($listItemInfo)
    $listItem["Title"] = "c"
    $listItem.Update()   
    $ctx.load($list)   
    $ctx.executeQuery()
    Write-Host "Item Added with ID - " $listItem.Id   
}
catch{
    write-host "$($_.Exception.Message)" -foregroundcolor red
}  

SharePoint Online : CSOM : PowerShell: Get List Items

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll" 
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" 
 
$siteURL = "" 
$userId = "" 
$pwd = Read-Host -Prompt "Enter password" -AsSecureString 
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd) 
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL) 
$ctx.credentials = $creds 
try{ 
    $lists = $ctx.web.Lists 
    $list = $lists.GetByTitle("TestList") 
    $listItems = $list.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()) 
    $ctx.load($listItems) 
     
    $ctx.executeQuery() 
    foreach($listItem in $listItems) 
    { 
        Write-Host "ID - " $listItem["ID"] "Title - " $listItem["Title"] 
    } 

catch{ 
    write-host "$($_.Exception.Message)" -foregroundcolor red 
}  

SharePoint 2013 CSOM - PowerShell script to get web title

#clear
#Download SharePoint 2013 CSOM from http://www.microsoft.com/en-us/download/details.aspx?id=35585
$showResultsOnly = $false;
$rowLimit = 10;
$siteUrl = "https://abc.xyz.net/"

#$isapi15 = "C:\Users\ssspp\Documents\csom15APIs"
$isapi15 = "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI"

Import-Module "$isapi15\Microsoft.SharePoint.Client.dll"
Import-Module "$isapi15\Microsoft.SharePoint.Client.Runtime.dll"

$execTime = $(get-date -Format "yyyyMMMdd-hhmm-sstt")
write-host "Execution Time: $execTime, $PSScriptRoot"

function main()
{
    $username = [System.Environment]::UserName
    write-host "Using default credentials for: $username" -f Yellow
    $cred = [System.Net.CredentialCache]::DefaultNetworkCredentials;
    $cacheCred = $cred
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
    $ctx.Credentials = $cacheCred;

    if ($ctx)
    {
        Write-Host "Opening Web..."
        $web = $ctx.Site.RootWeb
        $ctx.Load($web);
        $ctx.ExecuteQuery();
        $title = $web.Title;
        write-host "Opened Web: $($web.Title) from $siteUrl" -f Cyan;

        if ([String]::IsNullOrEmpty($title))
        {
            write-host "Unable to open web: check your site url or user permissions" -f Red
            return;
        }
    }
}

main
#pause


Office 365 - CSOM - PowerShell script to retrieve list data from a SharePoint online site

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

$UserName= "***@xxzz.onmicrosoft.com"
$Password = "***"

$credentials= New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
$webURL="https://xxzz.sharepoint.com/sites/Team"
$ctx= New-Object Microsoft.SharePoint.Client.ClientContext($webURL)
$ctx.Credentials = $credentials
try{
$lists = $ctx.web.Lists
$list = $lists.GetByTitle("TestList")
$listItems = $list.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$ctx.load($listItems)

$ctx.executeQuery()
foreach($listItem in $listItems)
{
Write-Host "ID - " $listItem["ID"] "Title - " $listItem["Title"] "DateTime - " $listItem["DateTime"] "Choices - " $listItem["Choices"]
}
}
catch{
write-host "$($_.Exception.Message)" -foregroundcolor red
}

For look up columns:
$lookup = [Microsoft.SharePoint.Client.FieldLookupValue]$listItem["Lookup"]
$lookupValue=$lookup.LookupValue

Thursday, November 16, 2017

C# - SharePoint - Get Current User Audience Group

public static string GetCurrentUserAudienceGroup(string publishingSiteURL, string loginName)
 {
AcenetLogger.LogMessage("Entering into the Method GetCurrentUserAudienceGroup", "CommonHelper", null);
string audienceGroups = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(publishingSiteURL))
{
SPWeb web = site.RootWeb;

Microsoft.Office.Server.ServerContext context = Microsoft.Office.Server.ServerContext.GetContext(site);
AudienceManager audManager = new AudienceManager(context);
AudienceCollection audiences = audManager.Audiences;

for (int i = 0; i < audiences.Count; i++)
{
if (audiences[i].IsMember(loginName))
{
audienceGroups = audienceGroups + "," + audiences[i].AudienceID;
}
}

}
});
}
catch (Exception ex)
{
Logger.LogException("Error has occured On the Method”);
audienceGroups = string.Empty;
}
return audienceGroups.TrimStart(',');
 }

C# - Retrieve information for audiences associated with a SharePoint site

AudienceCollection Audiences;
AudienceManager AudMgr = New AudienceManager();
Audiences = AudMgr.Audiences;

for (int list=0; list < Audiences.Count; list++)
{
    System.Console.WriteLine("{0}", list);
    Audience = (Audience)Audiences[list];
    System.Console.WriteLine("  Audience.Count ", Audience.Count);
    System.Console.WriteLine("  Audience.AudienceCompiledSofar ", Audience.AudienceCompiledSofar);
    System.Console.WriteLine("  Audience.LastCompileStartTime ", Audience.LastCompileStartTime);
    System.Console.WriteLine("  Audience.LastCompileStartTime ", Audience.LastCompileFinishTime);
    System.Console.WriteLine("  Audience.LastCompileError ", Audience.LastCompileError);
    System.Console.WriteLine("  Audience.CompileInProgress ", Audience.CompileInProgress);
}
System.Console.WriteLine("End");

PowerShell - Export SharePoint Audience Members (username & email) to CSV

$Output="D:\Output.csv"
"Username"+","+"Email" | Out-File -Encoding Default -FilePath $Output;
$Site = Get-SPSite "http://test.contoso.com"
$Context=[Microsoft.Office.Server.ServerContext]::GetContext($Site)
$AudManager=New-Object Microsoft.Office.Server.Audience.AudienceManager($Context)
$Audience=$AudManager.Audiences | Where {$_.AudienceName -eq "TestAudienceGroup"}
Foreach ($Member in $Audience.GetMembership())
{
Write-Host $Member.NTName
Write-Host $Member.Email
$Member.NTName + "," + $Member.Email | Out-File -Encoding Default -Append -FilePath $Output
}

C# - Create Static XML Node

public static void CreateStaticXmlNode(XmlDocument xmlDoc, XmlNode parentNode)
{
//Node 1
XmlNode childNodeOne = xmlDoc.CreateElement("MFITEM");
XmlAttribute attMFTYPE = xmlDoc.CreateAttribute("TYPE");
attMFTYPE.InnerText = "FILE";
childNodeOne.Attributes.Append(attMFTYPE);
XmlAttribute attMFKEY = xmlDoc.CreateAttribute("KEY");
attMFKEY.InnerText = "FileName.pdf";
childNodeOne.Attributes.Append(attMFKEY);
XmlNode nodeMFTitle = xmlDoc.CreateElement("TITLE");
nodeMFTitle.InnerText = "<![CDATA[Test Form]]>";
childNodeOne.AppendChild(nodeMFTitle);
parentNode.AppendChild(childNodeOne);
//Node 2
XmlNode childNodeTwo = xmlDoc.CreateElement("MFITEM");
XmlAttribute attIncSheetType = xmlDoc.CreateAttribute("TYPE");
attIncSheetType.InnerText = "FILE";
childNodeTwo.Attributes.Append(attIncSheetType);
XmlAttribute attSK = xmlDoc.CreateAttribute("KEY");
attSK.InnerText = "FileName.pdf";
childNodeTwo.Attributes.Append(attSK);
XmlNode childNodeTwoTitle = xmlDoc.CreateElement("TITLE");
childNodeTwoTitle.InnerText = "<![CDATA[Test Text]]>";
childNodeTwo.AppendChild(childNodeTwoTitle);
parentNode.AppendChild(childNodeTwo);
}

CSOM - Get Document metadata from SharePoint Library - C#

public ListItemCollection GetDocumentMetaData(ClientContext clientContext, string libraryName)
{
ListItemCollection items = null;
try
{
 // true to enable 100-Continue behavior.The default value is true.
ServicePointManager.Expect100Continue = true;
  // Default .Net SecurityProtocol. To disable SSL fallback
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

List library = clientContext.Web.Lists.GetByTitle(libraryName);

clientContext.Load(library);
clientContext.Load(library.RootFolder);
clientContext.Load(library.RootFolder.Folders);
clientContext.Load(library.RootFolder.Files);
clientContext.ExecuteQuery();

if (library != null && library.ItemCount > 0)
{
// Add all your CAML query conditions in below variable
List<string> conditions = new List<string>();
CamlQuery camlQuery = new CamlQuery();
string serverRelativeUrl = library.RootFolder.ServerRelativeUrl + "/Folder Name";
camlQuery.FolderServerRelativeUrl = serverRelativeUrl;
string viewXml = @"<View Scope='Recursive'>
<Query><Where>" + conditions +
   @"</Where></Query>                           
</View>";
camlQuery.ViewXml = viewXml;

items = library.GetItems(camlQuery);

clientContext.Load(items, listItems => listItems.Include
(item => item.FileSystemObjectType,
item => item.ContentType,
item => item.DisplayName,
item => item["FileLeafRef"],
item => item["Modified"],
item => item["Title"],
item => item["FileRef"],
item => item["CustomField1"],
item => item["CustomField2"],
item => item["Created"]));
clientContext.ExecuteQuery();

}

}
catch (Exception exec)
{
logger.WriteEventLog("Please contact admin : " + exec.Message);
throw exec;
}
int count = items.Count;
return items;
}

Method to merge multiple Or, And condition in same CAML query - C# CSOM

enum MergeType { Or, And };


        /// <summary>
        /// Use this method to merge multiple Or, And condition in same CAML query for same or different columns
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private string MergeCAMLConditions(List<string> conditions, MergeType type)
        {
            try
            {
                if (conditions.Count == 0) return "";
                string typeStart = (type == MergeType.And ? "<And>" : "<Or>"); string typeEnd = (type == MergeType.And ? "</And>" : "</Or>");
                // Build hierarchical structure 
                while (conditions.Count >= 2)
                {
                    List<string> complexConditions = new List<string>();
                    for (int i = 0; i < conditions.Count; i += 2)
                    {
                        if (conditions.Count == i + 1)
                            // Only one condition left             
                            complexConditions.Add(conditions[i]);
                        else
                            // Two condotions - merge             
                            complexConditions.Add(typeStart + conditions[i] + conditions[i + 1] + typeEnd);
                    }
                    conditions = complexConditions;
                }
            }
            catch (Exception exec)
            {
                logger.WriteEventLog("Please contact admin : " + exec.Message);
                throw exec;
            }
            return conditions[0];
        }


How to use this method:

List<string> conditions = new List<string>();
 foreach (string id in ids)
  {
      conditions.Add("<Eq><FieldRef Name='Model' /><Value Type='Text'>" + id + "</Value></Eq>");
  }
string merged = MergeCAMLConditions(conditions, MergeType.Or);

string viewXml = @"<View Scope='Recursive'>
                                            <Query><Where>" + merged +
                                       @"</Where></Query>                           
                                        </View>";
camlQuery.ViewXml = viewXml;

CSOM Method to return list data from SharePoint - C#

        /// <summary>
        /// CSOM method to return list data from SharePoint
        /// </summary>
        /// <param name="clientContext"></param>
        /// <returns></returns>
        public ListItemCollection LoadListData(ClientContext clientContext)
        {
            Web site = clientContext.Web;
            List oList = clientContext.Web.Lists.GetByTitle("ListName");
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = @"<View Scope='Recursive'>
                                            <Query></Query>
                                        </View>";
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            clientContext.Load(collListItem, listItems => listItems.Include
                                           (item => item["Column1"],
                                            item => item["Column2"]));

            clientContext.ExecuteQuery();
            return collListItem;
        }

Format XML - C#, Replace Special Characters from XML File

public class FormatXML
    {
        /// <summary>
        /// Read the xml file to string
        /// </summary>
        /// <param name="fileName">full file path</param>
        /// <returns></returns>
        public string ReadXmlFile(string fileName)
        {
            string xmlString = System.IO.File.ReadAllText(fileName);
            return xmlString;
        }

/// <summary>
        /// Replace special characters from xml file
        /// </summary>
        /// <param name="fileName">full file path</param>
        /// <returns></returns>
        public string ReplaceSpecialChar(string fileName)
        {
            string xmlString = ReadXmlFile(fileName);
            xmlString = xmlString.Replace("&lt;", "<").Replace("&gt;", ">");
            return xmlString;
        }
    }

Download File from SharePoint CSOM C#

public class DownloadFile
    {
        Logger logger = new Logger();
        public void FileRef(ListItem item, ClientContext clientContext)
        {
            try
            {
                string strFileRelativeUrl = string.Empty;
                string tempLocation = CreateDirectory();
                if (item != null)
                {

                    strFileRelativeUrl = item["FileRef"].ToString();
                    string fileName = strFileRelativeUrl.Substring(strFileRelativeUrl.LastIndexOf('/') + 1);
                    if (!string.IsNullOrEmpty(strFileRelativeUrl))
                    {
                        // string fileName = System.IO.Path.GetFileName(mf.FileRef);
                        clientContext.ExecuteQuery();
                        //download

                        FileInformation fromFileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, strFileRelativeUrl);
                        clientContext.ExecuteQuery();

                        Stream fs = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, strFileRelativeUrl).Stream;
                        clientContext.ExecuteQuery();
                        byte[] binary = ReadFully(fs);
                        FileStream stream = new FileStream(tempLocation + "\\" + fileName, System.IO.FileMode.Create);
                        BinaryWriter writer = new BinaryWriter(stream);
                        writer.Write(binary);
                        writer.Close();
                    }

                }
            }
            catch (Exception exec)
            {
                logger.WriteEventLog("Please contact admin : " + exec.Message);
                throw exec;
            }

        }

        public static byte[] ReadFully(Stream input)
        {

            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        public string CreateDirectory()
        {
            string fileDirectory = ConfigurationManager.AppSettings["FileLocation"];
            if (!Directory.Exists(fileDirectory))
            {
                Directory.CreateDirectory(fileDirectory);
            }       
            return fileDirectory;
        }
    }

Write Log File - C#

 class Logger
    {
        public void WriteEventLog(string errorMessage)
        {
            StringBuilder errorBuilder = new StringBuilder();
            try
            {

                if (!string.IsNullOrEmpty(errorMessage))
                {
                    string fileDateFormat = "yyyyMMdd";
                    string fileDirectory = ConfigurationManager.AppSettings["FileLocation"];
                    string errorLogFilePath = fileDirectory + "ErrorLog";

                    if (!Directory.Exists(errorLogFilePath))
                    {
                        Directory.CreateDirectory(errorLogFilePath);
                    }

                    errorLogFilePath = errorLogFilePath + @"\ErrorLogFile" + DateTime.Now.ToString(fileDateFormat) + ".log";
                    errorBuilder.Append("-------------------------------------------------------------------------------------------------\n");
                    errorBuilder.AppendLine(System.DateTime.Now.ToString());
                    errorBuilder.AppendLine("Error Message :" + errorMessage);
                    errorBuilder.AppendLine("-------------------------------------------------------------------------------------------------");

                    //Writing to Text File.
                    TextWriter oTW = System.IO.File.AppendText(errorLogFilePath);
                    oTW.WriteLine(errorBuilder.ToString());
                    oTW.Close();
                }

            }
            catch (Exception exec)
            {
                throw exec;
            }
        }   
    }