Getting error while connecting to Office 365 sharepoint - sharepoint

I am trying to connect to office 365 sharepoint using clientid and clientsecret in OfficeDevPnP.Core.AuthenticationManager() method but i am getting below error
I am using below code to connect to sharepoint:
var authManager = new OfficeDevPnP.Core.AuthenticationManager();
string appId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string appSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string siteURL = "https://xxxxxxxx.sharepoint.com/";
string siteName = "";
using (ClientContext context = authManager.GetAppOnlyAuthenticatedContext(siteURL, appId, appSecret))
{
Site objSite = context.Site;
context.Load(objSite);
context.ExecuteQuery();
siteName = objSite.Url.ToString();
Console.WriteLine("Site Url:" + objSite.Url);
}
What am I doing wrong? Currently my site is localhost so have setup below details

Your company must have a Proxy, it will be necessary to define the following information in your Web Config:
<system.net>
<defaultProxy enabled="true">
<proxy proxyaddress="http://urlyourproxy:port" bypassonlocal="True"/>
</defaultProxy>
</system.net>
Right after inserting this works fine!

Related

How to use the PNP Framework to authenticate client credentials in SharePoint Online

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (ClientContext context = new ClientContext("https://abc.sharepoint.com/sites/app"))
{
SecureString passWord = new SecureString();
foreach (char c in "password".ToCharArray()) passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("Admin#sample.onmicrosoft.com", passWord);
context.Load(context.Web, x => x.Url);
context.ExecuteQuery();
}
This is my old code block and this is working Azure "security default" disabled environment.
When I run this in an environment with Azure security default enabled, an error appears. I need to use a code block connected to the PNP framework to execute this code. Any recommendations?
You can use GetACSAppOnlyContext to access SharePoint online. Please refer to following code
string siteUrl = "https://xxx.sharepoint.com/sites/demo";
string clientId = "*******-****-4818-a928-f14658a9fe90";
string clientSecret = "*****************";
using (var clientContext = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, clientId, clientSecret))
{
clientContext.Load(clientContext.Web, p => p.Title);
clientContext.ExecuteQuery();
Console.WriteLine(clientContext.Web.Title);
};

error while trying to run the provider hosted app to SharePoint online

Recently I was trying to create a provider hosted app to share point online.
I have configured Azure web apps and created the app and published it to share point online. I can now see the app in the SharePoint online appcataloge. but when I tried to run the application it is throwing the below error.
System.IO.FileNotFoundException: msoidcliL.dll at Microsoft.SharePoint.Client.Idcrl.IdcrlNativeMethodsSelector..ctor(String dllPath) at Microsoft.SharePoint.Client.Idcrl.ManagedIdcrl.get_IdcrlNativeMethods() at Microsoft.SharePoint.Client.Idcrl.ManagedIdcrl.EnsureInited() at Microsoft.SharePoint.Client.Idcrl.ManagedIdcrl.LogonIdentity(String username, SecureString password) at Microsoft.SharePoint.Client.Idcrl.SharePointOnlineAuthenticationProvider.Logon(String username, SecureString password) at Microsoft.SharePoint.Client.SharePointOnlineCredentials..ctor(String username, SecureString password) at SharePointApp5Web.Default.Page_Load(Object sender, EventArgs e)
Code
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
try
{
string str;
using (ClientContext ctx = new ClientContext("https://mydomain.sharepoint.com/sites/General/Community%20Portal/HR/Acknowledgements"))
{
ctx.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials("myname#domain.com", ConvertToSecureString("password"));
Web myweb = ctx.Web;
List myList = myweb.Lists.GetByTitle("Timesheet Administration Policy");
ListItemCreationInformation ItemCreationInfo = new ListItemCreationInformation();
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =
#"<Query>
<Where>
<Neq>
<FieldRef Name='ID' />
<Value Type='Counter'>946</Value>
</Neq>
</Where>
</Query>";
Microsoft.SharePoint.Client.ListItemCollection listItems = myList.GetItems(camlQuery);
ctx.Load(listItems);
ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem listItem in listItems.ToList())
{
try
{
Response.Write(listItem["Email_x0020_Address"].ToString().Trim());
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
Looks like an issue with the CSOM dll. Please install the latest CSOM online version and then deploy/publish your code.
Go to your project references in Visual studio, right to open Manage Nuget packages as below:
Search for CSOM and install the Microsoft.SharePointOnline.CSOM
Or, alternately, you can download it from the Microsoft download link mentioned below and add the references manually:
SharePoint Online Client Components SDK
Also, ensure that .NET framework is targeted to v4.5 and the platform target is set to Any CPU. Also, ensure that the v16 assemblies are referenced.
Also, add the following code below the ctx.Credentials line:
ctx.AuthenticationMode = ClientAuthenticationMode.Default;

How do I pass user credentials from the console to SharePoint Online?

I am trying to connect SharePoint 2013 Online website using a Context Token from a console executable. However, it is giving me error The remote server returned an error: (403) Forbidden.
Here is the code snippet:
string spurl = ConfigurationManager.AppSettings["Sharepoint_URL"].ToString();
using (ClientContext context = new ClientContext(spurl))
{
context.Credentials = new NetworkCredential("username", "password", "domain");
context.ExecuteQuery();
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine(context.Web.Title);
}
Console.ReadKey();
How can I make a connection with SharePoint Online? Does it only support claims-based authentication?
I think the method with which you are trying to authenticate is outdated. The SharePoint 2013 Client Object Model now has a class called SharePointOnlineCredentials which abstracts away all the tedious cookie container stuff. E.g.:
using (ClientContext clientContext = new ClientContext("https://yoursite.sharepoint.com/"))
{
SecureString passWord = new SecureString();
clientContext.Credentials = new SharePointOnlineCredentials("loginname#yoursite.onmicrosoft.com", passWord);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
Console.WriteLine(web.Title);
Console.ReadLine();
}
Please refer to this link for more information: https://sharepoint.stackexchange.com/questions/83985/access-the-sharepoint-online-webservice-from-a-console-application

Sharepoint 2013 Client Object Model file larger than 2 Mb exception

I am new to Sharepoint and Client Object model. I am stuck with a problem and not been able to fix the issue. I want to upload files more than 10 MB using Client Object Model in Sharepoint 2013. I get the following exception
The request message is too large. The server does not allow messages
that are larger than 2097152 bytes.
I have tried everything. Here is the list of things that i did
1- Changed the settings in web.config file of my local web application
<system.web>
<httpRuntime useFullyQualifiedRedirectUrl="true" maxRequestLength="2147483647" requestLengthDiskThreshold="2147483647" executionTimeout="18000"/> </system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483647" />
</requestFiltering>
</security>
</system.webServer>
2- In the powershell on my server ran the following commands and restarted the application in the IIS. Even restarted the whole IIS.
$ws = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$ws.ClientRequestServiceSettings.MaxReceivedMessageSize = 2147483647
$ws.Update()
Here is my code :
private void UploadDataToSharepointTest(List<UploadData> pDataObjList)
{
string lServerUrl = #"http://xxxxxxx:2000/";
string lFolderName = DateTime.Now.ToString(#"yyyyMMddHHmmss");
ClientContext context = new ClientContext(lServerUrl);
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new System.Net.NetworkCredential("user", "password", "domain");
Web web = context.Web;
List docs = web.Lists.GetByTitle("ABC");
Folder lNewFolder = web.Folders.Add(lServerUrl + "ABC/" + lFolderName + "/");
docs.Update();
int fileIndex = 1;
foreach (var item in pDataObjList)
{
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(item.CompleteFilePath);
newFile.Url = fileIndex.ToString() + "-" + item.fileName;
fileIndex++;
Microsoft.SharePoint.Client.File uploadFile = lNewFolder.Files.Add(newFile);
context.Load(uploadFile);
context.ExecuteQuery();
Dictionary<string, string> metadata = new Dictionary<string, string>();
metadata.Add("Comments", item.comments);
metadata.Add("Plan_x0020_Size", item.planSize);
metadata.Add("Density", item.density);
metadata.Add("First_x0020_Name", txtFirstName.Text.Trim());
metadata.Add("Last_x0020_Name", txtLastName.Text.Trim());
metadata.Add("Company", txtCompany.Text.Trim());
metadata.Add("Contact", txtContact.Text.Trim());
metadata.Add("Additional_x0020_Comments", txtAdditionalComments.Text.Trim());
Microsoft.SharePoint.Client.ListItem items = uploadFile.ListItemAllFields;
context.Load(items);
context.ExecuteQuery();
foreach (KeyValuePair<string, string> metadataitem in metadata)
{
items[metadataitem.Key.ToString()] = metadataitem.Value.ToString();
}
items.Update();
context.ExecuteQuery();
}
}
Note: I am able to upload small files.
There are file size limit if you use the build-in upload function.
To upload a large file, please upload it with filestream.
Take a look at the article below:
http://blogs.msdn.com/b/sridhara/archive/2010/03/12/uploading-files-using-client-object-model-in-sharepoint-2010.aspx
SharePoint allows you to configure this via Central Admin, I'd stick with that to make sure it makes all the appropriate changes for you. You need to have farm level permissions. Also in SharePoint 2013 you can have different file max limits for different file types so make sure your file type wasn't changed by anyone. Different Max based on File Types
Accessing SharePoint Webapp properties via central Admin

Sharepoint 2010 ClientContext with kerberos & a 401 unauthorised

I can get a remote console app talking to a NTLM Sharepoint site with ClientContext and I can it talking to a remote Kerberos Sharepoint box with HttpWebRequest.GetResponse();
But I cannot get it talking to the Kerberos Sharepoint box with CientContext. Any additional pointers would be gratefully recieved.
string siteURL = "http://my.remote.sharepoint";
ClientContext ctx = new ClientContext(siteURL);
CredentialCache cc = new CredentialCache();
cc.Add(new Uri(siteURL), "Kerberos", CredentialCache.DefaultNetworkCredentials);
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ctx.Credentials =cc;
/////////////////////////////////////////////////////////////////////////////////
// This code confirms that I can access "my.remote.sharepoint" with KRB
// HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(siteURL);
// myHttpWebRequest.Credentials = cc;
// myHttpWebRequest.UseDefaultCredentials = true;
// HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
/////////////////////////////////////////////////////////////////////////////////
Web remoteWeb = ctx.Web;
ctx.Load(remoteWeb);
ctx.ExecuteQuery();
//401 unauthorised returned from here
Wireshark suggests that it returns the initial 401 & then gives up! Any ideas
Please check if a SPN is registered for that host and a reverse DNS entry exists.

Resources