/// <summary>
        /// Retreive all of the OneDrive for Business profiles
        /// </summary>
        /// <param name="adminSiteContext"></param>
        /// <param name="traceLogger"></param>
        /// <param name="MySiteUrl"></param>
        /// <param name="includeProperties"></param>
        /// <returns></returns>
        public static List <OD4BSiteCollectionModel> GetOneDriveSiteCollections(this ClientContext adminSiteContext, ITraceLogger traceLogger, string MySiteUrl, bool includeProperties = false)
        {
            var results = new List <OD4BSiteCollectionModel>();

            MySiteUrl = MySiteUrl.EnsureTrailingSlashLowered();
            MySiteUrl = MySiteUrl.Substring(0, MySiteUrl.Length - 1);

            using (var _UserProfileService = new UserProfileService(adminSiteContext, adminSiteContext.Url))
            {
                var userProfileResult = _UserProfileService.OWService.GetUserProfileByIndex(-1);
                var userProfilesCount = _UserProfileService.OWService.GetUserProfileCount();
                var rowIndex          = 1;

                // As long as the next User profile is NOT the one we started with (at -1)...
                while (int.TryParse(userProfileResult.NextValue, out int nextValueIndex) && nextValueIndex != -1)
                {
                    if ((rowIndex % 50) == 0 || rowIndex > userProfilesCount)
                    {
                        traceLogger.LogInformation($"Next set {rowIndex} of {userProfilesCount}");
                    }

                    try
                    {
                        var personalSpace    = userProfileResult.RetrieveUserProperty("PersonalSpace");
                        var personalSpaceUrl = $"{MySiteUrl}{personalSpace}";
                        var model            = new OD4BSiteCollectionModel();

                        if (includeProperties == false)
                        {
                            model = new OD4BSiteCollectionModel
                            {
                                PersonalSpaceProperty = personalSpace,
                                Url          = personalSpaceUrl,
                                NameProperty = userProfileResult.RetrieveUserProperty("PreferredName"),
                                UserName     = userProfileResult.RetrieveUserProperty("UserName"),
                                Title        = userProfileResult.RetrieveUserProperty("Title")
                            };
                        }
                        else
                        {
                            model = new OD4BSiteCollectionModel
                            {
                                PersonalSpaceProperty = personalSpace,
                                Url               = personalSpaceUrl,
                                NameProperty      = userProfileResult.RetrieveUserProperty("PreferredName"),
                                UserName          = userProfileResult.RetrieveUserProperty("UserName"),
                                PictureUrl        = userProfileResult.RetrieveUserProperty("PictureURL"),
                                AboutMe           = userProfileResult.RetrieveUserProperty("AboutMe"),
                                SpsSkills         = userProfileResult.RetrieveUserProperty("SPS-Skills"),
                                Manager           = userProfileResult.RetrieveUserProperty("Manager"),
                                WorkPhone         = userProfileResult.RetrieveUserProperty("WorkPhone"),
                                Department        = userProfileResult.RetrieveUserProperty("Department"),
                                Company           = userProfileResult.RetrieveUserProperty("Company"),
                                AccountName       = userProfileResult.RetrieveUserProperty("AccountName"),
                                DistinguishedName = userProfileResult.RetrieveUserProperty("SPS-DistinguishedName"),
                                FirstName         = userProfileResult.RetrieveUserProperty("FirstName"),
                                LastName          = userProfileResult.RetrieveUserProperty("LastName"),
                                UserPrincipalName = userProfileResult.RetrieveUserProperty("SPS-UserPrincipalName"),
                                Title             = userProfileResult.RetrieveUserProperty("Title"),
                                WorkEmail         = userProfileResult.RetrieveUserProperty("WorkEmail"),
                                HomePhone         = userProfileResult.RetrieveUserProperty("HomePhone"),
                                CellPhone         = userProfileResult.RetrieveUserProperty("CellPhone"),
                                Office            = userProfileResult.RetrieveUserProperty("Office"),
                                Location          = userProfileResult.RetrieveUserProperty("SPS-Location"),
                                Fax               = userProfileResult.RetrieveUserProperty("Fax"),
                                MailingAddress    = userProfileResult.RetrieveUserProperty("MailingAddress"),
                                School            = userProfileResult.RetrieveUserProperty("SPS-School"),
                                WebSite           = userProfileResult.RetrieveUserProperty("WebSite"),
                                Education         = userProfileResult.RetrieveUserProperty("Education"),
                                JobTitle          = userProfileResult.RetrieveUserProperty("SPS-JobTitle"),
                                Assistant         = userProfileResult.RetrieveUserProperty("Assistant"),
                                HireDate          = userProfileResult.RetrieveUserProperty("SPS-HireDate"),
                                TimeZone          = userProfileResult.RetrieveUserProperty("SPS-TimeZone"),
                                Locale            = userProfileResult.RetrieveUserProperty("SPS-Locale"),
                                EmailOptin        = userProfileResult.RetrieveUserProperty("SPS-EmailOptin"),
                                PrivacyPeople     = userProfileResult.RetrieveUserProperty("SPS-PrivacyPeople"),
                                PrivacyActivity   = userProfileResult.RetrieveUserProperty("SPS-PrivacyActivity"),
                                MySiteUpgrade     = userProfileResult.RetrieveUserProperty("SPS-MySiteUpgrade"),
                                ProxyAddresses    = userProfileResult.RetrieveUserProperty("SPS-ProxyAddresses"),
                                OWAUrl            = userProfileResult.RetrieveUserProperty("SPS-OWAUrl")
                            };
                        }
                        results.Add(model);

                        userProfileResult = _UserProfileService.OWService.GetUserProfileByIndex(int.Parse(userProfileResult.NextValue));
                        rowIndex++;
                    }
                    catch (Exception e)
                    {
                        traceLogger.LogWarning("Failed to execute while loop {0}", e.Message);
                    }
                }

                // Final processing
                traceLogger.LogWarning($"Total Profiles {rowIndex} processed...");
            }

            return(results);
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            var objects = new List <SPWorkflowInstance>();


            var FieldDefinitions = new List <SPFieldDefinitionModel>
            {
                new SPFieldDefinitionModel(FieldType.Boolean)
                {
                    FieldGuid    = new Guid("da2872c4-e9b6-4804-9837-6e9dd85ecd7e"),
                    InternalName = FieldBoolean_RestartWorkflow,
                    Description  = "RestartWorkflow provides a way to identify items that should be restarted.",
                    Title        = FieldBoolean_RestartWorkflow,
                    MaxLength    = 255,
                    DefaultValue = "No"
                }
            };


            var SelectedWeb = this.ClientContext.Web;

            Ilogger = new DefaultUsageLogger(
                (string msg, object[] margs) =>
            {
                LogVerbose(msg, margs);
            },
                (string msg, object[] margs) =>
            {
                LogWarning(msg, margs);
            },
                (Exception ex, string msg, object[] margs) =>
            {
                LogError(ex, msg, margs);
            });

            var list = List.GetList(SelectedWeb, lctx => lctx.Id, lctx => lctx.Title);


            var workflowSubscriptionId = new List <Guid>();

            if (!string.IsNullOrEmpty(WorkflowName))
            {
                var servicesManager     = new WorkflowServicesManager(ClientContext, SelectedWeb);
                var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
                var subscriptions       = subscriptionService.EnumerateSubscriptionsByList(list.Id);

                ClientContext.Load(subscriptions);
                ClientContext.ExecuteQueryRetry();

                subscriptions.Where(subs => subs.Name == WorkflowName).Select(s => s.Id).ToList().ForEach(subscriptionId =>
                {
                    workflowSubscriptionId.Add(subscriptionId);
                });
            }


            // Check if the field exists
            var viewFields     = new string[] { "Id", "Title", FieldBoolean_RestartWorkflow };
            var internalFields = new List <string>();

            internalFields.AddRange(FieldDefinitions.Select(s => s.InternalName));

            try
            {
                var checkFields = list.GetFields(internalFields.ToArray());
            }
            catch (Exception ex)
            {
                Ilogger.LogError(ex, "Failed to retreive the fields {0}", ex.Message);

                foreach (var field in FieldDefinitions)
                {
                    // provision the column
                    var provisionedColumn = list.CreateListColumn(field, Ilogger, null);
                    if (provisionedColumn != null)
                    {
                        internalFields.Add(provisionedColumn.InternalName);
                    }
                }
            }

            var view = View.GetView(list);
            var internalViewFieldXml = new List <string>()
            {
                CAML.FieldRef("Id")
            };

            foreach (var vfield in view.ViewFields.Where(w => !w.Equals("ID", StringComparison.CurrentCultureIgnoreCase)))
            {
                internalViewFieldXml.Add(CAML.FieldRef(vfield));
            }

            var itemIds  = new List <int>();
            var viewCaml = new CamlQuery()
            {
                ViewXml = CAML.ViewQuery(ViewScope.RecursiveAll, view.ViewQuery, string.Empty, CAML.ViewFields(internalViewFieldXml.ToArray()), view.RowLimit.ToString().ToInt32(5)),
                ListItemCollectionPosition = null
            };

            do
            {
                var items = list.GetItems(viewCaml);
                this.ClientContext.Load(items, ftx => ftx.ListItemCollectionPosition, ftx => ftx.Include(ftcx => ftcx.Id, ftcx => ftcx.ParentList.Id, ftcx => ftcx[FieldBoolean_RestartWorkflow]));
                this.ClientContext.ExecuteQueryRetry();
                viewCaml.ListItemCollectionPosition = items.ListItemCollectionPosition;

                foreach (var item in items)
                {
                    // Load ParentList ID to Pull Workflow Instances
                    var allinstances = SelectedWeb.GetWorkflowInstances(item);
                    if (allinstances.Any())
                    {
                        foreach (var instance in allinstances)
                        {
                            objects.Add(new SPWorkflowInstance(instance, item.Id));
                        }

                        itemIds.Add(item.Id);
                    }
                }
            }while (viewCaml.ListItemCollectionPosition != null);

            var rowprocessed = itemIds.Count();

            if (rowprocessed > 0 && this.ShouldProcess($"Setting Restart Flag for {rowprocessed} items"))
            {
                var rowdx = 0; var totaldx = rowprocessed;

                foreach (var itemId in itemIds)
                {
                    rowdx++;
                    totaldx--;

                    var wfItem = list.GetItemById(itemId);
                    list.Context.Load(wfItem);
                    wfItem[FieldBoolean_RestartWorkflow] = true;
                    wfItem.SystemUpdate();

                    if (rowdx >= 50 || totaldx <= 0)
                    {
                        list.Context.ExecuteQueryRetry();
                        Ilogger.LogInformation($"Processing {rowprocessed} rows; Persisted {rowdx} rows; {totaldx} remaining");
                        rowdx = 0;
                    }
                }

                var cancelDirty      = false;
                var viewFieldXml     = CAML.ViewFields(viewFields.Select(s => CAML.FieldRef(s)).ToArray());
                var terminatedWFCaml = new CamlQuery()
                {
                    ViewXml = CAML.ViewQuery(ViewScope.RecursiveAll, CAML.Where(CAML.Eq(CAML.FieldValue(FieldBoolean_RestartWorkflow, FieldType.Boolean.ToString("f"), 1.ToString()))), string.Empty, viewFieldXml, 100),
                    ListItemCollectionPosition = null
                };

                do
                {
                    var items = list.GetItems(terminatedWFCaml);
                    list.Context.Load(items, ftx => ftx.ListItemCollectionPosition, ftx => ftx.Include(ftcx => ftcx.Id, ftcx => ftcx.ParentList.Id, ftcx => ftcx[FieldBoolean_RestartWorkflow]));
                    list.Context.ExecuteQueryRetry();
                    terminatedWFCaml.ListItemCollectionPosition = items.ListItemCollectionPosition;

                    rowdx = 0; totaldx = items.Count();

                    foreach (var item in items)
                    {
                        rowdx++;
                        totaldx--;

                        var itemId       = item.Id;
                        var allinstances = SelectedWeb.GetWorkflowInstances(item);
                        foreach (var instance in allinstances)
                        {
                            var instanceId = instance.Id;

                            var msg = $"List Item {itemId} => Cancelling subscription {instance.WorkflowSubscriptionId} instance Id {instanceId}";
                            Ilogger.LogWarning(msg);
                            cancelDirty = true;
                            instance.CancelWorkFlow();
                        }


                        if (cancelDirty &&
                            (rowdx >= 50 || totaldx <= 0))
                        {
                            list.Context.ExecuteQueryRetry();
                            Ilogger.LogInformation($"Processing {rowprocessed} rows; Persisted {rowdx} rows; {totaldx} remaining");
                            rowdx = 0;
                        }
                    }
                }while (terminatedWFCaml.ListItemCollectionPosition != null);
            }


            WriteObject(objects, true);
        }
Esempio n. 3
0
        /// <summary>
        /// Generate a portable JSON object from the List Template
        /// </summary>
        /// <param name="context">Client Context web</param>
        /// <param name="hostWeb">Client Context web</param>
        /// <param name="list">Hydrated SharePoint list Object</param>
        /// <param name="ExpandObjects">true - enumerate fields, views, content types</param>
        /// <param name="logger">Logger implementation for Verbose/Exception handling</param>
        /// <param name="skiptypes">Collection of field types to be used as a filter statement</param>
        /// <param name="siteGroups">Collection of hostWeb groups</param>
        /// <returns></returns>
        public static SPListDefinition GetListDefinition(this ClientContext context, Web hostWeb, List list, bool ExpandObjects, ITraceLogger logger, IEnumerable <FieldType> skiptypes, IEnumerable <Microsoft.SharePoint.Client.Group> siteGroups = null)
        {
            logger.LogInformation("Processing Web list {0}", list.Title);

            if (!hostWeb.IsPropertyAvailable(ctx => ctx.ServerRelativeUrl))
            {
                hostWeb.Context.Load(hostWeb, ctx => ctx.ServerRelativeUrl);
                hostWeb.Context.ExecuteQueryRetry();
            }

            list.EnsureProperties(
                lctx => lctx.Id,
                lctx => lctx.Title,
                lctx => lctx.Description,
                lctx => lctx.DefaultViewUrl,
                lctx => lctx.OnQuickLaunch,
                lctx => lctx.BaseTemplate,
                lctx => lctx.BaseType,
                lctx => lctx.CrawlNonDefaultViews,
                lctx => lctx.Created,
                lctx => lctx.ContentTypesEnabled,
                lctx => lctx.CreatablesInfo,
                lctx => lctx.EnableFolderCreation,
                lctx => lctx.EnableModeration,
                lctx => lctx.EnableVersioning,
                lctx => lctx.Hidden,
                lctx => lctx.IsApplicationList,
                lctx => lctx.IsCatalog,
                lctx => lctx.IsSiteAssetsLibrary,
                lctx => lctx.IsPrivate,
                lctx => lctx.IsSystemList,
                lctx => lctx.RootFolder.ServerRelativeUrl,
                lctx => lctx.SchemaXml,
                lctx => lctx.LastItemModifiedDate,
                lctx => lctx.LastItemUserModifiedDate,
                lctx => lctx.ListExperienceOptions,
                lctx => lctx.TemplateFeatureId);

            var weburl           = hostWeb.ServerRelativeUrl.EnsureTrailingSlashLowered();
            var listTemplateType = list.GetListTemplateType();

            var listdefinition = new SPListDefinition()
            {
                Id                       = list.Id,
                ListName                 = list.Title,
                ListDescription          = list.Description,
                ServerRelativeUrl        = list.DefaultViewUrl,
                BaseTemplate             = list.BaseTemplate,
                ListTemplate             = listTemplateType,
                Created                  = list.Created,
                LastItemModifiedDate     = list.LastItemModifiedDate,
                LastItemUserModifiedDate = list.LastItemUserModifiedDate,
                QuickLaunch              = list.OnQuickLaunch ? QuickLaunchOptions.On : QuickLaunchOptions.Off,
                ContentTypeEnabled       = list.ContentTypesEnabled,
                EnableFolderCreation     = list.EnableFolderCreation,
                Hidden                   = list.Hidden,
                IsApplicationList        = list.IsApplicationList,
                IsCatalog                = list.IsCatalog,
                IsSiteAssetsLibrary      = list.IsSiteAssetsLibrary,
                IsPrivate                = list.IsPrivate,
                IsSystemList             = list.IsSystemList
            };

            if (ExpandObjects)
            {
                var contentTypesFieldset = new List <dynamic>();
                var definitionListFields = new List <SPFieldDefinitionModel>();
                var listurl = TokenHelper.EnsureTrailingSlash(list.RootFolder.ServerRelativeUrl);

                // content types
                var listContentType = list.Context.LoadQuery(list.ContentTypes
                                                             .Include(
                                                                 ict => ict.Id,
                                                                 ict => ict.Group,
                                                                 ict => ict.Description,
                                                                 ict => ict.Name,
                                                                 ict => ict.Hidden,
                                                                 ict => ict.JSLink,
                                                                 ict => ict.FieldLinks,
                                                                 ict => ict.Fields));

                // list fields
                var listFields = list.Context.LoadQuery(list.Fields.Where(wf => wf.ReadOnlyField == false && wf.Hidden == false)
                                                        .Include(
                                                            fctx => fctx.Id,
                                                            fctx => fctx.AutoIndexed,
                                                            fctx => fctx.CanBeDeleted,
                                                            fctx => fctx.DefaultFormula,
                                                            fctx => fctx.DefaultValue,
                                                            fctx => fctx.Group,
                                                            fctx => fctx.Description,
                                                            fctx => fctx.EnforceUniqueValues,
                                                            fctx => fctx.FieldTypeKind,
                                                            fctx => fctx.Filterable,
                                                            fctx => fctx.FromBaseType,
                                                            fctx => fctx.Hidden,
                                                            fctx => fctx.Indexed,
                                                            fctx => fctx.InternalName,
                                                            fctx => fctx.JSLink,
                                                            fctx => fctx.NoCrawl,
                                                            fctx => fctx.ReadOnlyField,
                                                            fctx => fctx.Required,
                                                            fctx => fctx.SchemaXml,
                                                            fctx => fctx.Scope,
                                                            fctx => fctx.Title
                                                            ));

                // list views
                var listViews = list.Context.LoadQuery(list.Views
                                                       .Include(
                                                           lvt => lvt.Title,
                                                           lvt => lvt.DefaultView,
                                                           lvt => lvt.ServerRelativeUrl,
                                                           lvt => lvt.Id,
                                                           lvt => lvt.Aggregations,
                                                           lvt => lvt.AggregationsStatus,
                                                           lvt => lvt.BaseViewId,
                                                           lvt => lvt.Hidden,
                                                           lvt => lvt.ImageUrl,
                                                           lvt => lvt.JSLink,
                                                           lvt => lvt.HtmlSchemaXml,
                                                           lvt => lvt.ListViewXml,
                                                           lvt => lvt.MobileDefaultView,
                                                           lvt => lvt.ModerationType,
                                                           lvt => lvt.OrderedView,
                                                           lvt => lvt.Paged,
                                                           lvt => lvt.PageRenderType,
                                                           lvt => lvt.PersonalView,
                                                           lvt => lvt.ReadOnlyView,
                                                           lvt => lvt.Scope,
                                                           lvt => lvt.RowLimit,
                                                           lvt => lvt.StyleId,
                                                           lvt => lvt.TabularView,
                                                           lvt => lvt.Threaded,
                                                           lvt => lvt.Toolbar,
                                                           lvt => lvt.ToolbarTemplateName,
                                                           lvt => lvt.ViewFields,
                                                           lvt => lvt.ViewJoins,
                                                           lvt => lvt.ViewQuery,
                                                           lvt => lvt.ViewType,
                                                           lvt => lvt.ViewProjectedFields,
                                                           lvt => lvt.Method
                                                           ));

                list.Context.ExecuteQueryRetry();


                if (listContentType != null && listContentType.Any())
                {
                    listdefinition.ContentTypes = new List <SPContentTypeDefinition>();
                    foreach (var contenttype in listContentType)
                    {
                        logger.LogInformation("Processing list {0} content type {1}", list.Title, contenttype.Name);

                        var ctypemodel = new SPContentTypeDefinition()
                        {
                            Inherits         = true,
                            ContentTypeId    = contenttype.Id.StringValue,
                            ContentTypeGroup = contenttype.Group,
                            Description      = contenttype.Description,
                            Name             = contenttype.Name,
                            Hidden           = contenttype.Hidden,
                            JSLink           = contenttype.JSLink
                        };

                        if (contenttype.FieldLinks.Any())
                        {
                            ctypemodel.FieldLinks = new List <SPFieldLinkDefinitionModel>();
                            foreach (var cfieldlink in contenttype.FieldLinks)
                            {
                                ctypemodel.FieldLinks.Add(new SPFieldLinkDefinitionModel()
                                {
                                    Id       = cfieldlink.Id,
                                    Name     = cfieldlink.Name,
                                    Hidden   = cfieldlink.Hidden,
                                    Required = cfieldlink.Required
                                });

                                contentTypesFieldset.Add(new { ctypeid = contenttype.Id.StringValue, name = cfieldlink.Name });
                            }
                        }

                        if (contenttype.Fields.Any())
                        {
                            foreach (var cfield in contenttype.Fields.Where(cf => !ctypemodel.FieldLinks.Any(fl => fl.Name == cf.InternalName)))
                            {
                                ctypemodel.FieldLinks.Add(new SPFieldLinkDefinitionModel()
                                {
                                    Id       = cfield.Id,
                                    Name     = cfield.InternalName,
                                    Hidden   = cfield.Hidden,
                                    Required = cfield.Required
                                });
                            }
                        }

                        listdefinition.ContentTypes.Add(ctypemodel);
                    }
                }


                if (listFields != null && listFields.Any())
                {
                    var filteredListFields = listFields.Where(lf => !skiptypes.Any(st => lf.FieldTypeKind == st)).ToList();
                    logger.LogWarning("Processing list {0} found {1} fields to be processed", list.Title, filteredListFields.Count());

                    foreach (Field listField in listFields)
                    {
                        logger.LogInformation("Processing list {0} field {1}", list.Title, listField.InternalName);

                        try
                        {
                            var fieldXml = listField.SchemaXml;
                            if (!string.IsNullOrEmpty(fieldXml))
                            {
                                var xdoc      = XDocument.Parse(fieldXml, LoadOptions.PreserveWhitespace);
                                var xField    = xdoc.Element("Field");
                                var xSourceID = xField.Attribute("SourceID");
                                //if (xSourceID != null && xSourceID.Value.IndexOf(ConstantsXmlNamespaces.SharePointNS.NamespaceName, StringComparison.CurrentCultureIgnoreCase) < 0)
                                //{
                                //    continue; // skip processing an OOTB field
                                //}
                                var customField = context.RetrieveField(listField, logger, siteGroups, xField);
                                if (xSourceID != null)
                                {
                                    customField.SourceID = xSourceID.Value;
                                }
                                definitionListFields.Add(customField);

                                if (customField.FieldTypeKind == FieldType.Lookup)
                                {
                                    listdefinition.ListDependency.Add(customField.LookupListName);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.LogError(ex, "Failed to parse field {0} MSG:{1}", listField.InternalName, ex.Message);
                        }
                    }

                    listdefinition.FieldDefinitions = definitionListFields;
                }


                if (listViews != null && listViews.Any())
                {
                    listdefinition.InternalViews = new List <SPViewDefinitionModel>();
                    listdefinition.Views         = new List <SPViewDefinitionModel>();

                    foreach (var view in listViews)
                    {
                        logger.LogInformation("Processing list {0} view {1}", list.Title, view.Title);

                        var vinternal = (view.ServerRelativeUrl.IndexOf(listurl, StringComparison.CurrentCultureIgnoreCase) == -1);

                        ViewType viewCamlType = InfrastructureAsCode.Core.Extensions.ListExtensions.TryGetViewType(view.ViewType);

                        var viewmodel = new SPViewDefinitionModel()
                        {
                            Id                 = view.Id,
                            Title              = view.Title,
                            DefaultView        = view.DefaultView,
                            FieldRefName       = new List <string>(),
                            Aggregations       = view.Aggregations,
                            AggregationsStatus = view.AggregationsStatus,
                            BaseViewId         = view.BaseViewId,
                            Hidden             = view.Hidden,
                            ImageUrl           = view.ImageUrl,
                            Toolbar            = view.Toolbar,
                            ListViewXml        = view.ListViewXml,
                            MobileDefaultView  = view.MobileDefaultView,
                            ModerationType     = view.ModerationType,
                            OrderedView        = view.OrderedView,
                            Paged              = view.Paged,
                            PageRenderType     = view.PageRenderType,
                            PersonalView       = view.PersonalView,
                            ReadOnlyView       = view.ReadOnlyView,
                            Scope              = view.Scope,
                            RowLimit           = view.RowLimit,
                            StyleId            = view.StyleId,
                            TabularView        = view.TabularView,
                            Threaded           = view.Threaded,
                            ViewJoins          = view.ViewJoins,
                            ViewQuery          = view.ViewQuery,
                            ViewCamlType       = viewCamlType
                        };

                        if (vinternal)
                        {
                            viewmodel.SitePage     = view.ServerRelativeUrl.Replace(weburl, "");
                            viewmodel.InternalView = true;
                        }
                        else
                        {
                            viewmodel.InternalName = view.ServerRelativeUrl.Replace(listurl, "").Replace(".aspx", "");
                        }

                        if (view.ViewFields != null && view.ViewFields.Any())
                        {
                            foreach (var vfields in view.ViewFields)
                            {
                                viewmodel.FieldRefName.Add(vfields);
                            }
                        }

                        if (view.JSLink != null && view.JSLink.Any())
                        {
                            var vjslinks = view.JSLink.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                            if (vjslinks != null && !vjslinks.Any(jl => jl == "clienttemplates.js"))
                            {
                                viewmodel.JsLinkFiles = new List <string>();
                                foreach (var vjslink in vjslinks)
                                {
                                    viewmodel.JsLinkFiles.Add(vjslink);
                                }
                            }
                        }

                        if (view.Hidden)
                        {
                            listdefinition.InternalViews.Add(viewmodel);
                        }
                        else
                        {
                            listdefinition.Views.Add(viewmodel);
                        }
                    }
                }
            }

            return(listdefinition);
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();


            var objects = new List <SPWorkflowInstance>();


            var FieldDefinitions = new List <SPFieldDefinitionModel>
            {
                new SPFieldDefinitionModel(FieldType.Boolean)
                {
                    FieldGuid    = new Guid("da2872c4-e9b6-4804-9837-6e9dd85ecd7e"),
                    InternalName = FieldBoolean_RestartWorkflow,
                    Description  = "RestartWorkflow provides a way to identify items that should be restarted.",
                    Title        = FieldBoolean_RestartWorkflow,
                    MaxLength    = 255,
                    DefaultValue = "No"
                }
            };


            var SelectedWeb = this.ClientContext.Web;

            Ilogger = new DefaultUsageLogger(
                (string msg, object[] margs) =>
            {
                LogVerbose(msg, margs);
            },
                (string msg, object[] margs) =>
            {
                LogWarning(msg, margs);
            },
                (Exception ex, string msg, object[] margs) =>
            {
                LogError(ex, msg, margs);
            });

            var list = List.GetList(SelectedWeb, lctx => lctx.Id, lctx => lctx.Title);

            var workflowSubscriptionId = new List <Guid>();

            if (!string.IsNullOrEmpty(WorkflowName))
            {
                var servicesManager     = new WorkflowServicesManager(ClientContext, SelectedWeb);
                var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
                var subscriptions       = subscriptionService.EnumerateSubscriptionsByList(list.Id);

                ClientContext.Load(subscriptions);
                ClientContext.ExecuteQueryRetry();

                subscriptions.Where(subs => subs.Name == WorkflowName).Select(s => s.Id).ToList().ForEach(subscriptionId =>
                {
                    workflowSubscriptionId.Add(subscriptionId);
                });
            }


            // Check if the field exists
            var viewFields     = new string[] { "Id", "Title", FieldBoolean_RestartWorkflow };
            var internalFields = new List <string>();

            internalFields.AddRange(FieldDefinitions.Select(s => s.InternalName));

            try
            {
                var checkFields = list.GetFields(internalFields.ToArray());
            }
            catch (Exception ex)
            {
                Ilogger.LogError(ex, "Failed to retreive the fields {0}", ex.Message);

                foreach (var field in FieldDefinitions)
                {
                    // provision the column
                    var provisionedColumn = list.CreateListColumn(field, Ilogger, null);
                    if (provisionedColumn != null)
                    {
                        internalFields.Add(provisionedColumn.InternalName);
                    }
                }
            }

            var workflowStati = new List <Microsoft.SharePoint.Client.WorkflowServices.WorkflowStatus>()
            {
                Microsoft.SharePoint.Client.WorkflowServices.WorkflowStatus.Started
            };

            var rowprocessed = 0;
            var rowdx = 0; var totaldx = 0;
            var startedDirty   = false;
            var viewFieldXml   = CAML.ViewFields(viewFields.Select(s => CAML.FieldRef(s)).ToArray());
            var initiateWFCaml = new CamlQuery()
            {
                ViewXml = CAML.ViewQuery(ViewScope.RecursiveAll, CAML.Where(CAML.Eq(CAML.FieldValue(FieldBoolean_RestartWorkflow, FieldType.Boolean.ToString("f"), 1.ToString()))), string.Empty, viewFieldXml, 100),
                ListItemCollectionPosition = null
            };


            do
            {
                var items = list.GetItems(initiateWFCaml);
                list.Context.Load(items, ftx => ftx.ListItemCollectionPosition, ftx => ftx.Include(ftcx => ftcx.Id, ftcx => ftcx.ParentList.Id, ftcx => ftcx[FieldBoolean_RestartWorkflow]));
                list.Context.ExecuteQueryRetry();
                initiateWFCaml.ListItemCollectionPosition = items.ListItemCollectionPosition;

                rowprocessed = items.Count();
                rowdx        = 0; totaldx = rowprocessed;

                foreach (var item in items)
                {
                    rowdx++;
                    totaldx--;

                    var itemId       = item.Id;
                    var allinstances = SelectedWeb.GetWorkflowInstances(item);
                    if (!allinstances.Any(w => workflowStati.Any(wx => wx == w.Status)))
                    {
                        foreach (var subscriptionId in workflowSubscriptionId)
                        {
                            Ilogger.LogWarning($"List Item {itemId} => Restarting subscription {subscriptionId}");
                            var instanceId = item.StartWorkflowInstance(subscriptionId, new Dictionary <string, object>());
                            Ilogger.LogWarning($"List Item {itemId} => Successfully restarted subscription {subscriptionId} with new instance Id {instanceId}");
                            startedDirty = true;

                            objects.Add(new SPWorkflowInstance()
                            {
                                Id = instanceId,
                                WorkflowSubscriptionId = subscriptionId,
                                ListItemId             = itemId,
                                InstanceCreated        = DateTime.UtcNow
                            });
                        }

                        var wfItem = list.GetItemById(itemId);
                        list.Context.Load(wfItem);
                        wfItem[FieldBoolean_RestartWorkflow] = false;
                        wfItem.SystemUpdate();
                    }

                    if (startedDirty && (rowdx >= 50 || totaldx <= 0))
                    {
                        list.Context.ExecuteQueryRetry();
                        Ilogger.LogInformation($"Processing {rowprocessed} rows; Persisted {rowdx} rows; {totaldx} remaining");
                        rowdx = 0;
                    }
                }
            }while (initiateWFCaml.ListItemCollectionPosition != null);


            WriteObject(objects, true);
        }