calling a https api from another web api - asp.net-web-api

I am attaching the below piece of code which works perfectly fine in localhost but throws web exception/socket when hosted in IIS on another server.
System.Net.Sockets.SocketException (0x80004005): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 40.113.232.243:443
It was throwing the same error in local too, unless I added this line-
httpWebRequest.Proxy = WebRequest.GetSystemWebProxy();
yet it throws socketexception when hosted in iis server.
public async Task<string> Get()
{
try
{
string uri = "https://hp-reporting-*****.azurewebsites.net/********";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Timeout = 600000;
httpWebRequest.Proxy = WebRequest.GetSystemWebProxy(); // adding this line resolved error in local but still same issue persists when hosted in iis in another server
httpWebRequest.Method = "GET";
HttpWebResponse httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = streamReader.ReadToEnd();
// this is your code here...
System.Xml.Linq.XNode node = JsonConvert.DeserializeXNode(response, "Root");
return node.ToString();
}

well, look at what that line does : https://learn.microsoft.com/en-us/dotnet/api/system.net.webrequest.getsystemwebproxy?view=netframework-4.7.2
On your local machine, you have a web proxy defined in Internet Explorer which you use when making the call. On the deployed IIS you clearly don't have it.
So, either you setup the server exactly how you setup your local machine or find another way to solve this issue locally, without using that local proxy. When you get it working, then you deploy again and it will work.

Related

System.Net.Http.HttpRequestException 'No route to host' on local network address?

I am trying to connect to one of mine IOT ESP32 based web server from Xamarin Android native based project with the following code:
client = new HttpClient();
Uri uri = new Uri( "http://192.168.0.5/sensors" );
client.Timeout = TimeSpan.FromSeconds(10);
HttpResponseMessage response = client.GetAsync( uri ).GetAwaiter().GetResult();
if( response.IsSuccessStatusCode )
{
string content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
Yet seems like the timout is ignored, and with or without it I am receiving
System.Net.Http.HttpRequestException: 'No route to host'
How to properly connect from Xamarin Android native app to an address inside my local network ?
What is causing this exception ?
The network is all fine, and the server is reachable from practically any other OS, including microcontrollers within it except Android.
Found workaround - redirecting port from the router to the server, and using external IP on this port seems like working.

RavenDB domain error

I have set up an instance of RavenDB on IIS. I can connect to it just fine using a network service application, however when I try and connect then initialize using an application running under local administrator I get an error "Unable to determine the identity of domain". The only thing I can think of is trying to impersonate "Network Service", but I am not sure if that is possible. The administrator has full rights to raven web folder.
Figured out this problem. I had to run my Raven document store connect and initialize in a different application domain. I ended up doing this.
string pathToDLL = installerFolder + "\\RavenSiteSetup.dll";
AppDomainSetup domainSetup = new AppDomainSetup {
ApplicationBase = installerFolder,
PrivateBinPath = pathToDLL
};
Evidence ev1 = new Evidence();
ev1.AddAssemblyEvidence(new ApplicationDirectory(
typeof(RavenSetup).Assembly.FullName)
);
ev1.AddHostEvidence(new Zone(SecurityZone.Internet));
AppDomain ad = AppDomain.CreateDomain("RavenSetup", ev1, domainSetup,
Assembly.GetExecutingAssembly().PermissionSet,null);
IIdentity identity = new GenericIdentity("RavenSetup");
IPrincipal principal = new GenericPrincipal(identity, null);
ad.SetThreadPrincipal(principal);
RavenSetup remoteWorker = (RavenSetup)ad.CreateInstanceFromAndUnwrap(
pathToDLL,
typeof(RavenSetup).FullName);
remoteWorker.Connect(sitePath);
Connecting locally, are you using http://localhost:[port]? I've had problems using the domain name locally.
Try running your application locally and connect to the RavenDB via locahost address.

Communication between C# running on Windows and C running on linux with protobuf

I have a server application running on Linux. This application was
developed using protobuf c and protobuf.rpc.c files for RPC communication.
I have a client application which was running on windows.It was developed in c# using protobuf-net.dll and ProtobufRemote.dll for RPC communication.Both application using the same proto file having same service methods.
I can able to create a proxy from C# client application with the below code.
using System.Configuration;
using System.Net.Sockets;
using ProtoBufRemote; // rpc reference
using StarCall; // proto file
#region Create client connection
Int32 port = Convert.ToInt32(ConfigurationManager.AppSettings["PORT"]);
TcpClient tcpClient = new TcpClient(ConfigurationManager.AppSettings["SERVERIP"].ToString(), port);
var controller = new RpcController();
var client = new RpcClient(controller);
var channel = new NetworkStreamRpcChannel(controller, tcpClient.GetStream());
channel.Start();
var service = client.GetProxy<Istarcall_services>();
if (service == null)
Console.WriteLine("error creating client..");
//now calls can be made, they will block until a result is received
Console.WriteLine("Client connected to Server....\n");
#endregion
But whenever I am trying to invoke a service method from C# client application as shown below, the application is hanging and not getting any response from Linux c server application.
try
{
Room_Config room = new Room_Config();
room.Room_Dial_Num = 1;
Room_Config roomRet = service.read_room(room); // service method
}
catch (Exception)
{
throw;
}
The application is hanging in the below code.
protected RpcMessage.Parameter EndAsyncCallHelper(string methodName, IAsyncResult asyncResult)
{
PendingCall pendingCall = (PendingCall)asyncResult;
pendingCall.AsyncWaitHandle.WaitOne(); // application hanging here
pendingCall.AsyncWaitHandle.Close();
if (pendingCall.IsFailed)
throw new InvalidRpcCallException(serviceName, methodName,
String.Format("Server failed to process call, returned error message: \"{0}\".",
pendingCall.ServerErrorMessage));
return pendingCall.Result;
}
According to above mentioned scenarios, I have the following queries.
Whether this protobuf remote c# dll can help to create a communicatgion from the linux c code. If not please help me how to create a communication channel with the linux c code.
Please provide if any alternative rpc dll for c# client application to communicate to linux protobuf c and protobuf rpc.c file.
Please tell me if my above approach is wrong and rectify with the suitable solution.
Please help me out. If not clear please send to mail mentioned below.
Have you implemented your server in Linux with ProtoBufRemote cpp available at https://code.google.com/p/protobuf-remote/ ??
If yes, then you must have replaced or modified SocketRpcChannel.cpp class as it is using WinSock2 that is not applicable on Linux.
Have you done so? If yes, please share modified SocketRpcChannel class that you have used in your server.
Thank you.

bits , sharpBits.net

I using in my project BITS - Background Intelligent Transfer Service for send file with larg size. Using SharpBITS.NET in C# code.
I want to upload file from server to client. I now note the sides.
-------------client side---------------
static void Main(string[] args)
{
string local = #"I:\a.mp3";
string destination = "http://192.168.56.128/BitsTest/Home/FileUpload";
string remoteFile = #destination;
string localFile = local;
if (!string.IsNullOrEmpty(localFile) && System.IO.File.Exists(localFile))
{
var bitsManager = new BitsManager();
var job = bitsManager.CreateJob("uploading file", JobType.Upload);
job.NotificationFlags = NotificationFlags.JobErrorOccured | NotificationFlags.JobModified |
NotificationFlags.JobTransferred;
job.AddFile(remoteFile, localFile);
job.Resume();
job.OnJobError += new EventHandler<JobErrorNotificationEventArgs>(job_OnJobError);
}
}
This is a simple console application. the local -- path the file that I want to send, destination -- the path is receiver it is remote server.
When I run program the job.Error take mi follow --- "The server's response was not valid. The server was not following the defined protocol. Resume the job, and then Background Intelligent Transfer Service (BITS) will try again. -- BG_E_HTTP_ERROR_200 .-2145845048, 0x801900C8"
For Client (receiver) i have the follow code: It is Mvs 3 small project and I View only action
where to go by our destination path.
public ActionResult FileUpload()
{
try
{
HttpPostedFileBase file = Request.Files[0];
file.SaveAs(System.IO.Path.Combine(Server.MapPath("/BitsTest/"), file.FileName));
}
catch
{ }
/*System.IO.File.Move(Server.MapPath("/BitsTest/bin/aa.png"), Server.MapPath("/BitsTest/Content/aa.png"));*/
}
But FileUpload action thas not recevie file. I don't know how I can receive file in client Side.
As you can see, I used HttpPostedFileBase for recive file but that is not working.
My host server is Windows server 2008 r2 and I done needed steps for BITS. For more information you can visit the follow site http://technet.microsoft.com/en-us/library/cc431377.aspx ---- How to Configure Windows Server 2008 for Configuration Manager 2007 Site Systems.
So I don't know what doing that I can receive file in host server.You can tell me what you can do.
With a stateless methdology like the one web applications use, there is no connection to the server once the response is completed. You can poll the server from the client side, but the client is not listening for the server to send additional bits.
In "the past" you could set up ActiveX controls, Java applets, etc (Silverlight today?) to continue to listen, but this is not straight web style development.
HTML5 expands your options, if you are willing to use the websocketAPI. As with all parts of HTML5, you have some risk using these bits for implementation as not all browsers have adopted the "standard" yet (adoption expected to be complete in the next 10-12 years:->).

Get Proxy configuration before accessing an external webservice (.NET 2.0)

When trying to invoke a method on an external webservice (over the Internet) it throws me
"The remote server returned an error: (407) Proxy Authentication Required."
To solve this, I used the following code to set the proxy we use in the office:
//Set the system proxy with valid server address or IP and port.
System.Net.WebProxy pry = new System.Net.WebProxy("MyHost", 8080);
//The DefaultCredentials automically get username and password.
pry.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Net.WebRequest.DefaultWebProxy = pry;
That works fine, but now... I need to do that "less harcoded" trying to get the information from my system instead of setting that manually.
This will use whatever the default proxy is for IE I believe (not deprecated):
Services.MyService service = new Services.MyService();
service.UseDefaultCredentials = true;
service.Proxy = new System.Net.WebProxy();
service.Proxy.Credentials = service.Credentials;
System.Net.WebProxy.GetDefaultProxy() although VS cautions its been deprecated.

Resources