Friday, February 9, 2018

Powershell to add dummy documents to SharePoint List for Testing purpose

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

# ---- Script settings ----
$sourceDocumentPath = "C:\temp\TestDoc.docx" # Source document to spawn new documents from for the creation
$newFilenamePrefix = "TestDoc"
$newFilenameExtension = ".docx"
$numberDocsToCreate = 5000

# Settings for the destination to create documents in

$webUrl = "http://site:1111/sites/tdm3"
$docLibraryName = "Lib"
$folderPathWithinDocLibrary = "" # Leave empty e.g. "" to create documents in root folder of library otherwise specify path relative to root folder e.g. "/Testing/Folder A"

# -------------------------

#Open web and library
$web = Get-SPWeb $webUrl
$docLibrary = $web.Lists[$docLibraryName]
$docLibraryUrl = $docLibrary.RootFolder.ServerRelativeUrl
$uploadfolder = $web.getfolder($docLibraryUrl + $folderPathWithinDocLibrary)

#Open file
$file = get-item $sourceDocumentPath
$fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()

# Create documents in SharePoint
write-host "Creating $i documents based on the file $sourceDocumentPath"

for($i=1; $i -le $numberDocsToCreate; $i++)
{
$newFilePath = $docLibraryUrl + $folderPathWithinDocLibrary + "/" + $newFilenamePrefix+$i+$newFilenameExtension
write-host "Creating document: $newFilePath ..."
$spFile = $uploadfolder.Files.Add($newFilePath, [System.IO.Stream]$fileStream, $true)
}

write-host "Completed"

#Close file stream
$fileStream.Close()

#Dispose web
$web.Dispose()

Schedule Nintex Workflows to ListItems via Nintex web service


Small Utility to Schedule Nintex Workflows to SharePoint ListItems via Nintex web service

internal class Program
    {
        private static void Main(string[] args)
        {
            var sourceListName = "EIQ"; //
            var siteUrl = "http://site:3333";
            var UserName = "dtu";
            var pwd = "Password10";
            var domain = "dev";
            string env = "DEV";
            string workflowName = "IncompleteForm_WF";
            try
            {
                ClientContext clientContext = null;
                if (env.ToUpper() == "DEV")
                {
                    clientContext = Auth(siteUrl, UserName, pwd, domain);
                }
                else if (env.ToUpper() == "UAT")
                {
                    clientContext = MixedAuthRequest(siteUrl, UserName, pwd, domain);
                }

                NintexWorkflowWSSoapClient soapClient = InitializeNintexSoapClienn(UserName, pwd, domain);
                Microsoft.SharePoint.Client.User spUser;
                spUser = clientContext.Web.CurrentUser;
                Console.WriteLine("Loading User!");
                clientContext.Load(spUser, user => user.LoginName);
                Console.WriteLine("Loading Login Name");
                clientContext.ExecuteQuery();
                Console.WriteLine(spUser.LoginName);
                //Process EID list items
                ProcessEIQItems(clientContext, sourceListName, soapClient, workflowName);
                Console.ReadLine();
            }
            catch (Exception ex)
            {

                string message = "Error in main method";
                Console.WriteLine(message);
                ErrorLogging(ex, message);
                Console.ReadLine();
            }
        }

        private static NintexWorkflowWSSoapClient InitializeNintexSoapClienn(string UserName, string pwd, string domain)
        {
            try
            {
                var soapClient = new NintexWorkflowWSSoapClient("NintexWorkflowWSSoap");
                //need to name the endpoint being used.
                soapClient.ClientCredentials.Windows.ClientCredential.UserName = UserName;
                soapClient.ClientCredentials.Windows.ClientCredential.Password = pwd;
                soapClient.ClientCredentials.Windows.ClientCredential.Domain = domain; //optional
                                                                                       //soapClient.ClientCredentials.Windows.AllowNtlm = true; //optional
                soapClient.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; //optional
                return soapClient;
            }
            catch (Exception ex)
            {
                string message = "Error in Initialising the Nintexwebservice soap method";
                Console.WriteLine(message);
                ErrorLogging(ex, message);
                throw ex;
            }
        }

        private static void ProcessEIQItems(ClientContext clientContext, string listName, NintexWorkflowWSSoapClient soapClient, string workflowName)
        {
            ListItemCollection olistItems = null; 
            try
            {
                Microsoft.SharePoint.Client.List oList = clientContext.Web.Lists.GetByTitle(listName);
                CamlQuery query = new CamlQuery();
                query.ViewXml = string.Format("true" +
                    "
");
                olistItems = oList.GetItems(query);
                clientContext.Load(olistItems);
                clientContext.ExecuteQuery();
                if (olistItems != null && olistItems.Count > 0)
                {
                    foreach (ListItem listItem in olistItems)
                    {
                        var strDate = Convert.ToDateTime(listItem["NextReminderDate"].ToString());
                        if (strDate != null)
                        {
                            ScheduleNintexWrorkflow(listName, soapClient, workflowName, listItem, strDate);
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                string message = "Error in ProcessEIQItems method";
                Console.WriteLine(message);
                ErrorLogging(ex, message);
                throw ex;
            }
        }

        private static void ScheduleNintexWrorkflow(string listName, NintexWorkflowWSSoapClient soapClient, string workflowName, ListItem listItem, DateTime strDate)
        {
            try
            {             
                Schedule sc = new Schedule();
                sc.StartTime = strDate;
                RepeatInterval ri = new RepeatInterval();
                ri.CountBetweenIntervals = 14;
                ri.Type = RepeatIntervalType.Hourly;
                sc.RepeatInterval = ri;
                sc.MaximumRepeats = 0;
                sc.WorkdaysOnly = false;
                sc.EndOn = EndScheduleOn.RepeatCount;
                var ret = soapClient.AddWorkflowScheduleOnListItem(Convert.ToInt32(listItem["ID"]), listName, workflowName, "", sc, true);
            }
            catch (Exception ex)
            {
                string message = "Error in Scheduling the item ID: " + Convert.ToString(listItem["ID"]);
                Console.WriteLine(message);
                ErrorLogging(ex, message);
            }
        }

        public static void ErrorLogging(Exception ex, string message)
        {
            string strPath = @"D:\NintexScheuldeWFLog.txt";
            if (!System.IO.File.Exists(strPath))
            {
                System.IO.File.Create(strPath).Dispose();
            }
            using (StreamWriter sw = System.IO.File.AppendText(strPath))
            {
                sw.WriteLine(message + ",Error Message: " + ex.Message);
            }
        }

        private static ClientContext MixedAuthRequest(string siteUrl, string userName, string pwd, string domain)
        {
            ClientContext returnContext = null;
            ClientContext spClientContext = null;

            int retryCount = 5; // Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["retryCount"]);   

            for (int i = 0; i <= retryCount; i++)
            {
                try
                {
                    using (spClientContext = new ClientContext(siteUrl))
                    {

                        spClientContext.ExecutingWebRequest += new EventHandler(Ctx_MixedAuthRequest);
                        spClientContext.AuthenticationMode = ClientAuthenticationMode.Default;




                        spClientContext.Credentials = new NetworkCredential(userName, pwd, domain);
                        returnContext = spClientContext;

                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (i == retryCount)
                    {
                        Console.WriteLine("Falied Mixed Auth Context: " + ex.Message);
                        throw;
                    }
                }
            }
            return returnContext;
        }

        private static void Ctx_MixedAuthRequest(object sender, WebRequestEventArgs e)
        {
            //Add the header that tells SharePoint to use Windows authentication.
            e.WebRequestExecutor.RequestHeaders.Add(
            "X-FORMS_BASED_AUTH_ACCEPTED", "f");
        }

        public static ClientContext Auth(string siteURL, string username, string password, string domain)
        {
            ClientContext context = new ClientContext(siteURL);
            Web web = context.Web;


            // for network credentials
            NetworkCredential _myCredentials = new NetworkCredential(username, password, domain);
            context.AuthenticationMode = ClientAuthenticationMode.Default;
            context.Credentials = _myCredentials;
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // .NET 4.0

            //context.Credentials = new SharePointOnlineCredentials(spoUserName, pwd);
            try
            {
                context.Load(web);
                context.ExecuteQuery();
                Console.WriteLine("Authentication Succesful for " + web.Title + " site");
                return context;
            }
            catch (Exception e)
            {
                Console.WriteLine("Authentication failed.");
                return null;
            }
        }

    }

Get All List Items from SharePoint List page wise to handle threshold limit


Below is the common error during development:
The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.
How to handle in client object model?
  • To avoid threshold error, we can use below orderby query.
OrderBy Override='TRUE'>

  • Using Sorting on the returned list
items = items.OrderBy(item => item.FieldValues["FileLeafRef"]).ToList();
  • Implementing the search on the items. Sample below which brings matched document string name on the page
items = items.FindAll(f => f.FieldValues["FileLeafRef"].ToString().ToLower().Contains("".ToLower())).ToList();

  • Complete Method

public static List<ListItem> GetAllListItemsInaList1(ClientContext ctx, string siteurl)

        {

List<ListItem> items = new List<ListItem>();

            ctx.Load(ctx.Web, a => a.Lists);

            ctx.ExecuteQuery();

List list = ctx.Web.Lists.GetByTitle("EngagementDocumentLibrary");

ListItemCollectionPosition position = null;

int rowLimit = 4999;

var camlQuery = new CamlQuery();

            camlQuery.ViewXml = @"<View Scope='RecursiveAll'>

            <Query>

<OrderBy Override='TRUE'><FieldRef Name='ID'/></OrderBy>              

            </Query>

            <ViewFields>

                <FieldRef Name='FileLeafRef'/><FieldRef Name='File_x0020_Type' /><FieldRef Name='FileRef' /><FieldRef Name='Editor' />

            </ViewFields>

            <RowLimit Paged='TRUE'>" + rowLimit + "</RowLimit></View>";

do

            {

ListItemCollection listItems = null;

                camlQuery.ListItemCollectionPosition = position;

                listItems = list.GetItems(camlQuery);

                ctx.Load(listItems);

                ctx.ExecuteQuery();

                position = listItems.ListItemCollectionPosition;

                items.AddRange(listItems.ToList());

            }

while (position != null);

            items = items.OrderBy(item => item.FieldValues["FileLeafRef"]).ToList();

return items;

        }


Check if SharePoint Group Exists Client Object Model


Check if SharePoint Group Exists Client Object Model

Web web = clientContext.Site.RootWeb;
clientContext.ExecuteQuery();
var currentGroups = web.SiteGroups;
clientContext.Load(currentGroups);
clientContext.ExecuteQuery();
bool isGroupExists = false;
if (currentGroups.Count > 0)
{
isGroupExists = currentGroups.OfTypeGroup>().Count(g => g.Title.Equals(“Pass your groupname”, StringComparison.InvariantCultureIgnoreCase)) > 0;


}