Exemplo n.º 1
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();
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// uploads the file and adds metadata
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="FolderName"></param>
        /// <param name="Filepath"></param>
        /// <param name="Pairs"></param>
        /// <remarks>
        /// the pairs argument accepts key value pairs of strings only
        /// </remarks>
        public static void UploadFileWithMeta(string URL, string FolderName, string Filepath, Dictionary <string, string> Pairs)
        {
            string Filename;

            try
            {
                Filename = Path.GetFileName(Filepath);

                AuthenticationManager authManager = new AuthenticationManager();

                var    context = authManager.GetWebLoginClientContext(URL);
                Web    web     = context.Web;
                List   library = web.Lists.GetByTitle(FolderName);
                Folder folder  = library.RootFolder;
                context.Load(folder);
                context.ExecuteQuery();

                using (FileStream fs = new FileStream(Filepath, FileMode.Open))
                {
                    FileCreationInformation fileInfo = new FileCreationInformation();
                    fileInfo.ContentStream = fs;
                    fileInfo.Url           = library.RootFolder.ServerRelativeUrl + "/" + Filename;
                    fileInfo.Overwrite     = true;
                    Microsoft.SharePoint.Client.File file = folder.Files.Add(fileInfo);

                    foreach (var pair in Pairs)
                    {
                        file.ListItemAllFields["" + pair.Key + ""] = "" + pair.Value + "";
                    }

                    file.ListItemAllFields.Update();
                    context.Load(file);
                    context.ExecuteQuery();

                    if (file.CheckOutType != CheckOutType.None)
                    {
                        file.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                    }

                    var message = "File uploaded with metadata";
                    Console.WriteLine(message);

                    using (StreamWriter sw = System.IO.File.CreateText("C:\\Apps\\UploadFileWithMeta.txt"))
                    {
                        sw.WriteLine(message);
                    }
                }
            }
            catch (Exception e)
            {
                using (StreamWriter sw = System.IO.File.CreateText("C:\\Apps\\UploadFileWithMeta.txt"))
                {
                    sw.WriteLine("Error: " + e.Message);
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Can be used ot deploy page layouts to master page gallyery.
        /// <remarks>Should be only used with root web of site collection where publishing features are enabled.</remarks>
        /// </summary>
        /// <param name="web">Web as the root site of the publishign site collection</param>
        /// <param name="sourceFilePath">Full path to the file which will be uploaded</param>
        /// <param name="title">Title for the page layout</param>
        /// <param name="description">Description for the page layout</param>
        /// <param name="associatedContentTypeID">Assocated content type ID</param>
        public static void DeployPageLayout(this Web web, string sourceFilePath, string title, string description, string associatedContentTypeID)
        {
            // Get the path to the file which we are about to deploy
            List   masterPageGallery = web.GetCatalog(116);
            Folder rootFolder        = masterPageGallery.RootFolder;

            web.Context.Load(masterPageGallery);
            web.Context.Load(rootFolder);
            web.Context.ExecuteQuery();

            string fileName  = Path.GetFileName(sourceFilePath);
            var    fileBytes = System.IO.File.ReadAllBytes(sourceFilePath);

            // Use CSOM to upload the file in
            FileCreationInformation newFile = new FileCreationInformation();

            newFile.Content   = fileBytes;
            newFile.Url       = UrlUtility.Combine(rootFolder.ServerRelativeUrl, fileName);
            newFile.Overwrite = true;

            Microsoft.SharePoint.Client.File uploadFile = rootFolder.Files.Add(newFile);
            web.Context.Load(uploadFile);
            web.Context.ExecuteQuery();

            // Check out the file if needed
            if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning)
            {
                if (uploadFile.CheckOutType == CheckOutType.None)
                {
                    uploadFile.CheckOut();
                }
            }

            // Get content type for ID to assign assocated content type information
            ContentType associatedCt = web.GetContentTypeById(associatedContentTypeID);

            var listItem = uploadFile.ListItemAllFields;

            listItem["Title"] = title;
            listItem["MasterPageDescription"] = description;
            // set the item as page layout
            listItem["ContentTypeId"] = "0x01010007FF3E057FA8AB4AA42FCB67B453FFC100E214EEE741181F4E9F7ACC43278EE811";
            // Set teh associated content type ID property
            listItem["PublishingAssociatedContentType"] = ";#" + associatedCt.Name + ";#" + associatedCt.Id + ";#";
            listItem["UIVersion"] = Convert.ToString(15);
            listItem.Update();

            // Check in the page layout if needed
            if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning)
            {
                uploadFile.CheckIn("", CheckinType.MajorCheckIn);
                listItem.File.Publish("");
            }
            web.Context.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.º 5
0
        public static void DeployMasterPage(this Web web, string sourceFilePath, string title, string description, string uiVersion = "15", string defaultCSSFile = "")
        {
            // Get the path to the file which we are about to deploy
            List   masterPageGallery = web.GetCatalog(116);
            Folder rootFolder        = masterPageGallery.RootFolder;

            web.Context.Load(masterPageGallery);
            web.Context.Load(rootFolder);
            web.Context.ExecuteQuery();

            // Get the file name from the provided path
            string fileName  = Path.GetFileName(sourceFilePath);
            var    fileBytes = System.IO.File.ReadAllBytes(sourceFilePath);

            // Use CSOM to upload the file in
            FileCreationInformation newFile = new FileCreationInformation();

            newFile.Content   = fileBytes;
            newFile.Url       = UrlUtility.Combine(rootFolder.ServerRelativeUrl, fileName);
            newFile.Overwrite = true;

            Microsoft.SharePoint.Client.File uploadFile = rootFolder.Files.Add(newFile);
            web.Context.Load(uploadFile);
            web.Context.ExecuteQuery();


            var listItem = uploadFile.ListItemAllFields;

            if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning)
            {
                if (uploadFile.CheckOutType == CheckOutType.None)
                {
                    uploadFile.CheckOut();
                }
            }

            listItem["Title"] = title;
            listItem["MasterPageDescription"] = description;
            // Set content type as master page
            listItem["ContentTypeId"] = "0x01010500B45822D4B60B7B40A2BFCC0995839404";
            listItem["UIVersion"]     = uiVersion;
            listItem.Update();
            if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning)
            {
                uploadFile.CheckIn("", CheckinType.MajorCheckIn);
                listItem.File.Publish("");
            }
            web.Context.Load(listItem);
            web.Context.ExecuteQuery();
        }
Exemplo n.º 6
0
        public static void UploadFileToFolder(Web web, string filePath, Folder folder)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                FileCreationInformation flciNewFile = new FileCreationInformation();

                flciNewFile.ContentStream = fs;
                flciNewFile.Url           = System.IO.Path.GetFileName(filePath);
                flciNewFile.Overwrite     = true;

                Microsoft.SharePoint.Client.File uploadFile = folder.Files.Add(flciNewFile);
                uploadFile.CheckIn("CSR sample js file", CheckinType.MajorCheckIn);

                folder.Context.Load(uploadFile);
                folder.Context.ExecuteQuery();
            }
        }
Exemplo n.º 7
0
 private void UploadFilesToLibary(ClientContext clientContext, Web web, List list, string fileURL, string romoteFileURL)
 {
     try
     {
         FileCreationInformation newFile = new FileCreationInformation();
         newFile.Content   = System.IO.File.ReadAllBytes(HostingEnvironment.MapPath(string.Format("~/{0}", fileURL)));
         newFile.Url       = romoteFileURL;
         newFile.Overwrite = true;
         Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(newFile);
         web.Context.Load(uploadFile);
         uploadFile.CheckIn("", CheckinType.MajorCheckIn);
         web.Context.ExecuteQuery();
     }
     catch
     {
     }
 }
Exemplo n.º 8
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.º 9
0
        // ---------- METHODS ----------

        /// <summary>
        /// Uploads a file to the folder.
        /// </summary>
        /// <param name="name">The name of the file to upload.</param>
        /// <param name="stream">The IO stream object representing the file's contents.</param>
        /// <param name="fileLength">The length of the file in bytes.</param>
        /// <param name="client">The SharePoint client that will be used to upload the file.</param>
        /// <param name="requiredFieldValues">Optional: A dictionary with values for fields that are required to be supplied
        /// when uploading the file to the folder in SharePoint.</param>
        /// <returns>True if the file could be uploaded, false otherwise.</returns>
        public bool UploadFile(string name, Stream stream, int fileLength, SharePointClient client, Dictionary <string, object> requiredFieldValues = null)
        {
            if (!string.IsNullOrWhiteSpace(name) && stream != null && fileLength > 0 && client != null)
            {
                try
                {
                    Microsoft.SharePoint.Client.File.SaveBinaryDirect((ClientContext)folder.Context, Url + @"/" + name, stream, true);
                    Microsoft.SharePoint.Client.File file = client.GetFileByUrl(Url + @"/" + name);

                    // Add required field values if supplied.
                    if (requiredFieldValues != null)
                    {
                        ListItem listItem = file.ListItemAllFields;
                        foreach (string fieldName in requiredFieldValues.Keys)
                        {
                            listItem[fieldName] = requiredFieldValues[fieldName];
                        }
                        listItem.Update();
                    }

                    // Update the server with the changes.
                    folder.Context.ExecuteQuery();

                    // The file is automatically checked out. Check it back in.
                    file.CheckIn("", CheckinType.OverwriteCheckIn);

                    return(true);
                }
                catch
                {
                    // There was an error uploading the file.
                    return(false);
                }
            }
            else
            {
                // Parameters were not supplied.
                return(false);
            }
        }
Exemplo n.º 10
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);
            }
        }
Exemplo n.º 11
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)
                {
                    var metadataProperties = directory.GetMetadataProperties();
                    directoryFiles.AddRange(directory.GetDirectoryFiles(metadataProperties));
                }

                foreach (var file in template.Files.Union(directoryFiles))
                {
                    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)
                        {
                            targetFile.CheckIn("", CheckinType.MajorCheckIn);
                            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.º 12
0
        static void Main(string[] args)
        {
            try
            {
                //Get site URL and credentials values from config
                Uri siteUri = new Uri(ConfigurationManager.AppSettings["SourceSite"].ToString());

                //Connect to SharePoint Online
                using (ClientContext clientContext = new ClientContext(siteUri.ToString()))
                {
                    SecureString passWord = new SecureString();
                    foreach (char c in ConfigurationManager.AppSettings["DestinationPassword"].ToCharArray())
                    {
                        passWord.AppendChar(c);
                    }
                    clientContext.Credentials = new SharePointOnlineCredentials("*****@*****.**", passWord);

                    if (clientContext != null)
                    {
                        //Source list
                        List sourceList = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["SourceList"]);
                        //Destination library
                        List destinationLibrary = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["DestinationLibrary"]);

                        // try to get all the list items
                        // could get in sections if it exceeds List View Threshold
                        CamlQuery camlQuery = new CamlQuery();
                        camlQuery.ViewXml = "<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>";

                        ListItemCollection listItems  = sourceList.GetItems(camlQuery);
                        FieldCollection    listFields = sourceList.Fields;
                        clientContext.Load(sourceList);
                        clientContext.Load(listFields);
                        clientContext.Load(listItems);
                        clientContext.ExecuteQuery();

                        // Download attachments for each list item and then upload to new list item
                        foreach (ListItem item in listItems)
                        {
                            string attachmentURL = siteUri + "/Lists/" + ConfigurationManager.AppSettings["SourceList"].ToString() + "/Attachments/" + item["ID"];
                            Folder folder        = clientContext.Web.GetFolderByServerRelativeUrl(attachmentURL);
                            clientContext.Load(folder);

                            try
                            {
                                clientContext.ExecuteQuery();
                            }
                            catch (ServerException ex)
                            {
                                Console.WriteLine(ex.Message);
                                Console.WriteLine("No Attachment for ID " + item["ID"].ToString());
                            }

                            FileCollection attachments = folder.Files;
                            clientContext.Load(attachments);
                            clientContext.ExecuteQuery();

                            // write each file to local disk
                            foreach (SP.File file in folder.Files)
                            {
                                if (clientContext.HasPendingRequest)
                                {
                                    clientContext.ExecuteQuery();
                                }
                                var fileRef  = file.ServerRelativeUrl;
                                var fileInfo = SP.File.OpenBinaryDirect(clientContext, fileRef);

                                using (var memory = new MemoryStream())
                                {
                                    byte[] buffer = new byte[1024 * 64];
                                    int    nread  = 0;
                                    while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        memory.Write(buffer, 0, nread);
                                    }
                                    memory.Seek(0, SeekOrigin.Begin);
                                    // at this point you have the contents of your file in memory
                                    // save to computer
                                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, string.Format("/{0}/{1}", ConfigurationManager.AppSettings["AttachmentLibrary"], System.IO.Path.GetFileName(file.Name)), memory, true);
                                }

                                // this call avoids potential problems if any requests are still pending
                                if (clientContext.HasPendingRequest)
                                {
                                    clientContext.ExecuteQuery();
                                }

                                SP.File newFile = clientContext.Web.GetFileByServerRelativeUrl(string.Format("/{0}/{1}", ConfigurationManager.AppSettings["AttachmentLibrary"], System.IO.Path.GetFileName(file.Name)));
                                clientContext.Load(newFile);
                                clientContext.ExecuteQuery();

                                //check out to make sure not to create multiple versions
                                newFile.CheckOut();

                                FieldLookupValue applicationName = item["Source"] as FieldLookupValue;

                                // app name may be null
                                if (applicationName == null)
                                {
                                    applicationName = new FieldLookupValue();
                                }

                                applicationName.LookupId = Convert.ToInt32(item["ID"]);
                                ListItem newItem = newFile.ListItemAllFields;
                                newItem["From_x0020_Source"] = applicationName;
                                newItem.Update();

                                // use OverwriteCheckIn type to make sure not to create multiple versions
                                newFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);

                                // Clear requests if any if pending
                                if (clientContext.HasPendingRequest)
                                {
                                    clientContext.ExecuteQuery();
                                }
                            }
                            Console.WriteLine("All list items and attachments copied over. Press any key to close");
                            Console.ReadKey();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed: " + ex.Message);
                Console.WriteLine("Stack Trace: " + ex.StackTrace);
                Console.ReadKey();
            }
        }
Exemplo n.º 13
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.º 14
0
        /// <summary>
        /// Can be used to deploy page layouts to master page gallery.
        /// <remarks>Should be only used with root web of site collection where publishing features are enabled.</remarks>
        /// </summary>
        /// <param name="web">Web as the root site of the publishing site collection</param>
        /// <param name="sourceFilePath">Full path to the file which will be uploaded</param>
        /// <param name="title">Title for the page layout</param>
        /// <param name="description">Description for the page layout</param>
        /// <param name="associatedContentTypeID">Associated content type ID</param>
        public static void DeployPageLayout(this Web web, string sourceFilePath, string title, string description, string associatedContentTypeID)
        {
            if (string.IsNullOrEmpty(sourceFilePath))
            {
                throw new ArgumentNullException("sourceFilePath");
            }

            if (!System.IO.File.Exists(sourceFilePath))
            {
                throw new FileNotFoundException("File for param sourceFilePath file does not exist", sourceFilePath);
            }

            string fileName = Path.GetFileName(sourceFilePath);

            LoggingUtility.Internal.TraceInformation((int)EventId.DeployPageLayout, "Deploying page layout '{0}' to '{1}'.", fileName, web.Context.Url);

            // Get the path to the file which we are about to deploy
            List   masterPageGallery = web.GetCatalog((int)ListTemplateType.MasterPageCatalog);
            Folder rootFolder        = masterPageGallery.RootFolder;

            web.Context.Load(masterPageGallery);
            web.Context.Load(rootFolder);
            web.Context.ExecuteQuery();

            var fileBytes = System.IO.File.ReadAllBytes(sourceFilePath);

            // Use CSOM to upload the file in
            FileCreationInformation newFile = new FileCreationInformation();

            newFile.Content   = fileBytes;
            newFile.Url       = UrlUtility.Combine(rootFolder.ServerRelativeUrl, fileName);
            newFile.Overwrite = true;

            Microsoft.SharePoint.Client.File uploadFile = rootFolder.Files.Add(newFile);
            web.Context.Load(uploadFile);
            web.Context.ExecuteQuery();

            // Check out the file if needed
            if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning)
            {
                if (uploadFile.CheckOutType == CheckOutType.None)
                {
                    uploadFile.CheckOut();
                }
            }

            // Get content type for ID to assign associated content type information
            ContentType associatedCt = web.GetContentTypeById(associatedContentTypeID);

            var listItem = uploadFile.ListItemAllFields;

            listItem["Title"] = title;
            listItem["MasterPageDescription"] = description;
            // set the item as page layout
            listItem["ContentTypeId"] = Constants.PAGE_LAYOUT_CONTENT_TYPE;
            // Set the associated content type ID property
            listItem["PublishingAssociatedContentType"] = string.Format(";#{0};#{1};#", associatedCt.Name, associatedCt.Id);
            listItem["UIVersion"] = Convert.ToString(15);
            listItem.Update();

            // Check in the page layout if needed
            if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning)
            {
                uploadFile.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                listItem.File.Publish(string.Empty);
            }
            web.Context.ExecuteQuery();
        }
Exemplo n.º 15
0
        public static void DeployMasterPage(this Web web, string sourceFilePath, string title, string description, string uiVersion = "15", string defaultCSSFile = "")
        {
            if (string.IsNullOrEmpty(sourceFilePath))
            {
                throw new ArgumentNullException("sourceFilePath");
            }

            if (!System.IO.File.Exists(sourceFilePath))
            {
                throw new FileNotFoundException("File for param sourceFilePath not found.", sourceFilePath);
            }

            string fileName = Path.GetFileName(sourceFilePath);

            LoggingUtility.Internal.TraceInformation((int)EventId.DeployMasterPage, "Deploying masterpage '{0}' to '{1}'.", fileName, web.Context.Url);

            // Get the path to the file which we are about to deploy
            List   masterPageGallery = web.GetCatalog((int)ListTemplateType.MasterPageCatalog);
            Folder rootFolder        = masterPageGallery.RootFolder;

            web.Context.Load(masterPageGallery);
            web.Context.Load(rootFolder);
            web.Context.ExecuteQuery();

            // Get the file name from the provided path
            var fileBytes = System.IO.File.ReadAllBytes(sourceFilePath);

            // Use CSOM to upload the file in
            FileCreationInformation newFile = new FileCreationInformation();

            newFile.Content   = fileBytes;
            newFile.Url       = UrlUtility.Combine(rootFolder.ServerRelativeUrl, fileName);
            newFile.Overwrite = true;

            Microsoft.SharePoint.Client.File uploadFile = rootFolder.Files.Add(newFile);
            web.Context.Load(uploadFile);
            web.Context.ExecuteQuery();


            var listItem = uploadFile.ListItemAllFields;

            if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning)
            {
                if (uploadFile.CheckOutType == CheckOutType.None)
                {
                    uploadFile.CheckOut();
                }
            }

            listItem["Title"] = title;
            listItem["MasterPageDescription"] = description;
            // Set content type as master page
            listItem["ContentTypeId"] = Constants.MASTERPAGE_CONTENT_TYPE;
            listItem["UIVersion"]     = uiVersion;
            listItem.Update();
            if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning)
            {
                uploadFile.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                listItem.File.Publish(string.Empty);
            }
            web.Context.Load(listItem);
            web.Context.ExecuteQuery();
        }
Exemplo n.º 16
0
        public static bool AddFileToSPLib(string fullFileName, string webUrl, string libName)
        {
            try
            {
                SPAccount account = Global.SPAccounts().FirstOrDefault(s => s.SPSite.ToLower() == webUrl.ToLower());

                if (account == null)
                {
                    Global.WriteLog("There is no SPAccount entry for " + webUrl + " in the setting xml file.", EventLogEntryType.Error);
                    return(false);
                }

                SecureString securePassword = new SecureString();
                foreach (var passwordChar in account.Password)
                {
                    securePassword.AppendChar(passwordChar);
                }
                using (context = new ClientContext(webUrl))
                {
                    context.Credentials = new SharePointOnlineCredentials(account.UserName, securePassword);
                    context.Load(context.Web, w => w.Title);
                    context.ExecuteQuery();

                    Microsoft.SharePoint.Client.ListCollection collList = context.Web.Lists;

                    context.LoadQuery(collList.Include(
                                          list => list.Title,
                                          list => list.Id,
                                          list => list.Hidden,
                                          list => list.BaseType));

                    context.Load(collList);

                    context.ExecuteQuery();

                    var targetList = collList.FirstOrDefault(l => l.Title.ToLower() == libName.ToLower());

                    string fileName = System.IO.Path.GetFileName(fullFileName);

                    fileName = Global.CleanInvalidCharacters(fileName);

                    context.Load(targetList);
                    context.ExecuteQuery();

                    context.Load(targetList.RootFolder);
                    context.ExecuteQuery();

                    Microsoft.SharePoint.Client.File currentFile = null;

                    var tempcurrentFile = CheckIfItemAlreadyExistByDisplayName(fileName, targetList);
                    if (tempcurrentFile != null && tempcurrentFile.Count() != 0)
                    {
                        currentFile = tempcurrentFile.FirstOrDefault().File;
                        if (targetList.ForceCheckout)
                        {
                            currentFile.CheckOut();
                        }
                    }

                    using (FileStream fs = new FileStream(fullFileName, FileMode.Open))
                    {
                        string targetLocation = targetList.RootFolder.ServerRelativeUrl + "/" + fileName;
                        Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, targetLocation, fs, true);
                    }

                    if (targetList.ForceCheckout)
                    {
                        currentFile.CheckIn("Updated on " + DateTime.Now, CheckinType.MajorCheckIn);
                    }
                    return(true);
                }
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("it is being used by another process"))
                {
                    Global.WriteLog(string.Format("Can not add the file {0} in the SP lib {1}. Reason: ",
                                                  fullFileName,
                                                  libName,
                                                  ex.Message), EventLogEntryType.Error);
                }
                return(false);
            }
        }
Exemplo n.º 17
0
        public void UnGhostFile(string absoluteFilePath, string outPutFolder, string OperationType, string SharePointOnline_OR_OnPremise = Constants.OnPremise, string UserName = "******", string Password = "******", string Domain = "NA")
        {
            string fileName               = string.Empty;
            string newFileName            = string.Empty;
            string directoryName          = string.Empty;
            bool   headerCSVColumns       = false;
            string exceptionCommentsInfo1 = string.Empty;

            GhostingAndUnGhosting_Initialization(outPutFolder, "UNGHOST");

            Logger.AddMessageToTraceLogFile(Constants.Logging, "############## Un Ghosting - Trasnformation Utility Execution Started - For Web ##############");
            Console.WriteLine("############## Un Ghosting - Trasnformation Utility Execution Started - For Web ##############");

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[DATE TIME] " + Logger.CurrentDateTime());
            Console.WriteLine("[DATE TIME] " + Logger.CurrentDateTime());

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[START] ::: UnGhostFile");
            Console.WriteLine("[START] ::: UnGhostFile");

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[UnGhostFile] Initiated Logger and Exception Class. Logger and Exception file will be available in path " + outPutFolder);
            Console.WriteLine("[UnGhostFile] Initiated Logger and Exception Class. Logger and Exception file will be available in path" + outPutFolder);

            try
            {
                exceptionCommentsInfo1 = "FilePath: " + absoluteFilePath;
                AuthenticationHelper ObjAuth       = new AuthenticationHelper();
                ClientContext        clientContext = null;

                Uri fileUrl = new Uri(absoluteFilePath);

                clientContext = new ClientContext(fileUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped));
                Uri siteUrl = Web.WebUrlFromPageUrlDirect(clientContext, fileUrl);
                clientContext = new ClientContext(siteUrl);

                Logger.AddMessageToTraceLogFile(Constants.Logging, "[UnGhostFile] WebUrl is " + siteUrl.ToString());
                Console.WriteLine("[UnGhostFile] WebUrl is " + siteUrl.ToString());

                ExceptionCsv.WebUrl = siteUrl.ToString();

                //SharePoint on-premises / SharePoint Online Dedicated => OP (On-Premises)
                if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.OnPremise)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][UnGhostFile] GetNetworkCredentialAuthenticatedContext for WebUrl: " + siteUrl.ToString());
                    clientContext = ObjAuth.GetNetworkCredentialAuthenticatedContext(siteUrl.ToString(), UserName, Password, Domain);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][UnGhostFile] GetNetworkCredentialAuthenticatedContext for WebUrl: " + siteUrl.ToString());
                }
                //SharePointOnline  => OL (Online)
                else if (SharePointOnline_OR_OnPremise.ToUpper() == Constants.Online)
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START][UnGhostFile] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + siteUrl.ToString());
                    clientContext = ObjAuth.GetSharePointOnlineAuthenticatedContextTenant(siteUrl.ToString(), UserName, Password);
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END][UnGhostFile] GetSharePointOnlineAuthenticatedContextTenant for WebUrl: " + siteUrl.ToString());
                }

                if (clientContext != null)
                {
                    Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(fileUrl.AbsolutePath);
                    clientContext.Load(file);
                    clientContext.ExecuteQuery();
                    directoryName = GetLibraryName(fileUrl.ToString(), siteUrl.ToString(), fileName);

                    Folder folder = clientContext.Web.GetFolderByServerRelativeUrl(directoryName);
                    clientContext.Load(folder);
                    clientContext.ExecuteQuery();

                    fileName    = file.Name;
                    newFileName = GetNextFileName(fileName);
                    string path = System.IO.Directory.GetCurrentDirectory();
                    string downloadedFilePath = path + "\\" + newFileName;

                    using (WebClient myWebClient = new WebClient())
                    {
                        myWebClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                        myWebClient.DownloadFile(absoluteFilePath, downloadedFilePath);
                    }

                    Microsoft.SharePoint.Client.File uploadedFile = FileFolderExtensions.UploadFile(folder, newFileName, downloadedFilePath, true);
                    if (uploadedFile.CheckOutType.Equals(CheckOutType.Online))
                    {
                        uploadedFile.CheckIn("File is UnGhotsed and Updated", CheckinType.MinorCheckIn);
                    }
                    clientContext.Load(uploadedFile);
                    clientContext.ExecuteQuery();

                    bool UnGhostFile_Status = false;
                    if (OperationType.ToUpper().Trim().Equals("MOVE"))
                    {
                        uploadedFile.MoveTo(directoryName + fileName, MoveOperations.Overwrite);
                        clientContext.ExecuteQuery();

                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[UnGhostFile] Created the new version of the file " + fileName + " using MOVE operation");
                        Console.WriteLine("[UnGhostFile] Created the new version of the file " + fileName + " using MOVE operation");
                        UnGhostFile_Status = true;
                    }
                    else if (OperationType.ToUpper().Trim().Equals("COPY"))
                    {
                        uploadedFile.CopyTo(directoryName + fileName, true);
                        clientContext.ExecuteQuery();

                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[UnGhostFile] Created the new version of the file " + fileName + " using COPY operation");
                        Console.WriteLine("[UnGhostFile] Created the new version of the file " + fileName + " using COPY operation");
                        UnGhostFile_Status = true;
                    }
                    else
                    {
                        Logger.AddMessageToTraceLogFile(Constants.Logging, "[UnGhostFile] The Operation input in not provided to unghost the file " + fileName + "");
                        Console.WriteLine("[UnGhostFile] The Operation input in not provided to unghost the file " + fileName + "");
                    }

                    //If Un-Ghost File Operation is Successful
                    if (UnGhostFile_Status)
                    {
                        GhostingAndUnGhostingBase objUGBase = new GhostingAndUnGhostingBase();
                        objUGBase.FileName       = fileName;
                        objUGBase.FilePath       = absoluteFilePath;
                        objUGBase.WebUrl         = siteUrl.ToString();
                        objUGBase.SiteCollection = Constants.NotApplicable;
                        objUGBase.WebApplication = Constants.NotApplicable;

                        if (objUGBase != null)
                        {
                            FileUtility.WriteCsVintoFile(outPutFolder + @"\" + Constants.UnGhosting_Output, objUGBase,
                                                         ref headerCSVColumns);
                        }

                        //Deleting the files, which is downloaded to Un-Ghost the file
                        if (System.IO.File.Exists(downloadedFilePath))
                        {
                            System.IO.File.Delete(downloadedFilePath);
                        }
                        //Deleting the files, which is downloaded to Un-Ghost the file
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[Exception] UnGhostFile. Exception Message: " + ex.Message);
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "UnGhost", ex.Message, ex.ToString(), "UnGhostFile", ex.GetType().ToString(), exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Exception] UnGhostFile. Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[END] ::: UnGhostFile");
            Console.WriteLine("[END] ::: UnGhostFile");

            Logger.AddMessageToTraceLogFile(Constants.Logging, "############## UnGhostFile - Trasnformation Utility Execution Completed for Web ##############");
            Console.WriteLine("############## UnGhostFile - Trasnformation Utility Execution Completed for Web ##############");
        }
Exemplo n.º 18
0
        public void Upload()
        {
            try
            {
                using (context = new MSC.ClientContext(sharePointSite))
                {
                    SecureString s = new SecureString();
                    //s.
                    MSC.SharePointOnlineCredentials cred = new MSC.SharePointOnlineCredentials(ConfigurationManager.AppSettings["UsrName"], getPassword(ConfigurationManager.AppSettings["PassWord"]));
                    context.Credentials = cred;
                    var list = context.Web.Lists.GetByTitle(documentLibraryName);
                    context.Load(list);

                    var root = list.RootFolder;
                    context.Load(root);
                    context.ExecuteQuery();

                    // ADDITION
                    string SourceDocPath = ConfigurationManager.AppSettings["SourceDocsPath"];

                    DirectoryInfo         dInfo       = new DirectoryInfo(SourceDocPath);
                    FileInfo[]            ListofFiles = dInfo.GetFiles();
                    List <linkIdentifier> listofLinks = new List <linkIdentifier>();
                    XmlDocument           doc         = new XmlDocument();
                    doc.Load("Links.xml");
                    XmlNodeList listXml = doc.GetElementsByTagName("link");
                    foreach (XmlNode n1 in listXml)
                    {
                        linkIdentifier id = new linkIdentifier();
                        id.rowIndex  = Convert.ToInt32(n1["rowIndex"].InnerText);
                        id.colIndex  = Convert.ToInt32(n1["colIndex"].InnerText);
                        id.SheetName = n1["SheetName"].InnerText;
                        listofLinks.Add(id);
                    }

                    foreach (FileInfo fileInstance in ListofFiles)
                    {
                        bool   IsgoodLink = false;
                        string path       = fileInstance.FullName;

                        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                        Workbook wb = excel.Workbooks.Open(path);

                        //***********************LINK CHECK*****************************************
                        //Read the first cell
                        foreach (linkIdentifier identifier in listofLinks)
                        {
                            Worksheet excelSheet = wb.Sheets[identifier.SheetName];
                            string    test       = excelSheet.Cells[identifier.rowIndex, identifier.colIndex].Formula;

                            test = test.Split(',')[0].TrimEnd("\"".ToCharArray());
                            String[] pathList = test.Split('/');

                            try
                            {
                                if (test.Contains(".aspx"))
                                {
                                    //LinkCheck(test);
                                    IsgoodLink = CheckLink(pathList, cred);
                                }
                                else
                                {
                                    IsgoodLink = CheckLink(pathList, cred);
                                }
                            }
                            catch (MSC.ServerException e)
                            {
                                if (e.ServerErrorTypeName == "System.IO.FileNotFoundException")
                                {
                                    IsgoodLink = false;
                                }
                                wb.Close();
                                IsgoodLink = false;
                            }
                            if (IsgoodLink == false)
                            {
                                Console.WriteLine("File {0} is having deadlinks.", fileInstance.Name);
                                wb.Close();
                                return;
                            }
                        }
                        wb.Close();
                        //***********************LINK CHECK*****************************************


                        string tempdir = fileInstance.Name;
                        tempdir = tempdir.Substring("2019.craft ".Length);
                        tempdir = tempdir.Trim(' ');
                        tempdir = tempdir.Remove((tempdir.Length - ".xlsm".Length));
                        String ParentDirectoryName = tempdir.Split('-')[0];
                        ParentDirectoryName = ParentDirectoryName.Trim();
                        string ChildDirectoryName = tempdir.Split('-')[1];
                        ChildDirectoryName = ChildDirectoryName.Trim();
                        try
                        {
                            MSC.ListItemCreationInformation information = new MSC.ListItemCreationInformation();
                            string targetFolder = ConfigurationManager.AppSettings["RootFolder"];
                            if (ConfigurationManager.AppSettings["Testing"] == "1")
                            {
                                targetFolder = ConfigurationManager.AppSettings["RootFolderTest"];
                            }
                            ;
                            information.FolderUrl = list.RootFolder.ServerRelativeUrl + targetFolder + ParentDirectoryName;
                            MSC.Folder parentFolder = list.RootFolder.Folders.Add(information.FolderUrl);
                            context.Load(parentFolder);
                            context.ExecuteQuery();
                            information.FolderUrl = information.FolderUrl + "/" + ChildDirectoryName;

                            MSC.Folder childDirectory = list.RootFolder.Folders.Add(information.FolderUrl);
                            context.Load(childDirectory);
                            context.ExecuteQuery();


                            if (IsgoodLink)
                            {
                                string     filePath       = fileInstance.FullName;
                                FileStream documentStream = System.IO.File.OpenRead(filePath);
                                byte[]     info           = new byte[documentStream.Length];
                                documentStream.Read(info, 0, (int)documentStream.Length);
                                string fileURL = information.FolderUrl + "/" + fileInstance.Name;

                                MSC.FileCreationInformation fileCreationInformation = new MSC.FileCreationInformation();
                                fileCreationInformation.Overwrite = true;
                                fileCreationInformation.Content   = info;
                                fileCreationInformation.Url       = fileURL;
                                try
                                {
                                    Microsoft.SharePoint.Client.File f = context.Web.GetFileByServerRelativeUrl(fileURL);
                                    context.Load(f);
                                    context.ExecuteQuery();
                                    f.CheckOut();
                                }
                                catch (Microsoft.SharePoint.Client.ServerException ex)
                                {
                                    if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                                    {
                                        Console.WriteLine("File is not found for Checkout");
                                    }
                                }
                                Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(fileCreationInformation);


                                uploadFile.CheckIn("Improvement Plan", MSC.CheckinType.MajorCheckIn);

                                context.Load(uploadFile, w => w.MajorVersion, w => w.MinorVersion);
                                context.ExecuteQuery();
                                Console.WriteLine("Document {0} is uploaded and checked in into SharePoint", fileURL);
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                new EventLog().WriteEntry(ex.Message, EventLogEntryType.Error);
                return;
            }
        }
Exemplo n.º 19
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.º 20
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.º 21
0
        /// <summary>
        /// Uploads the document to matter library.
        /// </summary>
        /// <param name="requestObject">Request Object containing SharePoint App Token</param>
        /// <param name="sourceUrl">URL of the source document</param>
        /// <param name="documentStream">Content stream of the document</param>
        /// <param name="versionInfo">The version information.</param>
        /// <param name="comments">The comments.</param>
        /// <param name="retainCheckOut">retain check out option</param>
        /// <returns>Content Type List for the Request Object containing SharePoint App Token</returns>
        internal static string UploadtoMatter(RequestObject requestObject, string sourceUrl, Stream documentStream, int versionInfo, string comments, bool retainCheckOut)
        {
            string status = ConstantStrings.FALSE;
            string result = ConstantStrings.FALSE;

            try
            {
                if (null != requestObject)
                {
                    ClientContext clientContext;
                    if (!string.IsNullOrWhiteSpace(sourceUrl) && null != documentStream)
                    {
                        string[] sourceUrlParts = sourceUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture));
                        if (2 == sourceUrlParts.Length)
                        {
                            using (clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(sourceUrlParts[0]), requestObject.RefreshToken))
                            {
                                Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(sourceUrlParts[1]);
                                string documentLibraryName            = BriefcaseHelperFunction.getLibraryName(clientContext, file);
                                string contentType = string.Empty;
                                contentType = BriefcaseContentTypeHelperFunctions.ContentTypeByName(requestObject, clientContext, file.Name, sourceUrl, 1, contentType, documentLibraryName);
                                string listContentType = BriefcaseContentTypeHelperFunctions.GetContentTypeList(requestObject, clientContext, sourceUrl, contentType, 1, documentLibraryName);
                                status = BriefcaseContentTypeHelperFunctions.GetContentTypeList(requestObject, clientContext, sourceUrl, contentType, 2, documentLibraryName);
                                FileSaveBinaryInformation fileSaveBinaryInformation = new FileSaveBinaryInformation();
                                fileSaveBinaryInformation.ContentStream = documentStream;
                                file.SaveBinary(fileSaveBinaryInformation);
                                // Check if file is already checked out
                                if (file.CheckOutType == CheckOutType.None)
                                {
                                    file.CheckOut();
                                }
                                // Check the type of Check in to be performed
                                switch (versionInfo)
                                {
                                case 0:
                                    file.CheckIn(comments, CheckinType.MinorCheckIn);
                                    break;

                                case 1:
                                    file.CheckIn(comments, CheckinType.MajorCheckIn);
                                    break;

                                case 2:
                                    file.CheckIn(comments, CheckinType.OverwriteCheckIn);
                                    break;
                                }
                                // Load the Stream data for the file
                                clientContext.ExecuteQuery();
                                status = BriefcaseContentTypeHelperFunctions.GetContentTypeList(requestObject, clientContext, sourceUrl, listContentType, 2, documentLibraryName);
                                // Check whether we need to retain checkout
                                if (retainCheckOut)
                                {
                                    file.CheckOut();
                                    clientContext.ExecuteQuery();
                                }
                                status = string.Concat(ConstantStrings.TRUE, ConstantStrings.Comma, ConstantStrings.Space, file.ServerRelativeUrl);
                            }
                        }
                        result = status;
                    }
                    else
                    {
                        status = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, TextConstants.MissingParametersMessage);
                        result = status;
                    }
                }
            }
            catch (Exception exception)
            {
                status = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, ServiceUtility.RemoveEscapeCharacter(exception.Message));
                result = status;
            }
            return(result);
        }
Exemplo n.º 22
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_Files);

            var context = web.Context as ClientContext;

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

            foreach (var file in template.Files)
            {
                var folderName = file.Folder.ToParsedString();

                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)
                    {
                        checkedOut = CheckOutIfNeeded(web, targetFile);

                        using (var stream = template.Connector.GetFileStream(file.Src))
                        {
                            targetFile = folder.UploadFile(template.Connector.GetFilenamePart(file.Src), stream, file.Overwrite);
                        }
                    }
                    else
                    {
                        checkedOut = CheckOutIfNeeded(web, targetFile);
                    }
                }
                else
                {
                    using (var stream = template.Connector.GetFileStream(file.Src))
                    {
                        targetFile = folder.UploadFile(template.Connector.GetFilenamePart(file.Src), stream, file.Overwrite);
                    }

                    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 => property.Value.ToParsedString());
                        targetFile.SetFileProperties(transformedProperties, false); // if needed, the file is already checked out
                    }

                    if (file.WebParts != null && file.WebParts.Any())
                    {
                        if (!targetFile.IsPropertyAvailable("ServerRelativeUrl"))
                        {
                            web.Context.Load(targetFile, f => f.ServerRelativeUrl);
                            web.Context.ExecuteQuery();
                        }
                        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)
                            {
                                var wpEntity = new WebPartEntity();
                                wpEntity.WebPartTitle = webpart.Title;
                                wpEntity.WebPartXml   = webpart.Contents.ToParsedString().Trim(new[] { '\n', ' ' });
                                wpEntity.WebPartZone  = webpart.Zone;
                                wpEntity.WebPartIndex = (int)webpart.Order;

                                web.AddWebPartToWebPartPage(targetFile.ServerRelativeUrl, wpEntity);
                            }
                        }
                    }

                    if (checkedOut)
                    {
                        targetFile.CheckIn("", CheckinType.MajorCheckIn);
                        web.Context.ExecuteQueryRetry();
                    }
                }
            }
        }