Search This Blog

Monday, January 25, 2016

Programmatically Start Workflow in SharePoint 2013 using Client Object Model



 public void StartWorkflow()
 {
 try
 {
 ClientContext clientContext = new ClientContext("http://www.xyz.com/sites/ABC");
string listName = "Test";
 List list = clientContext.Web.Lists.GetByTitle(listName);
 clientContext.Load(list);
 clientContext.ExecuteQuery();

 CamlQuery camlQuery = new CamlQuery();
 camlQuery.ViewXml = "<View/>";

 ListItemCollection itemColl = list.GetItems(camlQuery);
 clientContext.Load(itemColl);
 clientContext.ExecuteQuery();

 foreach (ListItem item in itemColl)
 {

 clientContext.Load(item);
 clientContext.ExecuteQuery();


 var workflowServicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);
 // connect to the deployment service
 var workflowDeploymentService = workflowServicesManager.GetWorkflowDeploymentService();

 // connect to the subscription service
 var workflowSubscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();



 // get all installed workflows
 var publishedWorkflowDefinitions = workflowDeploymentService.EnumerateDefinitions(true);
 clientContext.Load(publishedWorkflowDefinitions);
 clientContext.ExecuteQuery();

 // display list of all installed workflows
 /*foreach (var workflowDefinition in publishedWorkflowDefinitions)
 {
 Console.WriteLine("{0} - {1}", workflowDefinition.Id.ToString(), workflowDefinition.DisplayName);
 }*/


 //Guid newGuid = new Guid("92F3EC44-8DDB-4B00-9369-37B07FCD37E2");

 // get all workflow associations
 var workflowAssociations = workflowSubscriptionService.EnumerateSubscriptionsByList(list.Id);

 // This line will is used to get the association by providing the workflow GUID.
 //var workflowAssociations = workflowSubscriptionService.EnumerateSubscriptionsByDefinition(newGuid);

 clientContext.Load(workflowAssociations);
 clientContext.ExecuteQuery();

 // find the first association
 var firstWorkflowAssociation = workflowAssociations.First();
 // connect to the instance service
 var workflowInstanceService = workflowServicesManager.GetWorkflowInstanceService();

 // start the workflow
 var startParameters = new Dictionary<string, object>();
 workflowInstanceService.StartWorkflowOnListItem(firstWorkflowAssociation, item.Id, startParameters);
 clientContext.ExecuteQuery();
 }

 }

 catch (Exception ex)
 {
   Throw ex;
 }
 }

Sunday, January 10, 2016

How to create sharepoint lookup site columns with csv file upload using powershell

Create the CSV file with the following columns and save with the name as you like it









Write the below code in a notepad and save the name as you like it and save the file with extension File1.ps1


Try
{
$create = Import-Csv -path "CsvFilePath"

"Site columns creating please wait..."

ForEach($row in $create) {
$row.SiteCollectionUrl

$web=Get-SPWeb -Identity $row.SiteCollectionUrl
$webID=$web.ID
Write-Host "WebID:" $webID
$list=$web.Lists[$row.ListName]
Write-Host "ListName:" $list
$list
$listID=$list.ID
Write-Host "ListID:" $listID

$fieldType=$row.FieldType
$fieldDisplayName=$row.FieldName
$fieldInternalName=$row.FieldName
$sitecolGroup =$row.GroupName
$showField =$row.LookupColumn
$fieldDescription = $row.Description
$fieldHidden=$row.IsFieldHidden
$fieldReadonly = $row.IsFieldReadOnly
$fieldRequired = $row.IsFieldRequired
$unlimitedLength = $row.IsUnlimitedLength
#End of configuration

$siteCollection = Get-SPWeb -Identity $row.SiteCollectionUrl
$rootWeb = $siteCollection.RootWeb
#Define lookup site column with a XMLString
$lookupXMLString = '<Field Type="' + $fieldType + '" DisplayName="' + $fieldDisplayName + '" Description="' + $fieldDescription + '"
Required="' + $fieldRequired + '" EnforceUniqueValues="FALSE" WebId="' + $webID + '" ShowField="' + $showField + '" UnlimitedLengthInDocumentLibrary="' + $unlimitedLength + '"
Group="' + $sitecolGroup + '" StaticName="' + $fieldInternalName + '" List="' + $listID + '"
Name="' + $fieldInternalName + '" Hidden="' + $fieldHidden + '" ReadOnly="' + $fieldReadonly + '"></Field>'
#Create site column from XML string
$siteCollection.Fields.AddFieldAsXml($lookupXMLString)
Write-Host "The sitecolumn has been added $fieldDisplayName" -foregroundcolor green
}
"Site columns created Successfully"
}
Catch
{
write-host "Exception Message: $($_.Exception.Message)" -foregroundcolor red
}




How to remove site collection in sharepoint 2013 using powershell

param(
[string]$SiteURL
)
Try
{
Remove-SPSite -Identity $SiteURL -Confirm:$false
}
Catch
{
write-host "Exception Message: $($_.Exception.Message)"
}

How to create subsites using powershell

param(
[string]$SiteCollectionURL,
[string]$SiteCollectionTemplate,
[string]$SiteCollectionLanguage,
[string]$SubSites
)
Try
{
$SiteUrl = ""
$SiteUrl = $SiteCollectionURL + "/"
$SiteUrl = $SiteUrl += $SubSites
#Write-Host $SiteUrl
New-SPWeb $SiteUrl -Template $SiteCollectionTemplate -Name $SubSites  -UseParentTopNav -Language $SiteCollectionLanguage -ErrorAction Stop
}
Catch
{
write-host "Exception Message: $($_.Exception.Message)" -foregroundcolor red
}

How to create new site collection using powershell

param
(
[string]$siteURL,
[string]$owner,
[string]$secondOwner,
[string]$template,
[string]$title,
[string]$description
)
try
{
New-SPSite $siteURL -OwnerAlias $owner -SecondaryOwnerAlias $secondOwner -name $title -Template $template -Description $description -ErrorAction Stop
}

Tuesday, January 5, 2016

How to get multi lookup values from SharePoint 2013 list item using LINQ

SPListItemCollection listitemcollection = lstActive.GetItems(query);
var ids = listitemcollection.Cast<SPListItem>().SelectMany(li => new SPFieldLookupValueCollection(Convert.ToString(li["Column1"])).Cast<SPFieldLookupValue>().Select(lv => lv.LookupValue)).ToArray();

Programmatically get multi lookup values from SharePoint 2013 list item

I have a team site in which I have created a custom list named “Test”. In the custom list I have created a Lookup field which allows multiple selections.

I have added a new item with multi lookup values as shown in Figure








using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Microsoft.SharePoint;

namespace MultiLookup
{
    class Program
    {
        static void Main(string[] args)
        {          
            using (SPSite site = new SPSite("http://serverName/sites/TestSite"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("Test");
                    SPListItem item = list.Items[0];
                    SPFieldLookupValueCollection values = new SPFieldLookupValueCollection(item["MultiLookup"].ToString());
                    foreach (SPFieldLookupValue value in values)
                    {
                        Console.WriteLine(value.LookupValue);
                    }
                    Console.ReadLine();
                }
            }
        }
    }
}                      

Output