Monday, December 21, 2015

Upload content type template throgh CSOM

A few years ago I bloged, read it there, on how through server site code could upload new content types templates. This snippet of code do it through CSOM.
1 string targetUrl = ""; 2 string username = ""; 3 string password = ""; 4 string contentTypeId = "0x01010043A8F0AB23DEB745AF7BF9D49A69F638"; 5 string templatePath = ""; 6 7 using (ClientContext clientContext = new ClientContext(targetUrl)) 8 { 9 SecureString pwd = new SecureString(); 10 foreach (char c in password.ToCharArray()) pwd.AppendChar(c); 11 12 //clientContext.Credentials = new NetworkCredential(username, pwd); 13 clientContext.Credentials = new SharePointOnlineCredentials(username, pwd); 14 clientContext.RequestTimeout = Timeout.Infinite; 15 16 FileInfo file = new FileInfo(templatePath); 17 18 ContentType contentType = clientContext.Web.ContentTypes.GetById(contentTypeId); 19 Web web = clientContext.Web; 20 21 clientContext.Load(contentType, c => c.Name); 22 clientContext.Load(web, w => w.ServerRelativeUrl); 23 clientContext.ExecuteQuery(); 24 25 string resourcePath = string.Format("{0}_cts/{1}", web.ServerRelativeUrl, contentType.Name); 26 27 using (FileStream stream = file.OpenRead()) 28 { 29 30 FileCreationInformation templateFile = new FileCreationInformation() 31 { 32 ContentStream = stream, 33 Url = file.Name, 34 Overwrite = true 35 }; 36 37 Folder folder = web.GetFolderByServerRelativeUrl(resourcePath); 38 folder.Files.Add(templateFile); 39 contentType.DocumentTemplate = file.Name; 40 contentType.Update(false); 41 clientContext.ExecuteQuery(); 42 } 43 }