Example #1
0
        protected override void ExecuteCmdlet()
        {
            if (Subscription != null)
            {
                // NOTE: Currently only supports List Webhooks
                if (ParameterSpecified(nameof(List)))
                {
                    // Get the list from the currently selected web
                    List list = List.GetList(SelectedWeb);
                    if (list != null)
                    {
                        // Ensure we have list Id (TODO Should be changed in the Core extension method)
                        list.EnsureProperty(l => l.Id);

                        // If the notification Url is specified, override the property of the subscription object
                        if (ParameterSpecified(nameof(NotificationUrl)))
                        {
                            Subscription.Subscription.NotificationUrl = NotificationUrl;
                        }
                        // If the expiration date is specified, override the property of the subscription object
                        if (ParameterSpecified(nameof(ExpirationDate)))
                        {
                            Subscription.Subscription.ExpirationDateTime = ExpirationDate;
                        }

                        // Write the result object (A flag indicating success)
                        WriteObject(list.UpdateWebhookSubscription(Subscription.Subscription));
                    }
                }
                else
                {
                    throw new PSNotImplementedException("This Cmdlet only supports List Webhooks currently");
                }
            }
        }
        private static void ReportContentTypeUsage(Web web, List list, string targetContentTypeId, string targetContentTypeName, string siteColUrl, string CTCFFileName)
        {
            try
            {
                ContentTypeCustomFieldOutput objCTCFOutput3 = new ContentTypeCustomFieldOutput();
                objCTCFOutput3.ComponentName = Constants.ContentTypes;
                objCTCFOutput3.ListId        = list.Id.ToString();
                objCTCFOutput3.ListTitle     = list.Title;
                objCTCFOutput3.ContentTypeOrCustomFieldId   = targetContentTypeId.ToString();
                objCTCFOutput3.ContentTypeOrCustomFieldName = targetContentTypeName;
                objCTCFOutput3.WebUrl         = web.Url;
                objCTCFOutput3.SiteCollection = siteColUrl;

                list.EnsureProperty(l => l.ContentTypesEnabled);

                if (!list.ContentTypesEnabled)
                {
                    return;
                }

                ContentTypeCollection ctCol = list.ContentTypes;
                list.Context.Load(ctCol);
                list.Context.ExecuteQuery();

                foreach (ContentType ct in ctCol)
                {
                    try
                    {
                        string contentTypeId = ct.Id.StringValue;
                        if (contentTypeId.StartsWith(targetContentTypeId, StringComparison.InvariantCultureIgnoreCase))
                        {
                            if (ct.Name.Equals(targetContentTypeName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                Logger.LogSuccessMessage(String.Format("FOUND: Content Type [{2}] on LIST [{0}] of WEB: {1}", list.Title, web.Url, targetContentTypeName), true);
                                FileUtility.WriteCsVintoFile(CTCFFileName, objCTCFOutput3, ref headerContentType);
                            }
                            else
                            {
                                Logger.LogSuccessMessage(String.Format("FOUND: Child Content Type [{3}] of [{2}] on LIST [{0}] of WEB: {1}", list.Title, web.Url, targetContentTypeName, ct.Name), true);
                                FileUtility.WriteCsVintoFile(CTCFFileName, objCTCFOutput3, ref headerContentType);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogErrorMessage(String.Format("ReportContentTypeUsage() failed on a Content Type of LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message), false);
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, web.Url, "ColumnORFieldAndTypeUsageReport", ex.Message, ex.ToString(), "ReportContentTypeUsage()", ex.GetType().ToString(), String.Format("ReportContentTypeUsage() failed on a Content Type of LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("ReportContentTypeUsage() failed for LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message), false);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, web.Url, "ColumnORFieldAndTypeUsageReport", ex.Message, ex.ToString(), "ReportContentTypeUsage()", ex.GetType().ToString(), String.Format("ReportContentTypeUsage() failed for LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message));
            }
        }
Example #3
0
        internal ListItem GetPage(Web web, string listToLoad)
        {
            if (!string.IsNullOrEmpty(this.Library))
            {
                listToLoad = this.Library;
            }

            web.EnsureProperty(w => w.ServerRelativeUrl);
            var listServerRelativeUrl = UrlUtility.Combine(web.ServerRelativeUrl, listToLoad);

            List libraryContainingPage = null;

            if (BaseTransform.GetVersion(web.Context) == SPVersion.SP2010)
            {
                libraryContainingPage = web.GetListByName(listToLoad);
            }
            else
            {
                libraryContainingPage = web.GetList(listServerRelativeUrl);
            }

            if (libraryContainingPage != null)
            {
                CamlQuery query = null;
                if (!string.IsNullOrEmpty(this.name))
                {
                    query = new CamlQuery
                    {
                        ViewXml = string.Format(CAMLQueryByExtensionAndName, this.name)
                    };

                    if (!string.IsNullOrEmpty(this.Folder))
                    {
                        libraryContainingPage.EnsureProperty(p => p.RootFolder);
                        query.FolderServerRelativeUrl = $"{libraryContainingPage.RootFolder.ServerRelativeUrl}/{Folder}";
                    }

                    var page = libraryContainingPage.GetItems(query);
                    web.Context.Load(page);
                    web.Context.ExecuteQueryRetry();

                    if (page.Count >= 1)
                    {
                        // Return the first match
                        return(page[0]);
                    }
                }
            }

            return(null);
        }
Example #4
0
        private List EnsureFreshTestList(ClientContext ctx)
        {
            if (ctx.Web.ListExists(PnPWebhookTestList))
            {
                List toDelete = ctx.Web.Lists.GetByTitle(PnPWebhookTestList);
                toDelete.DeleteObject();
                ctx.ExecuteQueryRetry();
            }

            // Create the test list
            List list = ctx.Web.CreateList(ListTemplateType.GenericList, PnPWebhookTestList, false);

            list.EnsureProperty(l => l.Id);
            return(list);
        }
Example #5
0
        public static bool CanRenderNewExperience(this List list)
        {
            list.EnsureProperty(p => p.BaseTemplate);

            if (list.BaseTemplate == (int)ListTemplateType.DocumentLibrary ||
                list.BaseTemplate == (int)ListTemplateType.PictureLibrary ||
                list.BaseTemplate == (int)ListTemplateType.WebPageLibrary ||
                list.BaseTemplate == (int)ListTemplateType.GenericList)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #6
0
        private static void ReportContentTypeUsage(Web web, List list, string targetContentTypeId, string targetContentTypeName)
        {
            try
            {
                list.EnsureProperty(l => l.ContentTypesEnabled);

                if (!list.ContentTypesEnabled)
                {
                    return;
                }

                ContentTypeCollection ctCol = list.ContentTypes;
                list.Context.Load(ctCol);
                list.Context.ExecuteQuery();

                foreach (ContentType ct in ctCol)
                {
                    try
                    {
                        string contentTypeId = ct.Id.StringValue;
                        if (contentTypeId.StartsWith(targetContentTypeId, StringComparison.InvariantCultureIgnoreCase))
                        {
                            if (ct.Name.Equals(targetContentTypeName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                Logger.LogSuccessMessage(String.Format("FOUND: Content Type [{2}] on LIST [{0}] of WEB: {1}", list.Title, web.Url, targetContentTypeName), true);
                            }
                            else
                            {
                                Logger.LogSuccessMessage(String.Format("FOUND: Child Content Type [{3}] of [{2}] on LIST [{0}] of WEB: {1}", list.Title, web.Url, targetContentTypeName, ct.Name), true);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogErrorMessage(String.Format("ReportContentTypeUsage() failed on a Content Type of LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message), false);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("ReportContentTypeUsage() failed for LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message), false);
            }
        }
        /// <summary>
        /// Add indexed columns to a list.
        /// </summary>
        /// <param name="sourceWeb">Web where the list exists.</param>
        /// <param name="list">List to add indexed columns to.</param>
        /// <param name="indexedColumns">XML configuration for indexed columns to add.</param>
        /// <param name="tokenParser"></param>
        private static void AddIndexedColumnsToList(Web sourceWeb, List list, IEnumerable <XElement> indexedColumns, TokenParser tokenParser)
        {
            list.EnsureProperty(i => i.Fields);

            foreach (var indexedColumn in indexedColumns)
            {
                var name = indexedColumn.GetAttributeValue(tokenParser, "Name");

                var field = list.Fields.Where(i => i.InternalName.Equals(name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (field != null)
                {
                    field.Indexed = true;
                    field.Update();
                }
            }

            list.Update();
            sourceWeb.Context.ExecuteQuery();
        }
        protected override void ExecuteCmdlet()
        {
            // NOTE: Currently only supports List Webhooks
            if (MyInvocation.BoundParameters.ContainsKey("List"))
            {
                // Get the list from the currently selected web
                List list = List.GetList(SelectedWeb);
                if (list != null)
                {
                    // Ensure we have list Id (TODO Should be changed in the Core extension method)
                    list.EnsureProperty(l => l.Id);

                    // Get all the webhook subscriptions for the specified list
                    WriteObject(list.GetWebhookSubscriptions());
                }
            }
            else
            {
                throw new PSNotImplementedException("This Cmdlet only supports List Webhooks currently");
            }
        }
        protected override void ExecuteCmdlet()
        {
            // NOTE: Currently only supports List Webhooks
            if (ParameterSpecified(nameof(List)))
            {
                // Get the list from the currently selected web
                List list = List.GetList(CurrentWeb);
                if (list != null)
                {
                    // Ensure we have list Id (TODO Should be changed in the Core extension method)
                    list.EnsureProperty(l => l.Id);

                    // Write the subscription result object
                    WriteObject(list.AddWebhookSubscription(NotificationUrl, ExpirationDate, ClientState));
                }
            }
            else
            {
                throw new PSNotImplementedException("This Cmdlet only supports List Webhooks currently");
            }
        }
        /// <summary>
        /// Adds content types to a given list.
        /// </summary>
        /// <param name="sourceWeb">Web where the content types exist.</param>
        /// <param name="list">List to update.</param>
        /// <param name="contentTypeBindings">XML content type configuration.</param>
        /// <param name="tokenParser"></param>
        /// <param name="removeExistingContentTypes">Whether to remove existing content types on the list.</param>
        private static void AddContentTypesToList(Web sourceWeb, List list, IEnumerable <XElement> contentTypeBindings, TokenParser tokenParser, bool removeExistingContentTypes)
        {
            list.EnsureProperty(i => i.ContentTypes);
            var existingContentTypes = list.ContentTypes.Select(i => i.Name).ToList();

            foreach (var contentTypeBinding in contentTypeBindings)
            {
                var contentTypeId = contentTypeBinding.GetAttributeValue(tokenParser, "ContentTypeID");
                var isDefault     = bool.Parse(contentTypeBinding.GetAttributeValue(tokenParser, "Default"));

                var contentType = sourceWeb.GetContentTypeById(contentTypeId);

                list.AddContentTypeToList(contentType, isDefault);
            }

            if (removeExistingContentTypes)
            {
                foreach (var contentType in existingContentTypes)
                {
                    list.RemoveContentTypeByName(contentType);
                }
            }
        }
Example #11
0
        public static bool CanRenderNewExperience(this List list)
        {
            list.EnsureProperty(p => p.BaseTemplate);

            if (list.BaseTemplate == (int)ListTemplateType.Announcements ||
                list.BaseTemplate == (int)ListTemplateType.Links ||
                list.BaseTemplate == (int)ListTemplateType.DocumentLibrary ||
                list.BaseTemplate == (int)ListTemplateType.PictureLibrary ||
                list.BaseTemplate == (int)ListTemplateType.WebPageLibrary ||
                list.BaseTemplate == (int)ListTemplateType.Announcements ||
                list.BaseTemplate == (int)ListTemplateType.Links ||
                list.BaseTemplate == 851 || // Assets
                list.BaseTemplate == 170 || // Promoted Links
                list.BaseTemplate == (int)ListTemplateType.XMLForm ||
                list.BaseTemplate == (int)ListTemplateType.GenericList)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        private static void ReportContentTypeUsage(Web web, List list, string targetContentTypeId, string targetContentTypeName, string siteColUrl, string CTCFFileName)
        {
            try
            {
                ContentTypeCustomFieldOutput objCTCFOutput3 = new ContentTypeCustomFieldOutput();
                objCTCFOutput3.ComponentName = Constants.ContentTypes;
                objCTCFOutput3.ListId = list.Id.ToString();
                objCTCFOutput3.ListTitle = list.Title;
                objCTCFOutput3.ContentTypeOrCustomFieldId = targetContentTypeId.ToString();
                objCTCFOutput3.ContentTypeOrCustomFieldName = targetContentTypeName;
                objCTCFOutput3.WebUrl = web.Url;
                objCTCFOutput3.SiteCollection = siteColUrl;

                list.EnsureProperty(l => l.ContentTypesEnabled);

                if (!list.ContentTypesEnabled)
                {
                    return;
                }

                ContentTypeCollection ctCol = list.ContentTypes;
                list.Context.Load(ctCol);
                list.Context.ExecuteQuery();

                foreach (ContentType ct in ctCol)
                {
                    try
                    {

                        string contentTypeId = ct.Id.StringValue;
                        if (contentTypeId.StartsWith(targetContentTypeId, StringComparison.InvariantCultureIgnoreCase))
                        {
                            if (ct.Name.Equals(targetContentTypeName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                Logger.LogSuccessMessage(String.Format("FOUND: Content Type [{2}] on LIST [{0}] of WEB: {1}", list.Title, web.Url, targetContentTypeName), true);
                                FileUtility.WriteCsVintoFile(CTCFFileName, objCTCFOutput3, ref headerContentType);
                            }
                            else
                            {
                                Logger.LogSuccessMessage(String.Format("FOUND: Child Content Type [{3}] of [{2}] on LIST [{0}] of WEB: {1}", list.Title, web.Url, targetContentTypeName, ct.Name), true);
                                FileUtility.WriteCsVintoFile(CTCFFileName, objCTCFOutput3, ref headerContentType);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogErrorMessage(String.Format("ReportContentTypeUsage() failed on a Content Type of LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message), false);
                        ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, web.Url, "ColumnORFieldAndTypeUsageReport", ex.Message, ex.ToString(), "ReportContentTypeUsage()", ex.GetType().ToString(), String.Format("ReportContentTypeUsage() failed on a Content Type of LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(String.Format("ReportContentTypeUsage() failed for LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message), false);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, web.Url, "ColumnORFieldAndTypeUsageReport", ex.Message, ex.ToString(), "ReportContentTypeUsage()", ex.GetType().ToString(), String.Format("ReportContentTypeUsage() failed for LIST [{0}] of WEB {1}: Error={2}", list.Title, web.Url, ex.Message));
            }
        }
        protected override void ExecuteCmdlet()
        {
            List list = null;

            if (List != null)
            {
                list = List.GetList(SelectedWeb);
            }
            if (list != null)
            {
                ListItemCreationInformation liCI = new ListItemCreationInformation();
                if (Folder != null)
                {
                    // Create the folder if it doesn't exist
                    var rootFolder   = list.EnsureProperty(l => l.RootFolder);
                    var targetFolder =
                        SelectedWeb.EnsureFolder(rootFolder, Folder);

                    liCI.FolderUrl = targetFolder.ServerRelativeUrl;
                }
                var item = list.AddItem(liCI);

                if (ContentType != null)
                {
                    ContentType ct = null;
                    if (ContentType.ContentType == null)
                    {
                        if (ContentType.Id != null)
                        {
                            ct = SelectedWeb.GetContentTypeById(ContentType.Id, true);
                        }
                        else if (ContentType.Name != null)
                        {
                            ct = SelectedWeb.GetContentTypeByName(ContentType.Name, true);
                        }
                    }
                    else
                    {
                        ct = ContentType.ContentType;
                    }
                    if (ct != null)
                    {
                        ct.EnsureProperty(w => w.StringId);

                        item["ContentTypeId"] = ct.StringId;
                        item.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                }

                if (Values != null)
                {
                    item = ListItemHelper.UpdateListItem(item, Values, ListItemUpdateType.Update,
                                                         (warning) =>
                    {
                        WriteWarning(warning);
                    },
                                                         (terminatingErrorMessage, terminatingErrorCode) =>
                    {
                        ThrowTerminatingError(new ErrorRecord(new Exception(terminatingErrorMessage), terminatingErrorCode, ErrorCategory.InvalidData, this));
                    });
                }

                if (!String.IsNullOrEmpty(Label))
                {
                    IList <Microsoft.SharePoint.Client.CompliancePolicy.ComplianceTag> tags = Microsoft.SharePoint.Client.CompliancePolicy.SPPolicyStoreProxy.GetAvailableTagsForSite(ClientContext, ClientContext.Url);
                    ClientContext.ExecuteQueryRetry();

                    var tag = tags.Where(t => t.TagName == Label).FirstOrDefault();

                    if (tag != null)
                    {
                        item.SetComplianceTag(tag.TagName, tag.BlockDelete, tag.BlockEdit, tag.IsEventTag, tag.SuperLock);
                    }
                    else
                    {
                        WriteWarning("Can not find compliance tag with value: " + Label);
                    }
                }

                item.Update();
                ClientContext.Load(item);
                ClientContext.ExecuteQueryRetry();
                WriteObject(item);
            }
        }
Example #14
0
        protected override void ExecuteCmdlet()
        {
            List list = null;

            if (List != null)
            {
                list = List.GetList(SelectedWeb);
            }
            if (list != null)
            {
                ListItemCreationInformation liCI = new ListItemCreationInformation();
                if (Folder != null)
                {
                    // Create the folder if it doesn't exist
                    var rootFolder   = list.EnsureProperty(l => l.RootFolder);
                    var targetFolder =
                        SelectedWeb.EnsureFolder(rootFolder, Folder);

                    liCI.FolderUrl = targetFolder.ServerRelativeUrl;
                }
                var item = list.AddItem(liCI);

                if (ContentType != null)
                {
                    ContentType ct = null;
                    if (ContentType.ContentType == null)
                    {
                        if (ContentType.Id != null)
                        {
                            ct = SelectedWeb.GetContentTypeById(ContentType.Id, true);
                        }
                        else if (ContentType.Name != null)
                        {
                            ct = SelectedWeb.GetContentTypeByName(ContentType.Name, true);
                        }
                    }
                    else
                    {
                        ct = ContentType.ContentType;
                    }
                    if (ct != null)
                    {
                        ct.EnsureProperty(w => w.StringId);

                        item["ContentTypeId"] = ct.StringId;
                        item.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                }

                if (Values != null)
                {
                    Hashtable values = Values ?? new Hashtable();
                    // Load all list fields and their types
                    var fields = ClientContext.LoadQuery(list.Fields.Include(f => f.Id, f => f.InternalName, f => f.Title, f => f.TypeAsString));
                    ClientContext.ExecuteQueryRetry();

                    foreach (var key in values.Keys)
                    {
                        var field = fields.FirstOrDefault(f => f.InternalName == key as string || f.Title == key as string);
                        if (field != null)
                        {
                            switch (field.TypeAsString)
                            {
                            case "User":
                            case "UserMulti":
                            {
                                var userValues = new List <FieldUserValue>();

                                var value = values[key];
                                if (value.GetType().IsArray)
                                {
                                    foreach (var arrayItem in value as object[])
                                    {
                                        int userId;
                                        if (!int.TryParse(arrayItem as string, out userId))
                                        {
                                            var user = SelectedWeb.EnsureUser(arrayItem as string);
                                            ClientContext.Load(user);
                                            ClientContext.ExecuteQueryRetry();
                                            userValues.Add(new FieldUserValue()
                                                {
                                                    LookupId = user.Id
                                                });
                                        }
                                        else
                                        {
                                            userValues.Add(new FieldUserValue()
                                                {
                                                    LookupId = userId
                                                });
                                        }
                                    }
                                    item[key as string] = userValues.ToArray();
                                }
                                else
                                {
                                    int userId;
                                    if (!int.TryParse(value as string, out userId))
                                    {
                                        var user = SelectedWeb.EnsureUser(value as string);
                                        ClientContext.Load(user);
                                        ClientContext.ExecuteQueryRetry();
                                        item[key as string] = new FieldUserValue()
                                        {
                                            LookupId = user.Id
                                        };
                                    }
                                    else
                                    {
                                        item[key as string] = new FieldUserValue()
                                        {
                                            LookupId = userId
                                        };
                                    }
                                }
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }

                            case "TaxonomyFieldType":
                            case "TaxonomyFieldTypeMulti":
                            {
                                var value = values[key];
                                if (value.GetType().IsArray)
                                {
                                    var taxSession = ClientContext.Site.GetTaxonomySession();
                                    var terms      = new List <KeyValuePair <Guid, string> >();
                                    foreach (var arrayItem in value as object[])
                                    {
                                        TaxonomyItem taxonomyItem;
                                        Guid         termGuid = Guid.Empty;
                                        if (!Guid.TryParse(arrayItem as string, out termGuid))
                                        {
                                            // Assume it's a TermPath
                                            taxonomyItem = ClientContext.Site.GetTaxonomyItemByPath(arrayItem as string);
                                        }
                                        else
                                        {
                                            taxonomyItem = taxSession.GetTerm(termGuid);
                                            ClientContext.Load(taxonomyItem);
                                            ClientContext.ExecuteQueryRetry();
                                        }



                                        terms.Add(new KeyValuePair <Guid, string>(taxonomyItem.Id, taxonomyItem.Name));
                                    }

                                    TaxonomyField taxField = ClientContext.CastTo <TaxonomyField>(field);

                                    taxField.EnsureProperty(tf => tf.AllowMultipleValues);

                                    if (taxField.AllowMultipleValues)
                                    {
                                        var termValuesString = String.Empty;
                                        foreach (var term in terms)
                                        {
                                            termValuesString += "-1;#" + term.Value + "|" + term.Key.ToString("D") + ";#";
                                        }

                                        termValuesString = termValuesString.Substring(0, termValuesString.Length - 2);

                                        var newTaxFieldValue = new TaxonomyFieldValueCollection(ClientContext, termValuesString, taxField);
                                        taxField.SetFieldValueByValueCollection(item, newTaxFieldValue);
#if !ONPREMISES
                                        item.SystemUpdate();
#else
                                        item.Update();
#endif
                                        ClientContext.ExecuteQueryRetry();
                                    }
                                    else
                                    {
                                        WriteWarning($@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}""");
                                    }
                                }
                                else
                                {
                                    Guid termGuid = Guid.Empty;
                                    if (!Guid.TryParse(value as string, out termGuid))
                                    {
                                        // Assume it's a TermPath
                                        var taxonomyItem = ClientContext.Site.GetTaxonomyItemByPath(value as string);
                                        termGuid = taxonomyItem.Id;
                                    }
                                    item[key as string] = termGuid.ToString();
                                }
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }

                            case "Lookup":
                            case "LookupMulti":
                            {
                                int[] multiValue;
                                if (values[key] is Array)
                                {
                                    var arr = (object[])values[key];
                                    multiValue = new int[arr.Length];
                                    for (int i = 0; i < arr.Length; i++)
                                    {
                                        multiValue[i] = int.Parse(arr[i].ToString());
                                    }
                                }
                                else
                                {
                                    string valStr = values[key].ToString();
                                    multiValue = valStr.Split(',', ';').Select(int.Parse).ToArray();
                                }

                                var newVals = multiValue.Select(id => new FieldLookupValue {
                                        LookupId = id
                                    }).ToArray();

                                FieldLookup lookupField = ClientContext.CastTo <FieldLookup>(field);
                                lookupField.EnsureProperty(lf => lf.AllowMultipleValues);
                                if (!lookupField.AllowMultipleValues && newVals.Length > 1)
                                {
                                    WriteWarning($@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}""");
                                }

                                item[key as string] = newVals;
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }

                            default:
                            {
                                item[key as string] = values[key];
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }
                            }
                        }
                        else
                        {
                            ThrowTerminatingError(new ErrorRecord(new Exception("Field not present in list"), "FIELDNOTINLIST", ErrorCategory.InvalidData, key));
                        }
                    }
                }

                item.Update();
                ClientContext.Load(item);
                ClientContext.ExecuteQueryRetry();
                WriteObject(item);
            }
        }
Example #15
0
        protected override void ExecuteCmdlet()
        {
            List list = null;

            if (List != null)
            {
                list = List.GetList(SelectedWeb);
            }
            if (list != null)
            {
                ListItemCreationInformation liCI = new ListItemCreationInformation();
                if (Folder != null)
                {
                    // Create the folder if it doesn't exist
                    var rootFolder   = list.EnsureProperty(l => l.RootFolder);
                    var targetFolder =
                        SelectedWeb.EnsureFolder(rootFolder, Folder);

                    liCI.FolderUrl = targetFolder.ServerRelativeUrl;
                }
                var item = list.AddItem(liCI);

                if (ContentType != null)
                {
                    ContentType ct = null;
                    if (ContentType.ContentType == null)
                    {
                        if (ContentType.Id != null)
                        {
                            ct = SelectedWeb.GetContentTypeById(ContentType.Id, true);
                        }
                        else if (ContentType.Name != null)
                        {
                            ct = SelectedWeb.GetContentTypeByName(ContentType.Name, true);
                        }
                    }
                    else
                    {
                        ct = ContentType.ContentType;
                    }
                    if (ct != null)
                    {
                        ct.EnsureProperty(w => w.StringId);

                        item["ContentTypeId"] = ct.StringId;
                        item.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                }

                if (Values != null)
                {
                    item = ListItemHelper.UpdateListItem(item, Values, false,
                                                         (warning) =>
                    {
                        WriteWarning(warning);
                    },
                                                         (terminatingErrorMessage, terminatingErrorCode) =>
                    {
                        ThrowTerminatingError(new ErrorRecord(new Exception(terminatingErrorMessage), terminatingErrorCode, ErrorCategory.InvalidData, this));
                    });
                }

                item.Update();
                ClientContext.Load(item);
                ClientContext.ExecuteQueryRetry();
                WriteObject(item);
            }
        }
Example #16
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSpecified(nameof(Batch)))
            {
                var list = List.GetList(Batch);
                list.EnsureProperties(l => l.Id, l => l.Fields.LoadProperties(f => f.Id, f => f.Title, f => f.InternalName, f => f.TypeAsString));

                var values = ListItemHelper.GetFieldValues(list, null, Values, ClientContext);
                if (ContentType != null)
                {
                    var contentType = ContentType.GetContentType(Batch, list);
                    values.Add("ContentTypeId", contentType.StringId);
                }
                list.Items.AddBatch(Batch.Batch, values, Folder);
            }
            else
            {
                List list = List.GetList(CurrentWeb);
                ListItemCreationInformation liCI = new ListItemCreationInformation();
                if (Folder != null)
                {
                    // Create the folder if it doesn't exist
                    var rootFolder   = list.EnsureProperty(l => l.RootFolder);
                    var targetFolder =
                        CurrentWeb.EnsureFolder(rootFolder, Folder);

                    liCI.FolderUrl = targetFolder.ServerRelativeUrl;
                }
                var item = list.AddItem(liCI);

                bool systemUpdate = false;
                if (ContentType != null)
                {
                    var ct = ContentType.GetContentType(list);

                    if (ct != null)
                    {
                        item["ContentTypeId"] = ct.EnsureProperty(w => w.StringId);
                        item.Update();
                        systemUpdate = true;
                        ClientContext.ExecuteQueryRetry();
                    }
                }

                if (Values?.Count > 0)
                {
                    ListItemHelper.SetFieldValues(item, Values, this);
                }

                if (!String.IsNullOrEmpty(Label))
                {
                    IList <Microsoft.SharePoint.Client.CompliancePolicy.ComplianceTag> tags = Microsoft.SharePoint.Client.CompliancePolicy.SPPolicyStoreProxy.GetAvailableTagsForSite(ClientContext, ClientContext.Url);
                    ClientContext.ExecuteQueryRetry();

                    var tag = tags.Where(t => t.TagName == Label).FirstOrDefault();

                    if (tag != null)
                    {
                        item.SetComplianceTag(tag.TagName, tag.BlockDelete, tag.BlockEdit, tag.IsEventTag, tag.SuperLock);
                    }
                    else
                    {
                        WriteWarning("Can not find compliance tag with value: " + Label);
                    }
                }

                if (systemUpdate)
                {
                    item.SystemUpdate();
                }
                else
                {
                    item.Update();
                }
                ClientContext.Load(item);
                ClientContext.ExecuteQueryRetry();
                WriteObject(item);
            }
        }
Example #17
0
        protected override void ExecuteCmdlet()
        {
            List list = null;

            if (List != null)
            {
                list = List.GetList(SelectedWeb);
            }
            if (list != null)
            {
                ListItemCreationInformation liCI = new ListItemCreationInformation();
                if (Folder != null)
                {
                    // Create the folder if it doesn't exist
                    var rootFolder   = list.EnsureProperty(l => l.RootFolder);
                    var targetFolder =
                        SelectedWeb.EnsureFolder(rootFolder, Folder);

                    liCI.FolderUrl = targetFolder.ServerRelativeUrl;
                }
                var item = list.AddItem(liCI);

                if (ContentType != null)
                {
                    ContentType ct = null;
                    if (ContentType.ContentType == null)
                    {
                        if (ContentType.Id != null)
                        {
                            ct = SelectedWeb.GetContentTypeById(ContentType.Id, true);
                        }
                        else if (ContentType.Name != null)
                        {
                            ct = SelectedWeb.GetContentTypeByName(ContentType.Name, true);
                        }
                    }
                    else
                    {
                        ct = ContentType.ContentType;
                    }
                    if (ct != null)
                    {
                        ct.EnsureProperty(w => w.StringId);

                        item["ContentTypeId"] = ct.StringId;
                        item.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                }

                if (Values != null)
                {
                    // Load all list fields and their types
                    var fields = ClientContext.LoadQuery(list.Fields.Include(f => f.InternalName, f => f.Title, f => f.FieldTypeKind));
                    ClientContext.ExecuteQueryRetry();

                    foreach (var key in Values.Keys)
                    {
                        var field = fields.FirstOrDefault(f => f.InternalName == key as string || f.Title == key as string);
                        if (field != null)
                        {
                            switch (field.FieldTypeKind)
                            {
                            case FieldType.User:
                            {
                                var userValues = new List <FieldUserValue>();

                                var value = Values[key];
                                if (value.GetType().IsArray)
                                {
                                    foreach (var arrayItem in value as object[])
                                    {
                                        int userId;
                                        if (!int.TryParse(arrayItem as string, out userId))
                                        {
                                            var user = SelectedWeb.EnsureUser(arrayItem as string);
                                            ClientContext.Load(user);
                                            ClientContext.ExecuteQueryRetry();
                                            userValues.Add(new FieldUserValue()
                                                {
                                                    LookupId = user.Id
                                                });
                                        }
                                        else
                                        {
                                            userValues.Add(new FieldUserValue()
                                                {
                                                    LookupId = userId
                                                });
                                        }
                                    }
                                    item[key as string] = userValues.ToArray();
                                }
                                else
                                {
                                    int userId;
                                    if (!int.TryParse(value as string, out userId))
                                    {
                                        var user = SelectedWeb.EnsureUser(value as string);
                                        ClientContext.Load(user);
                                        ClientContext.ExecuteQueryRetry();
                                        item[key as string] = new FieldUserValue()
                                        {
                                            LookupId = user.Id
                                        };
                                    }
                                    else
                                    {
                                        item[key as string] = new FieldUserValue()
                                        {
                                            LookupId = userId
                                        };
                                    }
                                }
                                break;
                            }

                            default:
                            {
                                item[key as string] = Values[key];
                                break;
                            }
                            }
                        }
                        else
                        {
                            throw new Exception("Field not present in list");
                        }
                    }
                }

                item.Update();
                ClientContext.Load(item);
                ClientContext.ExecuteQueryRetry();
                WriteObject(item);
            }
        }
        private static ListInstance ExtractUserCustomActions(Web web, List siteList, ListInstance list, ProvisioningTemplateCreationInformation creationInfo, ProvisioningTemplate template)
        {
            foreach (var userCustomAction in siteList.UserCustomActions.AsEnumerable())
            {
                web.Context.Load(userCustomAction);
                web.Context.ExecuteQueryRetry();

                var customAction = new CustomAction
                {
                    Title = userCustomAction.Title,
                    Description = userCustomAction.Description,
                    Enabled = true,
                    Name = userCustomAction.Name,
                    //RegistrationType = userCustomAction.RegistrationType,
                    //RegistrationId = userCustomAction.RegistrationId,
                    Url = userCustomAction.Url,
                    ImageUrl = userCustomAction.ImageUrl,
                    Rights = userCustomAction.Rights,
                    Sequence = userCustomAction.Sequence,
                    ScriptBlock = userCustomAction.ScriptBlock,
                    ScriptSrc = userCustomAction.ScriptSrc,
                    CommandUIExtension = !System.String.IsNullOrEmpty(userCustomAction.CommandUIExtension) ?
                        XElement.Parse(userCustomAction.CommandUIExtension) : null,
                    Group = userCustomAction.Group,
                    Location = userCustomAction.Location,
                };

            #if !ONPREMISES
                if (creationInfo.PersistMultiLanguageResources)
                {
                    siteList.EnsureProperty(l => l.Title);
                    var listKey = siteList.Title.Replace(" ", "_");
                    var resourceKey = userCustomAction.Name.Replace(" ", "_");

                    if (UserResourceExtensions.PersistResourceValue(userCustomAction.TitleResource, string.Format("List_{0}_CustomAction_{1}_Title", listKey, resourceKey), template, creationInfo))
                    {
                        var customActionTitle = string.Format("{{res:List_{0}_CustomAction_{1}_Title}}", listKey, resourceKey);
                        customAction.Title = customActionTitle;

                    }
                    if (UserResourceExtensions.PersistResourceValue(userCustomAction.DescriptionResource, string.Format("List_{0}_CustomAction_{1}_Description", listKey, resourceKey), template, creationInfo))
                    {
                        var customActionDescription = string.Format("{{res:List_{0}_CustomAction_{1}_Description}}", listKey, resourceKey);
                        customAction.Description = customActionDescription;
                    }
                }
            #endif

                list.UserCustomActions.Add(customAction);
            }

            return list;
        }
Example #19
0
        internal ListItem GetPage(Web web, string listToLoad)
        {
            bool loadViaId = false;
            int  idToLoad  = -1;

            // Check what we got via the pagepipebind constructor and prep for getting the page
            if (!string.IsNullOrEmpty(this.name))
            {
                if (int.TryParse(this.Name, out int pageId))
                {
                    idToLoad  = pageId;
                    loadViaId = true;
                }
                else
                {
                    if (!this.BlogPage && !this.DelveBlogPage)
                    {
                        this.name = ClientSidePageUtilities.EnsureCorrectPageName(this.name);
                    }
                    this.pageListItem = null;
                }
            }
            else if (this.pageListItem != null)
            {
                if (this.pageListItem != null)
                {
                    if (this.BlogPage || this.DelveBlogPage)
                    {
                        this.name = this.pageListItem.FieldValues["Title"].ToString();
                    }
                    else
                    {
                        this.name = this.pageListItem.FieldValues["FileLeafRef"].ToString();
                    }
                }
            }

            if (!string.IsNullOrEmpty(this.Library))
            {
                listToLoad = this.Library;
            }

            // Blogs live in a list, not in a library
            if (this.BlogPage && !listToLoad.StartsWith("lists/", StringComparison.InvariantCultureIgnoreCase))
            {
                listToLoad = $"lists/{listToLoad}";
            }

            web.EnsureProperty(w => w.ServerRelativeUrl);
            var listServerRelativeUrl = UrlUtility.Combine(web.ServerRelativeUrl, listToLoad);

            List libraryContainingPage = null;

#if !NETSTANDARD2_1
            if (BaseTransform.GetVersion(web.Context) == SPVersion.SP2010)
            {
                libraryContainingPage = web.GetListByName(listToLoad);
            }
            else
            {
                libraryContainingPage = web.GetList(listServerRelativeUrl);
            }
#else
            libraryContainingPage = web.GetList(listServerRelativeUrl);
#endif

            if (libraryContainingPage != null)
            {
                if (loadViaId)
                {
                    var page = libraryContainingPage.GetItemById(idToLoad);
                    web.Context.Load(page);
                    web.Context.ExecuteQueryRetry();
                    return(page);
                }
                else
                {
                    CamlQuery query = null;
                    if (!string.IsNullOrEmpty(this.name))
                    {
                        if (this.BlogPage || this.DelveBlogPage)
                        {
                            query = new CamlQuery
                            {
                                ViewXml = string.Format(CAMLQueryForBlogByTitle, System.Text.Encodings.Web.HtmlEncoder.Default.Encode(this.name))
                            };
                        }
                        else
                        {
                            query = new CamlQuery
                            {
                                ViewXml = string.Format(CAMLQueryByExtensionAndName, System.Text.Encodings.Web.HtmlEncoder.Default.Encode(this.name))
                            };
                        }

                        if (!string.IsNullOrEmpty(this.Folder))
                        {
                            libraryContainingPage.EnsureProperty(p => p.RootFolder);
                            query.FolderServerRelativeUrl = $"{libraryContainingPage.RootFolder.ServerRelativeUrl}/{Folder}";
                        }

                        var page = libraryContainingPage.GetItems(query);
                        web.Context.Load(page);
                        web.Context.ExecuteQueryRetry();

                        if (page.Count >= 1)
                        {
                            // Return the first match
                            return(page[0]);
                        }
                    }
                }
            }

            return(null);
        }