Exemplo n.º 1
0
        public ActionResult Featured(int maxCount = 3)
        {
            using (var clientContext = HttpContext.GetUserClientContextForSPHost()) {
                ViewBag.SPHostUrl = HttpContext.Request.QueryString["SPHostUrl"];

                var caml = new CamlQuery()
                {
                    ViewXml = CAML.ViewQuery(
                        CAML.Where(
                            CAML.And(
                                CAML.Geq(
                                    CAML.FieldValue(Event.FIELD_DATE, "Date", CAML.Today())
                                    ),
                                CAML.Eq(
                                    CAML.FieldValue(Event.FIELD_CATEGORY, "Text", "Featured")
                                    )
                                )
                            ),
                        CAML.OrderBy(new OrderByField(Event.FIELD_DATE)),
                        rowLimit: maxCount)
                };

                var list = clientContext.Web.Lists.GetByTitle(ListDetails.EventsListName);
                clientContext.Load(list);
                clientContext.ExecuteQuery();

                var items = list.GetItems(caml);
                clientContext.Load(items);
                clientContext.ExecuteQuery();

                var result = items.Cast <ListItem>()
                             .Select(i => new Event(i)).ToList();
                return(View(result));
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Retreive file from the specified folder
        /// </summary>
        /// <param name="onlineLibrary"></param>
        /// <param name="destinationFolder"></param>
        /// <param name="onlineFileName"></param>
        /// <returns></returns>
        public static ListItem GetFileInFolder(this List onlineLibrary, Folder destinationFolder, string onlineFileName)
        {
            destinationFolder.Context.Load(destinationFolder, afold => afold.ServerRelativeUrl);
            destinationFolder.Context.ExecuteQuery();
            var relativeUrl = destinationFolder.ServerRelativeUrl;
            var context     = destinationFolder.Context;

            try
            {
                CamlQuery camlQuery    = new CamlQuery();
                var       camlAndValue = CAML.And(
                    CAML.Eq(CAML.FieldValue("LinkFilename", FieldType.Text.ToString("f"), onlineFileName)),
                    CAML.Eq(CAML.FieldValue("FileDirRef", FieldType.Text.ToString("f"), relativeUrl)));

                camlQuery.ViewXml = CAML.ViewQuery(ViewScope.RecursiveAll,
                                                   CAML.Where(camlAndValue),
                                                   string.Empty,
                                                   CAML.ViewFields(CAML.FieldRef("Title")),
                                                   5);
                ListItemCollection listItems = onlineLibrary.GetItems(camlQuery);
                context.Load(listItems);
                context.ExecuteQuery();

                if (listItems.Count() > 0)
                {
                    var newItem = listItems.FirstOrDefault();
                    return(newItem);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError("Failed to retrieve file {0} MSG:{1}", onlineFileName, ex.Message);
            }
            return(null);
        }
Exemplo n.º 3
0
        public ActionResult Index(string category = "")
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            using (var clientContext = HttpContext.GetUserClientContextForSPHost()) {
                ViewBag.SPHostUrl = spContext.SPHostUrl;
                ViewBag.Category  = category;

                var list          = clientContext.Web.GetListByTitle(ListDetails.EventsListName);
                var categoryQuery = string.Empty;
                if (!string.IsNullOrEmpty(category))
                {
                    categoryQuery = CAML.Where(CAML.Eq(CAML.FieldValue(Event.FIELD_CATEGORY, "Text", category)));
                }
                var orderByQuery = CAML.OrderBy(new OrderByField("Title"));

                var caml = new CamlQuery()
                {
                    ViewXml = CAML.ViewQuery(categoryQuery, orderByQuery, rowLimit: 50)
                };
                var events = list.GetItems(caml);
                clientContext.Load(events);
                clientContext.ExecuteQuery();

                var eventsList = events.Cast <ListItem>().Select(item => new Event(item)).ToList();
                return(View(eventsList));
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Returns the parent item ID
        /// </summary>
        /// <param name="cContext"></param>
        /// <param name="ItemName"></param>
        /// <param name="ParentListName"></param>
        /// <returns></returns>
        internal int GetParentItemID(ClientContext cContext, string ItemName, string ParentListName)
        {
            int nReturn = -1;

            try
            {
                LogVerbose("Start GetParentItemID");

                Web wWeb = cContext.Web;

                List lParentList = cContext.Web.Lists.GetByTitle(ParentListName);

                CamlQuery camlQuery = new CamlQuery
                {
                    ViewXml = CAML.Where(CAML.Eq(CAML.FieldValue("Title", FieldType.Text.ToString("f"), ItemName)))
                };
                ListItemCollection collListItem = lParentList.GetItems(camlQuery);

                cContext.Load(collListItem);

                cContext.ExecuteQuery();

                foreach (ListItem oListItem in collListItem)
                {
                    if (oListItem["Title"].ToString() == ItemName)
                    {
                        nReturn = oListItem.Id;
                        break;
                    }
                }

                LogVerbose("Complete GetParentItemID");
            }
            catch (Exception ex)
            {
                LogError(ex, ex.Message);
            }

            return(nReturn);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Retrieves or creates the folder as a ListItem
        /// </summary>
        /// <param name="onlineLibrary"></param>
        /// <param name="destinationFolder"></param>
        /// <param name="folderName"></param>
        /// <param name="defaultLastItemId"></param>
        /// <returns>The listitem as a folder</returns>
        public static Folder GetOrCreateFolder(this List onlineLibrary, Folder destinationFolder, string folderName, int?defaultLastItemId = default(int?))
        {
            destinationFolder.EnsureProperties(afold => afold.ServerRelativeUrl, afold => afold.Folders);
            var folderRelativeUrl = destinationFolder.ServerRelativeUrl;
            // Remove invalid characters
            var      trimmedFolder = HelperExtensions.GetCleanDirectory(folderName, string.Empty);
            ListItem folderItem    = null;

            var camlFields     = new string[] { "Title", "ContentType", "ID" };
            var camlViewFields = CAML.ViewFields(camlFields.Select(s => CAML.FieldRef(s)).ToArray());


            var camlClause = CAML.And(
                CAML.And(
                    CAML.Eq(CAML.FieldValue("FileDirRef", FieldType.Text.ToString("f"), folderRelativeUrl)),
                    CAML.Or(
                        CAML.Eq(CAML.FieldValue("LinkFilename", FieldType.Text.ToString("f"), trimmedFolder)),
                        CAML.Eq(CAML.FieldValue("Title", FieldType.Text.ToString("f"), trimmedFolder))
                        )
                    )
                ,
                CAML.Eq(CAML.FieldValue("FSObjType", FieldType.Integer.ToString("f"), 1.ToString()))
                );

            var camlQueries = onlineLibrary.SafeCamlClauseFromThreshold(camlClause, defaultLastItemId);

            foreach (var camlAndValue in camlQueries)
            {
                var camlWhereClause = CAML.Where(camlAndValue);
                var camlQuery       = new CamlQuery()
                {
                    ViewXml = CAML.ViewQuery(ViewScope.RecursiveAll, camlWhereClause, string.Empty, camlViewFields, 5)
                };
                var listItems = onlineLibrary.GetItems(camlQuery);
                onlineLibrary.Context.Load(listItems);
                onlineLibrary.Context.ExecuteQueryRetry();

                if (listItems.Count() > 0)
                {
                    folderItem = listItems.FirstOrDefault();
                    System.Diagnostics.Trace.TraceInformation("Item {0} exists in the destination folder.  Skip item creation file.....", folderName);
                    break;
                }
            }
            ;

            if (folderItem != null)
            {
                return(folderItem.Folder);
            }

            try
            {
                var info = new ListItemCreationInformation();
                info.UnderlyingObjectType = FileSystemObjectType.Folder;
                info.LeafName             = trimmedFolder;
                info.FolderUrl            = folderRelativeUrl;

                folderItem          = onlineLibrary.AddItem(info);
                folderItem["Title"] = trimmedFolder;
                folderItem.Update();
                onlineLibrary.Context.ExecuteQueryRetry();
                System.Diagnostics.Trace.TraceInformation("{0} folder Created", trimmedFolder);
                return(folderItem.Folder);
            }
            catch (Exception Ex)
            {
                System.Diagnostics.Trace.TraceError("Failed to create or get folder for name {0} MSG:{1}", folderName, Ex.Message);
            }

            return(null);
        }
        /// <summary>
        /// Retrieves or creates the folder as a ListItem
        /// </summary>
        /// <param name="onlineLibrary">The target list for the folder</param>
        /// <param name="destinationFolder">The parent folder of the folter to be created</param>
        /// <param name="folderName">The folder to be created</param>
        /// <param name="defaultStartItemId">(OPTIONAL) If the list/library is above the threshold this will be the start index of the caml queries</param>
        /// <param name="defaultLastItemId">(OPTIONAL) If the list/library is above the threshold this will be the terminating index of the caml queries</param>
        /// <returns>The listitem as a folder</returns>
        public static Folder GetOrCreateFolder(this List onlineLibrary, Folder destinationFolder, string folderName, Nullable <int> defaultStartItemId = default(int?), Nullable <int> defaultLastItemId = default(int?))
        {
            if (!onlineLibrary.IsPropertyAvailable(lctx => lctx.BaseType))
            {
                onlineLibrary.Context.Load(onlineLibrary, lctx => lctx.BaseType, lctx => lctx.BaseTemplate);
                onlineLibrary.Context.ExecuteQueryRetry();
            }

            if (!destinationFolder.IsPropertyAvailable(fctx => fctx.ServerRelativeUrl) ||
                !destinationFolder.IsObjectPropertyInstantiated(fctx => fctx.Folders))
            {
                destinationFolder.Context.Load(destinationFolder, afold => afold.ServerRelativeUrl, afold => afold.Folders);
                destinationFolder.Context.ExecuteQueryRetry();
            }


            ListItem folderItem = null;

            var folderRelativeUrl = destinationFolder.ServerRelativeUrl;
            var camlFields        = new string[] { "Title", "ID" };
            var camlViewFields    = CAML.ViewFields(camlFields.Select(s => CAML.FieldRef(s)).ToArray());

            // Remove invalid characters
            var trimmedFolder  = HelperExtensions.GetCleanDirectory(folderName, string.Empty);
            var linkFileFilter = CAML.Eq(CAML.FieldValue("Title", FieldType.Text.ToString("f"), trimmedFolder));

            if (onlineLibrary.BaseType == BaseType.DocumentLibrary)
            {
                linkFileFilter = CAML.Or(
                    linkFileFilter,
                    CAML.Eq(CAML.FieldValue("LinkFilename", FieldType.Text.ToString("f"), trimmedFolder)));
            }

            var camlClause = CAML.And(
                CAML.Eq(CAML.FieldValue("FileDirRef", FieldType.Text.ToString("f"), folderRelativeUrl)),
                CAML.And(
                    CAML.Eq(CAML.FieldValue("FSObjType", FieldType.Integer.ToString("f"), 1.ToString())),
                    linkFileFilter
                    )
                );

            var camlQueries = onlineLibrary.SafeCamlClauseFromThreshold(1000, camlClause, defaultStartItemId, defaultLastItemId);

            foreach (var camlAndValue in camlQueries)
            {
                ListItemCollectionPosition itemPosition = null;
                var camlWhereClause = CAML.Where(camlAndValue);
                var camlQuery       = new CamlQuery()
                {
                    ViewXml = CAML.ViewQuery(
                        ViewScope.RecursiveAll,
                        camlWhereClause,
                        string.Empty,
                        camlViewFields,
                        5)
                };
                camlQuery.ListItemCollectionPosition = itemPosition;
                var listItems = onlineLibrary.GetItems(camlQuery);
                onlineLibrary.Context.Load(listItems, lti => lti.ListItemCollectionPosition);
                onlineLibrary.Context.ExecuteQueryRetry();

                if (listItems.Count() > 0)
                {
                    folderItem = listItems.FirstOrDefault();
                    System.Diagnostics.Trace.TraceInformation("Folder {0} exists in the destination folder.  Skip folder creation .....", folderName);
                    break;
                }
            }
            ;

            if (folderItem != null)
            {
                return(folderItem.Folder);
            }

            try
            {
                var info = new ListItemCreationInformation
                {
                    UnderlyingObjectType = FileSystemObjectType.Folder,
                    LeafName             = trimmedFolder,
                    FolderUrl            = folderRelativeUrl
                };

                folderItem          = onlineLibrary.AddItem(info);
                folderItem["Title"] = trimmedFolder;
                folderItem.Update();
                onlineLibrary.Context.ExecuteQueryRetry();
                System.Diagnostics.Trace.TraceInformation("{0} folder Created", trimmedFolder);
                return(folderItem.Folder);
            }
            catch (Exception Ex)
            {
                System.Diagnostics.Trace.TraceError("Failed to create or get folder for name {0} MSG:{1}", folderName, Ex.Message);
            }

            return(null);
        }
        /// <summary>
        /// Returns the parent item ID
        /// </summary>
        /// <param name="cContext"></param>
        /// <param name="ItemName"></param>
        /// <param name="ParentListColumn"></param>
        /// <param name="logger">diagnostics logger</param>
        /// <returns></returns>
        static int GetParentItemID(ClientContext cContext, dynamic ItemName, SPFieldDefinitionModel ParentListColumn, ITraceLogger logger)
        {
            int nReturn                        = -1;
            var parentListName                 = string.Empty;
            var parentListColumnName           = string.Empty;
            NativeFieldLookupValue lookupValue = null;

            try
            {
                string itemJsonString = ItemName.ToString();
                Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.Parse(itemJsonString);
                lookupValue = jobject.ToObject <NativeFieldLookupValue>();



                parentListName       = ParentListColumn.LookupListName;
                parentListColumnName = ParentListColumn.LookupListFieldName;
                logger.LogInformation("Start GetParentItemID {0} for column {1}", parentListName, parentListColumnName);

                Web wWeb = cContext.Web;

                var lParentList = cContext.Web.GetListByTitle(parentListName, lctx => lctx.Id, lctx => lctx.Title);
                var camlQuery   = new CamlQuery()
                {
                    ViewXml = CAML.ViewQuery(
                        CAML.Where(
                            CAML.Eq(
                                CAML.FieldValue(parentListColumnName, FieldType.Text.ToString("f"), lookupValue.LookupValue))
                            ),
                        string.Empty,
                        10
                        )
                };

                ListItemCollectionPosition itemPosition = null;
                while (true)
                {
                    var collListItem = lParentList.GetItems(camlQuery);
                    cContext.Load(collListItem, lictx => lictx.ListItemCollectionPosition);
                    cContext.ExecuteQueryRetry();
                    itemPosition = collListItem.ListItemCollectionPosition;

                    foreach (var oListItem in collListItem)
                    {
                        nReturn = oListItem.Id;
                        break;
                    }

                    // we drop out of the forloop above but if we are paging do we want to skip duplicate results
                    if (itemPosition == null)
                    {
                        break;
                    }
                }

                logger.LogInformation("Complete GetParentItemID {0} resulted in ID => {1}", parentListName, nReturn);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Failed to query lookup value {0}", ex.Message);
            }

            return(nReturn);
        }
        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);
        }
        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);
        }
Exemplo n.º 10
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            LogVerbose("Scanning CSOM callout");

            var invalidLinks = new List <CalloutLinkModel>();

            var fields = new string[]
            {
                "_dlc_DocId", "_dlc_DocIdUrl", "Modified", "Editor", "ServerRedirectedEmbedUri", "FileRef", "Title"
            };
            var fieldsXml = CAML.ViewFields(fields.Select(s => CAML.FieldRef(s)).ToArray());

            var onlineLibrary = List.GetList(this.ClientContext.Web);

            if (!EndId.HasValue)
            {
                onlineLibrary.EnsureProperties(ol => ol.ItemCount);
                EndId = onlineLibrary.ItemCount;
            }
            ListItemCollectionPosition itemCollectionPosition = null;
            CamlQuery camlQuery = new CamlQuery();

            for (var idx = 1; idx <= EndId; idx += 1000)
            {
                camlQuery.ViewXml = string.Format(@"<View Scope='RecursiveAll'><Query>
    <OrderBy><FieldRef Name='ID' /></OrderBy>
    <Where>
        <And>
            <And>
                {0}{1}
            </And>
            <Or>
                {2}{3}
            </Or>
        </And>
    </Where>
    {4}
    <RowLimit Paged='TRUE'>30</RowLimit>
</Query></View>",
                                                  CAML.Geq(CAML.FieldValue("ID", FieldType.Integer.ToString("f"), idx.ToString())),
                                                  CAML.Leq(CAML.FieldValue("ID", FieldType.Integer.ToString("f"), (idx + 1000).ToString())),
                                                  CAML.Eq(CAML.FieldValue("FileDirRef", FieldType.Text.ToString("f"), Path)),
                                                  CAML.Contains(CAML.FieldValue("_dlc_DocIdUrl", FieldType.URL.ToString("f"), PartialUrl)),
                                                  fieldsXml
                                                  );

                while (true)
                {
                    camlQuery.ListItemCollectionPosition = itemCollectionPosition;
                    ListItemCollection listItems = onlineLibrary.GetItems(camlQuery);
                    this.ClientContext.Load(listItems);
                    this.ClientContext.ExecuteQuery();
                    itemCollectionPosition = listItems.ListItemCollectionPosition;
                    if (listItems.Count() > 0)
                    {
                        foreach (var listItem in listItems)
                        {
                            var item = onlineLibrary.GetItemById(listItem.Id);
                            this.ClientContext.Load(item);
                            this.ClientContext.ExecuteQuery();

                            var docId               = item.RetrieveListItemValue("_dlc_DocId");
                            var docIdUrl            = item.RetrieveListItemValueAsHyperlink("_dlc_DocIdUrl");
                            var modified            = item.RetrieveListItemValue("Modified").ToDateTime();
                            var editor              = item.RetrieveListItemUserValue("Editor");
                            var redirectEmbeddedUrl = item.RetrieveListItemValue("ServerRedirectedEmbedUri");
                            var fileRef             = item.RetrieveListItemValue("FileRef");
                            var title               = item.RetrieveListItemValue("Title");

                            invalidLinks.Add(new CalloutLinkModel()
                            {
                                DocId       = docId,
                                DocIdUrl    = (docIdUrl == null) ? string.Empty : docIdUrl.Url,
                                Modified    = modified,
                                EditorEmail = (editor == null) ? string.Empty : editor.ToUserEmailValue(),
                                EmbeddedUrl = redirectEmbeddedUrl,
                                FileUrl     = fileRef,
                                Title       = title,
                                Id          = listItem.Id
                            });
                        }
                    }

                    if (itemCollectionPosition == null)
                    {
                        break;
                    }
                }
            }

            WriteObject(invalidLinks);
        }