Thursday, June 25, 2020

Get all Lists and Guid using powershell

Try{
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'
}
catch {
}
$siteUrl = "https://SiteCollectionURL"
$username = "rb@pop.onmicrosoft.com"
$password=ConvertTo-SecureString "*********" -AsPlainText -Force
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$ctx.Credentials = $credentials
$web = $ctx.Web
$lists = $web.Lists
$ctx.Load($lists)
$ctx.ExecuteQuery()
$lists| select -Property Title, ID

Monday, June 8, 2020

Get Attached Remote Event Receiver and Delete Event Receiver with Powershell

function Get-SPOListEventreceivers
{
param (
[Parameter(Mandatory=$true,Position=1)]
[string]$Username,
[Parameter(Mandatory=$true,Position=2)]
$AdminPassword,
[Parameter(Mandatory=$true,Position=3)]
[string]$Url,
[Parameter(Mandatory=$true,Position=4)]
[string]$ListName,
[Parameter(Mandatory=$true,Position=5)]
[string]$EventReceiverId
)

$ctx=New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $AdminPassword)

try{
$ctx.ExecuteQuery()
}
catch [Net.WebException] {           
Write-Host $Url " failed to connect to the site" $_.Exception.Message.ToString() -ForegroundColor Red
}

#$ctx.Load($ctx.Site)
#$ctx.Load($ctx.Web.Lists)
$list = $ctx.Web.Lists.GetByTitle($ListName)
    $ctx.Load($list)
$ctx.ExecuteQuery()

$recevery=$list.EventReceivers
$ctx.Load($recevery)
$ctx.ExecuteQuery()

#$eventReceivers = $recevery | Where 
    #{ 
     #   $_.Id - eq $EventReceiverId
    #} 
    #if ($eventReceivers) 
    #{ 
     #   foreach($receiver in $eventReceivers) 
      #  { 
       #     Write - Host "Deleting Event Receiver from " 
        #    $List.RootFolder.ServerRelativeUrl - ForegroundColor Yellow 
         #   $receiver.Delete() 
          #  Write - Host Deleted event receiver successfully. - ForegroundColor Green 
        #}
#$ctx.ExecuteQuery()
    #} 
    #else 
    #{ 
        #Write - Host No Event Receivers on List with id $EventReceiverId present - ForegroundColor Yellow 
    #}

Write-Host $recevery.Count $list.Title
for($i=0;$i -lt $recevery.Count ; $i++)
{
$ctx.Load($recevery[$i])
$ctx.ExecuteQuery()
Write-Output $recevery[$i].ReceiverId
  if ($recevery[$i].ReceiverId -eq "17668f58-fad6-4af5-bdfc-8a190a74737d")
      {  
         $recevery[$i].DeleteObject()
         Write-Host "Event receiver " $recevery[$i].ReceiverUrl " is deleted"
      }
  Write-Output $recevery[$i]

$ctx.ExecuteQuery()
}

# Paths to SDK. Please verify location on your computer.
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"

# Insert the credentials and the name of the admin site
$Username="useremail@rbeerla.onmicrosoft.com"
$AdminPassword=Read-Host -Prompt "Password" -AsSecureString
$Url="https://domain.sharepoint.com/sites/sitecollectionname"
$ListName = "ListName"
$EventReceiverId = "ef3db358-e12c-452b-ba1b-a8a658185125"

#Get-SPOListEventreceivers -Username $Username -AdminPassword $AdminPassword -Url $Url $ProcessOneWayLIst $ef3db358-e12c-452b-ba1b-a8a658185125
Get-SPOListEventreceivers -Username $Username -AdminPassword $AdminPassword -Url $Url -ListName $ListName -EventReceiverId $EventReceiverId

Sunday, June 7, 2020

Update Taxonomy in SharePoint Online using CSOM

    public static void UpdateTaxonomy(ClientContext ctx, string url)
    {
        List list = ctx.Web.Lists.GetByTitle("SampleLibrary");
        var fields = list.Fields;
        var field = fields.GetByInternalNameOrTitle("Taxonomy");
        CamlQuery query = new CamlQuery();
        query.ViewXml = "@<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>1</Value></Eq></Where></Query></View>";
        var listItems = list.GetItems(query);
        ctx.Load(list);
        ctx.Load(listItems);
        ctx.Load(fields);
        ctx.Load(field);
        ctx.ExecuteQuery();
        if (listItems.Count != 1)
        {
            return;
        }
        var item = listItems[0];
        var txField = ctx.CastTo<TaxonomyField>(field);
        var tags = new string[] { "Test1" };
        var tagsString = EnsureTerms(tags, url, list.Id, "Taxonomy", ctx);
        string[] term = tagsString.Split('|');
        string[] termLabel = term[0].Split('#');
        var termValue = new TaxonomyFieldValue();
        termValue.Label = termLabel[1];
        termValue.TermGuid = term[1];
        termValue.WssId = -1;
        txField.SetFieldValueByValue(item, termValue);
        txField.Update();
        item["FileName"] = "Ramesh Beerla";
        item.Update();
        ctx.Load(item);
        ctx.ExecuteQuery();
    }
 
    private static string EnsureTerms(string[] termStrings, string targetUrl, Guid listId, string fieldName, ClientContext clientContext)
    {
        try
        {
            //Get the List Object
            var list = clientContext.Web.Lists.GetById(listId);
            var field = list.Fields.GetByInternalNameOrTitle(fieldName);

            //Get the Taxonomy Field
            var taxKeywordField = list.Context.CastTo<TaxonomyField>(field);
            clientContext.Load(taxKeywordField);
            clientContext.ExecuteQuery();
            clientContext.Load(taxKeywordField, f => f.TermSetId, f => f.SspId);
            clientContext.ExecuteQuery();

            //From the TaxonomyField, get the TermSetID in which we are going to create the Terms.
            var ssspId = taxKeywordField.SspId;
            var termSetId = taxKeywordField.TermSetId;

            //Get the TAxonomy Session
            var taxSession = TaxonomySession.GetTaxonomySession(clientContext);
            clientContext.Load(taxSession);
            clientContext.ExecuteQuery();

            //Get the TermStore
            var termStores = taxSession.TermStores;
            clientContext.LoadQuery(termStores.Where(t => t.Id == ssspId));
            clientContext.Load(termStores);
            clientContext.ExecuteQuery();

            var termStore = termStores.FirstOrDefault(s => s.Id == ssspId);
            clientContext.Load(termStore);
            clientContext.ExecuteQuery();

            //Get the TermSet
            var termSet = termStore.GetTermSet(termSetId);

            var allTerms = new List<Term>();

            Func<string, Term> EnsureTerm = (term) =>
            {
                try
                {
                    var allTermsInTermSet = termSet.GetAllTerms();
                    var results = clientContext.LoadQuery(allTermsInTermSet.Where(k => k.Name == term));
                    clientContext.ExecuteQuery();

                    if (results != null)
                    {
                        var result = results.FirstOrDefault();
                        if (result != null)
                        {
                            clientContext.Load(result, t => t.Name, t => t.Id);
                            clientContext.ExecuteQuery();
                            return result;
                        }
                    }

                    clientContext.Load(termSet);
                    clientContext.ExecuteQuery();
                    var newTerm = termSet.CreateTerm(term, termStore.DefaultLanguage, Guid.NewGuid());
                    termStore.CommitAll();
                    clientContext.Load(newTerm);
                    clientContext.Load(newTerm, t => t.Name, t => t.Id);
                    clientContext.ExecuteQuery();

                    return newTerm;
                }
                catch (Exception ex)
                {
                    if (ex.Message == "The data is not available. The query may not have been executed.")
                    {

                        clientContext.Load(termSet);

                        clientContext.ExecuteQuery();
                        var newTerm = termSet.CreateTerm(term, termStore.DefaultLanguage, Guid.NewGuid());
                        clientContext.Load(newTerm);
                        termStore.CommitAll();
                        clientContext.Load(newTerm);
                        clientContext.ExecuteQuery();
                        clientContext.Load(newTerm, t => t.Name, t => t.Id);
                        clientContext.ExecuteQuery();
                        return newTerm;

                    }
                    else
                    {


                        throw;
                    }
                }
            };

            foreach (string termString in termStrings)
            {
                try
                {
                    Thread.Sleep(1000);
                    if (termString != null)
                    {
                        allTerms.Add(EnsureTerm(termString));
                    }
                }
                catch (Exception)
                {
                    // Log the Exception
                }
            }

            return GetTermsString(allTerms);
        }
        catch (Exception ex)
        {
            //Log the Exception
        }

        return string.Empty;
    }

    public static string GetTermString(Term term)
    {

        if (term == null)
        {
            new ArgumentNullException("term");
        }


        return string.Format("-1;#{0}{1}{2}", term.Name, "|", term.Id);
    }

    public static string GetTermsString(IEnumerable<Term> terms)
    {
        if (terms == null)
        {
            new ArgumentNullException("terms");
        }

        var termsString = terms.Select(GetTermString).ToList();
        return string.Join(";#", termsString);
    }