Google Maps Works on Localhost, Fails in IIS - asp.net

I have a google map application that runs perfectly fine on local host. When I publish the application on IIS, the google api key v2 returns a 404 error.
I do not have google key, I am running without a key on a .net 4.0 Framework. Is the error because of a setting in IIS or I would need a key to query google REST API.
Below is an excerpt of my code -
private string GetLatitudeLongitudeFromAddress(string url)
{
string latitudeLongitude = string.Empty;
WriteToFile(path, "Entering GetLatitudeLongitudeFromAddress - url in parameter = "+url);
try
{
WebResponse response = null;
bool is_geocoded = true;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
//WriteToFile(path, "request response = " + request.GetResponse().ToString());
response = request.GetResponse();
WriteToFile(path, "response returned = "+response.ToString());
string lat = "";
string lng = "";
string loc_type = "";
if (response != null)
{
XPathDocument document = new XPathDocument(response.GetResponseStream());
XPathNavigator navigator = document.CreateNavigator();
// get response status
XPathNodeIterator statusIterator = navigator.Select("/GeocodeResponse/status");
while (statusIterator.MoveNext())
{
if (statusIterator.Current.Value != "OK")
{
is_geocoded = false;
}
}
// get results
if (is_geocoded)
{
XPathNodeIterator resultIterator = navigator.Select("/GeocodeResponse/result");
while (resultIterator.MoveNext())
{
XPathNodeIterator geometryIterator = resultIterator.Current.Select("geometry");
while (geometryIterator.MoveNext())
{
XPathNodeIterator locationIterator = geometryIterator.Current.Select("location");
while (locationIterator.MoveNext())
{
XPathNodeIterator latIterator = locationIterator.Current.Select("lat");
while (latIterator.MoveNext())
{
lat = latIterator.Current.Value;
//Console.WriteLine("Latitude value = {0}", lat);
latitudeLongitude = lat;
}
XPathNodeIterator lngIterator = locationIterator.Current.Select("lng");
while (lngIterator.MoveNext())
{
lng = lngIterator.Current.Value;
//Console.WriteLine("Longitude value = {0}", lng);
latitudeLongitude = latitudeLongitude + "#" + lng;
}
XPathNodeIterator locationTypeIterator = geometryIterator.Current.Select("location_type");
while (locationTypeIterator.MoveNext())
{
loc_type = locationTypeIterator.Current.Value;
}
}
}
}
//Console.ReadLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error in Calculating Coordinates Address - {0}", ex.Message + "GetLatitudeLongitudeFromAddress");
}
WriteToFile(path, "Exiting GetLatitudeLongitudeFromAddress - value returned = "+ latitudeLongitude);
return latitudeLongitude;
}

developer license is not guaranteed to have high availability, so maybe that's the reason of why you're getting 404's.

Related

Issue with loading dicom images in WADO loader

I am working on a web based OHIF Dicom viewer. I am using clear canvas as my PACs server. So I developed one broker application in .net core which works like WADO-RS and supply information to OHIF viewer from clear canvas. In my broker application I am passing metadata to OHIF viewer in json format by using FO-dicom json converter which converts dcm file into Json string.
My code for sending metadata:
var files = Directory.GetFiles(directory);
List<JObject> lstjo = new List<JObject>();
JObject jo;
foreach (var file in files)
{
var dicomDirectory = DicomFile.Open(file, FileReadOption.ReadAll);
if (dicomDirectory.Dataset.InternalTransferSyntax.UID.UID != DicomTransferSyntax.ImplicitVRLittleEndian.UID.UID)
{
var transcoder = new DicomTranscoder(dicomDirectory.Dataset.InternalTransferSyntax, DicomTransferSyntax.ImplicitVRLittleEndian);
dicomDirectory = transcoder.Transcode(dicomDirectory);
}
JsonDicomConverter dicomConverter = new JsonDicomConverter();
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter writer = new JsonTextWriter(sw);
Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
dicomConverter.WriteJson(writer, dicomDirectory.Dataset, serializer);
jo = JObject.Parse(sb.ToString());
// jo.Property("7FE00010").Remove();
retJsonstring += jo.ToString() + ",";
}
if (retJsonstring.Length > 6)
{
retJsonstring = retJsonstring.Substring(0, retJsonstring.Length - 1) + "]";
}
else
{
retJsonstring += "]";
}
retJsonstring = retJsonstring.Replace("\r", "").Replace("\n", "");
}
return retJsonstring;
During passing metadata there is no issue in Ohif viewer. After then OHIF viewer sending WADORS request for frames to display. My broker application also send responding for that request in multipart.
My code for sending Multipart response :
{
var dicomFile = DicomFile.Open(path, FileReadOption.ReadAll);
string transfersyntax = dicomFile.Dataset.InternalTransferSyntax.UID.UID;
MemoryStream streamContent = new MemoryStream();
if (transfersyntax != DicomTransferSyntax.ImplicitVRLittleEndian.UID.UID)
{
var transcoder = new DicomTranscoder(dicomFile.Dataset.InternalTransferSyntax, DicomTransferSyntax.ImplicitVRLittleEndian);
dicomFile = transcoder.Transcode(dicomFile);
}
dicomFile.Save(streamContent);
DicomImage img = new DicomImage(dicomFile.Dataset, 0);
streamContent.Seek(0, SeekOrigin.Begin);
string boundary = Guid.NewGuid().ToString();
MultipartContent multipartContent = new MultipartContent();
//newFile.Save(multipartContent.Stream);
multipartContent.Stream = streamContent;// File.OpenRead(path);
multipartContent.ContentType = "application/octet-stream";
multipartContent.transfersyntax = dicomFile.Dataset.InternalTransferSyntax.UID.UID;
multipartContent.FileName = "";
multiContentResult = new MultipartResult("related", boundary) { multipartContent };
return multiContentResult;
}
Mulitpart class and MulticontentResult Class:
public class MultipartContent
{
public string ContentType { get; set; }
public string FileName { get; set; }
public Stream Stream { get; set; }
public string transfersyntax { get; set; }
}
public class MultipartResult : Collection<MultipartContent>, IActionResult
{
private readonly System.Net.Http.MultipartContent content;
public MultipartResult(string subtype = "byteranges", string boundary = null)
{
if (boundary == null)
{
this.content = new System.Net.Http.MultipartContent(subtype);
}
else
{
this.content = new System.Net.Http.MultipartContent(subtype, boundary);
}
}
public async Task ExecuteResultAsync(ActionContext context)
{
foreach (var item in this)
{
if (item.Stream != null)
{
var content = new StreamContent(item.Stream);
if (item.ContentType != null)
{
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(item.ContentType);
content.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("transfer-syntax", item.transfersyntax));
}
this.content.Add(content);
}
}
context.HttpContext.Response.ContentLength = content.Headers.ContentLength;
context.HttpContext.Response.ContentType = content.Headers.ContentType.ToString();
await content.CopyToAsync(context.HttpContext.Response.Body);
}
}
After sending WAROrs response , I getting error in OHIF viewer in RangeError: offset is out of bounds in stackviewport.js during set pixeldata flat32array to scaledata flat32array like below Image
So I inspect in browser after then I come know that Pixel data size and scaledata size is different like below image..
To verify my dcm file I checked with ohif viewer by directly opened those file in https://v3-demo.ohif.org/local. It is opening properly.
So what are possible reason for this issue ? how to rectify?

Xamarin Http Request Timeout Issue

I have a mobile application based on Xamarin and a Web API based on .Net Core. Mobile app consumes methods of Web API via HttpClient. The code below is my base method to call any Web API method and the point is I want to set a timeout but could not achieved to set the exact timeout value whatever I have implemented. Tried Timespan.FromSeconds() or TimeSpan.FromMilliseconds() etc. When client makes a request to Web API, a loader is displayed to lock UI and removed after API response. Some clients gave me a feedback that the loader is displayed forever and request never ends. Maybe, the server is unreachable in this particular time or internet connection is broken for client etc. All I want to set a timeout and break the request and display an alert message to client. Of course, I googled and tried too much as mentioned but no result. If anyone can help me, will be appreciated.
public async Task<BaseResponseModel> Post(BasePostModel postModel)
{
var responseModel = new BaseResponseModel();
var json = postModel.ToString();
var jsonParam = new StringContent(json, Encoding.UTF8, "application/json");
var isPosted = true;
var clientHandler = new HttpClientHandler()
{
AllowAutoRedirect = true,
};
var url = GetURL(postModel.UrlKey);
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
ContractResolver = new DefaultContractResolver(),
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
var client = new HttpClient(clientHandler);
//client.Timeout = TimeSpan.FromSeconds(10);
//var cancellationTokenSource = new CancellationTokenSource();
//cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10));
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("X-Env", "MOBILE_API");
AttachToken(ref client, responseModel.Id);
try
{
if (Preferences.ContainsKey("UserJwtExprieDate"))
{
var expiryDate = Preferences.Get("UserJwtExprieDate", null);
if (DateTime.Now > DateTime.Parse(expiryDate))
{
Preferences.Remove("UserJwtExprieDate");
Preferences.Remove("HomePageInformation");
int index = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.Count - 1;
Page currPage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack[index];
if (currPage as SigninForFactorOne != null)
{}
else
{
App.LogoutUser();
}
}
else
{
var response = await client.PostAsync(url, jsonParam);
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
var resultModel = JsonConvert.DeserializeObject<BaseResponseModel>(result, settings);
if (resultModel.ErrorType == APIErrorTypes.NULL)
{
if (resultModel.IsSucceed)
{
responseModel.Data = resultModel.Data;
}
else
{
responseModel.Error = resultModel.Error;
}
responseModel.Message = resultModel.Message;
}
else
{
responseModel.Error = "Token Expried Date.";
Preferences.Remove("UserJwtExprieDate");
Preferences.Remove("HomePageInformation");
App.LogoutUser();
}
}
else
{
new AppException(new Exception("HTTP Client response is not succeed!"), responseModel.Id);
isPosted = false;
}
}
}
else
{
var response = await client.PostAsync(url, jsonParam);
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
var resultModel = JsonConvert.DeserializeObject<BaseResponseModel>(result, settings);
if (resultModel.ErrorType == APIErrorTypes.NULL)
{
if (resultModel.IsSucceed)
{
responseModel.Data = resultModel.Data;
}
else
{
responseModel.Error = resultModel.Error;
}
responseModel.Message = resultModel.Message;
}
else
{
responseModel.Error = "Token Expried Date.";
Preferences.Remove("UserJwtExprieDate");
Preferences.Remove("HomePageInformation");
App.LogoutUser();
}
}
else
{
new AppException(new Exception("HTTP Client response is not succeed!"), responseModel.Id);
isPosted = false;
}
}
}
catch (Exception ex)
{
new AppException(ex, responseModel.Id, 500, "anonymous.user", "Unable to post data to API!");
isPosted = false;
}
finally
{
if (!isPosted)
{
responseModel.Error = AppConfiguration.GetSystemMessage(contactYourSystemAdministratorMessage);
responseModel.Message = AppConfiguration.GetSystemMessage(contactYourSystemAdministratorMessage);
}
}
return responseModel;
}
I've used the solution below to manually set a time-out which works fine.
internal class TimeOutHandler : DelegatingHandler
{
private readonly TimeSpan TimeOut;
public TimeOutHandler(TimeSpan timeOut) => TimeOut = timeOut;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage req, CancellationToken ct)
{
using (var ctTimeOut = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
ctTimeOut.CancelAfter(TimeOut);
try
{
return await base.SendAsync(req, ctTimeOut.Token);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
throw new TimeoutException();
}
}
}
}
How to use
var interval = TimeSpan.FromSeconds(10);
var handler = new TimeOutHandler(interval)
{
InnerHandler = new HttpClientHandler()
};
var client = new HttpClient(handler);
For more information, check out: https://thomaslevesque.com/2018/02/25/better-timeout-handling-with-httpclient/

Reverse proxy in .NET Core Middleware “set-cookie” response does not set in browser and not showing in HttpResponseMessage

Here I am making a reverse proxy server to bypass an ASP.NET web application (following this tutorial). I am trying to read the session ID cookie from HttpResponseMessage. I used a cookie container as well but am unable to find it. Implemented in ASP.NET core invoke method, session is working properly but unable to catch session ID in request or response.
public async Task Invoke(HttpContext context, IBrowserDetector detector)
{
//context.Session.SetString(SessionKeyName, "The Doctor");
var browser = detector.Browser;
var targetUri = BuildTargetUri(context.Request);
if (context.Request.Method != HttpMethod.Get.Method)
{
var remoteIp = context.Connection.RemoteIpAddress;
//var gg= context.Request.Headers.ContainsKey.;
var clienttdatetime = context.Request.Headers["Date"].ToString();
//_logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp);
var badIp = true;
var bytes = remoteIp.GetAddressBytes();
//var testIp = IPAddress.Parse(address);
//if (testIp.GetAddressBytes().SequenceEqual(bytes))
//{
// badIp = false;
// break;
//}
if (remoteIp.IsIPv4MappedToIPv6)
{
remoteIp = remoteIp.MapToIPv4();
}
IPAddress remoteIpAddress = context.Request.HttpContext.Connection.RemoteIpAddress;
string result = "";
if (remoteIpAddress != null)
{
// If we got an IPV6 address, then we need to ask the network for the IPV4 address
// This usually only happens when the browser is on the same machine as the server.
if (remoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
remoteIpAddress = System.Net.Dns.GetHostEntry(remoteIpAddress).AddressList
.First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
}
result = remoteIpAddress.ToString();
}
if (badIp)
{
//_logger.LogWarning(
// "Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
//context.Response.StatusCode = StatusCodes.Status403Forbidden;
//return;
}
}
if (targetUri != null)
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
var targetRequestMessage = CreateTargetMessage(context, targetUri);
using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
foreach (Cookie cookie_ in responseCookies)
Console.WriteLine(cookie_.Name + ": " + cookie_.Value);
// ExtractCookiesFromResponse(responseMessage);
context.Response.StatusCode = (int)responseMessage.StatusCode;
CopyFromTargetResponseHeaders(context, responseMessage);
await responseMessage.Content.CopyToAsync(context.Response.Body);
//if(responseMessage.RequestMessage.RequestUri.ToString()== "http://localhost:51125/Menu.aspx")
//{
//Uri uri = new Uri("http://localhost:5000/login.aspx");
//Build the request
//Uri site = targetUri;
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create(site);
// CookieContainer cookiesq = new CookieContainer();
// request.CookieContainer = cookiesq;
// //Print out the number of cookies before the response (of course it will be blank)
// Console.WriteLine(cookiesq.GetCookieHeader(site),"1");
// //Get the response and print out the cookies again
// using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
// {
// Console.WriteLine(cookiesq.GetCookieHeader(site), "2");
// }
// Console.ReadKey();
//}
var cookie = context.Request.Cookies["ASP.NET_SessionId"];
}
return;
}
await _nextMiddleware(context);
}
------------------------------------------------------------------------------------
public static IDictionary<string, string> ExtractCookiesFromResponse(HttpResponseMessage response)
{
IDictionary<string, string> result = new Dictionary<string, string>();
IEnumerable<string> values;
if (response.Headers.TryGetValues("Set-Cookie", out values))
{
SetCookieHeaderValue.ParseList(values.ToList()).ToList().ForEach(cookie =>
{
result.Add(cookie.Name.ToString(), cookie.Value.ToString());
});
}
return result;
}
As far as I can see, you created the HttpClientHandler but didn't use it to build the HttpClient to make your request. You are still using the static _httpClient that nothing knows about the cookie container you created.
This should be the reason why you get the CookieContainer still empty.
Take a look here to learn how to get cookies from an HttpResponseMessage.
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
_httpClient = new HttpClient(handler);
var targetRequestMessage = CreateTargetMessage(context, targetUri);
using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
//var responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
{
if(cookie.Name=="ASP.NET_SessionId")
{
Console.WriteLine(cookie.Name + ": " + cookie.Value);
context.Response.Headers.Add("Set-Cookie", cookie.Name+"="+cookie.Value);
}
}

J2ME App in Blackberry Network connectivity issue

I have developed a J2ME App which i tried in Blackberry device. Application launched successfully but when i am making a network call its throwing exception. Currently the Blackberry device which i own doesn't have BIS(Blackberry Internet Service) plan enabled. I am testing it in Blackberry OS version less than six.
Here is my Coding for HTTP Get Method
public static Vector httpGet(String uri, String param) {
Vector buf = new Vector();
try {
String parameter = param;
String url = uri + "?" + parameter;
System.out.println("Passed URL:" + uri + "?" + parameter);
HttpConnection hc = (HttpConnection) Connector.open(url);
hc.setRequestMethod(HttpConnection.GET);
Commons.print(hc.getResponseCode() + ":" + HttpConnection.HTTP_OK
+ ":" + hc.getResponseMessage());
if (hc.getResponseCode() >= 400) {
hc = null;
return null;
}
InputStream inn = hc.openInputStream();
if (inn == null)
return null;
DataInputStream in = new DataInputStream(inn);
String st = "";
while ((st = readLine(in)) != null) {
buf.addElement(st);
}
if (in != null) {
in.close();
}
if (hc != null) {
hc.close();
setStatus(DataMembers.okStatus);
}
} catch (Exception ex) {
System.out.println("Error:" + ex.toString());
setStatus(DataMembers.failStatus);
buf = null;
}
return buf;
}
Does Blackberry requires BIS connection for making a network call? I am not appending any manual connection String to my URL.

Quickbooks Http Web Request code gives 400 Server error

I am using Quickbooks V3 SDK.It was also giving 400 error as In October 2014 they had changed their link from https://quickbooks.api.intuit.com/ to sandbox.quickbooks.api.intuit.com/, after correcting I can fetch results and can perform crud operations using its mentioned classes.
ServiceContext serviceContext = getServiceContext(profile);
serviceContext.IppConfiguration.BaseUrl.Qbo = "https://sandbox-quickbooks.api.intuit.com/";
QueryService<Item> ItemQueryService = new QueryService<Item>(serviceContext);
return ItemQueryService.Select(c => c).ToList();
This code works perfectly.
But when i try to perform the same operation as JSON request with HTTP web request, it gives me 400 error.
I am pasting HTTP Web request code below.
HttpContext.Current.Session["serviceEndPoint"] = "https://qb.sbfinance.intuit.com/v3/company/" + profile.RealmId +"/item&query=select * from item"; //
OAuthConsumerContext consumerContext = OAuthCR();
OAuthSession oSession = OAuthSession(consumerContext);
oSession.ConsumerContext.UseHeaderForOAuthParameters = true;
oSession.AccessToken = new TokenBase
{
Token = profile.OAuthAccessToken,
ConsumerKey = "qyprdB0F3beIfmSTdvpLG5J46xPGm2",
TokenSecret = profile.OAuthAccessTokenSecret
};
IConsumerRequest conReq = oSession.Request();
conReq = conReq.Post();
conReq.AcceptsType = "application/json";
conReq = conReq.ForUrl(HttpContext.Current.Session["serviceEndPoint"].ToString());
string header = conReq.Context.GenerateSignatureBase();
try
{
string res = conReq.ReadBody();
}
catch (WebException we)
{
HttpWebResponse rsp = (HttpWebResponse)we.Response;
if (rsp != null)
{
try
{
using (StreamReader reader = new StreamReader(rsp.GetResponseStream()))
{
string res2 = rsp.StatusCode + " | " + reader.ReadToEnd();
}
}
catch (Exception)
{
string res = "Status code: " + rsp.StatusCode;
}
}
else
{
string res = "Error Communicating with Mock Service" + we.Message;
}
}
}
They have mentioned wrong url on their sdk which is https://qb.sbfinance.intuit.com/v3/company/xxxxxxxxx/
but correct one is
https://sandbox-quickbooks.api.intuit.com/v3/company/xxxxxxxxxx/

Resources