Using the HTTPClient and Sharepoint 2013 REST APIs to get Documents - asp.net

I am working in a .NET web application.I am trying to connect to Sharepoint Online Premise to get documents in the "Document Library" by using the HTTPClient and the Sharepoint 2013 REST API .
I tested the following rest service in the browser for this ,
https://site_url/_vti_bin/ListData.svc/Documents
which gives the MetaData of all the documents present in the Document Library of the particular web site.
Now when i am trying to do the same programmatically by adding a reference to the service URL and by using the following code,
TestSiteDataContext ctx = new TestSiteDataContext(new Uri("https://site url/_vti_bin/ListData.svc"));
ctx.Credentials = new NetworkCredential("test#test.onmicrosoft.com", "test");
var data = ctx.Documents.ToList();
I am getting the following exception :
"The request was aborted: Could not create SSL/TLS secure channel."
The stack trace is as follows :
at System.Net.HttpWebRequest.GetResponse()
at System.Data.Services.Client.QueryResult.Execute()
at System.Data.Services.Client.DataServiceRequest.Execute[TElement](DataServiceContext context, QueryComponents queryComponents)
at System.Data.Services.Client.DataServiceQuery`1.Execute()
at System.Data.Services.Client.DataServiceQuery`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at SPO_AccessAWebService.Program.Main(String[] args) in Location\Program.cs:line 35
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
I have gone through various articles/blogs to find a solution for this.Bust couldn't find any.
I could see various samples tha shows authenticating by means of ,
ctx.Credentials = CredentialCache.DefaultNetworkCredentials;
This also is throwing the same error.
Is there is any other way to authenticate the SharePoint 2013 REST API?
Can someone provide me some insights to resolve this issue?

Based on the exception message you are reporting, it appears that the SSL cert is not valid for the site. I often see this message in development or test environments where self-signed cents are used. You should be able to tell if the cert is not valid if you have to click through a warning message when you visit the URL in a browser. To fix the issue, you can try connecting over http if transport security isn't a concern, obtain or install a valid cert, or import the current cert into Trusted Root Authorities store of the Current User or Local Machine.

Related

How do I prevent or catch "Unable to run: socket is null" from AsterNet?

Using AsterNet to connect to Asterisk, I've been seeing the following:
Unhandled Exception:
System.SystemException: Unable to run: socket is null.
at AsterNET.Manager.ManagerReader.Run() in
e:\Projects\Github\AsterNET\Asterisk.2013\Asterisk.NET\Manager\ManagerReader.cs:line 197
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback,
Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state,
Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
You can see the line that throws this exception in the AsterNet code at ManagerReader.cs, line 197. It looks like this happens when connect() (in ManagerConnection.cs) launches a new thread, but mrSocket is somehow null in ManagerReader.cs. But this exception gets thrown from that new thread, so I can't catch it and handle the error. It just crashes my application.
So I have two questions. First, how do I prevent this from happening? Am I doing something wrong with how I connect or reconnect? Second, is it possible to catch this somehow and try the connection again?
This was happening because I was trying to maintain the connection myself and I didn't have to. I had written a loop to check the connection every so often and reconnect if it dropped and send pings to keep it alive. You can see an example of what I was doing here:
https://gist.github.com/squaregear/80821130d221727c3836dba3224bf93e
But I didn't need to do that. The current versions of AsterNet do all that for you. And when I was also trying to do it manually, it was interfering with the steps the library was taking. So the bottom line is, just let the AsterNet library maintain your connection for you.
You can see my discussion with the maintainers here:
https://github.com/AsterNET/AsterNET/issues/107

Why do i need to have create database permissions for asp.net web app?

I am building an ASP.NET, code-first web app. I am using a company owned database, and have crud permissions for tables within one database on this server. I do not believe I have "Create Database" permissions. I am running into issues publishing my web app. I can run everything locally, but when I publish the code on the company server I get errors like:
Format of the initialization string does not conform to specification starting at index 0.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: Format of the initialization string does not conform to specification starting at index 0.]
System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue) +1742
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +191
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +136
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +75
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +35
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +241
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +78
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +116
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +104
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) +434
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +39
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +160
System.Data.Entity.Internal.LazyInternalConnection.get_Connection() +16
[Project].DBContext.Context..ctor() in C:\Users\[UserName]\Documents\[FilePath]\[Project]\DBContext\Context.cs:20
[Project].Data_Manager.DataManager..ctor() in C:\Users\[UserName]\Documents\[FilePath]\[Project]\Data_Manager\DataManager.cs:15
[Project].Controllers.HeaderController..ctor() in C:\Users\[UserName]\Documents\[FilePath]\[Project]\Controllers\HeaderController.cs:12
This error makes me believe I have an issue with my connection string. When using Unit Testing, I get the error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code
Additional information: CREATE DATABASE permission denied in database 'master'.
I recently changed my context constructor from:
public Context() : base("[server_Name].[database_name]")
{}
to:
public Context() : base("[server_Name].[full_company_server_file_path]")
{}
And when I ran the solution locally, also got the "CREATE DATABASE permission denied in database 'master'" error.
For the record, my connection string is:
<connectionStrings>
<clear />
<add name="[server_Name].[database_name]" providerName="System.Data.SqlClient" connectionString="Data Source=[server_Name].[full_company_server_file_path];Initial Catalog=[database_name];Persist Security Info=True;User ID=userid;Password=password;MultipleActiveResultSets=True;Application Name=EntityFramework" />
< /connectionStrings>
My question is:
Why do I need Create Database Permissions in order for this all to work?
And if that isn't the case, why do I keep getting this error? (No where in my code do I say create DB, nor should / can I).
Secondly, any suggestions as to fixing my connection string? I got this connectionString from database -> properties -> Connection String (so I feel like it's correct).
Thanks for all help / tips / explanations.
Using:
ASP.NET / Entity Framework / C#
Visual Studio 2015
SQL Server Management Studio 2014
There is nothing much you can do here except getting the privileges for your application to do such activities on db server which is very unlikely to happen in large organizations.
The best solution to this is not to include database creation operation as part of web application publishing process.
Surely organization's policy will not allow application to run with master db privileges.
Leave database creation activity to the DBAs who are managing the DB Servers and the databases. They will have necessary access and permissions to perform such operations. They will create database and run the script to make your database ready to use by the application.
Create a script which will create the entire database structure including tables, views, stored procs, functions, keys, indexes etc and raise a ticket or RFC or follow whatever process required to get the database created with proper structure on the target server. Let your application deal with the data only without worrying about database creation and updates.
That's how the applications in production environment works and that's how the processes are implemented and followed with very rare exceptions to it.
SOLUTION
For anyone curious, in the process of publishing (native Visual Studio action) the connection string was being garbled to:
connectionString="$(ReplacableToken_[server_name].[database_name]-Web.config Connection String_0)"
I edited the published connection string to my real connection string and that fixed the problem.

Exception Tracing on Web Services - .net

I have a Web service call, which is already tested in Local Environment , Works Great no exceptions, I have tested it in one of our servers and it works great there as well. But here comes the main server were i need to set up the Web service , I did deploy my code, got the Web Service up and Running .. Now a part of my calls 50% work great( where only few fields are sent out in a call) , they get me responses and the other part (where there are many fields )just return an exception.."Object Reference Not Set to an Instance of Object".
I have avoided all the possibilities for an null reference exception to occur, But still i get that, and I am kind of lost as i don't know what exact point the Code is failing, I have enabled tracing, it doesn't help.. I tried getting the exception information by turning on the NullReferenceException in CLR
[FaultException: Server was unable to process request. ---> Object reference not set to an instance of an object.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +14799942
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +622
WebServiceX.OrderingSoap.ProcessTeleReseller(ProcessTeleResellerRequest request) +0
WebServiceX.OrderingSoapClient.ProcessTeleReseller(OrderHeader Ord_Header, Int32 Num_PotsLines) +105
WFTransmitOrder2.SaveOrder() +997
WFTransmitOrder2.IBTransmit_Click(Object sender, ImageClickEventArgs e) +24
System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +134
System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +204
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804
this doesn't help much either, as i want to know the line number inside my Web Service class.
Why does this kind of issues happen, what is the relationship between Web Services and servers ? These Web Services are hosted on IIS on one of our communications servers for different company's . It is working on the servers we have hosted but not on the Customer Servers
Any Help is highly appreciated..I have been stuck on this issue for a while now :)
Thanks

MSMQ: Message Queue service is not available. Error message

have had MSMQ working for the past few months but I am suddenly getting this error message:
Message Queue service is not available.
This is when i test it locally when I test it in live i get the follwoing message:
Unable to validate data.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Unable to validate data.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): Unable to validate data.]
System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Boolean useValidationSymAlgo, Boolean useLegacyMode, IVType ivType, Boolean signData) +4961431
System.Web.Security.MachineKey.Decode(String encodedData, MachineKeyProtection protectionOption) +194
System.Web.Helpers.AntiForgeryDataSerializer.Deserialize(String serializedToken) +120
[HttpAntiForgeryException (0x80004005): A required anti-forgery token was not supplied or was invalid.]
System.Web.Helpers.AntiForgeryDataSerializer.Deserialize(String serializedToken) +754
System.Web.Helpers.AntiForgeryWorker.Validate(HttpContextBase context, String salt) +199
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +156
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +825488
System.Web.Mvc.Controller.ExecuteCore() +159
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +335
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +54
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +469
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375
Has anyone come across this problem where it has been working and then stops and any fixes for this?
Edit: I had a few issues setting up msmq see:
MSMQ creating errors: A workgroup installation computer does not support the operation / User's internal Message Queuing certificate does not exist
My set up we have 6 servers which are load balanced and all have msmq set up, the domain is set up as a Network service and there are two other server which are involved - the doamin controller which receives the messages and serach server which receives the message - i don t kow if there is a problem on all or just one particular server. I have tried to narrow it down by using the Host file (C:\Windows\System32\drivers\etc\Host )and pointing at each server at a time but they still seem to be sporadic in whther they work or not. We do use caching so I'm not sure if this may be affecting anything...
Thanks
I know this might sounds like a dummy solution, but it will worked with me for sure.
You need to remove MSMQ and install again, but in order for the other services to actually see it you need to restart in between every step ... so What you need to do as follow:
Remove MSMQ
Restart Server
Install MSMQ
Restart Server: Noting sometime this step is not needed it depends on whether the other services are able to see the MSMQ at this level or not.
Good luck
To resolve this problem, follow these steps:
Log on to your computer as an administrator.
Click Start, and then click
Run.
The Run dialog box appears.
In the Open box, type
Services.msc, and then click OK.
The Services window appears.
Locate Message Queuing. Right-click
Message Queuing, and then click
Properties.
The Message Queuing Properties (Local Computer) dialog box appears.
On the Log On tab, click Local System account.
Click Apply, and then click
OK.
Stop the Message Queuing service, and then start the Message Queuing service.

ASP.NET error: IsBadPath() Object reference not set to an instance of an object

I'm getting an {"Object reference not set to an instance of an object."} exception randomly (it seems random) on a server. I can reproduce the exception using fiddler and my local machine by passing in no header data.
The stack trace is
at Microsoft.VisualStudio.WebHost.Request.IsBadPath()
at Microsoft.VisualStudio.WebHost.Request.TryParseRequest()
at Microsoft.VisualStudio.WebHost.Request.Process()
at Microsoft.VisualStudio.WebHost.Host.ProcessRequest(Connection conn)
at Microsoft.VisualStudio.WebHost.Host.ProcessRequest(Connection conn)
at Microsoft.VisualStudio.WebHost.Server.OnSocketAccept(Object acceptedSocket)
at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)
any ideas? I can't get to the problematic code because No source available or symbols have not been loaded'.
ASP.NET 3.5
Looks like the unhandled leftovers from Response.Redirect call.
In my case this same problem happened because of invalid (too many?) cookies. I cleared the cookies and the problem went away.

Resources