In my WPF application I want to make a connection with a Web-Service through HTTPS ignoring possible certificate errors, which seems to be a fairly common thing to do, from what I've been researching.
I've found this nifty snippet:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
I've set a breakpoint on the return statement, and it is never called (tried it with a separate method too).
I've also tried setting the following properties to false:
ServicePointManager.UseNagleAlgorithm = false;
ServicePointManager.Expect100Continue = false; //tried true too
ServicePointManager.CheckCertificateRevocationList = false;
I've also tried to create my own ICertificatePolicy with a CheckValidationResult that always returns true and attributing it to ServicePointManager.CertificatePolicy. That also hasn't worked.
In all of these attempts, I get the following:
The underlying connection was closed: An unexpected error occurred on
a receive
I've created a separate windows forms application with just three lines:
WebReference.MySebService myWebService = new WebReference.MySebService();
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
bool result = myWebService.TestConnection();
//TestConnection is a method in my WebService that simply returns true.
And it WORKED.
What else could I try ?
Info:
WPF application
.NET 3.5
The web-service is consumed through a separate class
It works perfectly with regular HTTP
Not using proxy
Fails both on the server and with the WS on localhost
The same three lines that run on my test app, won't work in my WPF app
The two instances of the WebService are exactly the same (all properties, including URL)
Tried deleting and re-adding the web-reference just as in my test apps.
After stressing a lot about this, we've finally come to a solution.
The hint to it was in the inner-exception, which passed unnoticed before. It stated that it failed to load a Security assembly.
Coincidentally we had a project named Security with an output assembly named Security on this solution, which caused a conflict. And it was only incorrectly accessed when SSL was being used.
Interestingly enough, neither Visual Studio, nor the compiler have warned me that this wasn't such a good idea, and not even that there was a .NET assembly named just like ours.
The solution was to rename this assembly, and everything worked perfectly immediately without a flaw.
Lessons learned:
Use customized names that could never exist already, like
SPONGEBOBSQUAREPANTS_Security.
Do not trust that Visual Studio will check if my assembly is conflicting with anything.
Always check for inner exceptions, no matter how familiar their outer ones may seem.
Related
We've created a Selenium test project that starts the (ASP.NET) web application and runs a couple of tests using the ChromeDriver. Locally this all runs fine (in headless and non-headless mode).
But on the build server (using an Azure DevOps agent) this fails without ever starting the tests. It looks like it fails when starting the ChromeDriver: the driver starts, but then it's immediately followed by 403 errors. It never gets to the part where it actually loads a webpage.
Any ideas where to look?
Answering my own question to document possible solutions.
After some rigorous investigation (which included using the source code to get to the bottom of things) we found out that the proxy server somehow got in the way. It turned out that the ChromeDriver tries to communicate over a local port (e.g. http://localhost:12345), which was redirected through the proxy server. This failed with a 403 error.
This gave us a lead on possible solutions. First we tried to use the .proxybypass file to exclude localhost addresses. This didn't work -- it turns out that this proxy bypass only works for https requests. And the ChromeDriver control commands are sent over http :-(
We then made sure that no proxy was used in our test code. We did this with the following lines:
var options = new ChromeOptions();
options.AddArgument("--no-sandbox");
options.AddArgument("headless");
options.AddArgument("ignore-certificate-errors");
options.Proxy = new Proxy()
{
Kind = ProxyKind.Direct
};
var driver = new ChromeDriver(options);
In addition to these settings (note that some arguments were added to solve other issues and might not apply to your own situation), we also disabled the proxy for other requests:
WebRequest.DefaultWebProxy = null;
HttpClient.DefaultProxy = new WebProxy()
{
BypassProxyOnLocal = true,
};
This allowed our tests to finally run on the build server without the 403 errors.
One last remark (which might be obvious) is to always run your tests in non-headless mode if you encounter any issues. This allowed us to see the "invalid certificate error" which would otherwise be hidden.
I started using gRPC with Visual Studio 2022 and never saw so many issues as now.
When I wanted to create an additional Proto file I got the error saying that I need to specify the language. That's weird, because I selected the proper option which is designed for C#. So it never worked and I simply had to copy default greeter file.
I created the console app which uses this default greeter service and it even worked. But I added the additional proto and created another fairy simple service and it did not want to compile it referring to some missing types of something. I can't remember the exact error message but I resolved it only by reducing the grpc.* package version to 2.27.I found this answer by googling and I find it weird that Microsoft releases something what does not work in the most simple case scenario.
I decided to test my new test grpc service and created the client:
var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);
var reply = await client.MySimpleMethodAsync(new MyRequest { Id = 123 });
Console.WriteLine(reply.Message);
Console.ReadKey();
The MySimpleMethodAsync method is very simple, it just reads the record from the DB using Dapper, nothing special.
Surprisingly there was no compilation error, but when I tried to run it (along with the server app) I got the exception on the line var reply = await client.MySimpleMethodAsync, saying Grpc.Core.RpcException: 'Status(StatusCode=Unimplemented, Detail="Service is unimplemented.")'
I don't understand why it says so. The service is implemented, it's compilable! Googling did not help but I found that other people are having the same issue too.
Eventually I found that if I modify the grpc service and for some reason it does not like it and then I rollback the changes, it's not compilable anymore! I clearn solution, rebuild it - nothing helps! The only thing which helps is addting the brand new project and copy pasting the previous "stable" code.
I've never seen such the ...technology that never works!
Anyway, now the most important issue for me is #3 , why it says the service is not implemented?
I have an application which now needs to be deployed to the app store, as it is slowly becoming unavoidable thanks to Gatekeeper.
Only problem is that web requests seem to fail, in the sense that they aren't even being fired.
The following code snippet has been pulled from a Xamarin Bugzilla article, and succeeds when built for Release and Debug;
try
{
WebClient test = new WebClient();
Console.WriteLine("Testing SSL GET...");
string testresponse = test.DownloadString(checkFileUrl);
Console.WriteLine("testresponse = " + testresponse);
} catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.InnerException.Message);
}
However, when I flip over to AppStore build, with sandboxing and Network IO Entitlements, the request never gets sent out, as verified by Charles in Non-SSL decryption mode. The following gets spat out from the console;
Testing SSL GET...
Error getting response stream (Write: The authentication or decryption has failed.): SendFailure
The authentication or decryption has failed.
This seems to be the problem, as we use SOAP calls made to an IIS service to perform actions, the first of which is logging in. For Debug and Release, login works fine, as the calls are completed. Once again, the AppStore build doesn't even attempt to make contact.
Certificates are valid, and CA's installed in my keychain.
Leading up to this, I was getting some exceptions in the code (in Debug) such as;
System.Exception..ctor (message="invalid encoding specification.") in /private/tmp/source/bockbuild-mono-3.2.6/profiles/mono-mac-xamarin/build-root/mono-3.2.6/mcs/class/corlib/System/Exception.cs:81
and
System.Exception..ctor (message="Store Root doesn't exists.") in /private/tmp/source/bockbuild-mono-3.2.6/profiles/mono-mac-xamarin/build-root/mono-3.2.6/mcs/class/corlib/System/Exception.cs:81
and
System.Exception..ctor (message="Store CA doesn't exists.") in /private/tmp/source/bockbuild-mono-3.2.6/profiles/mono-mac-xamarin/build-root/mono-3.2.6/mcs/class/corlib/System/Exception.cs:81
which still leads me to believe it is a Certificate issue. The test URL is an S3 link, and the login server is an EC2 instance with valid Certificates.
Cheers.
Check how your application is being packaged.
By default, when building your project (either in Xamarin Studio or Visual Studio), it will call a tool called mtouch that includes a linker for managed code. This tool is used to remove features from the class libraries that the application is not using.
Or so mtouch would like you to believe.
The default option of the linker behaviour is to Link all assembiles. This will use mtouch to try to make the application as small as possible by modifying user code. This can and will break code that uses features in a way that mtouch cannot detect (such as webservices, reflection or serialisation).
The workaround that I have used is to disable linking. By changing the linker behaviour to Don't Link, this will make sure that no assemblies are modified.
You can find the menu to do this by right-clicking on the relevant project, and selecting Options:
Xamarin Studio - Project Options window
Try changing the linker behaviour to Don't Link (as shown above) and rebuild.
More information
Xamarin Guides - Linker with iOS
I have several web services residing on a LIVE server that return data to a client. For some reason since I have moved the services from TEST server to the LIVE server the services are breaking.
My logs indicate that the services are executing correctly serverside but on the client side 'nothing' is returned. I.e. the client exists unexpectedly and the local variables defined 'do not exist in the correct context' when debugging.
PDFLive.PDFServiceClient client = new PDFLive.PDFServiceClient();
string[] response = client2.ReceiptPDF("document string");
string foo = "othercodetobeexecuted";
If I debug over this code, it will attempt to execute 'string[] response ...' and then just skip over the other code and end the client without returning any errors or exceptions and making the local variables
string[] response
and
string foo
'Non existent in the current context'
I have enabled Diagnostics in my web.config and they indicate no errors. Again on the serverside the code executes correctly its the return data that isnt reaching the client or reaching the client but not being processed correctly on the client side.
Ive tried creating the default WCF project and deploying it on my LIVE server and consuming it externally alas, same issue. Could it be something on the Server that is disallowing data to be sent?
I have searched high and low but without any meaningful error being returned its difficult to know what the issue could be. Has anyone had any experience with this issue or come across it in anyway?
I can consume the service via an external test client but when adding a service reference to a C# project it displays the behaviour mentioned above.
SOLVED:
I had to uncheck 'optimize' code in the project settings and my debugger works perfectly now. I got the idea from this post A curious case of Visual Studio 2010 debugger
SOLVED: I had to uncheck 'optimize' code in the project settings and my debugger works perfectly now. I got the idea from this post A curious case of Visual Studio 2010 debugger
I am using the Mathematica .Net/Link platform to create a web service to format and calculate math problems. However I am unable to get it working.
I create it using this code:
_Log.IpDebug("Starting the Kernel Link");
if (string.IsNullOrEmpty(_MathLinkArguments))
_InternelKernel = MathLinkFactory.CreateKernelLink();
else
_InternelKernel = MathLinkFactory.CreateKernelLink(_MathLinkArguments);
_Log.IpDebug("Kernel Link Started");
_InternelKernel.WaitAndDiscardAnswer();
The value of _MathLinkArguments is -linkmode launch -linkname \"C:\\Program Files\\Wolfram Research\\Mathematica\\7.0\\Math.exe\".
This piece of code is called from the Application_Start method of the global.asax.cs file.
When it gets to the WaitAndDiscardAnswer() call it gives the server error:
Error code: 11. Connected MathLink program has closed the link, but there might still be data underway.
Note: The SampleCode given with the .NET/Link package (both a console app and a WinForms app) works.
Edit:
I copied the console app sample code given with Mathematica into an asp.net page and it gave me the same error the first load and then on subsequent loads it gave me:
Error code: 1. MathLink connection was lost.
Edit2:
I forgot to mention that when I have procmon and task manager open while running my app, I can tell that Math.exe starts but it immediately exits, which makes those error code make complete sense...but doesn't explain why that happened.
To allow the .Net/Link to work in Asp.net (at least in IIS 7.5) you need to enable the property loadUserProfile on the app pool for the web site.
I am not entirely sure why this is the case, but from what I found while trying to debug this, there are some things that are gotten from the user's profile. I know for a fact that the default location of the kernel is, which explains why I couldn't use it with no arguments, and so I can only assume that other things are needed as well and without the profile it couldn't determine that.
But whatever the reason is this is required, it is, or at least it is a fix if you are getting similar problems like this in your own application.
I got the same error in a .Net WinForm application.
mathKernel = new MathKernel();
mathKernel.Compute("<< XYZ`XYZGraphs`");
The error occurred on loading the package straight after instantiating the MathKernel.
To resolve it you can wait a couple of seconds and then instantiating the MathKernel works fine. During this state where there might still be data underway the following conditions are both false:
if (!MathKernel.IsConnected)
{
MathKernel.Connect();
}
if (MathKernel.IsComputing)
{
MathKernel.Abort();
}
Edit:
I've recieved the error again and this time was able to determine the problem.
Using a command line open the MathKernel.exe and view the error message: