Esempio n. 1
0
        public void ProcessListItem(IQueryable <TEntity> query, ContentIterator.ItemProcessor itemProcessor)
        {
            var caml     = GetSPQuery(query);
            var iterator = new ContentIterator();

            iterator.ProcessListItems(SPList, caml, itemProcessor, (e, i) => true);
        }
Esempio n. 2
0
        static void ExportTemplate(SPList list)
        {
            Log("Writing AutomatedTagging.csv...");

            Dictionary <SPContentTypeId, List <Guid> > taxonomyFieldsByContentTypeId = new Dictionary <SPContentTypeId, List <Guid> >();

            using (StreamWriter streamWriter = new StreamWriter("AutomatedTagging.csv"))
            {
                streamWriter.WriteLine("Filename,,Field,Tags,Field,Tags,...");
                ContentIterator contentIterator = new ContentIterator();
                contentIterator.ProcessListItems(list,
                                                 delegate(SPListItem listItem)
                {
                    List <Guid> fieldGuids;
                    if (!taxonomyFieldsByContentTypeId.TryGetValue(listItem.ContentTypeId, out fieldGuids))
                    {
                        fieldGuids = new List <Guid>();

                        foreach (SPField field in listItem.ContentType.Fields)
                        {
                            // Alternatively, the code could also support taxonomy fields that can take multiple values here.
                            if (field.TypeAsString == "TaxonomyFieldType")
                            {
                                fieldGuids.Add(field.Id);
                            }
                        }

                        taxonomyFieldsByContentTypeId.Add(listItem.ContentTypeId, fieldGuids);
                    }

                    if (fieldGuids.Count > 0)
                    {
                        streamWriter.Write(listItem.Url + ",");

                        foreach (Guid fieldGuid in fieldGuids)
                        {
                            SPField field = listItem.Fields[fieldGuid];
                            streamWriter.Write("," + field.InternalName + ",");
                        }
                        streamWriter.WriteLine();
                    }
                },
                                                 delegate(SPListItem listItem, Exception e)
                {
                    Debug.WriteLine("Error for item " + listItem.Url
                                    + ": " + e.Message);
                    return(true);
                }
                                                 );
            }
        }
Esempio n. 3
0
        public static void ProcessItems(this SPList list, SPQuery query, Action <SPListItemCollection> itemAction, Func <SPListItemCollection, Exception, bool> itemActionOnError)
        {
            if (query.RowLimit == 0)
            {
                query.RowLimit = SPHelper.MaxRowLimit;
            }

            ContentIterator cItems = new ContentIterator();

            //query.Query = query.Query + ContentIterator.ItemEnumerationOrderByNVPField;
            cItems.ProcessListItems(list, query, item => { if (itemAction != null)
                                                           {
                                                               itemAction(item);
                                                           }
                                    }, (item, ex) => itemActionOnError != null && itemActionOnError(item, ex));
        }
        public ArrayInstance GetAllWebs()
        {
            var webs = new List <SPWeb>();

            ContentIterator ci = new ContentIterator();

            ci.ProcessSite(m_site, true, webs.Add,
                           (web, ex) => false);

            var result = Engine.Array.Construct();

            foreach (var web in webs)
            {
                ArrayInstance.Push(result, new SPWebInstance(Engine, web));
            }
            return(result);
        }
Esempio n. 5
0
        /// <summary>
        /// Returns the total number of entities that correspond to the specified filter criteria.
        /// </summary>
        /// <param name="containerTitle"></param>
        /// <param name="path"></param>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public virtual int CountEntities(string containerTitle, string path, EntityFilterCriteria criteria)
        {
            SPSite site;
            var    web = GetDocumentStoreWeb(out site);

            SPList   list;
            SPFolder folder;

            if (SPDocumentStoreHelper.TryGetFolderFromPath(web, containerTitle, out list, out folder, path) == false)
            {
                return(0);
            }

            ContentIterator.EnsureContentTypeIndexed(list);

            var documentStoreEntityContentTypeId = list.ContentTypes.BestMatch(new SPContentTypeId(Constants.DocumentStoreEntityContentTypeId));

            var camlQuery = @"<Where>
    <Eq>
      <FieldRef Name=""ContentTypeId"" />
      <Value Type=""ContentTypeId"">" + documentStoreEntityContentTypeId + @"</Value>
    </Eq>
</Where>";

            var viewFields = SPDocumentStoreHelper.GetDocumentStoreEntityViewFieldsXml();

            var filteredListItems = new List <SPListItem>();

            var itemsIterator = new ContentIterator();

            itemsIterator.ProcessListItems(list, camlQuery + ContentIterator.ItemEnumerationOrderByPath + viewFields, ContentIterator.MaxItemsPerQueryWithViewFields, true, folder,
                                           spListItems =>
            {
                var listItems = FilterListItemEntities(spListItems.OfType <SPListItem>(),
                                                       criteria);
                // ReSharper disable AccessToModifiedClosure
                filteredListItems.AddRange(listItems);
                // ReSharper restore AccessToModifiedClosure
            },
                                           null);

            return(filteredListItems.Count);
        }
    protected void btnIterator_Click(object sender, EventArgs e)
    {
        using (SPSite site = new SPSite(SPContext.Current.Web.Url)) ;
        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.Lists.TryGetList("LargeList");
            if(list != null)
            {
                SPQuery camlQuery = new SPQuery();
                camlQuery.ViewFields = @"<FieldRef Name =""Title""/><FieldRef Name=""Description""/>";
                camlQuery.RowLimit = 8000;

                ContentIterator iterator = new ContentIterator();
                iterator.ProcessListItems(list, camlQuery, ProcessItem, ProcessError);
                grdData.DataSource = table;
                grdData.DataBind();
            }
        }
    }
Esempio n. 7
0
        private void MeasureUsage(SPList list)
        {
            SPQuery query = new SPQuery();

            query.Query = @"
                <View Scope='RecursiveAll'>

                <ViewFields>
                  <FieldRef Name='FileDirRef'/>
                  <FieldRef Name='ContentTypeId'/>
                </ViewFields>

                </View>
                ";

            Console.WriteLine("Querying usage for list: " + list.RootFolder.Url);
            Debug.WriteLine("Querying usage for list: " + list.RootFolder.Url);

            ContentIterator contentIterator = new ContentIterator();

            contentIterator.ProcessListItems(list,
                                             delegate(SPListItem listItem)
            {
                ReportRow row;
                if (this.rowsByContentTypeId.TryGetValue(listItem.ContentTypeId, out row))
                {
                    ++row.UsageCount;
                }
                else
                {
                    Debug.WriteLine("Error for item " + listItem.Url
                                    + ": Content Type Not Found: " + listItem.ContentTypeId.ToString());
                }
            },
                                             delegate(SPListItem listItem, Exception e)
            {
                Debug.WriteLine("Error for item " + listItem.Url
                                + ": " + e.Message);
                return(true);
            }
                                             );
        }
Esempio n. 8
0
        /// <summary>
        /// Lists all folders contained in the specified container.
        /// </summary>
        /// <param name="containerTitle">The container title.</param>
        /// <param name="path">The path.</param>
        /// <returns></returns>
        public virtual IList <Folder> ListAllFolders(string containerTitle, string path)
        {
            SPSite site;
            var    web = GetDocumentStoreWeb(out site);

            SPList   list;
            SPFolder folder;

            if (SPDocumentStoreHelper.TryGetFolderFromPath(web, containerTitle, out list, out folder, path) == false)
            {
                return(null);
            }

            ContentIterator.EnsureContentTypeIndexed(list);

            var folderContentTypeId = list.ContentTypes.BestMatch(SPBuiltInContentTypeId.Folder);

            var camlQuery = @"<Where>
    <Eq>
      <FieldRef Name=""ContentTypeId"" />
      <Value Type=""ContentTypeId"">" + folderContentTypeId + @"</Value>
    </Eq>
</Where>";

            var result        = new List <Folder>();
            var itemsIterator = new ContentIterator();

            itemsIterator.ProcessListItems(list, camlQuery + ContentIterator.ItemEnumerationOrderByPath, ContentIterator.MaxItemsPerQuery, false, folder,
                                           spListItems =>
            {
                // ReSharper disable ConvertToLambdaExpression
                result.AddRange(spListItems.OfType <SPListItem>()
                                .Select(
                                    spListItem =>
                                    SPDocumentStoreHelper.MapFolderFromSPFolder(
                                        spListItem.Folder)));
                // ReSharper restore ConvertToLambdaExpression
            },
                                           null);

            return(result);
        }
Esempio n. 9
0
        INode IXmlNodeProcessor <INode> .ProcessDocument <TProvider>(TProvider provider, ContentIterator <INode> content)
        {
            var baseNode = MakeUriNode(provider.BaseUri);

            rdf.HandleTriple(baseNode, value, MakeList(content(baseNode)) ?? nil);
            return(baseNode);
        }
Esempio n. 10
0
        INode IXmlNodeProcessor <INode> .ProcessElement <TProvider>(TProvider provider, INode baseNode, Uri originalBaseUri, INode defaultNamespace, ContentIterator <INode> content)
        {
            var  empty    = provider.IsEmpty;
            bool sameBase = provider.BaseUri == originalBaseUri;

            Action <INode> elementInit = null;
            var            elementType = CreateElementType(provider, defaultNamespace);

            elementInit += n => rdf.HandleTriple(n, a, elementType);

            string       id            = null;
            INode        innerBaseNode = baseNode;
            XmlValueInfo info          = default;

            while (provider.MoveToNextAttribute())
            {
                if (provider.IsDefault && !ExportDefault)
                {
                    continue;
                }
                var property = CreateAttributeType(provider, elementType);
                var value    = CreateAttributeValue(provider);
                elementInit += n => rdf.HandleTriple(n, property, value);

                if (value is ILiteralNode literal && UriComparer.Equals(literal.DataType, ID))
                {
                    id = XmlConvert.VerifyNCName(provider.Value);
                }
Esempio n. 11
0
        XPathNodeView FillSubRow(ContentIterator iter, Shape shape, object[] columns)
        {
            if (null == columns)
            {
                int colCount = shape.SubShapes.Count;
                if (0 == colCount)
                {
                    colCount = 1;
                }
                columns = new object[colCount];
            }

            switch (shape.BindingType)
            {
            case BindingType.Element:
                columns[0] = FillColumn(iter, shape);
                break;

            case BindingType.Sequence: {
                int iPrev = -1;
                int i;
                while (null != iter.Node)
                {
                    i = shape.FindMatchingSubShape(iter.Particle);
                    if (i <= iPrev)
                    {
                        break;
                    }
                    columns[i] = FillColumn(iter, shape.SubShape(i));
                    iPrev      = i;
                }
                break;
            }

            case BindingType.All: {
                while (null != iter.Node)
                {
                    int i = shape.FindMatchingSubShape(iter.Particle);
                    if (-1 == i || null != columns[i])
                    {
                        break;
                    }
                    columns[i] = FillColumn(iter, shape.SubShape(i));
                }
                break;
            }

            case BindingType.Choice: {
                int i = shape.FindMatchingSubShape(iter.Particle);
                if (-1 != i)
                {
                    columns[i] = FillColumn(iter, shape.SubShape(i));
                }
                break;
            }

            case BindingType.Repeat:
            default:
                // should not map to a row
                throw new NotSupportedException();
            }
            return(new XPathNodeView(this, null, columns));
        }
Esempio n. 12
0
        object FillColumn(ContentIterator iter, Shape shape)
        {
            object val;

            switch (shape.BindingType)
            {
            case BindingType.Element:
                val = iter.Node;
                iter.Next();
                break;

            case BindingType.ElementNested: {
                ArrayList rows = new ArrayList();
                rows.Add(iter.Node);
                iter.Next();
                val = new XPathDocumentView(null, rows, shape.NestedShape);
                break;
            }

            case BindingType.Repeat: {
                ArrayList rows     = new ArrayList();
                Shape     subShape = shape.SubShape(0);
                if (subShape.BindingType == BindingType.ElementNested)
                {
                    Shape             nestShape = subShape.NestedShape;
                    XPathDocumentView xivc      = new XPathDocumentView(null, null, nestShape);
                    XPathNode         nd;
                    while (null != (nd = iter.Node) &&
                           subShape.IsParticleMatch(iter.Particle))
                    {
                        rows.Add(nd);
                        iter.Next();
                    }
                    xivc.SetRows(rows);
                    val = xivc;
                }
                else
                {
                    XPathDocumentView xivc = new XPathDocumentView(null, null, subShape);
                    XPathNode         nd;
                    while (null != (nd = iter.Node) &&
                           shape.IsParticleMatch(iter.Particle))
                    {
                        rows.Add(xivc.FillSubRow(iter, subShape, null));
                    }
                    xivc.SetRows(rows);
                    val = xivc;
                }
                break;
            }

            case BindingType.Sequence:
            case BindingType.Choice:
            case BindingType.All: {
                XPathDocumentView docview = new XPathDocumentView(null, null, shape);
                ArrayList         rows    = new ArrayList();
                rows.Add(docview.FillSubRow(iter, shape, null));
                docview.SetRows(rows);
                val = docview;
                break;
            }

            default:
            case BindingType.Text:
            case BindingType.Attribute:
                throw new NotSupportedException();
            }
            return(val);
        }
        /// <summary>
        /// An item is being updated.
        /// </summary>
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
                  {
                      string originalMeetingID = properties.ListItem["CommitteeMeeting"].ToString();
                      if (properties.AfterProperties["CommitteeMeeting"] != null)
                      {
                          string newMeetingID = properties.AfterProperties["CommitteeMeeting"].ToString();
                          string originalTitle = properties.ListItem["Title"].ToString();
                          string newTitle = properties.AfterProperties["Title"].ToString();

                          if (originalMeetingID != newMeetingID)
                          {
                              InitializeWebAppProperties(properties);
                              // Get the meeting details (Meeting Title, Meeting Date)
                              string newMeetingTitle = null;
                              string newMeetingDate = null;

                              //Get the meeting date of the new Meeting ID
                              using (SPSite boardSite = new SPSite(boardSiteURL))
                              using (SPWeb boardWeb = boardSite.OpenWeb())
                              {
                                  SPList meetingsList = boardWeb.Lists[boardMeetingListName];
                                  SPQuery query = new SPQuery()
                                  {
                                      Query = string.Format(@"<Where>
                                                            <Eq>
                                                                <FieldRef Name='ID'/>
                                                                <Value Type='Number'>{0}</Value>
                                                            </Eq>
                                                        </Where>", newMeetingID)
                                  };
                                  foreach (SPListItem meeting in meetingsList.GetItems(query))
                                  {
                                      newMeetingTitle = meeting["Title"].ToString();
                                      newMeetingDate = meeting["EventDate"].ToString();
                                  }
                              }

                              //Before we move the meeting, ensure that this does not confict with the Bid Date if this is Procurement Resolution.
                              if (properties.ListItem["AgendaType"].ToString() == "Procurement Resolution")
                              {
                                  //Get the document workspace of this Agenda
                                  string documentWorkspaceLink = properties.ListItem["DocumentWorkspace"].ToString();
                                  documentWorkspaceLink = documentWorkspaceLink.Substring(0, documentWorkspaceLink.IndexOf("Shared Documents"));
                                  SPFieldUrlValue docWorkspaceURL = new SPFieldUrlValue(documentWorkspaceLink);
                                  SPWeb documentWorkspace = null;

                                  foreach (SPWeb workspace in properties.Web.Webs)
                                  {
                                      if (docWorkspaceURL.Url.Contains(workspace.Url))
                                      {
                                          documentWorkspace = workspace;
                                          break;
                                      }
                                  }

                                  using (documentWorkspace)
                                  {
                                      //Now get the list holding the document set.
                                      SPList sharedDocuments = documentWorkspace.Lists[libraryNameInDocumentWorkspace];

                                      Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet sourceDocumentSet = Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(sharedDocuments.Items[0].Folder);

                                      ContentIterator docSetIterator = new ContentIterator();
                                      docSetIterator.ProcessFilesInFolder(sourceDocumentSet.Folder,
                                          true,
                                          new ContentIterator.FileProcessor((SPFile file) =>
                                          {
                                              //Check if this is a Procurement Resolution
                                              if (file.Item.ContentType.Name == "Procurement Resolution")
                                              {
                                                  if (!string.IsNullOrEmpty(file.Properties["ContractBidDate"].ToString()))
                                                  {
                                                      DateTime contractBidDate = DateTime.Parse(file.Properties["ContractBidDate"].ToString());

                                                      DateTime meetingDate = DateTime.Parse(newMeetingDate);

                                                      if (meetingDate > contractBidDate)
                                                      {
                                                          properties.ErrorMessage = "Agenda cannot be moved to this meeting because the bid date specified for this Procurment Resolution is earlier than the new board meeting date";
                                                          properties.Status = SPEventReceiverStatus.CancelWithError;
                                                          properties.Cancel = true;
                                                      }
                                                  }
                                              }
                                          }),
                                          new ContentIterator.FileProcessorErrorCallout((SPFile file, Exception ex) =>
                                          {
                                              //TODO: Handle the error during iteration of files
                                              return false;
                                          })
                                              );

                                  }
                              }

                              if (properties.Cancel != true)
                              {
                                  SPListItem agendaItem = properties.ListItem;
                                  this.EventFiringEnabled = false;
                                  agendaItem["MeetingTitle"] = newMeetingTitle;
                                  agendaItem["MeetingDate"] = newMeetingDate;
                                  agendaItem.SystemUpdate(false);
                                  //agendaItem.Update();
                                  this.EventFiringEnabled = true;

                              }

                          }
                      }
                      //base.ItemUpdating(properties);
                  });
        }
Esempio n. 14
0
        static void ImportTemplate(SPList list)
        {
            TaxonomySession taxonomySession = new TaxonomySession(list.ParentWeb.Site, updateCache: true);

            // STEP 1: Load the TermSet objects for the SPField objects.
            Dictionary <string, TermSetLookup> termSetsByInternalName = new Dictionary <string, TermSetLookup>(StringComparer.OrdinalIgnoreCase);

            foreach (SPField field in list.Fields)
            {
                // Alternatively, the code could also support taxonomy fields that can take multiple values here.
                if (field.TypeAsString != "TaxonomyFieldType")
                {
                    continue;
                }

                TaxonomyField taxonomyField = field as TaxonomyField;
                if (taxonomyField == null)
                {
                    continue;
                }

                TermStore termStore = taxonomySession.TermStores[taxonomyField.SspId];
                TermSet   termSet   = termStore.GetTermSet(taxonomyField.TermSetId);
                termSetsByInternalName.Add(field.InternalName, new TermSetLookup(termSet));
            }

            // STEP 2: Load the Excel file.
            Dictionary <string, ExcelRow> excelRowsByUrl = new Dictionary <string, ExcelRow>(StringComparer.OrdinalIgnoreCase);

            // Parse the input file.
            Log("Reading AutomatedTagging.csv...");

            using (StreamReader streamReader = new StreamReader("AutomatedTagging.csv"))
            {
                if (!streamReader.ReadLine().Contains("Filename"))
                {
                    throw new InvalidOperationException("Invalid file format; header is missing");
                }

                int lineNumber = 1;
                for (; ;)
                {
                    string line = streamReader.ReadLine();
                    ++lineNumber;
                    if (line == null)
                    {
                        break;
                    }

                    string[] csvValues = ParseCsvLine(line);
                    if (csvValues == null)
                    {
                        throw new InvalidOperationException("[line " + lineNumber + "]: Syntax error");
                    }

                    if (csvValues.Length < 1)
                    {
                        continue;
                    }

                    ExcelRow excelRow = new ExcelRow(csvValues[0], lineNumber);
                    for (int i = 2; i + 1 < csvValues.Length;)
                    {
                        string key = csvValues[i++].Trim();
                        if (key == "")
                        {
                            break;
                        }

                        string value = csvValues[i++].Trim();
                        if (value == "")
                        {
                            break;
                        }

                        SPField       field         = list.Fields.GetFieldByInternalName(key);
                        TermSetLookup termSetLookup = termSetsByInternalName[key];
                        Guid          termId        = termSetLookup.GetTermId(value);

                        excelRow.Pairs.Add(new KeyValuePair <string, Guid>(field.InternalName, termId));
                    }

                    excelRowsByUrl.Add(excelRow.ListItemUrl, excelRow);
                }
            }

            // STEP 3: Update the list items.
            ContentIterator contentIterator = new ContentIterator();

            contentIterator.ProcessListItems(list,
                                             delegate(SPListItem listItem)
            {
                ExcelRow excelRow;
                if (!excelRowsByUrl.TryGetValue(listItem.Url, out excelRow))
                {
                    return;
                }

                excelRow.Processed = true;

                bool updated = false;
                foreach (KeyValuePair <string, Guid> pair in excelRow.Pairs)
                {
                    TaxonomyField taxonomyField = (TaxonomyField)listItem.Fields.GetFieldByInternalName(pair.Key);

                    TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(taxonomyField);
                    taxonomyFieldValue.TermGuid           = pair.Value.ToString();

                    TaxonomyFieldValue oldValue = listItem[taxonomyField.Id] as TaxonomyFieldValue;
                    if (oldValue == null || oldValue.TermGuid != taxonomyFieldValue.TermGuid)
                    {
                        taxonomyField.SetFieldValue(listItem, taxonomyFieldValue);
                        updated = true;
                    }
                }

                if (updated)
                {
                    Log("Updating item: " + listItem.Url);
                    listItem.Update();
                }
            },
                                             delegate(SPListItem listItem, Exception e)
            {
                Log("Error processing item " + listItem.Url
                    + ": " + e.Message);
                return(true);
            }
                                             );

            // Were any items missed?
            Log("");
            List <ExcelRow> missedRows = excelRowsByUrl.Values.Where(row => !row.Processed).ToList();

            if (missedRows.Count > 0)
            {
                Log("Failed to match these rows");
                foreach (ExcelRow row in missedRows)
                {
                    Log("  " + row.ListItemUrl);
                }
            }
        }
        public void PublishAgendaToBoard(int agendaID)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(emisSiteURL))
                {
                    using (SPWeb emisWeb = site.OpenWeb(emisSiteRelativeURl))
                    {
                        SPList agendaList = emisWeb.Lists["Board Agenda"];
                        SPQuery query = new SPQuery()
                        {
                            Query = string.Format(@"<Query>
                                              <Where>
                                                <Eq>
                                                  <FieldRef Name='ID' />
                                                  <Value Type='Counter'>{0}</Value>
                                                </Eq>
                                              </Where>
                                            </Query>", agendaID.ToString())
                        };

                        foreach (SPListItem agenda in agendaList.GetItems(query))
                        {
                            if ((agenda["ID"].ToString() == agendaID.ToString()) && (agenda["Agenda Status"].ToString() == "Ready to Publish"))
                            {
                                int meetingID = int.Parse(agenda["CommitteeMeeting"].ToString());
                                string AgendaTitle = agenda["Title"].ToString();

                                SPFieldUrlValue docSetHomePage = new SPFieldUrlValue(agenda["DocumentWorkspace"].ToString());

                                string documentWorkspaceURL = docSetHomePage.Url.Substring(0, docSetHomePage.Url.IndexOf("Shared%20Documents"));

                                using (SPWeb documentWorkspace = site.OpenWeb(documentWorkspaceURL))
                                {
                                    //Now get the list holding the document set.
                                    SPList sharedDocuments = documentWorkspace.Lists[libraryNameInDocumentWorkspace];

                                    Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet sourceDocumentSet = Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(sharedDocuments.Items[0].Folder);

                                    //Once you have your meetingID, find the meetingWorkspace
                                    using (SPSite boardSite = new SPSite(boardSiteURL))
                                    using (SPWeb boardWeb = boardSite.OpenWeb())
                                    {
                                        SPList meetingsList = boardWeb.Lists["Board Meeting"]; //TODO: Get from configuration

                                        SPListItem meeting = meetingsList.GetItemById(meetingID);

                                        //Now Get the Meeting Workspace
                                        SPFieldUrlValue meetingWorkspaceURL = new SPFieldUrlValue(meeting["Workspace"].ToString());
                                        using (SPWeb boardRootWeb = boardSite.OpenWeb())
                                        {
                                            SPMeeting meetingSites = SPMeeting.GetMeetingInformation(boardWeb);
                                            SPWebCollection meetingWorkspaces = meetingSites.GetWorkspacesToLinkTo(false);

                                            SPWeb meetingWeb = null;
                                            foreach (SPWeb meetingWorkspace in meetingWorkspaces)
                                            {
                                                if (meetingWorkspaceURL.Url.Contains(meetingWorkspace.Url))
                                                {
                                                    meetingWeb = meetingWorkspace;
                                                    break;
                                                }
                                            }

                                            SPList documentLibrary = meetingWeb.Lists["Document Library"];

                                            meetingWeb.AllowUnsafeUpdates = true;
                                            string instanceID = "1";

                                            Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet AgendaDocSetInMeetingWorkspace = CreateDocumentSet(documentLibrary, AgendaTitle);

                                            //AgendaDocSetInMeetingWorkspace.Item.Update();
                                            documentLibrary.Update();
                                            //Iterate through the source Document Set and copy the files over.

                                            ContentIterator docSetIterator = new ContentIterator();
                                            docSetIterator.ProcessFilesInFolder(sourceDocumentSet.Folder,
                                                true,
                                                new ContentIterator.FileProcessor((SPFile file) =>
                                                {
                                                    //documentLibrary.RootFolder.SubFolders[instanceID].Files.Add(AgendaDocSetInMeetingWorkspace.Item.Folder.Url, file.OpenBinary(), true);
                                                    if (bool.Parse(file.Properties["PublishDocumentToBoard"].ToString()) == true)
                                                    {
                                                        CopyFile(file, AgendaDocSetInMeetingWorkspace, AgendaTitle);
                                                        meetingWeb.Update();
                                                    }
                                                }),
                                                new ContentIterator.FileProcessorErrorCallout((SPFile file, Exception ex) =>
                                                {
                                                    //TODO: Handle the error during iteration of files
                                                    return false;
                                                })
                                                    );

                                            //Also update that particular agenda with all the pertinetn information
                                            SPList agendaListInWorkspace = meetingWeb.Lists["Agenda"];

                                            SPQuery agendaQuery = new SPQuery()
                                            {
                                                Query = string.Format(@"<Where>
                                                                    <Eq>
                                                                        <FieldRef Name='AgendaID'/>
                                                                        <Value Type='Number'>{0}</Value>
                                                                    </Eq>
                                                                </Where>", agendaID)
                                            };
                                            foreach (SPListItem agendaInWorkspace in agendaListInWorkspace.GetItems(agendaQuery))
                                            {
                                                SPFieldUrlValue docsURLValue = new SPFieldUrlValue();
                                                string URLValue = AgendaDocSetInMeetingWorkspace.ParentList.ParentWeb.Site.Url + AgendaDocSetInMeetingWorkspace.ParentList.ParentWebUrl + "/" + AgendaDocSetInMeetingWorkspace.Item.Url;
                                                URLValue = URLValue.Replace(" ", "%20");
                                                docsURLValue.Url = URLValue;
                                                docsURLValue.Description = "Documents";
                                                agendaInWorkspace["Documents"] = docsURLValue;

                                                //agendaInWorkspace["Documents"] = string.Format("{0}, Documents", AgendaDocSetInMeetingWorkspace.WelcomePageUrl);
                                                agendaInWorkspace.Update();
                                            }

                                            agenda["Agenda Status"] = "Published to Board";
                                            agenda.Update();

                                            meetingWeb.AllowUnsafeUpdates = false;

                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            });
        }
Esempio n. 16
0
        public DiffResultInstance Diff(SPFolderInstance targetFolder, object recursive)
        {
            if (targetFolder == null)
            {
                throw new JavaScriptException(Engine, "Error", "Target Folder must be specified.");
            }

            var bRecurse = true;

            if (recursive != Undefined.Value && recursive != Null.Value && recursive != null)
            {
                bRecurse = TypeConverter.ToBoolean(recursive);
            }

            var sourceFolderInfo = new List <DiffInfoInstance>();
            var targetFolderInfo = new List <DiffInfoInstance>();

            var itemsIterator = new ContentIterator();

            itemsIterator.ProcessFilesInFolder(m_folder, bRecurse,
                                               spFile =>
            {
                var fileInfo = new DiffInfoInstance(Engine)
                {
                    Url = spFile.Url.ReplaceFirstOccurenceIgnoreCase(m_folder.Url, ""),
                    TimeLastModified = JurassicHelper.ToDateInstance(Engine,
                                                                     spFile.TimeLastModified)
                };

                var fileBytes = spFile.OpenBinary(SPOpenBinaryOptions.SkipVirusScan);
                using (var md5 = MD5.Create())
                {
                    fileInfo.Hash =
                        Convert.ToBase64String(md5.ComputeHash(fileBytes));
                }

                sourceFolderInfo.Add(fileInfo);
            },
                                               null);

            itemsIterator.ProcessFilesInFolder(targetFolder.Folder, bRecurse,
                                               spFile =>
            {
                var fileInfo = new DiffInfoInstance(Engine)
                {
                    Url = spFile.Url.ReplaceFirstOccurenceIgnoreCase(targetFolder.Folder.Url, ""),
                    TimeLastModified = JurassicHelper.ToDateInstance(Engine,
                                                                     spFile.TimeLastModified)
                };

                var fileBytes = spFile.OpenBinary(SPOpenBinaryOptions.SkipVirusScan);
                using (var md5 = MD5.Create())
                {
                    fileInfo.Hash =
                        Convert.ToBase64String(md5.ComputeHash(fileBytes));
                }

                targetFolderInfo.Add(fileInfo);
            },
                                               null);

            var result = new DiffResultInstance(Engine);

            result.Process(sourceFolderInfo, targetFolderInfo);
            return(result);
        }
        /// <summary>
        /// An item is being updated.
        /// </summary>
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            string originalMeetingID = properties.ListItem["CommitteeMeeting"].ToString();
               if (properties.AfterProperties["CommitteeMeeting"] != null)
               {
               string newMeetingID = properties.AfterProperties["CommitteeMeeting"].ToString();
               string originalTitle = properties.ListItem["Title"].ToString();
               string newTitle = properties.AfterProperties["Title"].ToString();

               if (originalTitle != newTitle)
               {
                   //Update the Emis Look Ahead List
                   InitializeWebAppProperties(properties);

                   // Update Look Ahead list in Emis
                   using (PBEntitiesDataContext ctx = new PBEntitiesDataContext(emisSiteURL))
                   {
                       EntityList<FutureAgendaItemsLookAheadForEmis> agendas = ctx.GetList<FutureAgendaItemsLookAheadForEmis>("Future Agenda Items");
                       //TODO: FILTER this list based on agenda ID
                       var agendaInLookAheadEmis = agendas.Where(a => a.Id == properties.ListItemId).Single();

                       agendaInLookAheadEmis.BoardMeeting = newTitle;
                       ctx.SubmitChanges();
                   }

                   using (SPSite boardSite = new SPSite(boardSiteURL))
                   using (SPWeb boardWeb = boardSite.OpenWeb())
                   {
                       SPList meetingsList = boardWeb.Lists[boardMeetingListName];

                       //While we have the boardWeb object open, Update the look ahead list in Board

                       SPList lookAheadListInBoard = boardWeb.Lists[lookAheadListNameInBoard];
                       SPQuery queryForLookAheadList = new SPQuery()
                       {
                           Query = string.Format(@"<Where>
                                <Eq>
                                    <FieldRef Name='AgendaID'/>
                                    <Value Type='Text'>{0}</Value>
                                </Eq>
                            </Where>", properties.ListItemId)
                       };

                       foreach (SPListItem agendaInBoardLookAhead in lookAheadListInBoard.GetItems(queryForLookAheadList))
                       {
                           agendaInBoardLookAhead["Board Agenda"] = newTitle;
                           agendaInBoardLookAhead.Update();
                       }

                       //Get oldMeetingWorkspace first
                       string meetingURL = null;
                       SPQuery queryForMeeting = new SPQuery()
                       {
                           Query = string.Format(@"<Where>
                                        <Eq>
                                            <FieldRef Name='ID'/>
                                            <Value Type='Number'>{0}</Value>
                                        </Eq>
                                    </Where>", originalMeetingID)
                       };
                       foreach (SPListItem meeting in meetingsList.GetItems(queryForMeeting))
                       {
                           meetingURL = meeting["Workspace"].ToString();
                       }
                       SPFieldUrlValue meetingLink = new SPFieldUrlValue(meetingURL);

                       SPMeeting meetingSites = SPMeeting.GetMeetingInformation(boardWeb);
                       SPWebCollection meetingWorkspaces = meetingSites.GetWorkspacesToLinkTo(false);

                       foreach (SPWeb meetingWorkspace in meetingWorkspaces)
                       {
                           if ((meetingLink.Url.Contains(meetingWorkspace.Url)) )
                           {

                               //Now loop through the Agenda Items
                               SPList sourceAgendaList = meetingWorkspace.Lists["Agenda"];
                               foreach (SPListItem agenda in sourceAgendaList.Items)
                               {
                                   if (agenda["AgendaID"].ToString() == properties.ListItemId.ToString())
                                   {
                                       agenda["Subject"] = newTitle;
                                       agenda.Update();
                                   }
                               }
                               break;
                           }
                       }
                   }
                   //Update the Board look ahead list

                   //Update the agenda item in the board meeting workspace

               }

               if (originalMeetingID != newMeetingID)
               {
                   InitializeWebAppProperties(properties);
                   // Get the meeting details (Meeting Title, Meeting Date)
                   string newMeetingTitle = null;
                   string newMeetingDate = null;
                   string newMeetingURL = null;

                   //Get the meeting date of the new Meeting ID
                   using (SPSite boardSite = new SPSite(boardSiteURL))
                   using (SPWeb boardWeb = boardSite.OpenWeb())
                   {
                       SPList meetingsList = boardWeb.Lists[boardMeetingListName];
                       SPQuery query = new SPQuery()
                       {
                           Query = string.Format(@"<Where>
                                                            <Eq>
                                                                <FieldRef Name='ID'/>
                                                                <Value Type='Number'>{0}</Value>
                                                            </Eq>
                                                        </Where>", newMeetingID)
                       };
                       foreach (SPListItem meeting in meetingsList.GetItems(query))
                       {
                           newMeetingURL = meeting["Workspace"].ToString();
                           newMeetingTitle = meeting["Title"].ToString();
                           newMeetingDate = meeting["EventDate"].ToString();
                       }
                   }

                   //Before we move the meeting, ensure that this does not confict with the Bid Date if this is Procurement Resolution.
                   if (properties.ListItem["AgendaType"].ToString() == "Procurement Resolution")
                   {
                       //Get the document workspace of this Agenda
                       SPFieldUrlValue docWorkspaceURL = new SPFieldUrlValue(properties.ListItem["DocumentWorkspace"].ToString());
                       SPWeb documentWorkspace = null;

                        foreach (SPWeb workspace in properties.Web.Webs)
                        {
                            if (workspace.Url == docWorkspaceURL.Url)
                            {
                                documentWorkspace = workspace;
                                break;
                            }
                        }

                        using (documentWorkspace)
                        {
                            //Now get the list holding the document set.
                            SPList sharedDocuments = documentWorkspace.Lists[libraryNameInDocumentWorkspace];

                            Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet sourceDocumentSet = Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(sharedDocuments.Items[0].Folder);

                            ContentIterator docSetIterator = new ContentIterator();
                            docSetIterator.ProcessFilesInFolder(sourceDocumentSet.Folder,
                                true,
                                new ContentIterator.FileProcessor((SPFile file) =>
                                {
                                    //Check if this is a Procurement Resolution
                                    if (file.Item.ContentType.Name == "Procurement Resolution")
                                    {
                                        if (!string.IsNullOrEmpty(file.Properties["ContractBidDate"].ToString()))
                                        {
                                            DateTime contractBidDate = DateTime.Parse(file.Properties["ContractBidDate"].ToString());

                                            DateTime meetingDate = DateTime.Parse(newMeetingDate);

                                            if (meetingDate > contractBidDate)
                                            {
                                                properties.ErrorMessage = "Agenda cannot be moved to this meeting because the bid date specified for this Procurment Resolution is earlier than the new board meeting date";
                                                properties.Status = SPEventReceiverStatus.CancelWithError;
                                                properties.Cancel = true;
                                            }
                                        }

                                    }
                                }),
                                new ContentIterator.FileProcessorErrorCallout((SPFile file, Exception ex) =>
                                {
                                    //TODO: Handle the error during iteration of files
                                    return false;
                                })
                                    );

                        }
                   }

                   if (properties.Cancel != true)
                   {
                       SPListItem agendaItem = properties.ListItem;
                       this.EventFiringEnabled = false;
                       agendaItem["MeetingTitle"] = newMeetingTitle;
                       agendaItem["MeetingDate"] = newMeetingDate;
                       agendaItem.SystemUpdate(false);
                       //agendaItem.Update();
                       this.EventFiringEnabled = true;

                       using (SPSite boardSite = new SPSite(boardSiteURL))
                       using (SPWeb boardWeb = boardSite.OpenWeb())
                       {
                           SPList meetingsList = boardWeb.Lists[boardMeetingListName];

                           //While we have the boardWeb object open, Update the look ahead list in Board

                           SPList lookAheadListInBoard = boardWeb.Lists[lookAheadListNameInBoard];
                           SPQuery queryForLookAheadList = new SPQuery()
                           {
                               Query = string.Format(@"<Where>
                                <Eq>
                                    <FieldRef Name='AgendaID'/>
                                    <Value Type='Text'>{0}</Value>
                                </Eq>
                            </Where>", properties.ListItemId)
                           };
                           foreach (SPListItem agendaInEmisLookAhead in lookAheadListInBoard.GetItems(queryForLookAheadList))
                           {
                               agendaInEmisLookAhead["Meeting Date"] = newMeetingDate;
                               agendaInEmisLookAhead["Meeting Workspace"] = newMeetingURL;

                               agendaInEmisLookAhead.Update();
                               //Also Check the Agenda Status. If 'Published To Board', then move document set to new Meeting Workspace
                               if (agendaInEmisLookAhead["Agenda Status"].ToString() == "Published to Board")
                               {
                                   //Get oldMeetingWorkspace first
                                   string oldMeetingURL = null;
                                   SPQuery queryForOldMeeting = new SPQuery()
                                   {
                                       Query = string.Format(@"<Where>
                                        <Eq>
                                            <FieldRef Name='ID'/>
                                            <Value Type='Number'>{0}</Value>
                                        </Eq>
                                    </Where>", originalMeetingID)
                                   };
                                   foreach (SPListItem meeting in meetingsList.GetItems(queryForOldMeeting))
                                   {
                                       oldMeetingURL = meeting["Workspace"].ToString();
                                   }
                                   SPFieldUrlValue oldMeetingLink = new SPFieldUrlValue(oldMeetingURL);
                                   SPFieldUrlValue newMeetingLink = new SPFieldUrlValue(newMeetingURL);
                                   SPWeb oldMeetingWorkspace = null;
                                   SPWeb newMeetingWorkspace = null;

                                   SPMeeting meetingSites = SPMeeting.GetMeetingInformation(boardWeb);
                                   SPWebCollection meetingWorkspaces = meetingSites.GetWorkspacesToLinkTo(false);

                                   bool oldMeetingWorkspaceFound = false;
                                   bool newMeetingWorkspaceFound = false;

                                   foreach (SPWeb meetingWorkspace in meetingWorkspaces)
                                   {
                                       if ((oldMeetingLink.Url.Contains(meetingWorkspace.Url)) && (!oldMeetingWorkspaceFound))
                                       {
                                           oldMeetingWorkspace = meetingWorkspace;
                                           oldMeetingWorkspaceFound = true;
                                           if ((oldMeetingWorkspaceFound) && (newMeetingWorkspaceFound))
                                               break;
                                       }

                                       if ((newMeetingLink.Url.Contains(meetingWorkspace.Url)) && (!newMeetingWorkspaceFound))
                                       {
                                           newMeetingWorkspace = meetingWorkspace;
                                           newMeetingWorkspaceFound = true;
                                           if ((oldMeetingWorkspaceFound) && (newMeetingWorkspaceFound))
                                               break;
                                       }
                                   }

                                   //Get the document Set
                                   Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet sourceDocumentSet;
                                   //= Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(sharedDocuments.Items[0].Folder);
                                   SPList sourceDocumentLibrary = oldMeetingWorkspace.Lists["Document Library"];
                                   string destinationDocumentSetURL = null;
                                   foreach (SPListItem sourceDoc in sourceDocumentLibrary.Items)
                                   {

                                       //If the title of the item being moved matches the name of the Document Set, its our Document Set List Item.
                                       if (sourceDoc["Name"].ToString() == properties.ListItem.Title)
                                       {
                                           SPList destinationDocumentLibrary = newMeetingWorkspace.Lists["Document Library"];

                                           //Get the source Document Set.
                                           sourceDocumentSet = Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(sourceDocumentLibrary.Items[sourceDoc.UniqueId].Folder);

                                           newMeetingWorkspace.AllowUnsafeUpdates = true;
                                           oldMeetingWorkspace.AllowUnsafeUpdates = true;
                                           //Create new Document Set in new meeting workspace
                                           Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet destinationDocumentSet = CreateDocumentSet(destinationDocumentLibrary, properties.ListItem.Title);

                                           ContentIterator docSetIterator = new ContentIterator();
                                           docSetIterator.ProcessFilesInFolder(sourceDocumentSet.Folder,
                                               true,
                                               new ContentIterator.FileProcessor((SPFile file) =>
                                               {
                                                   CopyFile(file, destinationDocumentSet);
                                                   newMeetingWorkspace.Update();
                                               }),
                                               new ContentIterator.FileProcessorErrorCallout((SPFile file, Exception ex) =>
                                               {
                                                   //TODO: Handle the error during iteration of files
                                                   return false;
                                               })
                                                   );

                                           destinationDocumentSetURL = destinationDocumentSet.ParentList.ParentWeb.Site.Url + destinationDocumentSet.ParentList.ParentWebUrl + "/" + destinationDocumentSet.Item.Url;
                                           //Delete the document set from the source document library.
                                           sourceDocumentLibrary.Items.DeleteItemById(sourceDoc.ID);
                                       }
                                   }

                                   //Now loop through the Agenda Items
                                   SPList sourceAgendaList = oldMeetingWorkspace.Lists["Agenda"];
                                   foreach (SPListItem agenda in sourceAgendaList.Items)
                                   {
                                       if (agenda["AgendaID"].ToString() == properties.ListItemId.ToString())
                                       {
                                           SPList destinationAgendaList = newMeetingWorkspace.Lists["Agenda"];
                                           SPListItem movedAgenda = destinationAgendaList.Items.Add();
                                           movedAgenda["Subject"] = agenda["Subject"].ToString();
                                           if (agenda["Owner"] != null)
                                           {
                                               movedAgenda["Owner"] = agenda["Owner"].ToString();
                                           }
                                           if (agenda["Time"] != null)
                                           {
                                               movedAgenda["Time"] = agenda["Time"].ToString();
                                           }

                                           string sponsorValue = agenda["Sponsor"].ToString();
                                           SPFieldUser userField = sourceAgendaList.Fields.GetFieldByInternalName("Sponsor") as SPFieldUser;
                                           SPFieldUserValue itemValue = (SPFieldUserValue)userField.GetFieldValue(sponsorValue);
                                           SPUser sponsor = itemValue.User;

                                           movedAgenda["Sponsor"] = sponsor;

                                           if (agenda["Office"] != null)
                                           {
                                               movedAgenda["Office"] = agenda["Office"].ToString();
                                           }
                                           if (agenda["Documents"] != null)
                                           {
                                               SPFieldUrlValue docsURLValue = new SPFieldUrlValue();
                                               destinationDocumentSetURL = destinationDocumentSetURL.Replace(" ", "%20");
                                               docsURLValue.Url = destinationDocumentSetURL;
                                               docsURLValue.Description = "Documents";
                                               movedAgenda["Documents"] = docsURLValue;
                                           }

                                           movedAgenda.Update();

                                           sourceAgendaList.Items.DeleteItemById(agenda.ID);
                                       }
                                   }

                                   newMeetingWorkspace.AllowUnsafeUpdates = false;
                                   oldMeetingWorkspace.AllowUnsafeUpdates = false;
                               }
                           }
                       }
                       // Update Look Ahead list in Emis
                       using (PBEntitiesDataContext ctx = new PBEntitiesDataContext(emisSiteURL))
                       {
                           EntityList<FutureAgendaItemsLookAheadForEmis> agendas = ctx.GetList<FutureAgendaItemsLookAheadForEmis>("Future Agenda Items");
                           //TODO: FILTER this list based on agenda ID
                           var agendaInLookAheadEmis = agendas.Where(a => a.Id == properties.ListItemId).Single();

                           agendaInLookAheadEmis.BoardMeeting = newMeetingTitle;
                           agendaInLookAheadEmis.CommitteeMeetingID = newMeetingID;
                           agendaInLookAheadEmis.MeetingDate = DateTime.Parse(newMeetingDate);

                           ctx.SubmitChanges();
                       }

                   }

               }
               }
               //base.ItemUpdating(properties);
        }
Esempio n. 18
0
        public DiffResultInstance DiffWithZip(object target)
        {
            byte[] zipBytes;
            if (target is Base64EncodedByteArrayInstance)
            {
                //Create the excel document instance from a byte array.
                var byteArray = target as Base64EncodedByteArrayInstance;
                zipBytes = byteArray.Data;
            }
            else
            {
                var targetUrl = TypeConverter.ToString(target);
                if (Uri.IsWellFormedUriString(targetUrl, UriKind.Relative))
                {
                    targetUrl = SPUtility.ConcatUrls(SPBaristaContext.Current.Web.Url, targetUrl);
                }
                SPFile file;
                if (SPHelper.TryGetSPFile(targetUrl, out file))
                {
                    zipBytes = file.OpenBinary(SPOpenBinaryOptions.SkipVirusScan);
                }
                else
                {
                    throw new JavaScriptException(Engine, "Error",
                                                  "A file was not found in the specified location: " + targetUrl);
                }
            }

            var sourceFolderInfo = new List <DiffInfoInstance>();
            var targetFolderInfo = new List <DiffInfoInstance>();

            var itemsIterator = new ContentIterator();

            itemsIterator.ProcessFilesInFolder(m_folder, true,
                                               spFile =>
            {
                var fileInfo = new DiffInfoInstance(Engine)
                {
                    Url = spFile.Url.ReplaceFirstOccurenceIgnoreCase(m_folder.Url, ""),
                    TimeLastModified = JurassicHelper.ToDateInstance(Engine,
                                                                     spFile.TimeLastModified)
                };

                var fileBytes = spFile.OpenBinary(SPOpenBinaryOptions.SkipVirusScan);
                using (var md5 = MD5.Create())
                {
                    fileInfo.Hash =
                        Convert.ToBase64String(md5.ComputeHash(fileBytes));
                }

                sourceFolderInfo.Add(fileInfo);
            },
                                               null);

            using (var ms = new MemoryStream(zipBytes))
            {
                using (var zf = new ZipFile(ms))
                {
                    foreach (ZipEntry ze in zf)
                    {
                        if (ze.IsDirectory)
                        {
                            continue;
                        }

                        var fileInfo = new DiffInfoInstance(Engine)
                        {
                            Url = "/" + ze.Name,
                            TimeLastModified = JurassicHelper.ToDateInstance(Engine,
                                                                             ze.DateTime)
                        };

                        using (var zs = zf.GetInputStream(ze))
                        {
                            using (var md5 = MD5.Create())
                            {
                                fileInfo.Hash =
                                    Convert.ToBase64String(md5.ComputeHash(zs));
                            }
                        }

                        targetFolderInfo.Add(fileInfo);
                    }
                }
            }

            var result = new DiffResultInstance(Engine);

            result.Process(sourceFolderInfo, targetFolderInfo);
            return(result);
        }
Esempio n. 19
0
        /// <summary>
        /// Lists the entities.
        /// </summary>
        /// <param name="containerTitle">The container title.</param>
        /// <param name="path">The path.</param>
        /// <param name="criteria">The criteria.</param>
        /// <returns></returns>
        public virtual IList <Entity> ListEntities(string containerTitle, string path, EntityFilterCriteria criteria)
        {
            SPSite site;
            var    web = GetDocumentStoreWeb(out site);

            SPList   list;
            SPFolder folder;

            if (SPDocumentStoreHelper.TryGetFolderFromPath(web, containerTitle, out list, out folder, path) == false)
            {
                return(null);
            }

            ContentIterator.EnsureContentTypeIndexed(list);

            var documentStoreEntityContentTypeId = list.ContentTypes.BestMatch(new SPContentTypeId(Constants.DocumentStoreEntityContentTypeId));

            var camlQuery = @"<Where>
    <Eq>
      <FieldRef Name=""ContentTypeId"" />
      <Value Type=""ContentTypeId"">" + documentStoreEntityContentTypeId + @"</Value>
    </Eq>
</Where>";

            var viewFields = SPDocumentStoreHelper.GetDocumentStoreEntityViewFieldsXml();

            var filteredListItems = new List <SPListItem>();

            var itemsIterator = new ContentIterator();

            itemsIterator.ProcessListItems(list, camlQuery + ContentIterator.ItemEnumerationOrderByPath + viewFields, ContentIterator.MaxItemsPerQueryWithViewFields, true, folder,
                                           spListItems =>
            {
                var listItems = FilterListItemEntities(spListItems.OfType <SPListItem>(),
                                                       criteria);
                // ReSharper disable AccessToModifiedClosure
                filteredListItems.AddRange(listItems);
                // ReSharper restore AccessToModifiedClosure
            },
                                           null);

            var result = new List <Entity>();

            if (criteria == null || criteria.IncludeData)
            {
                result.AddRange(
                    filteredListItems
                    .Select(li =>
                {
                    // ReSharper disable AccessToDisposedClosure
                    var listItemFolder = li.Folder ?? web.GetFolder(SPUtility.GetUrlDirectory(li.Url));
                    // ReSharper restore AccessToDisposedClosure

                    return(SPDocumentStoreHelper.MapEntityFromDocumentSet(
                               DocumentSet.GetDocumentSet(listItemFolder), null));
                })
                    .Where(entity => entity != null)
                    );

                ProcessEntityList(containerTitle, path, criteria, folder, result);
            }
            else
            {
                if (criteria.Skip.HasValue)
                {
                    filteredListItems = filteredListItems.Skip((int)criteria.Skip.Value).ToList();
                }

                if (criteria.Top.HasValue)
                {
                    filteredListItems = filteredListItems.Take((int)criteria.Top.Value).ToList();
                }

                result.AddRange(
                    filteredListItems
                    .Select(
                        li =>
                        SPDocumentStoreHelper.MapEntityFromDocumentSet(DocumentSet.GetDocumentSet(li.Folder), null, null))
                    .Where(entity => entity != null)
                    );

                ProcessEntityList(containerTitle, path, criteria, folder, result);
            }

            return(result);
        }
        XPathNodeView FillSubRow(ContentIterator iter, Shape shape, object[] columns) {
            if (null == columns) {
                int colCount = shape.SubShapes.Count;
                if (0 == colCount)
                    colCount = 1;
                columns = new object[colCount];
            }

            switch (shape.BindingType) {
                case BindingType.Element:
                    columns[0] = FillColumn(iter, shape);
                    break;

                case BindingType.Sequence: {
                    int iPrev = -1;
                    int i;
                    while (null != iter.Node) {
                        i = shape.FindMatchingSubShape(iter.Particle);
                        if (i <= iPrev)
                            break;
                        columns[i] = FillColumn(iter, shape.SubShape(i));
                        iPrev = i;
                    }
                    break;
                }

                case BindingType.All: {
                    while (null != iter.Node) {
                        int i = shape.FindMatchingSubShape(iter.Particle);
                        if (-1 == i || null != columns[i])
                            break;
                        columns[i] = FillColumn(iter, shape.SubShape(i));
                    }
                    break;
                }

                case BindingType.Choice: {
                    int i = shape.FindMatchingSubShape(iter.Particle);
                    if (-1 != i) {
                        columns[i] = FillColumn(iter, shape.SubShape(i));
                    }
                    break;
                }

                case BindingType.Repeat:
                default:
                    // should not map to a row
                    throw new NotSupportedException();
            }
            return new XPathNodeView(this, null, columns);
        }
        object FillColumn(ContentIterator iter, Shape shape) {
            object val;
            switch (shape.BindingType) {
                case BindingType.Element:
                    val = iter.Node;
                    iter.Next();
                    break;

                case BindingType.ElementNested: {
                    ArrayList rows = new ArrayList();
                    rows.Add(iter.Node);
                    iter.Next();
                    val = new XPathDocumentView(null, rows, shape.NestedShape);
                    break;
                }

                case BindingType.Repeat: {
                    ArrayList rows = new ArrayList();
                    Shape subShape = shape.SubShape(0);
                    if (subShape.BindingType == BindingType.ElementNested) {
                        Shape nestShape = subShape.NestedShape;
                        XPathDocumentView xivc = new XPathDocumentView(null, null, nestShape);
                        XPathNode nd;
                        while (null != (nd = iter.Node)
                            && subShape.IsParticleMatch(iter.Particle)) {
                            rows.Add(nd);
                            iter.Next();
                        }
                        xivc.SetRows(rows);
                        val = xivc;
                    }
                    else {
                        XPathDocumentView xivc = new XPathDocumentView(null, null, subShape);
                        XPathNode nd;
                        while (null != (nd = iter.Node)
                            && shape.IsParticleMatch(iter.Particle)) {
                            rows.Add(xivc.FillSubRow(iter, subShape, null));
                        }
                        xivc.SetRows(rows);
                        val = xivc;
                    }
                    break;
                }

                case BindingType.Sequence:
                case BindingType.Choice:
                case BindingType.All: {
                    XPathDocumentView docview = new XPathDocumentView(null, null, shape);
                    ArrayList rows = new ArrayList();
                    rows.Add(docview.FillSubRow(iter, shape, null));
                    docview.SetRows(rows);
                    val = docview;
                    break;
                }

                default:
                    case BindingType.Text:
                case BindingType.Attribute:
                    throw new NotSupportedException();
            }
            return val;
        }