Esempio n. 1
0
        public SPDocumentSetInstance AddDocumentSet(string name, object contentType, [DefaultParameterValue(null)] object properties, [DefaultParameterValue(true)] bool provisionDefaultContent)
        {
            var contentTypeId = SPContentTypeId.Empty;

            if (contentType is SPContentTypeIdInstance)
            {
                contentTypeId = (contentType as SPContentTypeIdInstance).ContentTypeId;
            }
            else if (contentType is SPContentTypeInstance)
            {
                contentTypeId = (contentType as SPContentTypeInstance).ContentType.Id;
            }
            else if (contentType is string)
            {
                contentTypeId = new SPContentTypeId(contentType as string);
            }

            if (contentTypeId == SPContentTypeId.Empty)
            {
                return(null);
            }

            var htProperties = SPHelper.GetFieldValuesHashtableFromPropertyObject(properties);

            var docSet = DocumentSet.Create(m_folder, name, contentTypeId, htProperties, provisionDefaultContent);

            return(new SPDocumentSetInstance(Engine.Object.InstancePrototype, null, null, docSet));
        }
Esempio n. 2
0
        protected override void ExecuteCmdlet()
        {
            var list = List.GetList(SelectedWeb);

            list.EnsureProperties(l => l.RootFolder, l => l.ContentTypes);

            // Try getting the content type from the Web
            var contentType = ContentType.GetContentType(SelectedWeb);

            // If content type could not be found but a content type ID has been passed in, try looking for the content type ID on the list instead
            if (contentType == null && !string.IsNullOrEmpty(ContentType.Id))
            {
                contentType = list.ContentTypes.FirstOrDefault(ct => ct.StringId.Equals(ContentType.Id));
            }
            else
            {
                // Content type has been found on the web, check if it also exists on the list
                if (list.ContentTypes.All(ct => !ct.StringId.Equals(contentType.Id.StringValue, System.StringComparison.InvariantCultureIgnoreCase)))
                {
                    contentType = list.ContentTypes.FirstOrDefault(ct => ct.Name.Equals(ContentType.Name));
                }
            }

            if (contentType == null)
            {
                throw new PSArgumentException("The provided contenttype has not been found", "ContentType");
            }

            // Create the document set
            var result = DocumentSet.Create(ClientContext, list.RootFolder, Name, contentType.Id);

            ClientContext.ExecuteQueryRetry();

            WriteObject(result.Value);
        }
Esempio n. 3
0
        protected override void ExecuteCmdlet()
        {
            var list = List.GetListOrThrow(nameof(List), CurrentWeb, l => l.RootFolder, l => l.ContentTypes);

            var listContentType = ContentType.GetContentType(list);

            if (listContentType is null)
            {
                var siteContentType = ContentType.GetContentTypeOrThrow(nameof(ContentType), CurrentWeb);
                listContentType = new ContentTypePipeBind(siteContentType.Name).GetContentTypeOrThrow(nameof(ContentType), list);
            }

            listContentType.EnsureProperty(ct => ct.StringId);

            if (!listContentType.StringId.StartsWith("0x0120D520"))
            {
                throw new PSArgumentException($"Content type '{ContentType}' does not inherit from the base Document Set content type. Document Set content type IDs start with 0x120D520");
            }

            // Create the document set
            var result = DocumentSet.Create(ClientContext, list.RootFolder, Name, listContentType.Id);

            ClientContext.ExecuteQueryRetry();

            WriteObject(result.Value);
        }
Esempio n. 4
0
        public string CreateDocumentSet(ClientContext ctx, List list, string title, bool autoDetectDocumentSetContentType, string contentTypeId = "")
        {
            var         rootFolder             = list.RootFolder;
            ContentType documentSetContentType = null;

            if (autoDetectDocumentSetContentType)
            {
                var contentTypes = list.ContentTypes;
                ctx.Load(contentTypes);
                ctx.ExecuteQueryWithIncrementalRetry();

                if (!CanAutoDetectDocumentSetContentType(contentTypes))
                {
                    throw new Exception("Could not detect a unique Document Set Content Type. Try to use the Content Type Id Param instead");
                }
                documentSetContentType = contentTypes.Single(x => x.Id.StringValue.StartsWith(DOCUMENT_SET_CONTENT_TYPE_START_ID));
            }
            else
            {
                documentSetContentType = list.ContentTypes.GetById(contentTypeId);
                ctx.Load(documentSetContentType);
                ctx.ExecuteQueryWithIncrementalRetry();
            }

            var result = DocumentSet.Create(ctx, rootFolder, title, documentSetContentType.Id);

            ctx.ExecuteQueryWithIncrementalRetry();

            if (!String.IsNullOrEmpty(result.Value))
            {
                return(result.Value);
            }

            return(null);
        }
Esempio n. 5
0
        protected override void ExecuteCmdlet()
        {
            var list = List.GetList(SelectedWeb);

            list.EnsureProperty(l => l.RootFolder);

            var result = DocumentSet.Create(ClientContext, list.RootFolder, Name, ContentType.GetContentType(SelectedWeb).Id);

            ClientContext.ExecuteQueryRetry();

            WriteObject(result.Value);
        }
Esempio n. 6
0
        private void DeployArtifact(CSOMModelHostBase modelHost, Folder folder, DocumentSetDefinition definition)
        {
            var currentDocumentSet = GetExistingDocumentSet(modelHost, folder, definition);

            var context = modelHost.HostClientContext;
            var web     = modelHost.HostWeb;

            var documentSetName = definition.Name;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = currentDocumentSet,
                ObjectType       = typeof(Folder),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });

            if (currentDocumentSet == null)
            {
                var contentType = GetContentType(modelHost, definition);

                DocumentSet.Create(context, folder, documentSetName, contentType.Id);
                context.ExecuteQueryWithTrace();

                currentDocumentSet = GetExistingDocumentSet(modelHost, folder, definition);
            }

            if (!string.IsNullOrEmpty(definition.Description))
            {
                currentDocumentSet.ListItemAllFields["DocumentSetDescription"] = definition.Description;
                currentDocumentSet.ListItemAllFields.Update();

                context.ExecuteQueryWithTrace();
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = currentDocumentSet,
                ObjectType       = typeof(Folder),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });
        }
Esempio n. 7
0
        public void GivenTheListHasADocumentSetCalled(string docSetTitle)
        {
            // Ensure the SharePoint Server Publishing Infrastructure feature is enabled
            var siteGivens = new SiteGivens(Context);

            siteGivens.GivenTheCurrentSiteHasTheFeatureEnabled("f6924d36-2fa8-4f0b-b16d-06b7250180fa");

            string documentSetContentType = "0x0120D520";

            using (var cc = Context.CreateClientContext())
            {
                var list = cc.Web.Lists.GetByTitle(Context.LastListTitle);
                cc.Load(list);
                cc.Load(list.RootFolder);
                cc.Load(list.RootFolder.Folders);
                cc.Load(list.ContentTypes);
                cc.Load(cc.Web);
                cc.Load(cc.Web.ContentTypes);
                cc.ExecuteQuery();

                if (list.RootFolder.Folders.Any(x => x.Name == docSetTitle))
                {
                    // Folder already exists with the given doc set title.
                    // Ensure that this folder is actually a docset...
                }
                else
                {
                    list.ContentTypesEnabled = true;
                    list.Update();
                    cc.ExecuteQuery();

                    var ct = list.ContentTypes.SingleOrDefault(x => x.Id.StringValue.StartsWith(documentSetContentType));
                    if (ct == null)
                    {
                        var docSetContentType = cc.Web.ContentTypes.GetById(documentSetContentType);
                        cc.Load(docSetContentType);
                        cc.ExecuteQuery();
                        ct = list.ContentTypes.AddExistingContentType(docSetContentType);
                        cc.Load(ct);
                        cc.ExecuteQuery();
                    }

                    var docSet = DocumentSet.Create(cc, list.RootFolder, docSetTitle, ct.Id);

                    cc.ExecuteQuery();
                }
            }
        }
Esempio n. 8
0
        private void DeployArtifact(SSOMModelHostBase modelHost, SPFolder folder, DocumentSetDefinition definition)
        {
            var currentDocumentSet = GetExistingDocumentSet(modelHost, folder, definition);

            var web             = folder.ParentWeb;
            var documentSetName = definition.Name;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = currentDocumentSet,
                ObjectType       = typeof(SPFolder),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });

            if (currentDocumentSet == null)
            {
                var contentType = GetContentType(web, definition);

                var props  = new Hashtable();
                var docSet = DocumentSet.Create(folder, documentSetName, contentType.Id, props);

                currentDocumentSet = docSet.Folder;
            }

            if (!string.IsNullOrEmpty(definition.Description))
            {
                currentDocumentSet.Item["DocumentSetDescription"] = definition.Description;
                currentDocumentSet.Item.Update();
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = currentDocumentSet,
                ObjectType       = typeof(SPFolder),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });
        }
Esempio n. 9
0
        static void main()
        {
            using (SPSite oSite = new SPSite("http://servername")){
                SPWeb  oWeb  = oSite.OpenWeb();
                SPList oList = oWeb.Lists["listName"];

                SPFolder      oFolder      = oList.RootFolder;
                SPContentType oContentType = oList.ContentTypes["DocumentSetCT"];

                Hashtable properties = new Hashtable();
                properties.Add("PropertyName1", "PropertyValue1");
                properties.Add("PropertyName2", "PropertyValue2");
                properties.Add("PropertyName3", "PropertyValue3");
                properties.Add("PropertyName4", "PropertyValue4");

                var oDocSet = DocumentSet.Create(oFolder, "First Document Set", oContentType.Id, properties);
            }
        }
Esempio n. 10
0
        public ActionResult CreateDocumentSet([Bind(Include = "DocumentLibName,FieldNames,ContentTypeName")] AddDocumentSetViewModel model)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                List <Field> fields = new List <Field>();
                foreach (string fieldName in model.FieldNames)
                {
                    Field field = CreateDocumentSetField(clientContext, fieldName);
                    fields.Add(field);
                }

                ContentType         ctTestSow      = CreateDocumentSetContentType(clientContext, model.ContentTypeName, fields);
                DocumentSetTemplate docSetTemplate = DocumentSetTemplate.GetDocumentSetTemplate(clientContext, ctTestSow);
                clientContext.Load(docSetTemplate, d => d.SharedFields, d => d.WelcomePageFields);
                clientContext.ExecuteQuery();

                if (!docSetTemplate.SharedFields.Contains(fields[0]))
                {
                    docSetTemplate.SharedFields.Add(fields[0]);
                    docSetTemplate.Update(true);
                    clientContext.ExecuteQuery();
                }
                if (!docSetTemplate.WelcomePageFields.Contains(fields[0]))
                {
                    docSetTemplate.WelcomePageFields.Add(fields[0]);
                    docSetTemplate.Update(true);
                    clientContext.ExecuteQuery();
                }

                //
                List listTestDoc = GetTestDocDocumentLibrary(clientContext, ctTestSow, model.DocumentLibName);
                clientContext.Load(listTestDoc.RootFolder);
                clientContext.ExecuteQuery();

                ClientResult <string> result = DocumentSet.Create(clientContext, listTestDoc.RootFolder, DOCUMENTSETNAME, ctTestSow.Id);
                clientContext.ExecuteQuery();
            }
            return(RedirectToAction("Index", new { SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri }));
        }
Esempio n. 11
0
        protected void createDocSetButton_Click(object sender, EventArgs e)
        {
            //Get the Shared Documents document library
            SPWeb             currentWeb    = SPContext.Current.Web;
            SPDocumentLibrary sharedDocsLib = (SPDocumentLibrary)currentWeb.Lists["Shared Documents"];
            //You can use a hashtable to populate properties of the document set
            Hashtable docsetProperties = new Hashtable();

            docsetProperties.Add("Name", nameTextbox.Text);
            docsetProperties.Add("Description", descriptionTextbox.Text);
            //Create the document set
            try
            {
                DocumentSet newDocSet = DocumentSet.Create(sharedDocsLib.RootFolder,
                                                           nameTextbox.Text, sharedDocsLib.ContentTypes["Document Set"].Id,
                                                           docsetProperties, true);
                resultLabel.Text = "Document set created";
            }
            catch (Exception ex)
            {
                resultLabel.Text = "An error occurred: " + ex.Message;
            }
        }
Esempio n. 12
0
        private static void CreateContracts(SPWeb web, int countToCreate)
        {
            Console.WriteLine($"Starting to create {countToCreate} contracts");

            var contractsLib = web.GetList(SPUtility.ConcatUrls(web.Url, Urls.ContractsList));

            for (int i = 0; i < countToCreate; i++)
            {
                try
                {
                    var ct = contractsLib.ContentTypes.BestMatch(new SPContentTypeId(ContentTypeIds.Contracts));

                    var docSet = DocumentSet.Create(contractsLib.RootFolder, "0", ct, null, true);

                    var msgCreated = $"Succesfully created contract #{docSet.Item.Title}";
                    Console.WriteLine(msgCreated);
                    Tracer.Trace(msgCreated);
                }
                catch (Exception exception)
                {
                    Tracer.Trace($"Unexpected error while creating contract: {exception}");
                }
            }
        }
        private void ExecuteCreateDocSetByName()
        {
            ServiceObject serviceObject = ServiceBroker.Service.ServiceObjects[0];

            serviceObject.Properties.InitResultTable();
            DataTable results = base.ServiceBroker.ServicePackage.ResultTable;

            string listTitle  = serviceObject.GetListTitle();
            string DocSetName = base.GetStringProperty(Constants.SOProperties.DocSetName, true);
            string FolderName = string.Empty;

            if (serviceObject.IsSPFolderEnabled())
            {
                FolderName = base.GetStringProperty(Constants.SOProperties.FolderName, false);
            }

            DataRow dataRow = results.NewRow();

            using (ClientContext context = InitializeContext(GetSiteURL()))
            {
                Web    spWeb = context.Web;
                List   list  = spWeb.Lists.GetByTitle(listTitle);
                Folder parentFolder;
                context.Load(list, l => l.Fields, l => l.RootFolder);
                context.Load(list, d => d.DefaultDisplayFormUrl, d => d.ItemCount);
                context.Load(list.ContentTypes);
                context.ExecuteQuery();

                if (string.IsNullOrEmpty(FolderName))
                {
                    parentFolder = list.RootFolder;
                }
                else
                {
                    parentFolder = spWeb.GetFolderByServerRelativeUrl(string.Concat(list.RootFolder.Name, '/', FolderName));
                    context.Load(parentFolder);
                    context.ExecuteQuery();
                }

                Microsoft.SharePoint.Client.ClientResult <string> FileLink = new ClientResult <string>();
                foreach (ContentType ct in list.ContentTypes)
                {
                    if (ct.Id.StringValue.StartsWith(Constants.SharePointProperties.DocSetContentType))
                    {
                        FileLink = DocumentSet.Create(context, parentFolder, DocSetName, ct.Id);
                        break;
                    }
                }
                context.ExecuteQuery();

                Folder documentSet = null;
                documentSet = context.Web.GetFolderByServerRelativeUrl(FileLink.Value);
                context.Load(documentSet, c => c.ListItemAllFields);
                context.ExecuteQuery();

                ListItem listItem = documentSet.ListItemAllFields;

                if (listItem == null)
                {
                    throw new Exception(Constants.ErrorMessages.RequiredDocNotFound);
                }

                foreach (Property prop in serviceObject.Properties)
                {
                    if (prop.Value != null && !prop.IsDocSetName() && !prop.IsFolderName())
                    {
                        Helpers.SPHelper.AssignFieldValue(listItem, prop);
                    }
                }
                listItem.Update();
                context.ExecuteQuery();

                if (FileLink != null)
                {
                    dataRow[Constants.SOProperties.LinkToItem] = FileLink.Value;
                    results.Rows.Add(dataRow);
                }
            }
        }
Esempio n. 14
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.");
        }
Esempio n. 15
0
        public SPDocumentSetInstance CreateDocumentSet(
            [JSDoc("The folder to create the document set in.")]
            SPFolderInstance folder,
            [JSDoc("The name of the new document set.")]
            string name,
            [JSDoc("The content type id of the new documentset. Use new ContentTypeId('<CTID>')")]
            SPContentTypeIdInstance ctid,
            [JSDoc("Optional. Specifies a hashtable of fields that will be set on the document set where the key is the static field name.")]
            object properties,
            [JSDoc("Optional. Specifies a value that indicates if the default document set content will be provisioned. Default is true.")]
            object provisionDefaultContent,
            [JSDoc("Optional. Specifies the SPUser that created the document set.")]
            object user)
        {
            if (folder == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "An instance of an SPFolder must be specified as the first argument.");
            }

            if (name.IsNullOrWhiteSpace())
            {
                throw new JavaScriptException(this.Engine, "Error", "The name of the new document set must be specified.");
            }

            if (ctid == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "The Content Type Id of the new document set must be specified.");
            }

            var htProperties = new Hashtable();

            if (properties != null && properties != Null.Value && properties != Undefined.Value)
            {
                htProperties = SPHelper.GetFieldValuesHashtableFromPropertyObject(properties);
            }

            var bProvisionDefaultContent = true;

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

            DocumentSet result;
            var         spUser = user as SPUserInstance;

            if (user == null || user == Null.Value || user == Undefined.Value || spUser == null)
            {
                result = DocumentSet.Create(folder.Folder, name, ctid.ContentTypeId, htProperties, bProvisionDefaultContent);
            }
            else
            {
                result = DocumentSet.Create(folder.Folder, name, ctid.ContentTypeId, htProperties, bProvisionDefaultContent, spUser.User);
            }

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

            return(new SPDocumentSetInstance(this.Engine.Object.InstancePrototype, folder.Folder.ParentWeb.Site,
                                             folder.Folder.ParentWeb, result));
        }
Esempio n. 16
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"Webhook was triggered!");

            try
            {
                var jsonContent = await req.Content.ReadAsStringAsync();

                log.Info(jsonContent);
                dynamic data = JsonConvert.DeserializeObject(jsonContent);

                // TODO: Rather than using web application settings, we should be using the Azure Key Vault for
                // credentials

                var connectionString  = WebUtility.UrlDecode(WebUtility.UrlDecode(data.SpoSiteName.ToString()));
                var documentSetUrl    = string.Empty;
                var applicationFolder = data.ApplicationFolder.ToString();
                var permitFolderName  = data.PermitFolder.ToString();

                using (ClientContext clientContext = new ClientContext(connectionString))
                {
                    var dummy = new TaxonomyItem(clientContext, null);

                    var username = ConfigurationManager.ConnectionStrings["UserName"].ConnectionString;
                    var password = ConfigurationManager.ConnectionStrings["Password"].ConnectionString;

                    var securePassword = new SecureString();
                    foreach (char p in password)
                    {
                        securePassword.AppendChar(p);
                    }

                    var credentials = new SharePointOnlineCredentials(username, securePassword);
                    clientContext.Credentials = credentials;

                    log.Info("Got client context and set credentials");
                    log.Info(string.Format("ListName is {0}", data.ListName.ToString()));

                    var list                 = clientContext.Web.Lists.GetByTitle(data.ListName.ToString());
                    var rootFolder           = list.RootFolder;
                    var permitFolderUrl      = String.Format("{0}/{1}", data.ListName.ToString(), permitFolderName);
                    var applicationFolderUrl = String.Format("{0}/{1}", permitFolderUrl, applicationFolder);

                    // Get the Permit folder content type
                    var ctPermit = GetByName(list.ContentTypes, data.PermitContentType.ToString());
                    log.Info(string.Format("Permit Content Type Id is {0}", ctPermit.Id.StringValue));

                    // Create permit sub folder inside list root folder if it doesn't exist
                    var permitFolder = CreateSubFolderIfDoesntExist(clientContext, permitFolderName, rootFolder, ctPermit, data.PermitFolder.ToString());
                    log.Info(string.Format("Folder is {0}", permitFolder.Name));

                    // Get the Application document set content type
                    var ctApplication = GetByName(list.ContentTypes, data.ApplicationContentType.ToString());
                    log.Info(string.Format("Applicaction Content Type Id is {0}", ctApplication.Id.StringValue));

                    // Create the Document Set
                    try
                    {
                        var ds = DocumentSet.Create(clientContext, permitFolder, applicationFolder, ctApplication.Id);
                        clientContext.ExecuteQuery();
                        documentSetUrl = ds.Value;
                        log.Info(string.Format("Document Set Id is {0}", documentSetUrl));
                    }
                    catch (ServerException ex) when(ex.Message.StartsWith("A document, folder or document set with the name") && ex.Message.EndsWith("already exists."))
                    {
                        documentSetUrl = "Document set exists already";
                        log.Info(string.Format("Handling {0} - {1}", ex.Source, ex.Message));
                    }
                }

                return(req.CreateResponse(HttpStatusCode.OK, "{ \"DocumentSetUrl\" : \"" + documentSetUrl + "\" }"));
            }
            catch (Exception ex)
            {
                log.Info(string.Format("{0} Exception {1}", ex.Source, ex.ToString()));
                return(req.CreateResponse(HttpStatusCode.InternalServerError, "Critial error creating SharePoint DocumentSet: " + ex.Message));
            }
        }