Beispiel #1
0
        public static bool IsDocumentSetItem(this SPListItem item)
        {
            bool documentSetItem = false;

            try
            {
                DocumentSet documentSet = null;
                if (null != item && null != item.File)
                {
                    documentSet = DocumentSet.GetDocumentSet(item.File.ParentFolder);
                    if (documentSet != null && documentSet.ContentType != null)
                    {
                        if (documentSet.ContentType.Id.IsChildOf(SPBuiltInContentTypeId.DocumentSet))
                        {
                            documentSetItem = true;
                        }
                    }
                }
            }
            catch (NullReferenceException nullEx)
            {
                //TODO: Find a better way to do this
                //if our content type is null, then we are likely dealing with a document library
                //so we'll swallow this here
            }
            return(documentSetItem);
        }
Beispiel #2
0
        protected void getDocSetsButton_Click(object sender, EventArgs e)
        {
            int count = 0;
            //Get the Shared Documents document libary
            SPWeb             currentWeb      = SPContext.Current.Web;
            SPDocumentLibrary sharedDocuments = (SPDocumentLibrary)currentWeb.Lists["Shared Documents"];

            //Loop though all the folders. Some of them will be document sets
            //NOTE: don't use the sharedDocuments.Folders collection! Use sharedDocuments.RootFolder.SubFolders
            foreach (SPFolder currentFolder in sharedDocuments.RootFolder.SubFolders)
            {
                //Get the corresponding document set
                DocumentSet currentDocSet = DocumentSet.GetDocumentSet(currentFolder);
                //Strangely the previous line always returns a document set object
                //Even if the current folder is not a document set. So we use the
                //following test to find out if the current folder is a document set
                if (currentDocSet.Item != null)
                {
                    //This folder is a document set. Increase the count
                    count += 1;
                    //Read some properties of the document set
                    resultLabel.Text += "Name: " + currentFolder.Name + "<br />";
                    resultLabel.Text += "Content Type: " + currentDocSet.ContentType.Name + "<br />";
                    resultLabel.Text += "Document Count: " + currentDocSet.Folder.ItemCount + "<br />";
                    resultLabel.Text += "Welcome Page: " + currentDocSet.WelcomePageUrl + "<br /><br />";
                }
            }
            //Display the count
            docSetCountLabel.Text = count.ToString();
        }
Beispiel #3
0
        public SPDocumentSetInstance Construct(object obj)
        {
            SPSite      site = null;
            SPWeb       web  = null;
            DocumentSet result;

            if (obj is SPFolderInstance)
            {
                var folderInstance = obj as SPFolderInstance;
                result = DocumentSet.GetDocumentSet(folderInstance.Folder);
            }
            else if (obj is string)
            {
                var      url = obj as string;
                SPFolder folder;
                if (SPHelper.TryGetSPFolder(url, out site, out web, out folder) == false)
                {
                    throw new JavaScriptException(this.Engine, "Error", "No documentSet is available at the specified url.");
                }
                result = DocumentSet.GetDocumentSet(folder);
            }
            else
            {
                throw new JavaScriptException(this.Engine, "Error", "Cannot create a document set with the specified object: " + TypeConverter.ToString(obj));
            }

            return(new SPDocumentSetInstance(this.InstancePrototype, site, web, result));
        }
Beispiel #4
0
        public SPDocumentSetInstance GetDocumentSet(SPFolderInstance folder)
        {
            if (folder == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "An instance of an SPFolder must be specified as the first argument.");
            }

            var result = DocumentSet.GetDocumentSet(folder.Folder);

            if (result == null)
            {
                return(null);
            }

            return(new SPDocumentSetInstance(this.Engine.Object.InstancePrototype, folder.Folder.ParentWeb.Site,
                                             folder.Folder.ParentWeb, result));
        }
Beispiel #5
0
        internal void CheckDocumentSetMapping(List docsetlist, string relativeUrl)
        {
            Folder docsetfolder = ClientContext.Web.GetFolderByServerRelativeUrl(relativeUrl);

            ClientContext.Load(docsetfolder, fld => fld.Name, fld => fld.ParentFolder.Name, fld => fld.ServerRelativeUrl, fld => fld.ListItemAllFields);
            ClientContext.ExecuteQueryRetry();

            var onlineurl    = relativeUrl.Replace(docsetlist.RootFolder.ServerRelativeUrl, "");
            var localdocuset = FullDocumentSetPath(this.TargetLocation, onlineurl, docsetfolder.Name);

            DocumentSet docSet       = DocumentSet.GetDocumentSet(ClientContext, docsetfolder);
            var         docSetStream = docSet.ExportDocumentSet();

            ClientContext.ExecuteQueryRetry();
            using (var fs = new System.IO.FileStream(localdocuset.FullName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
            {
                docSetStream.Value.CopyTo(fs);
            }
        }
Beispiel #6
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = "";

            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                    using (SPWeb web = site.OpenWeb())
                    {
                        string ListId     = Request.Params["ListId"];
                        Guid   id         = new Guid(ListId);
                        SPList sourceList = web.Lists.GetList(id, true);
                        string ItemId     = Request.Params["ItemId"];

                        SPListItem  sourceItem  = sourceList.GetItemById(Convert.ToInt32(ItemId));
                        DocumentSet documentSet = DocumentSet.GetDocumentSet(sourceItem.Folder);

                        SPList targetList = web.Lists[DropDownList1.SelectedItem.Text.ToString()];

                        string sourceCType = sourceItem.ContentType.Name.ToString();
                        //string sourceCTypeParentName = sourceItem.ContentType.Parent.Name;

                        SPContentTypeCollection oCTypeColl = targetList.ContentTypes;
                        StringCollection        Colec      = new StringCollection();
                        foreach (SPContentType conttype in oCTypeColl)
                        {
                            Colec.Add(conttype.Name.ToString());
                        }
                        if (Colec.Contains(sourceCType))
                        {
                            SPContentTypeId contentTypeId   = targetList.ContentTypes[sourceCType].Id;
                            byte[]          documentSetData = documentSet.Export();
                            string          documentSetName = documentSet.Item.Name;
                            SPFolder        targetFolder    = targetList.RootFolder;
                            Hashtable       properties      = sourceItem.Properties;
                            DocumentSet.Import(documentSetData, documentSetName, targetFolder, contentTypeId, properties, web.CurrentUser);

                            try
                            {
                                web.AllowUnsafeUpdates = true;
                                documentSet.VersionCollection.Add(true, "Document set item has been exported to destination library by: " + web.CurrentUser);
                                sourceItem.Update();
                                web.AllowUnsafeUpdates = false;
                            }
                            catch (Exception ex1)
                            {
                                Label1.ForeColor = System.Drawing.Color.Red;
                                Label1.Text      = ex1.Message;
                            }

                            string urlRed = site.Url + "/" + targetList + "/Forms/AllItems.aspx";
                            Response.Redirect(urlRed);
                        }
                        else
                        {
                            Label1.ForeColor = System.Drawing.Color.Red;
                            Label1.Text      = "No content type found. Go to your destination library and add content type.";
                        }
                    }
            }
            catch (Exception ex)
            {
                Label1.ForeColor = System.Drawing.Color.Red;
                Label1.Text      = ex.Message;
            }
        }
        /// <summary>
        /// Reverts the entity to version.
        /// </summary>
        /// <param name="containerTitle">The container title.</param>
        /// <param name="entityId">The entity id.</param>
        /// <param name="versionId">The version id.</param>
        /// <returns></returns>
        public EntityVersion RevertEntityToVersion(string containerTitle, Guid entityId, int versionId)
        {
            SPSite site;
            var    web = GetDocumentStoreWeb(out site);

            SPList   list;
            SPFolder folder;

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

            SPFile defaultEntityPart;

            if (SPDocumentStoreHelper.TryGetDocumentStoreDefaultEntityPart(list, folder, entityId, out defaultEntityPart) == false)
            {
                return(null);
            }

            var entityVersion = GetEntityVersion(containerTitle, entityId, versionId);

            web.AllowUnsafeUpdates = true;
            try
            {
                string currentData = defaultEntityPart.Web.GetFileAsString(defaultEntityPart.Url);

                if (entityVersion.Entity.Data != currentData)
                {
                    defaultEntityPart.SaveBinary(String.IsNullOrEmpty(entityVersion.Entity.Data) == false
                                                    ? System.Text.Encoding.Default.GetBytes(entityVersion.Entity.Data)
                                                    : System.Text.Encoding.Default.GetBytes(String.Empty));
                }

                var ds = DocumentSet.GetDocumentSet(defaultEntityPart.ParentFolder);
                if (ds.Item.Title != entityVersion.Entity.Title)
                {
                    ds.Item["Title"] = entityVersion.Entity.Title;
                }

                if ((ds.Item["DocumentSetDescription"] as string) != entityVersion.Entity.Description)
                {
                    ds.Item["DocumentSetDescription"] = entityVersion.Entity.Description;
                }

                if ((ds.Item["Namespace"] as string) != entityVersion.Entity.Namespace)
                {
                    ds.Item["Namespace"] = entityVersion.Entity.Namespace;
                }

                ds.Item.SystemUpdate(true);
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }

            var versions = ListEntityVersions(containerTitle, entityId);

            return(versions.FirstOrDefault(v => v.IsCurrentVersion));
        }
Beispiel #8
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);
        }
Beispiel #9
0
        /// <summary>
        /// Updates the data of the specified entity.
        /// </summary>
        /// <param name="containerTitle"></param>
        /// <param name="entityId"></param>
        /// <param name="eTag"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public virtual Entity UpdateEntityData(string containerTitle, Guid entityId, string eTag, string data)
        {
            SPSite site;
            var    web = GetDocumentStoreWeb(out site);

            SPList   list;
            SPFolder folder;

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

            SPFile defaultEntityPart;

            if (SPDocumentStoreHelper.TryGetDocumentStoreDefaultEntityPart(list, folder, entityId, out defaultEntityPart) == false)
            {
                return(null);
            }

            if (SPBaristaContext.Current.Web.CurrentUser == null)
            {
                throw new InvalidOperationException("User is not authenticated.");
            }

            if (defaultEntityPart.Item.DoesUserHavePermissions(SPBaristaContext.Current.Web.CurrentUser, SPBasePermissions.EditListItems) == false)
            {
                throw new InvalidOperationException("Insufficent Permissions.");
            }

            if (String.IsNullOrEmpty(eTag) == false && defaultEntityPart.ETag != eTag)
            {
                throw new InvalidOperationException(String.Format("Could not update the entity, the Entity has been updated by another user. New: {0} Existing:{1}", eTag, defaultEntityPart.ETag));
            }

            var entity = SPDocumentStoreHelper.MapEntityFromDocumentSet(DocumentSet.GetDocumentSet(defaultEntityPart.ParentFolder), data);

            web.AllowUnsafeUpdates = true;
            try
            {
                string currentData = defaultEntityPart.Web.GetFileAsString(defaultEntityPart.Url);

                if (data != currentData)
                {
                    defaultEntityPart.SaveBinary(String.IsNullOrEmpty(data) == false
                                                    ? System.Text.Encoding.Default.GetBytes(data)
                                                    : System.Text.Encoding.Default.GetBytes(String.Empty));

                    //Update the contents Entity Part.
                    string   contentHash;
                    DateTime contentModified;
                    SPDocumentStoreHelper.CreateOrUpdateContentEntityPart(web, list, defaultEntityPart.ParentFolder, entity, null, out contentHash, out contentModified);

                    var documentSetFolder = web.GetFolder(defaultEntityPart.ParentFolder.UniqueId);
                    documentSetFolder.Item["DocumentEntityContentsHash"]         = contentHash;
                    documentSetFolder.Item["DocumentEntityContentsLastModified"] = contentModified;
                    documentSetFolder.Item.UpdateOverwriteVersion();

                    entity.ContentsETag     = contentHash;
                    entity.ContentsModified = contentModified;
                }
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }

            return(entity);
        }
Beispiel #10
0
        /// <summary>
        /// Creates a new entity in the document store, contained in the specified container in the specified folder and namespace.
        /// </summary>
        /// <param name="containerTitle">The container title. Required.</param>
        /// <param name="path">The path. Optional.</param>
        /// <param name="title">The title of the entity. Optional.</param>
        /// <param name="namespace">The namespace of the entity. Optional.</param>
        /// <param name="data">The data to store with the entity. Optional.</param>
        /// <returns></returns>
        public virtual Entity CreateEntity(string containerTitle, string path, string title, string @namespace, string data)
        {
            if (data == null)
            {
                data = String.Empty;
            }

            SPSite site;
            var    web = GetDocumentStoreWeb(out site);

            SPList   list;
            SPFolder folder;

            if (SPDocumentStoreHelper.TryGetFolderFromPath(web, containerTitle, out list, out folder, path) == false)
            {
                throw new InvalidOperationException("Unable to retrieve the specified folder -- Folder does not exist.");
            }

            var newGuid     = Guid.NewGuid();
            var entityTitle = String.IsNullOrEmpty(title)
              ? newGuid.ToString()
              : title;
            var docEntityContentTypeId = list.ContentTypes.BestMatch(new SPContentTypeId(Constants.DocumentStoreEntityContentTypeId));

            var properties = new Hashtable
            {
                { "DocumentSetDescription", "Document Store Entity" },
                { "DocumentEntityGuid", newGuid.ToString() },
                { "Namespace", @namespace }
            };

            web.AllowUnsafeUpdates = true;
            try
            {
                if (SPBaristaContext.Current.Web.CurrentUser == null)
                {
                    throw new InvalidOperationException("User is not authenticated.");
                }

                if ((folder.Item == null && list.RootFolder == folder && list.DoesUserHavePermissions(SPBaristaContext.Current.Web.CurrentUser, SPBasePermissions.AddListItems) == false) ||
                    (folder.Item != null && (folder.Item.DoesUserHavePermissions(SPBaristaContext.Current.Web.CurrentUser, SPBasePermissions.AddListItems) == false)))
                {
                    throw new InvalidOperationException("Insufficient Permissions.");
                }

                DocumentSet documentSet;
                if (PermissionsHelper.IsRunningUnderElevatedPrivledges(site.WebApplication.ApplicationPool))
                {
                    var existingEntity = list.ParentWeb.GetFile(SPUtility.ConcatUrls(folder.Url, entityTitle));

                    //Double check locking
                    if (existingEntity.Exists == false)
                    {
                        var mutex = SPEntityMutexManager.GrabMutex(this.DocumentStoreUrl, newGuid);
                        mutex.WaitOne();

                        try
                        {
                            existingEntity = list.ParentWeb.GetFile(SPUtility.ConcatUrls(folder.Url, entityTitle));
                            if (existingEntity.Exists == false)
                            {
                                var currentUser = web.AllUsers[CurrentUserLoginName];
                                documentSet = DocumentSet.Create(folder, entityTitle, docEntityContentTypeId, properties, false,
                                                                 currentUser);

                                //Re-retrieve the document set folder, otherwise bad things happen.
                                var documentSetFolder = web.GetFolder(documentSet.Folder.Url);
                                documentSet = DocumentSet.GetDocumentSet(documentSetFolder);

                                var entityPartContentTypeId     = new SPContentTypeId(Constants.DocumentStoreEntityPartContentTypeId);
                                var listEntityPartContentTypeId = list.ContentTypes.BestMatch(entityPartContentTypeId);
                                var entityPartContentType       = list.ContentTypes[listEntityPartContentTypeId];

                                var entityPartProperties = new Hashtable
                                {
                                    { "ContentTypeId", entityPartContentType.Id.ToString() },
                                    { "Content Type", entityPartContentType.Name }
                                };


                                documentSet.Folder.Files.Add(Constants.DocumentStoreDefaultEntityPartFileName,
                                                             Encoding.Default.GetBytes(data), entityPartProperties, currentUser, currentUser, DateTime.UtcNow,
                                                             DateTime.UtcNow, true);

                                //Update the contents entity part and the modified by user stamp.
                                string   contentHash;
                                DateTime contentModified;
                                SPDocumentStoreHelper.CreateOrUpdateContentEntityPart(web, list, documentSet.Folder, null, null,
                                                                                      out contentHash, out contentModified);

                                //Set the created/updated fields of the new document set to the current user.
                                var userLogonName = currentUser.ID + ";#" + currentUser.Name;
                                documentSet.Item[SPBuiltInFieldId.Editor]              = userLogonName;
                                documentSet.Item["DocumentEntityContentsHash"]         = contentHash;
                                documentSet.Item["DocumentEntityContentsLastModified"] = contentModified;
                                documentSet.Item.UpdateOverwriteVersion();

                                return(SPDocumentStoreHelper.MapEntityFromDocumentSet(documentSet, data));
                            }
                        }
                        finally
                        {
                            mutex.ReleaseMutex();
                        }
                    }
                }
                else
                {
                    var existingEntity = list.ParentWeb.GetFile(SPUtility.ConcatUrls(folder.Url, entityTitle));

                    //Double check locking
                    if (existingEntity.Exists == false)
                    {
                        var mutex = SPEntityMutexManager.GrabMutex(this.DocumentStoreUrl, newGuid);
                        mutex.WaitOne();
                        try
                        {
                            existingEntity = list.ParentWeb.GetFile(SPUtility.ConcatUrls(folder.Url, entityTitle));

                            if (existingEntity.Exists == false)
                            {
                                documentSet = DocumentSet.Create(folder, entityTitle, docEntityContentTypeId, properties, false);

                                //Re-retrieve the document set folder, otherwise bad things happen.
                                var documentSetFolder = web.GetFolder(documentSet.Folder.Url);
                                documentSet = DocumentSet.GetDocumentSet(documentSetFolder);

                                var entityPartContentTypeId     = new SPContentTypeId(Constants.DocumentStoreEntityPartContentTypeId);
                                var listEntityPartContentTypeId = list.ContentTypes.BestMatch(entityPartContentTypeId);
                                var entityPartContentType       = list.ContentTypes[listEntityPartContentTypeId];

                                var entityPartProperties = new Hashtable
                                {
                                    { "ContentTypeId", entityPartContentType.Id.ToString() },
                                    { "Content Type", entityPartContentType.Name }
                                };

                                documentSet.Folder.Files.Add(Constants.DocumentStoreDefaultEntityPartFileName,
                                                             Encoding.Default.GetBytes(data), entityPartProperties, true);

                                //Update the contents Entity Part.
                                string   contentHash;
                                DateTime contentModified;
                                SPDocumentStoreHelper.CreateOrUpdateContentEntityPart(web, list, documentSet.Folder, null, null,
                                                                                      out contentHash, out contentModified);

                                documentSet.Item["DocumentEntityContentsHash"]         = contentHash;
                                documentSet.Item["DocumentEntityContentsLastModified"] = contentModified;
                                documentSet.Item.UpdateOverwriteVersion();

                                return(SPDocumentStoreHelper.MapEntityFromDocumentSet(documentSet, data));
                            }
                        }
                        finally
                        {
                            mutex.ReleaseMutex();
                        }
                    }
                }
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }

            throw new EntityExistsException("An entity with the specified title exists.");
        }
Beispiel #11
0
        // создание отчета
        protected void CreateDocument(SPListItem SelectedItem)
        {
            // адрес сайта
            String sharePointSite = "http://vizatech.westeurope.cloudapp.azure.com/sites/team";

            // получение контекста сайта
            SPSite oSite = new SPSite(sharePointSite);
            SPWeb  oWeb  = oSite.OpenWeb();

            // получение имени текущего пользователя
            string UserName = oWeb.CurrentUser.Name;

            // Создаем словарь заполнения шаблона отчета об архивации
            Dictionary <string, string> AddElementsDictionary = GetItemFields(SelectedItem, UserName);
            String TemplateLibraryName = "TemplateLib";
            String TemplateFileName    = "DocTemplate.dotx";
            String ArchiveLibraryName  = "QueueLib";
            String ArchiveFolderName   = AddElementsDictionary.Values.ElementAt(0) + "_" + AddElementsDictionary.Values.ElementAt(4);
            String ArchiveFileName     = ArchiveFolderName + ".dotx";

            oWeb.AllowUnsafeUpdates = true;
            // получаем контекст файла
            SPFile TemplateFile = (SPFile)oWeb.GetFileOrFolderObject(sharePointSite + "/Lists/" + TemplateLibraryName + "/" + TemplateFileName);
            // считываем файл в стрим
            Stream TemplateFileStream = new MemoryStream(TemplateFile.OpenBinary());

            // Заполняем поля шаблона данными
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(TemplateFileStream, true))
            {
                MainDocumentPart mainPart = wordDoc.MainDocumentPart;
                int CurrentBookMarkId     = 0;
                // перебираем метки шаблона
                foreach (BookmarkStart bookmarkStart in mainPart.RootElement.Descendants <BookmarkStart>())
                {
                    if (CurrentBookMarkId < AddElementsDictionary.Count)
                    {
                        if (AddElementsDictionary.ElementAt(CurrentBookMarkId).Key == bookmarkStart.Name)
                        {
                            // задаем свойства вносимого текста
                            RunProperties rPr = new RunProperties(new RunFonts()
                            {
                                Ascii = "Arial"
                            }, new Bold(), new Color()
                            {
                                Val = "green"
                            });
                            // вносим данные в шаблон
                            Run InsertToBookmarkOperation = new Run(new Text(AddElementsDictionary.ElementAt(CurrentBookMarkId).Value));
                            InsertToBookmarkOperation.PrependChild <RunProperties>(rPr);
                            bookmarkStart.Parent.InsertAfter(InsertToBookmarkOperation, bookmarkStart);
                            CurrentBookMarkId++;
                        }
                    }
                }
                // Сохраняем изменения
                mainPart.Document.Save();
            }

            // получаем контекст папки архива и создаем папку для архивированных документов
            SPFolder TrueArchiveLibrary = oWeb.Folders["Lists"].SubFolders["ArchiveLib"];

            TrueArchiveLibrary.SubFolders.Add(ArchiveFolderName);

            // получаем контекст папки очереди на архивирование и создаем папку
            SPFolder ArchiveLibrary = oWeb.Folders["Lists"].SubFolders[ArchiveLibraryName];

            ArchiveLibrary.SubFolders.Add(ArchiveFolderName);

            // переносим заполненный отчет в папку очереди
            ArchiveLibrary.SubFolders[ArchiveFolderName].Files.Add(ArchiveFileName, TemplateFileStream, true);

            // инициируем архивирование файлом доксета
            // получаем контекст доксета
            DocumentSet ItemDocSet = DocumentSet.GetDocumentSet(SelectedItem.Folder);

            // проверяем - может ли быть обработан данный файл службой конвертации
            char[] chars = { '.' };
            foreach (SPFile file in ItemDocSet.Folder.Files)
            {
                Stream DocSetFileStream = new MemoryStream(file.OpenBinary());
                if (new string[] { "docx", "docm", "dotx", "dotm", "doc", "dot", "rtf", "htm", "html", "mht", "mhtml", "xml" }.Contains(file.Name.Split(chars).ElementAt(1)))
                {
                    // если файл относится к группе конвертируемых, то он сатвится в очередь
                    ArchiveLibrary.SubFolders[ArchiveFolderName].Files.Add(file.Name, DocSetFileStream, true);
                }
                // иначе - сразу перенсится в папку обработанных документов без обработки
                else
                {
                    TrueArchiveLibrary.SubFolders[ArchiveFolderName].Files.Add(file.Name, DocSetFileStream, true);
                }
            }

            /*
             *  SPFolder AttachmentFolder = (SPFolder)oWeb.GetFileOrFolderObject(
             *          oSite.Url + "/Lists/Doc2/Attachments/" + SelectedItem["ID"]);
             *
             *  foreach (SPFile AttachmentFile in AttachmentFolder.Files)
             *  {
             *      AttachmentFile.CopyTo(ArchiveLibrary.SubFolders[ArchiveFolderName].Url + '/' + AttachmentFile.Name);
             *  }
             */
        }
        /// <summary>
        /// Processes events.
        /// </summary>
        /// <param name="properties"></param>
        protected virtual void ProcessEvent(SPItemEventProperties properties)
        {
            //TODO: Should there be folder events too? What happens to the files in a folder when a folder is deleted?

            var documentStoreEntityContentTypeId     = new SPContentTypeId(Constants.DocumentStoreEntityContentTypeId);
            var documentStoreEntityPartContentTypeId = new SPContentTypeId(Constants.DocumentStoreEntityPartContentTypeId);
            var attachmentContentTypeId = new SPContentTypeId(Constants.DocumentStoreEntityAttachmentContentTypeId);

            if (properties.ListItem.ContentTypeId.IsChildOf(documentStoreEntityContentTypeId))
            {
                //Note: This is the actual Document Set.
                switch (properties.EventType)
                {
                case SPEventReceiverType.ItemFileMoved:
                {
                    var documentSet = DocumentSet.GetDocumentSet(properties.ListItem.Folder);
                    var entity      = SPDocumentStoreHelper.MapEntityFromDocumentSet(documentSet, null);

                    using (var site = properties.OpenSite())
                    {
                        using (var web = properties.OpenWeb())
                        {
                            var before    = web.GetFolder(properties.BeforeUrl);
                            var after     = web.GetFolder(properties.AfterUrl);
                            var oldFolder = SPDocumentStoreHelper.MapFolderFromSPFolder(before.ParentFolder);
                            var newFolder = SPDocumentStoreHelper.MapFolderFromSPFolder(after.ParentFolder);
                            var context   = new SPBaristaContext(site, web);
                            EntityMoved(context, entity, oldFolder, newFolder);
                        }
                    }
                    break;
                }
                }
            }
            else if (properties.ListItem.ContentTypeId.IsChildOf(documentStoreEntityPartContentTypeId))
            {
                if (
                    String.Compare(properties.ListItem.File.Name, Constants.DocumentStoreDefaultEntityPartFileName,
                                   StringComparison.InvariantCulture) == 0)
                {
                    switch (properties.EventType)
                    {
                    case SPEventReceiverType.ItemAdded:
                    {
                        //TODO: See if this is appropraite.
                        if (properties.ListItem.Folder == null)
                        {
                            return;
                        }

                        var documentSet = DocumentSet.GetDocumentSet(properties.ListItem.Folder);
                        var entity      = SPDocumentStoreHelper.MapEntityFromDocumentSet(documentSet, properties.ListItem.File,
                                                                                         null);
                        using (var site = properties.OpenSite())
                        {
                            using (var web = properties.OpenWeb())
                            {
                                var context = new SPBaristaContext(site, web);
                                EntityAdded(context, entity);
                            }
                        }
                    }
                    break;

                    case SPEventReceiverType.ItemUpdated:
                    {
                        if (properties.ListItem.Folder != null)
                        {
                            var documentSet = DocumentSet.GetDocumentSet(properties.ListItem.Folder);
                            var entity      = SPDocumentStoreHelper.MapEntityFromDocumentSet(documentSet, properties.ListItem.File,
                                                                                             null);
                            using (var site = properties.OpenSite())
                            {
                                using (var web = properties.OpenWeb())
                                {
                                    var context = new SPBaristaContext(site, web);
                                    EntityUpdated(context, entity);
                                }
                            }
                        }
                    }
                    break;
                    }
                }
                else
                {
                    var entityPart = SPDocumentStoreHelper.MapEntityPartFromSPFile(properties.ListItem.File, null);

                    switch (properties.EventType)
                    {
                    case SPEventReceiverType.ItemAdded:
                        using (var site = properties.OpenSite())
                        {
                            using (var web = properties.OpenWeb())
                            {
                                var context = new SPBaristaContext(site, web);
                                EntityPartAdded(context, entityPart);
                            }
                        }
                        break;

                    case SPEventReceiverType.ItemUpdated:
                        using (var site = properties.OpenSite())
                        {
                            using (var web = properties.OpenWeb())
                            {
                                var context = new SPBaristaContext(site, web);
                                EntityPartUpdated(context, entityPart);
                            }
                        }
                        break;
                    }
                }
            }
            else if (properties.ListItem.ContentTypeId.IsChildOf(attachmentContentTypeId))
            {
                var attachment = SPDocumentStoreHelper.MapAttachmentFromSPFile(properties.ListItem.File);

                switch (properties.EventType)
                {
                case SPEventReceiverType.ItemAdded:
                    using (var site = properties.OpenSite())
                    {
                        using (var web = properties.OpenWeb())
                        {
                            var context = new SPBaristaContext(site, web);
                            AttachmentAdded(context, attachment);
                        }
                    }
                    break;

                case SPEventReceiverType.ItemUpdated:
                    using (var site = properties.OpenSite())
                    {
                        using (var web = properties.OpenWeb())
                        {
                            var context = new SPBaristaContext(site, web);
                            AttachmentUpdated(context, attachment);
                        }
                    }
                    break;
                }
            }
            else if (properties.ListItem.File != null &&
                     properties.ListItem.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Document) &&
                     String.Compare(properties.ListItem.File.Name, Constants.DocumentStoreDefaultEntityPartFileName,
                                    StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                //Apparently the Default documents in a Doc Set are initially added as a "Document"
                var documentSet = DocumentSet.GetDocumentSet(properties.ListItem.File.ParentFolder);
                var entity      = SPDocumentStoreHelper.MapEntityFromDocumentSet(documentSet, properties.ListItem.File, null);
                switch (properties.EventType)
                {
                case SPEventReceiverType.ItemAdded:
                    using (var site = properties.OpenSite())
                    {
                        using (var web = properties.OpenWeb())
                        {
                            var context = new SPBaristaContext(site, web);
                            EntityAdded(context, entity);
                        }
                    }
                    break;
                }
            }
        }