SharePoint 2013: Why getting 500 error while creating clientContext? - c#

I want to create a IIS webservice which has to write list items to SharePoint on Premise.
I want to use CSOM and try to create a ClientContext.
public string AddListItem()
string result = string.Empty;
string siteUrl = "https://serverUrl";
using (ClientContext context = new ClientContext(siteUrl))
{
context.Credentials = new NetworkCredential("User", "Password", "Domain");
List list = context.Web.Lists.GetByTitle("Test");
context.Load(list);
context.ExecuteQuery();
}
return result;
}
While executing, I get an error at context.ExecuteQuery();
System.Net.WebException: 'The remote server returned an error: (500) Internal Server Error.'
In the Event Log, I see following error:
WebHost failed to process a request.
Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/41028758
Exception: System.ServiceModel.ServiceActivationException: The service '/_vti_bin/client.svc' cannot be activated due to an exception during compilation. The exception message is: Operation is not valid due to the current state of the object.. ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.
at Microsoft.SharePoint.Administration.SPWebApplication.get_Context()
................................
In debugging, I also see after creating the ClientContext and before context.ExecuteQuery(); following error at some properties of ClientContext, e.g.:
ServerLibraryVersion = 'context.ServerLibraryVersion' threw an exception of type 'Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException'

Your code seems fine for on-prem SharePoint. I think You should check some settings on the farm that my be the cause of that.
Please check the services on farm server if the IIS Admin Service is on
also on SharePoint CA check the user profile service and the claims to windows token service (both should be on)
... sorry for the lang :)... usually I have access to SharePoint in PL language, but I tried to translate the most important stuff to ang.
Please also check if on IIS the app pools that You try to access are working correctly. I suppose yes, otherwise You would have a lot of other errors, but it's always better to check.

Use CSOM, what to use WCF is not clear:
ClientContextctx = newClientContext("http://gowtham.sharepoint.com");
List oList = ctx.Web.Lists.GetByTitle("Announcements");
ListItemCreationInformationitemCreateInfo = newListItemCreationInformation();
ListItemnewItem = oList.AddItem(itemCreateInfo);
newItem["Title"] = "Test Item!";
newItem["Body"] = "welcome to Gowtham Blog";
newItem.Update();
context.ExecuteQuery();

Try below code
using (ClientContext clientContext = new ClientContext(ServerURL))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
clientContext.Credentials = new SharePointOnlineCredentials(your_mail_ID, securePassword);
Web web = clientContext.Web;
var list = web.Lists.GetByTitle("your_list_name");
clientContext.Load(list.RootFolder);
clientContext.ExecuteQuery();
}

Check if the "SharePoint Web Servies Root" application pool was stopped or the "SharePoint Web Services" web application not start in IIS.
Go to IIS Application Pools, find the "SecurityTokenServiceApplicationPool" and click "Advanced Settings" from the action panel, then Scroll to "ProcessModel" section and change the Identity to your SharePoint Farm Account and do IISRESET.
And create a console application with the CSOM C# code to check if it works.

FWIW - I had exactly the same error - CSOM local mode to on-prem SP2016 with a 500 error requesting the list by title.
I had just applied a 10/2019 SharePoint update, but hadn't gone through Product Configuration Wizard and the prompts in Central Admin. Once I did that, CSOM requests worked again.

Related

SharePoint CSOM call failing to small list

We have a Console application which makes SharePoint CSOM calls to a list in a SharePoint site in an intranet.
This call works with a list with 1000+ records. However this call is failing when we deployed the Console application in a different machine in the intranet.
It cannot be MaxReceivedMessageSize or MaxParseMessageSize because it works elsewhere.
Is there a machine specific setting that needs to be taken care?
The code looks like this:
using (var clientContext = new ClientContext(SharePointSiteUrl))
{
clientContext.Credentials = AuthenticationHelper.GetNetworkCredential();
var list = clientContext.Web.Lists.GetByTitle(RequestsList);
var requestIdField = list.Fields.GetByInternalNameOrTitle("RequestID");
var query = CamlQuery.CreateAllItemsQuery();
var items = list.GetItems(query);
clientContext.Load(requestIdField);
clientContext.Load(items);
clientContext.ExecuteQuery();
foreach (var request in requests)
{
var itemCreateInfo = new ListItemCreationInformation();
var newItem = list.AddItem(itemCreateInfo);
newItem[requestIdField.InternalName] = request.RequestID;
newItem.Update();
}
clientContext.ExecuteQuery();
result = true;
}
ERROR:
AppName: Unhandled Exception: Details: Message:The request message is too big. The server does not allow messages larger than 2097152 bytes.
StackTrace: at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)
at Microsoft.SharePoint.Client.ClientRequest.ExecuteQuery()
at Microsoft.SharePoint.Client.ClientRuntimeContext.ExecuteQuery()
at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
at AppName.SharePoint.SharePointHelper.Method3(List`1 requests)
at AppName.Program.Method2()
at AppName.Program.Main(String[] args)
TargetSite:Void ProcessResponseStream(System.IO.Stream)
Source:Microsoft.SharePoint.Client.Runtime
SharePoint has its own limits for CSOM. Unfortunately, these limits cannot be configured in Central Administration and also cannot be set using CSOM for obvious reasons.
When googling for the issue, mostly a solution is given by setting the ClientRequestServiceSettings.MaxReceivedMessageSize property to the desired size.
Call the following PowerShell script from SharePoint Management Shell :
$ws = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$ws.ClientRequestServiceSettings.MaxReceivedMessageSize = 209715200
$ws.Update()
This will set the limit to 200 MB.
However, in SharePoint 2013 Microsoft apparently added another configuration setting to also limit the amount of data which the server shall process from a CSOM request (Why anyone would configure this one differently is beyond me...). After reading a very, very long SharePoint Log file and crawling through some disassembled SharePoint server code, I found that this parameter can be set via the property ClientRequestServiceSettings.MaxParseMessageSize.
We are now using the following script with SharePoint 2013 and it works great:
$ws = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$ws.ClientRequestServiceSettings.MaxReceivedMessageSize = 209715200
$ws.ClientRequestServiceSettings.MaxParseMessageSize = 209715200
$ws.Update()

LDAP search fails on server, not in Visual Studio

I'm creating a service to search for users in LDAP. This should be fairly straightforward and probably done a thousand times, but I cannot seem to break through properly. I thought I had it, but then I deployed this to IIS and it all fell apart.
The following is setup as environment variables:
ldapController
ldapPort
adminUsername 🡒 Definitely a different user than the error reports
adminPassword
baseDn
And read in through my Startup.Configure method.
EDIT I know they are available to IIS, because I returned them in a REST endpoint.
This is my code:
// Connect to LDAP
LdapConnection conn = new LdapConnection();
conn.Connect(ldapController, ldapPort);
conn.Bind(adminUsername, adminPassword);
// Run search
LdapSearchResults lsc = conn.Search(
baseDn,
LdapConnection.SCOPE_SUB,
lFilter,
new string[] { /* lots of attributes to fetch */ },
false
);
// List out entries
var entries = new List<UserDto>();
while (lsc.hasMore() && entries.Count < 10) {
LdapEntry ent = lsc.next(); // <--- THIS FAILS!
// ...
}
return entries;
As I said, when debugging this in visual studio, it all works fine. When deployed to IIS, the error is;
Login failed for user 'DOMAIN\IIS_SERVER$'
Why? The user specified in adminUsername should be the user used to login (through conn.Bind(adminUsername, adminPassword);), right? So why does it explode stating that the IIS user is the one doing the login?
EDIT I'm using Novell.Directory.Ldap.NETStandard
EDIT The 'user' specified in the error above, is actually NOT a user at all. It is the AD registered name of the computer running IIS... If that makes any difference at all.
UPDATE After consulting with colleagues, I set up a new application pool on IIS, and tried to run the application as a specified user instead of the default passthrough. Exactly the same error message regardless of which user I set.
Try going via Network credentials that allows you to specify domain:
var networkCredential = new NetworkCredential(userName, password, domain);
conn.Bind(networkCredential);
If that does not work, specify auth type basic (not sure that the default is) before the call to bind.
conn.AuthType = AuthType.Basic;

SSRS Report Portal Management

I am working on an C# utility that would help clients publishing SSRS reports on their sites. Here my code:
public void createFolder()
{
ReportingService2010 rs = new ReportingService2010();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
// Create a custom property for the folder.
Property newProp = new Property();
newProp.Name = "Department";
newProp.Value = "Finance";
Property[] props = new Property[1];
props[0] = newProp;
string folderName = "Budget";
try
{
rs.CreateFolder(folderName, "/", props);
Console.WriteLine("Folder created: {0}", folderName);
}
catch (SoapException e)
{
Console.WriteLine(e.Detail.InnerXml);
}
}
I am getting the following error:
ErrorCode xmlns="http://www.microsoft.com/sql/reportingservices">rsAccessDenied</ErrorCode><HttpStatus xmlns="http://www.microsoft.com/sql/reportingservices">400</HttpStatus><Message xmlns="http://www.microsoft.com/sql/reportingservices">The permissions granted to user 'NT AUTHORITY\NETWORK SERVICE' are insufficient for performing this operation.</Message><HelpLink xmlns="http://www.microsoft.com/sql/reportingservices">https://go.microsoft.com/fwlink/?LinkId=20476&EvtSrc=Microsoft.ReportingServices.Diagnostics.Utilities.ErrorStrings&EvtID=rsAccessDenied&ProdName=Microsoft%20SQL%20Server%20Reporting%20Services&ProdVer=13.0.1601.5</HelpLink><ProductName xmlns="http://www.microsoft.com/sql/reportingservices">Microsoft SQL Server Reporting Services</ProductName><ProductVersion xmlns="http://www.microsoft.com/sql/reportingservices">13.0.1601.5</ProductVersion><ProductLocaleId xmlns="http://www.microsoft.com/sql/reportingservices">127</ProductLocaleId><OperatingSystem xmlns="http://www.microsoft.com/sql/reportingservices">OsIndependent</OperatingSystem><CountryLocaleId xmlns="http://www.microsoft.com/sql/reportingservices">1033</CountryLocaleId><MoreInformation xmlns="http://www.microsoft.com/sql/reportingservices"><Source>ReportingServicesLibrary</Source><Message msrs:ErrorCode="rsAccessDenied" msrs:HelpLink="https://go.microsoft.com/fwlink/?LinkId=20476&EvtSrc=Microsoft.ReportingServices.Diagnostics.Utilities.ErrorStrings&EvtID=rsAccessDenied&ProdName=Microsoft%20SQL%20Server%20Reporting%20Services&ProdVer=13.0.1601.5" xmlns:msrs="http://www.microsoft.com/sql/reportingservices">The permissions granted to user 'NT AUTHORITY\NETWORK SERVICE' are insufficient for performing this operation.</Message></MoreInformation><Warnings xmlns="http://www.microsoft.com/sql/reportingservices" />
Any idea?
Please note that a point of this exercise is not just get it work but knowing that it is going to run on a client side ideally without any tweaking on their part.
Thanks for help.
Your question is a little unclear. It sounds like you're not sure why you're getting a permissions error. The answer is that you need to create a new role. I assume (after your comment) that your question is how you can do that using C#.
You can use the CreateRole() method, which will only work with SSRS Native Mode. If SSRS is installed in SharePoint Integrated mode, there is no supported method other than using the UI.
This method throws an OperationNotSupportedSharePointMode exception
when invoked in SharePoint mode

Acumatica Web Services API Login

I am attempting to perform some basic integration using Acumatica's web services. Unfortunatly, I'm having problems logging in. According to their documentation, this process should look something like:
apitest.Screen context = new apitest.Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.AllowAutoRedirect = true;
context.EnableDecompression = true;
context.Timeout = 1000000;
context.Url = "http://localhost/WebAPIVirtual/Soap/APITEST.asmx";
LoginResult result = context.Login("admin", "E618");
Simple enough. However, after creating and importing a WSDL file from Acumatica into Visual Studio, I found I don't have a Screen object. I do, however have a ScreenSoapClient object, which has a similar Login() method.
ScreenSoapClient context = new Acumatica.ScreenSoapClient("ScreenSoap");
LoginResult result = context.Login("username", "password");
That part works. In fact, the LoginResult give me a session ID. However, if I try to make any calls to the service, such as:
CR401000Content cr401000 = context.CR401000GetSchema();
I get an error: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> PX.Data.PXNotLoggedInException: Error #185: You are not currently logged in.
While the version of Acumatica we're using does appear to be slightly newer, I'm unsure why the Screen() object isn't available. Consequently, if I try a bad username/password, Login() does fail (as it should). From what I can the tell, the ScreenSoapClient class is using service model details from web.config, so it's getting the endpoint address and other details there.
Is there something I'm missing or doing wrong?
As i see, you use WCF to create your service reference.
So you should enable cookies in service binding:
var binding = new BasicHttpBinding()
{
AllowCookies = true
};
var address = new EndpointAddress("http://localhost/WebAPIVirtual/Soap/APITEST.asmx");
var c = new ServiceReference1.ScreenSoapClient(binding, address);
Or, you can use old asmx web service reference (http://msdn.microsoft.com/en-us/library/bb628649.aspx).
Then everything will be same as in Acumatica`s documentation.
As noted in a comment above, I was able to make contact with a representative from Acumatica. He had me remove then recreate the service references in our project and try again. That apparently did the trick and the "Error #185: You are not currently logged in" error went away.

Sharepoint connection with a username and password

i've searched during 2 days to resolve my problem but there is no way!
in fact, i'd like to connect to sharepoint using a user's account (there is no probleme when i use anonymous connexion).
i added a web reference of authentification and lists to use this code:
SPConnect.Authentication authSP = new SPConnect.Authentication();
SPLists.Lists spLists = new SPLists.Lists();
authSP.CookieContainer = new System.Net.CookieContainer();
authSP.AllowAutoRedirect = true;
SPConnect.LoginResult loginSP = authSP.Login("administrateur", "pass");
if (loginSP.ErrorCode == SPConnect.LoginErrorCode.NoError)
{
spLists.CookieContainer = authSP.CookieContainer;
//object list = spLists.GetList("presentationAccueil");
SPSite oSiteCollection = SPContext.Current.Site;
SPList listeee = oSiteCollection.AllWebs["http://vmspprod:25401"].Lists["presentationAccueil"];
}
i get this erro NotInFormsAuthenticationMode when i execute
SPConnect.LoginResult loginSP = authSP.Login("administrateur", "pass");
is there any other method to use a user's login and password?
Thank you in advance for your answers.
You need to configure your SharePoint server to use Forms Authentication (that's what the exception is telling you).
You didn't say which version of SharePoint you are targeting (WSS 3.0, SP 2007, SP 2010). Here is a link to an MSDN page that shows you how to configure your server to use Forms Authentication: http://msdn.microsoft.com/en-us/library/bb975136(v=office.12).aspx
If you cannot modify the server, then you will need to change your code to use whatever authentication mechanism the server employs.
I hope this helps.

Categories