WCF Security Exception caused by Directory.Delete() - c#

I am encountering a strange issue: I call a WCF-Operation from my client. The operation deletes all files in a specified directory and finally deletes their parent directory too.
ACtually, this works. No exception is thrown and the files within the folder and the folder itself are deleted successfully.
But: the wcf context of my client gets invalidated so I need to instantiate the Service Client again. If I do not delete the directory but only the files within everything works fine. Actually I do not have any clue why deleting a directory has an impact on the Client calling the service ??!
Thank You

Sorry for the late reply, but I just wasted an afternoon dealing with the exact same issue. I finally tracked down the issue to the call to Directory.Delete(). It was working fine, no exceptions etc.
In our case we were deleting a subfolder of the folder that hosted the WCF service. From what I understand, this forces the application to recycle, killing your session/service etc
Our service was storing/deleting files, so we moved the file storage location to outside of the applications folder and it now seems to work fine.
More info here:
http://www.geekays.net/post/2008/10/14/ASPNET-webdomain-recycle-on-subfolder-changes.aspx

Are you getting back a SOAP fault from your service call when you delete the directory??
If so, can you enable additional detailed debug information to find out what exactly that fault is on the server??
You do this by adding a service behavior to your config (on the server side):
<behaviors>
<serviceBehavior name="detailedDebugInfo">
<serviceDebug includeExceptionDetailInFaults="True" />
</serviceBehavior>
</behaviors>
and then assigning that service behavior configuration to your service declaration:
<services>
<service name="YourService"
behaviorConfiguration="detailedDebugInfo">
Once you do this, you should be getting back the detailed exception info from a potential server side exception into the SOAP fault you're getting back on the client.

Related

Can we have environment-based endpoints with a WCF Connected Service?

I recently migrated one of our assemblies (a referenced library) from the old CSProj format to the new CSProj format (the Microsoft.Net.Sdk format). This helps a lot due to the globbing rules and how it handles dependencies (reference, project reference, package reference) so well.
After the transition, there is no longer an option for "Service References", instead we have "Connected Services". I removed the old Service Reference files (code, wsdl, xsd, etc.) and created a new Connected Service.
It seems cleaner because it generates a json configuration (used for auto-generating code) and a single Reference.cs file. The auto-generated code is a bit different than the old service reference code that was generated. Firstly, all methods are async (makes sense), so I adjusted our code to account for this.
The problem I am running into is that we had originally relied on the application's Web.Config file (also Web.Dev.Config, Web.Test.Config, etc.) -- during our deploy process we rename/replace the Web.Config with the appropriate environments configuration. This worked just fine, our app added a reference to our library and the app held the config information.
With the new Connected Services auto-generated code, it is hard coding in the localhost address as the endpoint because I used that to auto-generate the code.
Basically, the old "Service Reference" generated code had the default constructor of the client pull the endpoint from the application config. The new Connected Service offers overloads, but does not by default pull the endpoint from the config.
<system.serviceModel>
<client>
<endpoint address="http://xdev/xservice.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IXService" contract="XService.IXService" name="BasicHttpBinding_IXService" />
</client>
</system.serviceModel>
What do I do different to take advantage of my app config with the new WCF Connected Services auto-generated code?
See this answer:
There is a partial abstract method partial void ConfigureEndpoint in your service client to override. There you can programmatically set the endpoint via serviceEndpoint.Address = new EndpointAddress(...).
This URL can be stored in the <appSettings> of your .config or in the appsettings.<Environment>.json, depending on your platform.
Note, that the development endpoint from which the code was generated gets hard-coded into the sources and remains as a fallback. If for some reason your overridden method does not get called, you have a very hard to spot error. If someone has a solution for that, I'd be very interested.

WCF client configuration from custom location

I'm new to WCF and am trying to make my first service (a simple usage reporting service). I've gone through examples and tutorials and created a service. I have a simple test program that can run my core code and send the report. Currently I'm running locally hosted in the debugger, but running this simple exe program hosts the service, sends the report, and the service creates the log file just like it's supposed to... all is good.
Now, my actual program is an addin to another commercial program that runs in it's API (Autodesk Revit). When I run the exact same code inside of the Revit API I get an error that there is no endpoint defined. My guess is that this is because it's looking for the main Revit.exe.config which obviously will not have my endpoint defined. I have a .config file for my dll created (MyLibrary.dll.config) and in the executing directory for my code and it defines the endpoint properly, but that doesn't seem to be recognized.
So my question is how do I get it to load the connection settings from this config file? Or is there another way I should be doing this? I'm open to setting it in code somehow or whatever, just can't figure out how to get it to connect...
I'm not sure if it matters, but here is the configuration that is working in the standalone program:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IReportingService" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8733/Design_Time_Addresses/SPECtrumReportingService/Service1/"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IReportingService"
contract="ReportService.IReportingService" name="BasicHttpBinding_IReportingService" />
</client>
</system.serviceModel>
</configuration>
My constructor that is throwing the endpoint exception is simply:
_reporter = new ReportingServiceClient();
Here is the exception that is thrown:
Could not find default endpoint element that references contract 'ReportService.IReportingService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
at System.ServiceModel.Description.ConfigLoader.LoadChannelBehaviors(ServiceEndpoint serviceEndpoint, String configurationName)
at System.ServiceModel.ChannelFactory.InitializeEndpoint(String configurationName, EndpointAddress address)
at System.ServiceModel.ChannelFactory`1..ctor(String endpointConfigurationName, EndpointAddress remoteAddress)
at System.ServiceModel.ConfigurationEndpointTrait`1.CreateSimplexFactory()
at System.ServiceModel.ClientBase`1.CreateChannelFactoryRef(EndpointTrait`1 endpointTrait)
at System.ServiceModel.ClientBase`1.InitializeChannelFactoryRef()
at RDES.Revit.Sumex.CommonUse.ReportService.ReportingServiceClient..ctor() in c:\RD\Projects\13-004 SPECtrum\Code\SPECtrumBase\Service References\ReportService\Reference.cs:line 241
at RDES.Revit.Sumex.CommonUse.ImportVM..ctor() in c:\RD\Projects\13-004 SPECtrum\Code\SPECtrumBase\ImportVM.cs:line 41
Any help would be greatly appreciated...
it's not relevant that the dll's configuration file is in the same folder as the application. only the application's (executable's) app.config file is read. the solution is to copy the WCF service configuration from the dll config file to you application's app.config file.
the other solution, for modular applications, is to set the service's ABC in code. the problem with this is that you cannot configure it without rebuilding and redeploying the addin.
to create a WCF proxy entirely in code you could use something like this:
IServiceContract proxy = ChannelFactory<IServiceContract>.CreateChannel(new WSHttpBinding(),
new EndpointAddress("<you url here>"));
I found this post that lead me to a possible answer. I have now updated my constructor as follows:
_reporter = new ReportingServiceClient(new BasicHttpBinding(), new EndpointAddress("http://localhost:8733/Design_Time_Addresses/SPECtrumReportingService/Service1/"));
I've left the binding as just default although it looks like I can set other properties if I need to. I just pulled the endpoint address out of the config file that worked in the standalone program and used that to construct.
This seems to be working as expected inside of Revit at least with preliminary tests. Can anyone comment on if this would cause any issues or if there is a better way to handle this situation?
Though you can inject endpoint info into a proxy class ReportingServiceClient through your application codes, the first class programming approach is to use app.config.
In your client config, you have an endpoint named "BasicHttpBinding_IReportingService", to use this endpoint, you should then write:
_reporter = new ReportingServiceClient("BasicHttpBinding_IReportingService");
If you want
_reporter = new ReportingServiceClient();
to work, remove the name attribute or make the name attribute value in the client endpoint defined in the client config. This will be the so called "default endpoint element" mentioned by the exception.

Getting "Request Error" after hosting WCF on IIS

Before hosting WCF Restful Services on IIS. I was getting response from server in my android application but now I have hosted my services on IIS but getting an error message of REQUEST ERROR. I don't know what's went wrong. can someone please sort out my problem. Thanks in Advance
Before Hosting on IIS
the above picture is before hosting the service on IIS. and the yellow highlighted text is param and the JSON is the response which is corresponding to that param.
After Hosting on IIS
I don't know why I'm getting this error. what went wrong and how to fix that. now im trying to retrieving data correspond to that param but getting an error message.
"SERVER LOG after includeexceptiondetailInfaults attribute value to true"
I'ms sure that database is causing the error and you can view the picture of server log below
The database was causing an error. I have found the solution. what we need to do? We need to add a login to SQL Server for IIS APPPOOL\ASP.NET v4.0 and grant permissions to the database.
In SQL Server Management, under the server, expand Security, then right click the Logins and select "New Login...".
In the New Login dialog, enter the app pool as the login name and click "OK"
now right click the login, select properties and then click on the User Mapping Option. Click the appropriate DATABASE and check the properties roles. And we are done :).
hope you good luck. Thanks
Possible solutions would be,
(i)Just ensure all your property are public.
(ii)To So see more details about the issue, you need to includeexceptiondetailInfaults attribute to true in servicedebug tag.
<servicebehaviors>
<behavior name="myServiceBehavior">
<servicedebug includeexceptiondetailinfaults="true" />
</behavior>
</servicebehaviors>
(iii)Remove the Enum types (or use their suggested work-around and use a wrapper around the enum properties) and this should go away.
(iv)Copy the connection strings from the class library app.config to the web project web.config If you are using a class library and a web project,
After hosting on iis
Request error occurred in iis
The server encountered on request error see server logs for more details
Solution
In your sql server change window authentic to sql authentic with username and password
and change on connection string
After changing these step and refresh the iis and
Your problem is solved

IIS7 URL Rewrite returns 404 for WCF requests (reverse proxy)

I am using IIS7.5, .net 4.0. I am working locally.
I have installed Application Request Routing, Web Farm Framework, WebDeploy and UrlRewrite to set up a reverse proxy. This works fine for the most part.
I have two websites:
DefaultWebSite (port 80, app pool: Default App Pool (.net 4)) and
Target (port 8085, app pool: TargetAppPool(my identity, .net 4)).
I have a rewrite rule on DefaultWebSite (created as directed on IIS.net) which redirects all localhost (port 80) traffic to localhost:8085 just as detailed in the above link. This works fine for most document types (.aspx, .xap, .htm, .ico) but a request to MyService.svc fails. It returns a 404.
To be clear:
When I paste localhost:8085/MyService.svc into a browser I get the requested WCF page.
When I paste localhost/MyService.svc into a browser I get a 404.
When I paste localhost:8085/MyIcon.ico into a browser I get the requested resource.
When I paste localhost/MyIcon.ico into a browser I get the requested resource.
.svc is the only document type that I've found that returns a 404.
I've got two pieces of info that might be of relevance.
App Pools. When I change the DefaultWebSite's app pool to TargetAppPool then the 404 becomes a 500 ("Failed to map the path '/'"). All other requests are successful when this change is made. Not sure if this relevant or not.
FREB (Failed Request Tracing) Log. I found a page (http://blogs.msdn.com/b/asiatech/archive/2011/08/25/return-404-4-not-found-when-url-rewrite.aspx) which details the steps in a FREB log when a URL rewrite is more successful than mine (it fails later on). I've not been able to find out how to generate a FREB log for a successful rewrite (if that's possible) so I can only compare my FREB log to the one on that blog. I can see that their step 21 (URL_CHANGED) in my FREB log but not 22 (URL_REWRITE_END). I've not got enough experience with these logs to notice anything more significant than that (suggestions welcomed).
My main question is: does anyone know why just URLs requesting .svc resources are not being rewritten?
A secondary question is: does anyone know how to generate a FREB log for successful request (if it's even possible)?
Thanks
Update:
I have changed the architecture to try to get more info.
I have moved the Target website to a different PC on which I have installed Microsoft Network Monitor to capture the incoming traffic.
Before I changed the url-rewrite rule to point at this new website I got the correct response when I made a request to MyService.svc on the new PC. Fine.
As soon as I changed the rewrite rule to route the request to the new Target website then it responds as before (404). I have made both POST and GET requests. There is no sign of any of the requests in the Network Monitor log (all other calls -200, 404 or otherwise- appear in this log).
This leads me to think that there is something incompatible with url-rewrites and *.svc requests. I tried making a request to MyService.asmx (having created this file) and it correctly returned a page, so it is limited to *.svc. Any ideas?
The solution to this is in the config file of the Target web site.
In web.config (in the Target application) there is a section which read:
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>.
I changed this to read:
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />.
Credit must go to http://forums.iis.net/post/1956671.aspx for this (although s/he claims it is the proxy's config which needs to be changed, but I found it be the Target app, not the proxy server).
If you still can't get it running, make sure you don't have the WCF handlers on the website which acts as the reverse proxy.
I disabled this by adding this web.config of the reverse proxy:
<system.webServer>
...
<handlers>
<remove name="svc-ISAPI-4.0_64bit" />
<remove name="svc-ISAPI-4.0_32bit" />
<remove name="svc-Integrated-4.0" />
</handlers>
</system.webServer>
Because the rewrite appears to work for all resources except when the extension is .svc I would say this would be the area to concentrate on.
I would imagine that the rewrite rules are matching your other resources, but not your service, and because these are usually regular expressions (which are often complicated) I would say it would be worth testing any rules you find with your urls. Details of how to find the regular expressions for an UrlRewrite can be found here.
It is also probably also worth looking at any outbound rules with the same mindset.

WCF Test Client cannot add service, cannot obtain metadata

Can anyone tell me why I get this error when I try to add my service?
Error: Cannot obtain Metadata from http://myserver/myapp. If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455. WS-Metadata Exchange Error URI: http://myserver/myapp Metadata contains a reference that cannot be resolved: 'http://myserver/myapp'. The remote server returned an unexpected response: (405) Method Not Allowed.
The remote server returned an error: (405) Method Not Allowed.HTTP GET Error URI: http://myserver/myapp There was an error downloading 'http://myserver/myapp'. The request failed with HTTP status 403: Forbidden.
Update: I have the following endpoint already,
<endpoint address="mex"
binding="mexHttpBinding"
name="Metadata"
contract="IMetadataExchange" />
I also have the service behaviors set:
<serviceBehaviors>
<behavior name="myBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
I had this issue, turns out that when I renamed the .svc file a reference to it hadn't been renamed from Service1.svc. Run a project wide search and replace .Service1 with your new name.
<%# ServiceHost Language="C#" Debug="true" Service="MyNamespace.Service1" CodeBehind="MyRenamedService.svc.cs" %>
Service="MyNamespace.Service1" should read Service="MyNamespace.MyRenamedService"
This can also happen when you try to return a custom class object from one of the functions and that function doesn't have the [DataContract] attribute on the class declaration. WCF cant figure out what type your returning so it throws the standard message.
[Serializable]
[DataContract]
public class ServiceResult
{
....
}
I figured it out. I was using an absolute path on one of my endpoints and I had more than one. I changed it to a relative path and then everything worked.
Also, this can happen if your service isn't running and may have nothing to do with metadata. If you have a ConfigurationErrorsException then you will see this result as well.
I also got it when trying to save configuration changes to the project and then it told me to save/overwrite/ignore, etc. It ended up adding a project subtype of "designer" and once I removed that it went back to working properly.
Some times there isn't anything to be done with metadata or the settings; instead we may simply use 127.0.0.1 instead of http:\localhost\
If adding the metadata endpoints is not your issue. Check further in the error message details. I had a missing library; "Could not load file or assembly *".
I needed to change the reference to Copy Local = True
I'm new to WCF and just got a project handed to me with WCF services inside.
I was having similar issues with using WCF Test Client in VS2010 on Win7. After trying all the config changes in this article and others I was still getting similar errors.
So I gave up and started reading up on WCF. Here I found that VS should be launched as administrator. Here's the article: Getting Started Tutorial WCF
Turns out I have to launch VS2010 with 'Run as Administrator' checked. This fixed the issue and I was able to test WCF services in VS2010. I'm posting this answer incase others over look the Run as Administrator.
I discovered that I had the same error because of a DataContract that I was using that inherited from Dictionary. The proper setup of the DataContract should be as follows:
[CollectionDataContract(Name = "AdditionalProperties",
ItemName = "Property",
KeyName = "Key",
ValueName = "Value")]
public class AdditionalProperties : Dictionary<string, string>
{
}
This is my experience on this error message,might be useful to others.
My WCF service is working fine on windows 2008 server.I copied the same solution to Dev machine, selected .svc file from solution so that WCF test client can be popped-up.
WCF test client opened with errors cannot obtain metadata,assembly can't be loaded etc.
Key is, first kick up the service (http://localhost:port/Service) then only try WCF test client.
In my case, I had not enabled BindingParams.AllowHttpGet. When that was set to true, it worked...
please check and read all text of error.
in my case another dll has error but show same error in above text of error.
Please check that you can resolve that address and that you have specified the correct virtual directory. Does myserver resolve to an IP with forexample ping myserver? Is myapp the correct virtual directory? You have enabled metadata for your wcf service, but the url is most likely wrong.

Categories