WCF Data Service - wcf

I have a Clustered Windows Hosting site which currently hosts an MVC Web Application using a MYSQL backing database.
What I have been trying to do for the past three weeks is host a WCF Data Service exposing the database behind the website to be consumed in a WPF application which will be installed on Windows machines.
I have followed every single tutorial that I have come across. None of them have worked and all of them give the example of using http://localhost as the location of where the Webservice is called from.
I have limited experience with Asp.Net and MVC but have published working websites before and as I mentioned currently am running a fully functional MVC web Application. I also have extensive .Net knowledge and experience, but, for the life of me cannot fathom this out at all.
I have seen no real examples of a WCF site being hosted from within a clustered hosting scenario. Practically every example I see mentions using IIS, but I do not have access to IIS on my hosting.
Could anyone point me in the right direction to a tutorial that will allow me to use a WCF service, or am I completely barking up the wrong tree?
Okay, an Update: After much experimenting I came across the following attribute and used it
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
This gave me an error which appeared to indicate that the Data Service was trying to access files on my local hard drive, indicating that I'd fudged some kind of reference. I also realised that I hadn't set up the Membership profiles and so scrapped my Data Service starting again.
First I added the Asp Membership profiles, then the Entity Model, set the permissions and used that attribute again and although looking more hopeful still got the following error.
The exception message is 'The specified store provider cannot be found in the configuration, or is not valid.'. See server logs for more details. The exception stack trace is:
at System.Data.EntityClient.EntityConnection.GetFactory(String providerString) at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString) at System.Data.EntityClient.EntityConnection..ctor(String connectionString) at System.Data.Objects.ObjectContext.CreateEntityConnection(String connectionString) at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName) at RotaSolutions.WCF.Models.rotasolu_crmEntities..ctor() in C:\Users\Paul\Dropbox\Projects\WCF\RotaSolutions.WCF\RotaSolutions.WCF\Models\CRMModel.Designer.cs:line 34 at invoke_constructor() at System.Data.Services.DataService1.CreateDataSource() at System.Data.Services.DataService1.CreateDataSourceInstance() at System.Data.Services.DataService1.CreateProvider() at System.Data.Services.DataService1.HandleRequest() at System.Data.Services.DataService`1.ProcessRequestForMessage(Stream messageBody) at SyncInvokeProcessRequestForMessage(Object , Object[] , Object[] ) at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
Although, still not able to use it. This is giving me more hope than previously. Again, if anyone has any suggestions, I'd be grateful to receive them.

I have actually managed to solve this. I'd post the full answer but can't due to sever formatting problems with the editor here so I'll have to do the short version.
Basically, I removed the MySQL version that I was using, downloaded the latest version and installed and added that reference.
I also added to the web.config a DbProviderFactories linking to the MySQL reference. Like I said, I'd post the code but this formatting system keeps rejecting my attempts.

Related

System.Security.Authentication.AuthenticationException: System error

I'm hosting an ASP.NET Core 3.1 web app with IIS 10, and it's throwing the following exception when trying to hit my API's through Postman:
System.Security.Authentication.AuthenticationException: System error.
at Microsoft.AspNetCore.Authorization.AuthorizationHandler`1.HandleAsync(AuthorizationHandlerContext context)
at Microsoft.AspNetCore.Authorization.DefaultAuthorizationService.AuthorizeAsync(ClaimsPrincipal user, Object resource, IEnumerable`1 requirements)
at Microsoft.AspNetCore.Authorization.Policy.PolicyEvaluator.AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, Object resource)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
When using Postman on the machine running the web app, I can make successful HTTP requests and not have any issues. It seems to only be happening when trying to make external requests, but the error text is extremely unhelpful and I'm not sure where to begin diagnosing. As far as I can tell, the directory containing the web app project files doesn't have any specific security restrictions and the Application Pool is using an account with sufficient permissions to access and use them.
Has anyone seen error text like this before, or have any idea what the issue might be?
As it turns out, this exception was being thrown as a result of an incorrect database connection string. This particular request checks against a local database to ensure the user exists there.
Strangely enough, I've encountered this same type of issue before (where a database connection string is broken / changed at some point), but the resulting exception was much more specific in its Exception text and stack trace. The only thing I can't explain here is why the above error is so generic.

Getting error by using NopCommerce services in WCF Project

I am using existing NopCommerce services in WCF project for my mobile application, after hosting in local IIS server, and by browsing, I am getting Exception as follows...
The server encountered an error processing the request. The exception message is 'Value cannot be null. Parameter name: instance'. See server logs for more details. The exception stack trace is:
at Autofac.RegistrationExtensions.RegisterInstance[T](ContainerBuilder
builder, T instance) at
Nop.Core.Infrastructure.DependencyManagement.ContainerManager.<>c__DisplayClass5.b__4(ContainerBuilder
x) at
Nop.Core.Infrastructure.DependencyManagement.ContainerManager.UpdateContainer(Action`1
action) at
Nop.Core.Infrastructure.DependencyManagement.ContainerConfigurer.Configure(IEngine
engine, ContainerManager containerManager, NopConfig configuration) at
Nop.Core.Infrastructure.EngineContext.CreateEngineInstance(NopConfig
config) at Nop.Core.Infrastructure.EngineContext.Initialize(Boolean
forceRecreate) at Nop.Core.Infrastructure.EngineContext.get_Current()
at NopServicesTest.AuthService..ctor() at
CreateNopServicesTest.AuthService() at
System.ServiceModel.InstanceContext.GetServiceInstance(Message
message) at
System.ServiceModel.Dispatcher.InstanceBehavior.EnsureServiceInstance(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&
rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean
isOperationContextSet)
Have you added WcfIntegration of AUtofac?

"Key not valid for use in specified state" Error for .Net 4.5 MVC 4 Application

To preface this question, please excuse me if I am getting any of my terminology wrong. The technology is very new to me.
I have a website in MVC 4, .Net 4.5 built with VS 2012 hosted on IIS7 and have used the "Identity and Access" wizard to configure authentication using a business identity provider. I have entered a path to an STS metadata document similar to:
https://xyz.mycompany.com/app/FederationMetadata/2007-06/FederationMetadata.xml
The site is currently hosted under three different realms. The first is my local development environment, second is standard integration testing and third is development.
http://localhost/myapp
http://sit.mycompanytest.com/myapp
http://dev.mycompanytest.com/myapp
It is important to note that the "dev" sub-domain is in a web farm or load balanced or something. I do not currently know the exact details of the load balancing architecture.
When I navigate to any of the above sites using IE 10 I am redirected to a login screen where I enter my credentials and gain access to the given site.
But, on the "dev" sub-domain, when navigating around the site using links and form submissions I eventually will get the following error:
Key not valid for use in specified state.
The stack trace of the error is:
[CryptographicException: Key not valid for use in specified state.]
System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) +397
System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +90
[InvalidOperationException: ID1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details). If you are using IIS 7.5, this could be due to the loadUserProfile setting on the Application Pool being set to false. ]
System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +1158198
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +173
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +756
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +100
System.IdentityModel.Services.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +668
System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +164
System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +173
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
I suspect the error is happening when the load balancer changes servers.
And, have been considering the 2nd workaround solution from the following web site: (http://blogs.msdn.com/b/distributedservices/archive/2012/10/29/wif-1-0-id1073-a-cryptographicexception-occurred-when-attempting-to-decrypt-the-cookie-using-the-protecteddata-api.aspx). But, the web site states that the solution is for .Net 4.0.
Will that solution work for .Net 4.5? And, if not, how can I fix the error?
I was able to fix the error by following the instructions in the following post by Vittorio Bertocci:
http://www.cloudidentity.com/blog/2013/01/28/running-wif-based-apps-in-windows-azure-web-sites-4/
Basically, I had to enable web farm cookies using the Identity and Access Tool.
In VS 2012, right click the project > select Identity Access > select the Configuration tab > check the Enable web farm ready cookies check box > click OK
IMHO the loadbalancing is the problem. You have to make sure the farm shares the same machine key. This can be done at machine level or in the web.config of your application.
Deleting the FedAuth cookies might work. When the exception occurs, try this in the Application_Error method of the Global.asax file:
Microsoft.IdentityModel.Web.FederatedAuthentication.SessionAuthenticationModule.SignOut();

IIS CRM 2011 web service invocation issue

I had a simple program , a asp.net website in which i added a webservice
One of the web methods accessed a CRM `
[WebMethod]
public bool RecordExists (String projectName)
{
var service = GetService("http://localhost/EventoCorp/");
Entity project = new Entity("new_project");
/*PROJECT DETAILS*/
project.Attributes["new_name"] = projectName;
var request = new RetrieveDuplicatesRequest
{
BusinessEntity = project,
MatchingEntityName = "new_project",
PagingInfo = new PagingInfo() { PageNumber = 1, Count = 50 }
};
Console.WriteLine("Retrieving duplicates");
var response = service.Execute(request);
EntityCollection collection = (EntityCollection)response.Results["DuplicateCollection"];
return collection.Entities.Count > 1 ? true : false;
}
When I press F5. the project runs fine . I invoke this record exists method , and it correctly brings data from the CRM 2011
However when i deploy this application on IIS 7.5 . I get greeted by this terribly uninformative exception
System.ServiceModel.FaultException: The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
I am a CRM 2011 noob . No idea what is going on . Please help me
This exception happens in the client you use when trying to connect your web service. It says only that unhandled exception happened on server side, but has no information about exception. Also there is advice to enable IncludeExceptionDetailInFaults in order to pass to the client unhandled exception details. But there is also other way to see what is going on, it's attach to IIS process and debug your web service.
Also it would be better add exception handling to your code, because now code is completely unsafe. Different exceptions can happen when you are accessing CRM, like authentication exception etc. Also you can just get null instead of collection you suppose to be there.
When you deploying this code to IIS authentication issues are possible, since IIS is working under NETWORK SERVICE account. And in case if CRM uses Windows Authentication it's possible your request will not be authorized.

System.Net.WebException: The request failed with HTTP status 401: Unauthorized

Ok, so I have this .NET 1.1 application (written by someone way back) which is like a document repository and it worked fine in the past. I suddenly get this error when trying to search for items/documents:
Page: /CPDEPforIT/SearchResults.aspx
Error:
System.Net.WebException: The request failed with HTTP status 401:
Unauthorized. at
System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage
message, WebResponse response, Stream responseStream, Boolean
asyncCall) at
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String
methodName, Object[] parameters) at
CPDEPforIT.InktomiSearchService.soapSearchService.getSearchResults(SearchInput
in0) at CPDEPforIT.SearchResults.GetDatasetForSearchQuery(SearchInput
searchInput) at CPDEPforIT.SearchResults.Page_Load(Object sender,
EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at
System.Web.UI.Control.LoadRecursive() at
System.Web.UI.Page.ProcessRequestMain()
I don't remember any changes. Could this have been caused by something external to the application (IIS configurations/permissions, Server, Database)?
There are several things you need to verify.
Does the web service you are trying to access allow Anonymous Access? Authentication can be tricky for web-to-web calls
What is the web application running under, IWAM_xxx or IUSR_xxx? Or are you using an application pool running under a specific identity?
You may want to make sure your web application server's ASPNET or NETWORK SERVICE accounts can access your web service server.
If you want to get it working you could just provide an account for Anonymous Access...
Thanks!
I have also faced this type of issue before. In my case permission to the code folder works. Please check the folder permissions and then try with the IIS permissions.