private void CheckInAndPublishPage(ClientContext context, PublishingWeb webPub, string fileUrl)
 {
     //get the home page
     Microsoft.SharePoint.Client.File home = context.Web.GetFileByServerRelativeUrl(fileUrl);
     home.CheckIn(string.Empty, CheckinType.MajorCheckIn);
     home.Publish(string.Empty);
 }
Exemplo n.º 2
0
        public static void UploadPageLayout(ClientContext ctx, string sourcePath, string targetListTitle, string targetUrl)
        {
            using (FileStream fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
            {
                byte[] data = new byte[fs.Length];
                fs.Read(data, 0, data.Length);
                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(data, 0, data.Length);
                    var newfile = new FileCreationInformation();
                    newfile.Content   = ms.ToArray();
                    newfile.Url       = targetUrl;
                    newfile.Overwrite = true;

                    List docs = ctx.Web.Lists.GetByTitle(targetListTitle);
                    Microsoft.SharePoint.Client.File uploadedFile = docs.RootFolder.Files.Add(newfile);
                    uploadedFile.CheckOut();
                    uploadedFile.CheckIn("Data storage model", CheckinType.MajorCheckIn);
                    uploadedFile.Publish("Data storage model layout.");

                    ctx.Load(uploadedFile);
                    ctx.ExecuteQuery();
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="dest"></param>
        /// <param name="path"></param>
        /// <param name="filter"></param>
        /// <param name="recursive"></param>
        private void CopyFolder(ClientContext clientContext, Folder dest, string path, string filter, bool recursive, bool checkin, bool publish)
        {
            string[] files = Directory.GetFiles(path, filter, SearchOption.TopDirectoryOnly);

            foreach (string f in files)
            {
                //upload the file to the sharepoint folder
                FileCreationInformation fci = new FileCreationInformation();
                string name = f.Substring(f.LastIndexOf("\\") + 1);
                System.Diagnostics.Trace.WriteLine("Copying file:" + name);
                fci.Url       = name;
                fci.Content   = System.IO.File.ReadAllBytes(f);
                fci.Overwrite = true;
                Microsoft.SharePoint.Client.File fileToUpload = dest.Files.Add(fci);
                //if it's the page layout
                if (name.EndsWith(".aspx"))
                {
                    fileToUpload.ListItemAllFields["Title"]         = name.Replace(".aspx", string.Empty);
                    fileToUpload.ListItemAllFields["UIVersion"]     = "15";
                    fileToUpload.ListItemAllFields["ContentTypeId"] = "0x01010007FF3E057FA8AB4AA42FCB67B453FFC100E214EEE741181F4E9F7ACC43278EE81100B432574477BA904292DFD58D26CE0E2";
                    fileToUpload.ListItemAllFields["PublishingAssociatedContentType"] = ";#Article Page;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D;#";
                    fileToUpload.ListItemAllFields.Update();
                }
                else if (name.EndsWith(".master"))//master page assuming only single custom master page exists
                {
                    //get the name of the master page
                    string masterPageFileName = name.Substring(0, name.LastIndexOf("."));
                    fileToUpload.ListItemAllFields["Title"]         = masterPageFileName;
                    fileToUpload.ListItemAllFields["UIVersion"]     = "15";
                    fileToUpload.ListItemAllFields["ContentTypeId"] = "0x01010500BF544AFE46ACEF42B8DA22C9CE89526E";
                    fileToUpload.ListItemAllFields.Update();
                }
                clientContext.Load(fileToUpload);
                clientContext.ExecuteQuery();
                if (checkin)
                {
                    fileToUpload.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                    fileToUpload.Publish(string.Empty);
                }
            }
            if (recursive)
            {
                foreach (string d in Directory.GetDirectories(path))
                {
                    //get the folder name
                    string name    = d.Substring(d.LastIndexOf("\\") + 1);
                    Folder newdest = dest.Folders.Add(name);
                    clientContext.ExecuteQuery();
                    CopyFolder(clientContext, newdest, d, filter, recursive, checkin, publish);
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Checks the in publish and approve file asynchronous.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="comment">The comment.</param>
        /// <param name="checkInType">Type of the check in.</param>
        public async Task CheckInPublishAndApproveFileAsync(File file, string comment = null, CheckinType?checkInType = null)
        {
            if (file.CheckOutType != CheckOutType.None)
            {
                file.CheckIn(comment ?? "Updating file", checkInType ?? CheckinType.MajorCheckIn);
            }
            if (file.Level == FileLevel.Draft)
            {
                file.Publish(comment ?? "Updating file");
            }
            file.Context.Load(file, f => f.ListItemAllFields);
            await file.Context.ExecuteQueryAsync();

            if (file.ListItemAllFields["_ModerationStatus"].ToString() == "2") //: pending
            {
                file.Approve(comment ?? "Updating file");
                await file.Context.ExecuteQueryAsync();
            }
        }
Exemplo n.º 5
0
        private void EnsurePublish(File file, string publishComment)
        {
            // Load dependent data.
            var parentList = file.ListItemAllFields.ParentList;
            if (!parentList.IsPropertyAvailable("EnableMinorVersion") || !parentList.IsPropertyAvailable("EnableModeration") || !file.IsPropertyAvailable("Level") || !file.IsPropertyAvailable("ListItemAllFields"))
            {
                _clientContext.Load(parentList);
                _clientContext.Load(file);
                _clientContext.ExecuteQuery();
            }

            var isDirty = false;
            if (file.Level == FileLevel.Checkout)
            {
                file.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                isDirty = true;
            }
            if (parentList.EnableMinorVersions && file.Level != FileLevel.Published)
            {
                file.Publish(publishComment);
                isDirty = true;
            }
            if (parentList.EnableModeration && Convert.ToInt32(file.ListItemAllFields["_ModerationStatus"]) != 0)
            {
                file.Approve(string.Empty);
                isDirty = true;
            }

            if (isDirty)
            {
                file.RefreshLoad();
                _clientContext.ExecuteQuery();
            }
        }
Exemplo n.º 6
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template)
        {
            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_Pages);

            var context = web.Context as ClientContext;

            if (!web.IsPropertyAvailable("ServerRelativeUrl"))
            {
                context.Load(web, w => w.ServerRelativeUrl);
                context.ExecuteQueryRetry();
            }

            foreach (var page in template.PublishingPages)
            {
                var url = String.Format("{0}/Pages/{1}.aspx", web.ServerRelativeUrl, page.PageName);


                if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower()))
                {
                    url = UrlUtility.Combine(web.ServerRelativeUrl, url);
                }


                var exists = true;
                Microsoft.SharePoint.Client.File file = null;
                try
                {
                    file = web.GetFileByServerRelativeUrl(url);
                    web.Context.Load(file);
                    web.Context.ExecuteQuery();
                }
                catch (ServerException ex)
                {
                    if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                    {
                        exists = false;
                    }
                }

                if (exists)
                {
                    if (page.Overwrite)
                    {
                        file.DeleteObject();
                        web.Context.ExecuteQueryRetry();
                        web.AddPublishingPage(page.PageName, page.PageLayoutName, page.Title, page.Content, page.Properties, page.Publish);
                    }

                    //if (file.CheckOutType == CheckOutType.None)
                    //{
                    //    file.CheckOut();
                    //}
                }
                else
                {
                    web.AddPublishingPage(page.PageName, page.PageLayoutName, page.Title, page.Content, page.Properties, page.Publish);
                }

                if (page.WelcomePage)
                {
                    if (!web.IsPropertyAvailable("RootFolder"))
                    {
                        web.Context.Load(web.RootFolder);
                        web.Context.ExecuteQueryRetry();
                    }

                    var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length);
                    web.SetHomePage(rootFolderRelativeUrl);
                }

                // Check out the file if needed



                if (page.WebParts != null & page.WebParts.Any())
                {
                    if (!exists)
                    {
                        file = web.GetFileByServerRelativeUrl(url);
                        web.Context.Load(file);
                        web.Context.ExecuteQuery();
                    }
                    file.CheckOut();


                    var existingWebParts = web.GetWebParts(url);

                    foreach (var webpart in page.WebParts)
                    {
                        if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
                        {
                            WebPartEntity wpEntity = new WebPartEntity();
                            wpEntity.WebPartTitle = webpart.Title;
                            wpEntity.WebPartIndex = (int)webpart.Order;
                            wpEntity.WebPartZone  = webpart.Zone;

                            if (!string.IsNullOrWhiteSpace(webpart.ListUrl))
                            {
                                var list = web.GetListByUrl(webpart.ListUrl);

                                var contents = String.Format(webpart.Contents, list.Id, list.Title);
                                wpEntity.WebPartXml = contents.Trim(new[] { '\n', ' ' });
                            }
                            else
                            {
                                wpEntity.WebPartXml = webpart.Contents.ToParsedString().Trim(new[] { '\n', ' ' });
                            }

                            //wpEntity.WebPartXml = webpart.Contents.ToParsedString().Trim(new[] {'\n', ' '});
                            web.AddWebPartToWebPartPage(url, wpEntity);
                        }
                    }

                    file.CheckIn("", CheckinType.MajorCheckIn);
                    file.Publish("");
                }
            }
        }
Exemplo n.º 7
0
        public virtual void SetProperties(ClientContext ctx, Web web)
        {
            if (!Created)
            {
                return;
            }

            if (ListViewWebParts != null && ListViewWebParts.Count > 0)
            {
                foreach (var webPart in ListViewWebParts.Values)
                {
                    if (!webPart.IsCalendar)
                    {
                        AddListViewWebPart(ctx, web, "IQAppProvisioningBaseClasses.ListViewWebParts.BaseListView.webpart",
                                           webPart.Title, webPart.ZoneId, webPart.Order, webPart.ListName);
                    }
                    else
                    {
                        AddListViewWebPart(ctx, web, "IQAppProvisioningBaseClasses.ListViewWebParts.Calendar.webpart",
                                           webPart.Title, webPart.ZoneId, webPart.Order, webPart.ListName, true);
                    }
                }
            }

            if (ViewSchemas != null && ViewSchemas.Count > 0)
            {
                UpdateViews();
            }

            if (IsHomePage)
            {
                var rootFolder = ctx.Web.RootFolder;
                rootFolder.WelcomePage = Url.Substring(0, 1) == "/" ? Url.Substring(1) : Url;
                rootFolder.Update();
            }

            UpdateListItem(ctx, web);

            ctx.ExecuteQueryRetry();

            try
            {
                File.CheckIn("", CheckinType.MajorCheckIn);
                ctx.ExecuteQueryRetry();
            }
            catch
            {
                //Exceptions expected since we aren't checking to see if the target is configured for checkin
                //Trace.WriteLine(ex);
            }

            try
            {
                File.Publish("");
                ctx.ExecuteQueryRetry();
            }
            catch
            {
                //Exceptions expected since we aren't checking to see if the target is configured for approval
                //Trace.WriteLine(ex);
            }
        }
        public static void CreateSubSites(XNamespace _NameSpace, TokenParser _TokenParser, XElement _Branding, string siteUrl, System.Net.ICredentials creds)
        {
            Console.WriteLine("Creating Sub-Sites . . . ");

            foreach (var site in _Branding.GetDescendants("sites", "site"))
            {
                string web                = site.GetAttributeValue(_TokenParser, "web");
                string title              = site.GetAttributeValue(_TokenParser, "title");
                string leafUrl            = site.GetAttributeValue(_TokenParser, "leafUrl");
                string description        = site.GetAttributeValue(_TokenParser, "description");
                string template           = site.GetAttributeValue(_TokenParser, "template");
                int    language           = site.GetAttributeValue <int>(_TokenParser, "language");
                bool   inheritPermissions = Convert.ToBoolean(site.GetAttributeValue(_TokenParser, "inheritpermissions"));
                bool   inheritNavigation  = Convert.ToBoolean(site.GetAttributeValue(_TokenParser, "inheritnavigation"));
                string lists              = site.GetAttributeValue(_TokenParser, "lists");

                //pre-pend site collection path
                if (String.IsNullOrEmpty(web))
                {
                    web = siteUrl;
                }
                else
                {
                    web = siteUrl + "/" + web;
                }

                // create new Sub-site after testing for existence
                Web newWeb = null;
                using (ClientContext clientContext = new ClientContext(web))
                {
                    clientContext.Credentials    = creds;
                    clientContext.RequestTimeout = 10 * 60 * 1000;
                    clientContext.Load(clientContext.Web);
                    clientContext.ExecuteQueryRetry();

                    string newWebUrl = clientContext.Web.Url + "/" + leafUrl;
                    if (clientContext.WebExistsFullUrl(newWebUrl))
                    {
                        Console.WriteLine("Sub-Site {0} already exists, skipping provisioning.", leafUrl);
                    }
                    else
                    {
                        Console.WriteLine("Creating Sub-Site {0} . . .", leafUrl);

                        newWeb = clientContext.Web.CreateWeb(title, leafUrl, description, template, language, inheritPermissions, inheritNavigation);

                        clientContext.Load(newWeb, w => w.Lists);
                        clientContext.ExecuteQueryRetry();

                        Microsoft.SharePoint.Client.File welcomePageFile = newWeb.Lists.GetByTitle("Pages").GetItemById(1).File;
                        welcomePageFile.Publish("Initial Publish");
                        clientContext.Load(welcomePageFile);
                        clientContext.ExecuteQueryRetry();

                        if (!inheritPermissions)
                        {
                            SitePermissions.ApplyPermissions(clientContext, newWeb);
                        }
                    }

                    if (!String.IsNullOrEmpty(lists))
                    {
                        CreateLists(_NameSpace, _TokenParser, _Branding, clientContext, lists);
                    }
                }
            }
        }
Exemplo n.º 9
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var context = web.Context as ClientContext;

                web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url);

                // Build on the fly the list of additional files coming from the Directories
                var directoryFiles = new List <Model.File>();
                foreach (var directory in template.Directories)
                {
                    Log.Debug(Constants.LOGGING_SOURCE, "Processing Directory {0}", directory.Src);
                    var metadataProperties = directory.GetMetadataProperties();
                    directoryFiles.AddRange(directory.GetDirectoryFiles(metadataProperties));
                }

                foreach (var file in template.Files.Union(directoryFiles))
                {
                    Log.Debug(Constants.LOGGING_SOURCE, "Processing File {0}", file.Src);
                    var folderName = parser.ParseString(file.Folder);

                    if (folderName.ToLower().StartsWith((web.ServerRelativeUrl.ToLower())))
                    {
                        folderName = folderName.Substring(web.ServerRelativeUrl.Length);
                    }

                    var folder = web.EnsureFolderPath(folderName);

                    File targetFile = null;

                    var checkedOut = false;

                    targetFile = folder.GetFile(template.Connector.GetFilenamePart(file.Src));

                    if (targetFile != null)
                    {
                        if (file.Overwrite)
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_and_overwriting_existing_file__0_, file.Src);
                            checkedOut = CheckOutIfNeeded(web, targetFile);

                            using (var stream = GetFileStream(template, file))
                            {
                                targetFile = UploadFile(template, file, folder, stream);
                            }
                        }
                        else
                        {
                            checkedOut = CheckOutIfNeeded(web, targetFile);
                        }
                    }
                    else
                    {
                        using (var stream = GetFileStream(template, file))
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_file__0_, file.Src);
                            targetFile = UploadFile(template, file, folder, stream);
                        }

                        checkedOut = CheckOutIfNeeded(web, targetFile);
                    }

                    if (targetFile != null)
                    {
                        if (file.Properties != null && file.Properties.Any())
                        {
                            Dictionary <string, string> transformedProperties = file.Properties.ToDictionary(property => property.Key, property => parser.ParseString(property.Value));
                            SetFileProperties(targetFile, transformedProperties, false);
                        }

                        if (file.WebParts != null && file.WebParts.Any())
                        {
                            targetFile.EnsureProperties(f => f.ServerRelativeUrl);

                            var existingWebParts = web.GetWebParts(targetFile.ServerRelativeUrl);
                            foreach (var webpart in file.WebParts)
                            {
                                // check if the webpart is already set on the page
                                if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
                                {
                                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Adding_webpart___0___to_page, webpart.Title);
                                    var wpEntity = new WebPartEntity();
                                    wpEntity.WebPartTitle = webpart.Title;
                                    wpEntity.WebPartXml   = parser.ParseString(webpart.Contents).Trim(new[] { '\n', ' ' });
                                    wpEntity.WebPartZone  = webpart.Zone;
                                    wpEntity.WebPartIndex = (int)webpart.Order;
                                    web.AddWebPartToWebPartPage(targetFile.ServerRelativeUrl, wpEntity);
                                }
                            }
                        }

                        if (checkedOut)
                        {
                            Log.Debug(Constants.LOGGING_SOURCE, "Checking-in File {0}", file.Src);
                            targetFile.CheckIn("", CheckinType.MajorCheckIn);
                            web.Context.ExecuteQueryRetry();
                        }

                        if (file.Level == Model.FileLevel.Published)
                        {
                            Log.Debug(Constants.LOGGING_SOURCE, "Publishing File {0}", file.Src);
                            targetFile.Publish("");
                            web.Context.ExecuteQueryRetry();
                        }

                        // Don't set security when nothing is defined. This otherwise breaks on files set outside of a list
                        if (file.Security != null &&
                            (file.Security.ClearSubscopes == true || file.Security.CopyRoleAssignments == true || file.Security.RoleAssignments.Count > 0))
                        {
                            targetFile.ListItemAllFields.SetSecurity(parser, file.Security);
                        }
                    }
                }
            }
            return(parser);
        }
Exemplo n.º 10
0
        public static void SetSupportCaseContent(ClientContext ctx, string pageName, string url, string queryurl)
        {
            List pages = ctx.Web.Lists.GetByTitle("Pages");

            ctx.Load(pages.RootFolder, f => f.ServerRelativeUrl);
            ctx.ExecuteQuery();

            Microsoft.SharePoint.Client.File file =
                ctx.Web.GetFileByServerRelativeUrl(pages.RootFolder.ServerRelativeUrl + "/" + pageName + ".aspx");
            ctx.Load(file);
            ctx.ExecuteQuery();

            file.CheckOut();

            LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);

            string quicklaunchmenuFormat =
                @"<div><a href='{0}/{1}'>Sample Home Page</a></div>
                <br />
                <div style='font-weight:bold'>CSR Dashboard</div>
                <div class='cdsm_mainmenu'>
                    <ul>
                        <li><a href='{0}/CSRInfo/{1}'>My CSR Info</a></li>
                        <li><a href='{0}/CallQueue/{1}'>Call Queue</a></li>
                        <li>
                            <span class='collapse_arrow'></span>
                            <span><a href='{0}/CustomerDashboard/{1}'>Customer Dashboard</a></span>
                            <ul>
                                <li><a href='{0}/CustomerDashboard/Orders{1}'>Recent Orders</a></li>
                                <li><a class='current' href='#'>Support Cases</a></li>
                                <li><a href='{0}/CustomerDashboard/Notes{1}'>Notes</a></li>
                            </ul>
                        </li>
                    </ul>
                </div>
                <div class='cdsm_submenu'>

                </div>";

            string quicklaunchmenu = string.Format(quicklaunchmenuFormat, url, queryurl);

            string            qlwebPartXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><webParts><webPart xmlns=\"http://schemas.microsoft.com/WebPart/v3\"><metaData><type name=\"Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" /><importErrorMessage>Cannot import this Web Part.</importErrorMessage></metaData><data><properties><property name=\"Content\" type=\"string\"><![CDATA[" + quicklaunchmenu + "​​​]]></property><property name=\"ChromeType\" type=\"chrometype\">None</property></properties></data></webPart></webParts>";
            WebPartDefinition qlWpd        = limitedWebPartManager.ImportWebPart(qlwebPartXml);
            WebPartDefinition qlWpdNew     = limitedWebPartManager.AddWebPart(qlWpd.WebPart, "SupportCasesZoneLeft", 0);

            ctx.Load(qlWpdNew);

            //Customer Dropdown List Script Web Part
            string            dpwebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/CustomerDropDownlist.webpart");
            WebPartDefinition dpWpd        = limitedWebPartManager.ImportWebPart(dpwebPartXml);
            WebPartDefinition dpWpdNew     = limitedWebPartManager.AddWebPart(dpWpd.WebPart, "SupportCasesZoneTop", 0);

            ctx.Load(dpWpdNew);

            //Support Case CBS Info Web Part
            string            cbsInfoWebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/SupportCaseCBSWebPartInfo.webpart");
            WebPartDefinition cbsInfoWpd        = limitedWebPartManager.ImportWebPart(cbsInfoWebPartXml);
            WebPartDefinition cbsInfoWpdNew     = limitedWebPartManager.AddWebPart(cbsInfoWpd.WebPart, "SupportCasesZoneMiddle", 0);

            ctx.Load(cbsInfoWpdNew);

            //Support Case Content By Search Web Part
            string            cbswebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/SupportCase CBS Webpart/SupportCaseCBS.webpart");
            WebPartDefinition cbsWpd        = limitedWebPartManager.ImportWebPart(cbswebPartXml);
            WebPartDefinition cbsWpdNew     = limitedWebPartManager.AddWebPart(cbsWpd.WebPart, "SupportCasesZoneMiddle", 1);

            ctx.Load(cbsWpdNew);

            //Support Cases App Part
            string            appPartXml  = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/SupportCaseAppPart.webpart");
            WebPartDefinition appPartWpd  = limitedWebPartManager.ImportWebPart(appPartXml);
            WebPartDefinition appPartdNew = limitedWebPartManager.AddWebPart(appPartWpd.WebPart, "SupportCasesZoneBottom", 0);

            ctx.Load(appPartdNew);

            //Get Host Web Query String and show support case list web part
            string            querywebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/GetHostWebQueryStringAndShowList.webpart");
            WebPartDefinition queryWpd        = limitedWebPartManager.ImportWebPart(querywebPartXml);
            WebPartDefinition queryWpdNew     = limitedWebPartManager.AddWebPart(queryWpd.WebPart, "SupportCasesZoneBottom", 1);

            ctx.Load(queryWpdNew);


            file.CheckIn("Data storage model", CheckinType.MajorCheckIn);
            file.Publish("Data storage model");
            ctx.Load(file);
            ctx.ExecuteQuery();
        }
Exemplo n.º 11
0
        public static void ProvisionFiles()
        {
            string        srcSiteUrl       = "http://win-f33ohjutmmi/sites/cms";
            ClientContext clientContextSRC = new ClientContext(srcSiteUrl);
            Site          srcSite          = clientContextSRC.Site;

            clientContextSRC.Load(srcSite, s => s.ServerRelativeUrl, s => s.Url);
            clientContextSRC.ExecuteQuery();

            Web srcRootWeb    = clientContextSRC.Site.RootWeb;
            Web srcCurrentWeb = clientContextSRC.Web;

            clientContextSRC.Load(srcRootWeb, rw => rw.Id);
            clientContextSRC.ExecuteQuery();
            clientContextSRC.Load(srcCurrentWeb, cw => cw.Id);
            clientContextSRC.ExecuteQuery();

            string srcMasterUrl = String.Format("{0}/_catalogs/masterpage/APCMS.master", srcSite.ServerRelativeUrl);
            File   apcmsSrcFile = null;

            string srcLayoutUrl       = String.Format("{0}/_catalogs/masterpage/BridgePage.aspx", srcSite.ServerRelativeUrl);
            File   apcmsLayoutSrcFile = null;

            string srcColourFileUrl  = String.Format("{0}/_catalogs/theme/15/PaletteAPCMS.spcolor", srcSite.ServerRelativeUrl);
            File   apcmsColorSrcFile = null;


            ClientResult <System.IO.Stream> rs       = null;
            ClientResult <System.IO.Stream> rsLayout = null;
            ClientResult <System.IO.Stream> rsColor  = null;

            if (srcRootWeb.Id.ToString() == srcCurrentWeb.Id.ToString())
            {
                //load master page and page layout
                List   masterPageGallery = srcRootWeb.Lists.GetByTitle("Master Page Gallery");
                Folder rootFolder        = masterPageGallery.RootFolder;

                apcmsSrcFile       = srcCurrentWeb.GetFileByServerRelativeUrl(srcMasterUrl);
                apcmsLayoutSrcFile = srcCurrentWeb.GetFileByServerRelativeUrl(srcLayoutUrl);

                clientContextSRC.Load(apcmsSrcFile);
                clientContextSRC.Load(apcmsLayoutSrcFile);

                clientContextSRC.ExecuteQuery();

                rs       = apcmsSrcFile.OpenBinaryStream();
                rsLayout = apcmsLayoutSrcFile.OpenBinaryStream();

                clientContextSRC.ExecuteQuery();

                //load color file
                List themeGallery = srcRootWeb.Lists.GetByTitle("Theme Gallery");
                rootFolder = themeGallery.RootFolder;

                apcmsColorSrcFile = srcCurrentWeb.GetFileByServerRelativeUrl(srcColourFileUrl);

                clientContextSRC.Load(apcmsColorSrcFile);
                clientContextSRC.ExecuteQuery();
                rsColor = apcmsColorSrcFile.OpenBinaryStream();

                clientContextSRC.ExecuteQuery();
            }


            string        siteUrl       = "http://win-f33ohjutmmi/sites/pltest";
            ClientContext clientContext = new ClientContext(siteUrl);

            Site site = clientContext.Site;

            clientContext.Load(site, s => s.ServerRelativeUrl, s => s.Url);
            clientContext.ExecuteQuery();

            Web rootWeb    = clientContext.Site.RootWeb;
            Web currentWeb = clientContext.Web;

            clientContext.Load(rootWeb, rw => rw.Id);
            clientContext.ExecuteQuery();
            clientContext.Load(currentWeb, cw => cw.Id);
            clientContext.ExecuteQuery();

            #region upload and set master page, also upload the page layout

            string masterUrl = String.Format("{0}/_catalogs/masterpage/APCMS.master", site.ServerRelativeUrl);
            string colorUrl  = String.Format("{0}/_catalogs/theme/15/PaletteAPCMS.spcolor", site.ServerRelativeUrl);


            if (rootWeb.Id.ToString() == currentWeb.Id.ToString())
            {
                List   masterPageGallery = rootWeb.Lists.GetByTitle("Master Page Gallery");
                Folder rootFolder        = masterPageGallery.RootFolder;
                //master page
                FileCreationInformation fci = new FileCreationInformation();
                fci.ContentStream = rs.Value;
                fci.Url           = "APCMS.master";
                fci.Overwrite     = true;

                Microsoft.SharePoint.Client.File fileToUpload = rootFolder.Files.Add(fci);

                clientContext.Load(fileToUpload);

                fileToUpload.Publish("");

                currentWeb.CustomMasterUrl = masterUrl;
                currentWeb.Update();
                clientContext.ExecuteQuery();

                //page layout
                fci = new FileCreationInformation();
                fci.ContentStream = rsLayout.Value;
                fci.Url           = "BridgePage.aspx";
                fci.Overwrite     = true;

                fileToUpload = rootFolder.Files.Add(fci);

                fileToUpload.Publish("");
                clientContext.ExecuteQuery();

                ListItem item = fileToUpload.ListItemAllFields;

                ContentType targetDocumentSetContentType = GetContentType(clientContext, rootWeb, "Page Layout");
                item["ContentTypeId"] = targetDocumentSetContentType.Id.ToString();
                item.Update();
                clientContext.ExecuteQuery();

                targetDocumentSetContentType            = GetContentType(clientContext, rootWeb, "Article Page");
                item["PublishingAssociatedContentType"] = String.Format(";#{0};#{1};#", targetDocumentSetContentType.Name, targetDocumentSetContentType.Id.ToString());
                item.Update();
                clientContext.ExecuteQuery();

                //color file
                List themeGallery = rootWeb.Lists.GetByTitle("Theme Gallery");
                clientContext.Load(themeGallery.RootFolder.Folders); //load the sub folder first !!!
                clientContext.ExecuteQuery();                        //must call

                rootFolder        = themeGallery.RootFolder.Folders[0];
                fci               = new FileCreationInformation();
                fci.ContentStream = rsColor.Value;
                fci.Url           = "PaletteAPCMS.spcolor";
                fci.Overwrite     = true;

                fileToUpload = rootFolder.Files.Add(fci);

                clientContext.ExecuteQuery();

                clientContext.Load(fileToUpload);

                rootWeb.ApplyTheme(colorUrl, null, null, true);
                rootWeb.Update();

                clientContext.ExecuteQuery();
            }

            #endregion
        }