Example #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));
            }
        }
Example #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);
        }
Example #3
0
        /// <summary>
        /// Will evaluate the Library/List and if the list has reached the threshold it will produce SAFE queries
        /// </summary>
        /// <param name="onlineLibrary">The list to query</param>
        /// <param name="camlStatement">A base CAML query upon which the threshold query will be constructed</param>
        /// <returns>A collection of CAML queries NOT including WHERE</returns>
        public static List <string> SafeCamlClauseFromThreshold(this List onlineLibrary, string camlStatement = null, int?defaultLastItemId = default(int?))
        {
            var camlQueries = new List <string>();

            onlineLibrary.EnsureProperties(olp => olp.ItemCount, olp => olp.LastItemModifiedDate, olp => olp.LastItemUserModifiedDate);

            // we have reached a threshold and need to parse based on other criteria
            var itemCount = onlineLibrary.ItemCount;

            if (itemCount > 5000)
            {
                var lastItemId  = (defaultLastItemId.HasValue) ? defaultLastItemId.Value : onlineLibrary.QueryLastItemId(onlineLibrary.LastItemModifiedDate);
                var startIdx    = 0;
                var incrementor = 1000;

                for (var idx = startIdx; idx < lastItemId + 1;)
                {
                    var startsWithId = idx + 1;
                    var endsWithId   = (idx + incrementor);
                    if (endsWithId >= lastItemId)
                    {
                        endsWithId = lastItemId + 1;
                    }

                    var thresholdEq = new SPThresholdEnumerationModel()
                    {
                        StartsWithId = startsWithId,
                        EndsWithId   = endsWithId
                    };

                    var camlThresholdClause = thresholdEq.AndClause;
                    if (!string.IsNullOrEmpty(camlStatement))
                    {
                        camlThresholdClause = CAML.And(camlThresholdClause, camlStatement);
                    }
                    camlQueries.Add(camlThresholdClause);

                    idx += incrementor;
                }
            }
            else
            {
                camlQueries.Add(camlStatement ?? string.Empty);
            }

            return(camlQueries);
        }
Example #4
0
        public void Tag_ComplicatedQuery_DoesNotThrowXmlException()
        {
            Assert.DoesNotThrow(() =>
            {
                var fieldRefId    = CAML.FieldRef(BuiltInInternalFieldNames.ID);
                var orderByAsCaml = CAML.OrderBy(
                    CAML.FieldRef(BuiltInInternalFieldNames.ID, CAML.SortType.Ascending)
                    );

                var viewFields = new List <string>
                {
                    BuiltInInternalFieldNames.ID,
                    BuiltInInternalFieldNames.Title
                };
                var viewFieldsAsCaml = CAML.ViewFieldsByFieldNames(viewFields.ToArray());

                const int maxRowLimit = 1000;
                var rowLimitAsCaml    = CAML.RowLimit(maxRowLimit);

                const int startId = 1;
                const int endId   = maxRowLimit;

                CAML.View(
                    string.Concat(
                        CAML.Query(
                            string.Concat(
                                CAML.Where(
                                    CAML.And(
                                        CAML.Geq(
                                            fieldRefId,
                                            CAML.Value(startId)
                                            ),
                                        CAML.Leq(
                                            fieldRefId,
                                            CAML.Value(endId)
                                            )
                                        )
                                    ),
                                orderByAsCaml
                                )
                            ),
                        viewFieldsAsCaml,
                        rowLimitAsCaml
                        )
                    );
            });
        }
Example #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>
        /// Process the internals of the CmdLet
        /// </summary>
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            // Load email notification list
            var listInSite = this.ListTitle.GetList(this.ClientContext.Web);


            // get site and query the list for pending requests
            var fieldNames = new List <string>()
            {
                "ID"
            };

            if (ViewFields != null && ViewFields.Length > 0)
            {
                fieldNames.AddRange(ViewFields);
            }
            ;

            var fieldsXml       = CAML.ViewFields(fieldNames.Select(s => CAML.FieldRef(s)).ToArray());
            var camlWhereClause = string.Empty;
            var camlWhereConcat = false;

            if (!string.IsNullOrEmpty(this.OverrideCamlQuery))
            {
                camlWhereConcat = true;
                camlWhereClause = this.OverrideCamlQuery;
            }

            if (StartsWithId > 0)
            {
                var camlWhereSubClause = CAML.Geq(CAML.FieldValue("ID", FieldType.Number.ToString("f"), StartsWithId.ToString()));
                if (camlWhereConcat)
                {
                    // Wrap in an And Clause
                    camlWhereClause = CAML.And(camlWhereClause, camlWhereSubClause);
                }
                else
                {
                    camlWhereConcat = true;
                    camlWhereClause = camlWhereSubClause;
                }
            }

            if (EndsWithId > 0)
            {
                var camlWhereSubClause = CAML.Leq(CAML.FieldValue("ID", FieldType.Number.ToString("f"), EndsWithId.ToString()));
                if (camlWhereConcat)
                {
                    // Wrap in an And Clause
                    camlWhereClause = CAML.And(camlWhereClause, camlWhereSubClause);
                }
                else
                {
                    camlWhereConcat = true;
                    camlWhereClause = camlWhereSubClause;
                }
            }


            if (string.IsNullOrEmpty(camlWhereClause))
            {
                throw new Exception("Failed to construct a valid CAML Query.");
            }

            try
            {
                ListItemCollectionPosition ListItemCollectionPosition = null;
                var camlQuery = new CamlQuery()
                {
                    ViewXml = CAML.ViewQuery(ViewScope.RecursiveAll, CAML.Where(camlWhereClause), string.Empty, fieldsXml, 50)
                };

                var ids = new List <int>();
                while (true)
                {
                    camlQuery.ListItemCollectionPosition = ListItemCollectionPosition;
                    var spListItems = listInSite.GetItems(camlQuery);
                    this.ClientContext.Load(spListItems);
                    this.ClientContext.ExecuteQueryRetry();
                    ListItemCollectionPosition = spListItems.ListItemCollectionPosition;

                    foreach (var spListItem in spListItems)
                    {
                        var s = string.Empty;
                        LogWarning("ListItem [{0}] will be deleted.", spListItem.Id);
                        foreach (var fieldName in fieldNames)
                        {
                            s += string.Format("...[{0}]==[{1}]...", fieldName, spListItem[fieldName]);
                        }
                        LogVerbose("LISTITEM: {0}", s);
                        ids.Add(spListItem.Id);
                    }

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

                // enumerate the ids to be deleted and process if -WhatIf (not passed)
                foreach (var id in ids)
                {
                    if (this.ShouldProcess(string.Format("ListItem [{0}] now being deleted.", id)))
                    {
                        var spListItem = listInSite.GetItemById(id);
                        spListItem.DeleteObject();
                        listInSite.Update();
                        this.ClientContext.ExecuteQueryRetry();
                    }
                }
            }
            catch (Exception ex)
            {
                LogError(ex, "Failed to query list {0} with message {1}", this.ListTitle, ex.Message);
            }
        }
        /// <summary>
        /// Will evaluate the Library/List and if the list has reached the threshold it will produce SAFE queries
        /// </summary>
        /// <param name="onlineLibrary">The list to query</param>
        /// <param name="incrementor">(Default) 1000 rows in the query, can specify up to 5000</param>
        /// <param name="camlStatement">A base CAML query upon which the threshold query will be constructed</param>
        /// <param name="defaultStartItemId">(OPTIONAL) if specified the caml queries will begin at ID >= this value</param>
        /// <param name="defaultLastItemId">(OPTIONAL) if specified the caml queries will terminate at this value; if not specified a query will be executed to retreive the lastitemid</param>
        /// <returns>A collection of CAML queries NOT including WHERE</returns>
        public static List <string> SafeCamlClauseFromThreshold(this List onlineLibrary, int incrementor = 1000, string camlStatement = null, Nullable <int> defaultStartItemId = default(Nullable <int>), Nullable <int> defaultLastItemId = default(Nullable <int>))
        {
            if (incrementor > 5000)
            {
                throw new InvalidOperationException(string.Format("CAML Queries must return fewer than 5000 rows, you specified {0}", incrementor));
            }

            var camlQueries = new List <string>();
            var lastItemId  = 0;
            var startIdx    = 0;

            // Check if the List/Library ItemCount exists
            if (!onlineLibrary.IsPropertyAvailable(octx => octx.ItemCount))
            {
                onlineLibrary.Context.Load(onlineLibrary, octx => octx.ItemCount);
                onlineLibrary.Context.ExecuteQueryRetry();
            }

            // we have reached a threshold and need to parse based on other criteria
            var itemCount = onlineLibrary.ItemCount;

            if (itemCount > 5000)
            {
                if (defaultStartItemId.HasValue)
                {
                    startIdx = defaultStartItemId.Value;
                }

                if (defaultLastItemId.HasValue)
                {
                    lastItemId = defaultLastItemId.Value;
                }
                else
                {
                    lastItemId = onlineLibrary.QueryLastItemId();
                }

                for (var idx = startIdx; idx < lastItemId + 1;)
                {
                    var startsWithId = idx + 1;
                    var endsWithId   = (idx + incrementor);
                    if (endsWithId >= lastItemId)
                    {
                        endsWithId = lastItemId + 1;
                    }

                    var thresholdEq = new SPThresholdEnumerationModel()
                    {
                        StartsWithId = startsWithId,
                        EndsWithId   = endsWithId
                    };

                    var camlThresholdClause = thresholdEq.AndClause;
                    if (!string.IsNullOrEmpty(camlStatement))
                    {
                        camlThresholdClause = CAML.And(camlThresholdClause, camlStatement);
                    }
                    camlQueries.Add(camlThresholdClause);

                    idx += incrementor;
                }
            }
            else
            {
                camlQueries.Add(camlStatement ?? string.Empty);
            }

            return(camlQueries);
        }
        /// <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);
        }