Server Version, Site, Web in ClientContext of SharePoint throws error - c#

I'm new to sharepoint. Im trying to upload a file and add metadata to the file. Below is my code. I can see some internal exceptions are their while declaring ClientContext
Exception: clientContext.ServerVersion threw an exception of type PropertyOrFieldNotInitializedException
The same is happening for Site, Web.
using (ClientContext clientContext = new ClientContext(SPURL))
{
//ClientContext clientContext = new ClientContext(SPURL);
clientContext.Credentials = new System.Net.NetworkCredential(userName, password, domain);
Web web = clientContext.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(PPTPath);
newFile.Url = "F:\\log.txt";
List docs = web.Lists.GetByTitle("Test");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
clientContext.ExecuteQuery();
using (FileStream fileStream =
new FileStream(PPTPath, FileMode.Open))
ClientOM.File.SaveBinaryDirect(clientContext,
DocumentRepository + PPTfilename, fileStream, true);
}

the CSOM libraries expect you to tell them what you want to query from the SharePoint environment upon calling ExecuteQuery().
Therefor you need to tell the clientcontext object what you want to load.
For instance:
Web web = clientContext.Web; should be followed by clientContext.Load(web);
This is a simple example. For uploading files your best bet is making use of the File.SaveBinaryDirect function. An example on how to use it can be found elsewhere on stackoverflow.

Related

How to fix 'operation has timed out' while connecting to sharepoint on Office 365 using C#

"Operation has timed out" error while connecting to Office 365 Sharepoint from asp.net web application
I have tried finding answers and implementing solutions like below:
How to connect to SharePoint on Office 365 with CSOM from C#?
Also some blogs suggested making an asynchronous query, which does not throw error but also does not give any results.
Also tried setting timeout property without any help.
Below is my code:
SharePointOnlineCredentials networkCredential = new
SharePointOnlineCredentials(SharePointUser, SharePointPassword);
Context = new ClientContext(SharePointURL);
Context.Credentials = networkCredential;
Web = Context.Web;
Context.Load(Web);
Context.ExecuteQuery();`
Also, strangely I am able to connect and get data using Console application, but I need to get this working in web application.
After a lot of search I realized that we need proxy to connect to Sharepoint Online and implemented following code to achieve
clientContext.ExecutingWebRequest += (s, e) =>
{
e.WebRequestExecutor.WebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
};
Add clientContext.RequestTimeout = -1 in the code, the code below for your reference.
string siteUrl = "https://tenant.sharepoint.com/sites/lz";
string userName = "lz#tenant.onmicrosoft.com";
string password = "xxx";
var securePassword = new SecureString();
foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
using (ClientContext clientContext = new ClientContext(siteUrl))
{
clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);
clientContext.RequestTimeout = -1;
var web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
}

upload image to sharepoint generic list using csom C#

How I can upload image to a SharePoint List "custom List" not library using CSOM C#?
Here is what I have tried so far:
FieldUrlValue url = new FieldUrlValue();
url.Url = FileUpload.PostedFile.FileName;
url.Description = "Your description here";
newItem["Image"] = url;
You can use this code to upload documents into SharePoint via the CSOM:
using (ClientContext ctx = new ClientContext("http://urlToYourSiteCollection")) {
FileCreationInformation fci = new FileCreationInformation();
fci.Content = System.IO.File.ReadAllBytes("PathToSourceDocument");
fci.Url = System.IO.Path.GetFileName("PathToSourceDocument");
Web web = ctx.Web;
List targetDocLib = ctx.Web.Lists.GetByTitle("yourTargetLibrary");
ctx.ExecuteQuery();
Microsoft.SharePoint.Client.File newFile = targetDocLib.RootFolder.Files.Add(fci);
ctx.Load(newFile);
ctx.ExecuteQuery();
}
If you want to set properties of the new item, you can do it this way:
ListItem lItem = newFile.ListItemAllFields;
lItem.File.CheckOut(); //CHECK OUT VERY IMPORTANT TO CHANGE PROPS
ctx.ExecuteQuery();
lItem["yourProperty"] = "somewhat";
lItem.Update();
lItem.File.CheckIn("Z", CheckinType.OverwriteCheckIn);
ctx.ExecuteQuery();
If you need to upload files to a SharePoint site please visit the following link where it is explained how to read and upload files using CSOM
How to download/upload files from/to SharePoint 2013 using CSOM?

Uploading a file to sharepoint without a password

i am trying to upload a file to sharepoint with c# using the microsoft sharepoint client
i have no issues when i create my context and give it my username and password like this
using (ClientContext ctx = new ClientContext(spSite))
{
if (!System.IO.File.Exists(fileLocation))
throw new FileNotFoundException("File not found.", fileLocation);
var credentials = new NetworkCredential("username", "password");
ctx.Credentials = credentials;
Web web = ctx.Web;
ctx.Load(user);
ctx.ExecuteQuery();
String fileName = System.IO.Path.GetFileName(fileLocation);
FileStream fileStream = System.IO.File.OpenRead(fileLocation);
ctx.Load(web.Folders);
ctx.ExecuteQuery();
Folder spFolder = web.Folders.FirstOrDefault(x => x.Name.Equals(spListCleanName));
FileCreationInformation fci = new FileCreationInformation();
fci.Url = spSite + spLibraryName + file;
byte[] bytes = System.IO.File.ReadAllBytes(fileLocation);
fci.Content = bytes;
Microsoft.SharePoint.Client.File spFile = spFolder.Files.Add(fci);
spFile.ListItemAllFields.Update();
ctx.ExecuteQuery();
}
but my issue comes in the network credentials part. is there a way to use the current users credentials (through iis or .net or anything) so that i don't have to ask for their password? since that isn't something we want to save in plain text anywhere.
thank you in advance
Use the CredentialCache.DefaultCredentials (https://msdn.microsoft.com/en-us/library/system.net.credentialcache.defaultcredentials(v=vs.110).aspx) instead of NetworkCredential object.
This will use the users security context.

How to upload a file in Sharepoint 2010 using c# console

Is there a way to automatically upload a file in Sharepoint 2010 using c#? We have no administrative control on the Sharepoint server. We just need to write a program that will upload a local file to a designated sharepoint library. The program will run on our server which in no way affiliated with the sharepoint server.
The following options could be considered for uploading the file into SharePoint via CSOM.
Prerequisites: SharePoint Foundation 2010 Client Object Model Redistributable
Using FileCollection.Add method
FileCollection.Add method adds a file to the collection based on provided file creation information
public static void UploadFile(ClientContext context, string uploadFolderUrl, string uploadFilePath)
{
var fileCreationInfo = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(uploadFilePath),
Overwrite = true,
Url = Path.GetFileName(uploadFilePath)
};
var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);
var uploadFile = targetFolder.Files.Add(fileCreationInfo);
context.Load(uploadFile);
context.ExecuteQuery();
}
Usage
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = credentials;
UploadFile(ctx,"Documents/Orders",#"c:\upload\user guide.docx");
}
where Orders is a folder in Documents library
According to Uploading files using Client Object Model in SharePoint 2010:
The above code might fail throwing a (400) Bad Request error depending
on the file size.
Using File.SaveBinaryDirect method
File.SaveBinaryDirect method - uploads the specified file to a SharePoint site without requiring an ExecuteQuery() method call.
public static void UploadFile(ClientContext context, string folderUrl, string uploadFilePath)
{
using (var fs = new FileStream(uploadFilePath, FileMode.Open))
{
var fileName = Path.GetFileName(uploadFilePath);
var fileUrl = String.Format("{0}/{1}", folderUrl, fileName);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
}
}
Usage
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = credentials;
UploadFile(ctx,"/News/Documents/Orders",#"c:\upload\user guide.docx");
}
where Orders is a folder in Documents library located on web site News.
FolderUrl format: /<web url>/<list url>/<folder url>

How do you create a page using the API for sharepoint 2010?

I have just started using Sharepoint Foundation 2010 and I'm trying to write a function from c# to add pages to a site.
I got some code working to create a new site, but I can't seem to find any documentation about adding a page to an existing site using the client object model.
This is probably a simple question but if anyone can help me out I would appreciated it.
Thanks.
Update
This is what I have so far:
private void createPage()
{
ClientContext context = new ClientContext(url);
Site siteCollection = context.Site;
Web site = context.Web;
List pages = site.Lists.GetByTitle("Pages");
FileCreationInformation fileCreateInfo = new FileCreationInformation();
fileCreateInfo.Url = "NewPage";
fileCreateInfo.Content = System.Text.Encoding.ASCII.GetBytes("Test");
context.Load(pages.RootFolder.Files.Add(fileCreateInfo));
context.ExecuteQuery();
context.Dispose();
}
But I get a server exception "List 'Pages' does not exist at site with URL"
This is what I eventually did to add my page. Essentially I just needed to find the appropriate list title. These are just the names of the Document Libraries on the site.
private void createPage()
{
ClientContext context = new ClientContext(URL);
Site siteCollection = context.Site;
Web site = context.Web;
List pages = site.Lists.GetByTitle("Site Pages");
Microsoft.SharePoint.Client.
FileCreationInformation fileCreateInfo = new FileCreationInformation();
fileCreateInfo.Url = "NewPage.aspx";
context.Load(pages.RootFolder.Files.Add(fileCreateInfo));
context.ExecuteQuery();
context.Dispose();
}
If you are talking about creating a new site page I would recommend looking at this tutorial:
http://blogs.msdn.com/b/kaevans/archive/2010/06/28/creating-a-sharepoint-site-page-with-code-behind-using-visual-studio-2010.aspx
Take a second and make sure you actually want to add this through code. As someone who recently started development with SharePoint I can tell you that there is a fairly steep learning curve when working with the Object Model. Also, tasks that are easy to do through the UI may be quite difficult using code.
Good luck!!!
This Code works for me. It Creates an Page("NewPage.aspx") With the Content Test.
private void createPage()
{
ClientContext context = new ClientContext(URL);
Site siteCollection = context.Site;
Web site = context.Web;
List pages = site.Lists.GetByTitle("Site Pages");
Microsoft.SharePoint.Client.
FileCreationInformation fileCreateInfo = new FileCreationInformation();
fileCreateInfo.Url = "NewPage.aspx";
fileCreateInfo.Content = System.Text.Encoding.ASCII.GetBytes("Test");
context.Load(pages.RootFolder.Files.Add(fileCreateInfo));
context.ExecuteQuery();
context.Dispose();
}

Categories

Resources