I'm trying to unit test some basic System.Net.WebClient code to download a string using an HTTPS endpoint. It seems that using HTTPS from within the NUnit test fails no matter what. I can use HTTP within the NUnit test without issue. I can run the HTTPS code in a Console application without issue.
Here's the code...
[Test()]
public void TestWebclientHttp()
{
using (System.Net.WebClient wc = new System.Net.WebClient())
{
string data = wc.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address=alvis%20court&sensor=true");
System.Diagnostics.Debug.WriteLine(data);
}
}
[Test()]
public void TestWebClientHttps()
{
using (System.Net.WebClient wc = new System.Net.WebClient())
{
string data = wc.DownloadString("https://maps.googleapis.com/maps/api/geocode/json?address=alvis%20court&sensor=true");
System.Diagnostics.Debug.WriteLine(data);
}
}
Here's the stack trace...
at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x0005e] in /private/tmp/monobuild/build/BUILD/mono-2.10.6/mcs/class/System/System.Net/HttpWebRequest.cs:828
at System.Net.HttpWebRequest.GetResponse () [0x0000e] in /private/tmp/monobuild/build/BUILD/mono-2.10.6/mcs/class/System/System.Net/HttpWebRequest.cs:836
at System.Net.WebClient.GetWebResponse (System.Net.WebRequest request) [0x00000] in /private/tmp/monobuild/build/BUILD/mono-2.10.6/mcs/class/System/System.Net/WebClient.cs:1433
at System.Net.WebClient.ReadAll (System.Net.WebRequest request, System.Object userToken) [0x00000] in /private/tmp/monobuild/build/BUILD/mono-2.10.6/mcs/class/System/System.Net/WebClient.cs:866
at System.Net.WebClient.DownloadDataCore (System.Uri address, System.Object userToken) [0x0000a] in /private/tmp/monobuild/build/BUILD/mono-2.10.6/mcs/class/System/System.Net/WebClient.cs:246
Development Environment...
Mac OS X 10.6.8
Mono develop 2.8.5
Mono runtime 2.10.6
Thanks.
Mono does not ship with any trusted root certificate by default.
You can install them yourself using mozroot or, just for testing (not for production), allow any SSL certificate to be used.
Related
I have a C# .Net Core 3.1 Razor Page where I am calling a 3rd Party API. When I run it locally in debug it returns a full JSON and is parsed into a strongly typed class successfully, but on the server hosting within IIS in process it fails with a 500 error that looks like an empty JSON object
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0
I am using an AJAX call to a Razor handler method. The website is using oAuth2 to authenticate the user (this is an intranet application) and this part works as expected both locally and on the server. My suspicion is that the user is "authenticated" locally (through windows or some other method and that data is being sent to the API) but on the server the Claims are validated but not passed to the API. I have used Postman on the server to validate the API can be reached. I have also contacted the API host and verified the request is not failing from the API, its not even reaching it. It requires HTTPS on port 443 which I confirmed is open between the server and the API.
Here is the Razor page method (called from AJAX).
public async Task<JsonResult> OnGetPerson()
{
var userInfo = await whitePages.GetPersonByIDAsync(ID);
return new JsonResult(userInfo);
}
This calls a function within an Interface
public async Task<Models.PeopleAPI> GetPersonByIDAsync(string id)
{
string uriString = createGetPersonByidUriString(id); //This just builds the https string
var response = await _httpClient.GetAsync(uriString);
List<Models.PeopleAPI> people=JsonConvert.DeserializeObject<List<Models.PeopleAPI(await response.Content.ReadAsStringAsync());
return people.Single(); // use Single to guarantee only one result was receieved, otherwise throw an exception
}
My peopleAPI model is as follows.
public class PeopleAPI
{
public int PersonID { get; set; }
public string Domain { get; set; }
public string NTID { get; set; }
public string EmployeeID { get; set; }
public string UnixID { get; set; }
etc
etc
}
Please help, I have tried adding in user credentials to make the API call, various other Stack suggestions (5 to 10 different approaches, sync, async, etc) and just cannot seem to come to a solution (each one works locally, but not on the IIS server).
HELP!!!
I was able to solve my own issue using the visual studio remote debugging on my server. It turns out the local debug on my machine was not using the proxy server (System.Net.Http.HttpWindowsProxy was showing empty) but on the server it was using a different version (system.Net.Http.HttpEnvironmentProxy) and using the default proxy specified within netsh winhttp proxy. Once I set the startup.cs to specify the AddHttpClient I also included the useProxy = false. This was within an intranet and hope maybe someone else can use this in the future.
services.AddHttpClient("coolapi", c =>
{
c.BaseAddress = new Uri("https://something.com/");
c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
UseProxy = false
}) ;
I'm attempting to create a Windows Runtime Component for use in a Windows 8 app.
This is essentially a helloworld level application and so has nothing complex. The only thing that I need to do to replicate the issue is to include a pair of methods such as the following:
public IAsyncOperation<string[]> GetThings()
{
return GetThingsAsync().AsAsyncOperation();
}
private async Task<string[]> GetThingsAsync()
{
return new List<string>().ToArray();
}
Whenever I compile the project, the Windows Metadata Exporter crashes.
I've dug into the errors generated in the output window by increasing the build verbosity and I've found that the error occurs after "Exporting 'obj\Debug\HelloWorld.Logic.winmdobj'."
By attempting to run winmdexp.exe from command line with the same parameters, it seems that it's having trouble finding metadata for the System.Xml files. (warning WME0004 : Could not find referenced metadata 'C:\Program Files(x86)\ReferenceAssemblies\Microoft\Framework.NETCore\v4.5.1\System.Xml.Serialization.dll'.)
The full stack trace of the error is:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Tools.WinMDExp.AssemblyReferenceExtensionMethods.IsWindowsRuntimeMetadata(IAssemblyReference assembly)
at Microsoft.Tools.WinMDExp.ExportVisitor.IsWindowsRuntimeType(ITypeReference type, Boolean allowGenericParam)
at Microsoft.Tools.WinMDExp.ExportValidator.<>c__DisplayClasse.<GetAlternativeTypes>b__8(<>f__AnonymousType0`2 <>h__TransparentIdentifier5)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection)
at Microsoft.Tools.WinMDExp.ExportValidator.GetAlternativeTypes(ITypeReference parameterType, IMethodDefinition containingMethod, Boolean& isTask, Boolean allowGenericTypeParam)
at Microsoft.Tools.WinMDExp.ExportValidator.GetAlternativesTypesForGenericTypes(IGenericTypeInstanceReference parameterType, IMethodDefinition containingMethod, String& errorMsg)
at Microsoft.Tools.WinMDExp.ExportValidator.CheckAlternateTypes(ITypeReference parameterType, IMethodDefinition containingMethod, Boolean& reportedError)
at Microsoft.Tools.WinMDExp.ExportValidator.ValidateExportParameterType(IMethodDefinition containingMethod, ITypeReference parameterType, Boolean& reportedError)
at Microsoft.Tools.WinMDExp.ExportValidator.ValidateExportMethod(IMethodDefinition method)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IMethodDefinition method)
at Microsoft.Cci.MetadataTraverser.Traverse(IMethodDefinition method)
at Microsoft.Cci.MetadataTraverser.Traverse(IEnumerable`1 methods)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(ITypeDefinition typeDefinition)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(ITypeDefinition typeDefinition)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(INamedTypeDefinition namedTypeDefinition)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataTraverser.Traverse(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataTraverser.Dispatcher.Visit(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataReader.ObjectModelImplementation.NamespaceType.Dispatch(IMetadataVisitor visitor)
at Microsoft.Tools.WinMDExp.ExportValidator.Validate(ITypeDefinition type)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IModule module)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(IAssembly assembly)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IAssembly assembly)
at Microsoft.Cci.MetadataTraverser.Traverse(IAssembly assembly)
at Microsoft.Tools.WinMDExp.ExportVisitor.Export(IAssembly assembly)
at Microsoft.Tools.WinMDExp.Exporter.Export()
at Microsoft.Tools.WinMDExp.Program.Main(String[] args)
If anyone has any idea what's going on and how I can get my component compiling I'd be grateful.
James
P.S. I transferred the project to a colleague's PC and they had the same issue so I doubt if it's anything to do with my setup (Windows 8.1 x64, Visual Studio 2013 Ultimate).
I've managed to figure this out myself.
It seems as though there is a bug when using string[] (or other arrays) as the generic type for IAsyncOperation.
I have managed to work around this because actually I will want to return IDictionary objects and ILists, which work fine:
/* //Won't Work - crashes Windows Metadata Exporter
public IAsyncOperation<string[]> GetThings()
{
return GetThingsAsync().AsAsyncOperation();
}
private async Task<string[]> GetThingsAsync()
{
return new [] {"I am a string"};
}
*/
//This Works
public IAsyncOperation<IList<string>> GetThingsList()
{
return GetThingsListAsync().AsAsyncOperation();
}
private async Task<IList<string>> GetThingsListAsync()
{
return new[] { "I am a string" };
}
Hopefully this will be of use to anyone else who comes across this weird behaviour.
I need to send a stub response over http to a requesting client from Jetty. It works when I run the Junit test independently, implies, I get the correct XML response .. but it fails when I run the same thing from maven. The error I see is "java.net.SocketException: Unexpected end of file from server". I have tried everything! Please help!
Here's my code -
Junit (when run as a Junit test - it works)
public class MyTest {
#Test
public void testGetOpenLots() throws Exception {
// create fixture
MyService fixture = new MyService();
// create jetty server instance
Server server = new Server(8080);
// set a handler
server.setHandler(new HelloHandler());
// set shutdown conditions
// server.setStopAtShutdown(true);
// start server
server.start();
// invoke operation
MyResponse result = fixture.getWeather(someDummyRequest);
assertNotNull(result);
}
}
Somewhere down the line, inside getWeather(), I create a URL object and pass the URL http://localhost:8080 to it and send the request to that URL. At this point, I expect that the HelloHandler's handle method will get invoked and will write this dummy XML response to stream and getWeather() method will receive the response.
Here's the handler:
public class HelloHandler extends AbstractHandler {
public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("application/xml;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<result>a simple response</result>");
}
}
When I run the same thing from maven, it throws the error mentioned above. What am I doing wrong?
Instead of implementing your own jetty handler you can try Jadler (http://jadler.net), an http stubbing/mocking library I've been working on for a while.
I have several WebMethods involving sql, when I call a method it sends a soapException involving the com.mysql.jdbc.driver
This is my connection method (it is not a web method but it is on the web service class along with the rest of the web methods)
public Connection connect() throws Exception
{
if (con == null)
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ProyectGameSmart","root","root");
}
return con;
}
This is one of the web methods that need to get a connection instance
public int insert_publisher(String pub, String phone, String addr) throws Exception
{
int ResultValue = 0;
connect();
query="INSERT INTO ProyectGameSmart.Publisher(Publisher,Phone,Address)VALUES('"+pub+"','"+phone+"','"+addr+"');";
pstmt = con.prepareStatement(query);
ResultValue = pstmt.executeUpdate();
return ResultValue;
}
Can anyone help me on how to implement a web service involving sql connection. I have only been able to find web services with simple math methods. I'm using Eclipse and Tomcat 7.
Thank you in advance
If your code is working locally, I mean without running as a web service. Then You have to put the correct version of the mysql JDBC driver in to your classpath of the web services server. Here Tomcat lib folder. That will solve th problem.
I've read a lot of examples/tutorials (incl. Ayende's Alexandria on MSDN).
But just getting somewhat updated assemblies have proven to be an obstacle in itself. After getting the correct version of Castle.Windsor - it cannot find the correct section in the app.config file. The syntax in both Rhino Service Bus and the CastleBootstrapper has been changed as well - and I'm now totally confused. The 'documentation' on Hibernating Rhinos is really not helping me get started.
Could anyone please help me a working sample with Rhino Service Bus with either Castle Windsor v. 3.0 (beta) or 2.5.3, point me at something already online or just giving me a step-by-step pointers on what I need to get up and running?
after downloading the latest Rhino-ESB bits from github (https://github.com/hibernating-rhinos/rhino-esb) and building it, it's pretty straightforward to get started.
I have a asp.net MVC application which communicates with a backend through Rhino-ESB.
On the asp.net MVC side:
On global.asax.cs:
private IWindsorContainer _container;
protected void Application_Start()
{
_container = new WindsorContainer();
new RhinoServiceBusConfiguration().UseCastleWindsor(_container).Configure();
_container.Install(new YourCustomInstaller());
//Don't forget to start the bus
_container.Resolve<IStartableServiceBus>().Start();
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_container));
}
Note that YourCustomInstaller must implement IWindsorInstaller and you register your controllers with the container in the Installmethod:
public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
{
container.Register(Component
.For<HomeController>().LifeStyle.PerWebRequest.ImplementedBy<HomeController>());
Also note that the WindsorControllerFactory internally delegates controller creation to the container:
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
return null;
return (IController)this.container.Resolve(controllerType);
}
Last but not least, provide the configuration on your web.config
<configSections>
<section name="rhino.esb" type="Rhino.ServiceBus.Config.BusConfigurationSection, Rhino.ServiceBus"/>
</configSections>
<rhino.esb>
<bus threadCount="1"
numberOfRetries="5"
endpoint="rhino.queues://localhost:31316/Client"
queueIsolationLevel="ReadCommitted"
name="Client"/>
<messages>
<add name="YourMessagesNamespace"endpoint="rhino.queues://localhost:31315/Backend"/>
</messages>
</rhino.esb>
This configuration assumes that the backend runs a queue in localhost:31315 and the client runs its queue on localhost:31316.
On the backend side:
assuming we're running it as a console application,
static void Main(string[] args)
{
IWindsorContainer container;
container = new WindsorContainer();
new RhinoServiceBusConfiguration()
.UseCastleWindsor(container)
.Configure();
var host = new RemoteAppDomainHost(typeof(YourBootstrapper));
host.Start();
Console.WriteLine("Starting to process messages");
Console.ReadLine();
Notice that YourBootstrapperclass implements CastleBootstrapper
public class YourBootstrapper: Rhino.ServiceBus.Castle.CastleBootStrapper
{
protected override void ConfigureContainer()
{
Container.Register(Component.For<OneOfYourMessages>());
}
}
in which we're registering a consumer for OneOfYourMessages