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/
Related
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/
When made I post request is made its giving internal server. Is the implementation of Flurl is fine or I am doing something wrong.
try
{
Models.PaymentPost paymentPost = new Models.PaymentPost();
paymentPost.Parts = new Models.Parts();
paymentPost.Parts.Specification = new Models.Specification();
paymentPost.Parts.Specification.CharacteristicsValue = new List<Models.CharacteristicsValue>();
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue { CharacteristicName = "Amount", Value = amount });
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue { CharacteristicName = "AccountReference", Value = accountId });
foreach (var item in extraParameters)
{
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue {
CharacteristicName = item.Key, Value = item.Value });
}
var paymentInJson = JsonConvert.SerializeObject(paymentPost);
var selfCareUrl = "http://svdt5kubmas01.safari/auth/processPaymentAPI/v1/processPayment";
var fUrl = new Flurl.Url(selfCareUrl);
fUrl.WithBasicAuth("***", "********");
fUrl.WithHeader("X-Source-System", "POS");
fUrl.WithHeader("X-Route-ID", "STKPush");
fUrl.WithHeader("Content-Type", "application/json");
fUrl.WithHeader("X-Correlation-ConversationID", "87646eaa-2605-405e-967c-56e8002b5");
fUrl.WithHeader("X-Route-Timestamp", "150935");
fUrl.WithHeader("X-Source-Operator", " ");
var response = await clientFactory.Get(fUrl).Request().PostJsonAsync(paymentInJson).ReceiveJson<IEnumerable<IF.Models.PaymentPost>>();
return response;
}
catch (FlurlHttpException ex)
{
dynamic d = ex.GetResponseJsonAsync();
//string s = ex.GetResponseStringAsync();
return d;
}
You don't need to do this:
var paymentInJson = JsonConvert.SerializeObject(paymentPost);
PostJsonAsync just takes a regular object and serializes it to JSON for you. Here you're effectively double-serializing it and the server is probably confused by that format.
You're also doing a lot of other things that Flurl can do for you, such as creating those Url and client objects explicitly. Although that's not causing errors, this is how Flurl is typically used:
var response = await selfCareUrl
.WithBasicAuth(...)
.WithHeader(...)
...
.PostJsonAsync(paymentPost)
.ReceiveJson<List<IF.Models.PaymentPost>>();
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.
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.
Trying to implement a WebRequest and return to the caller synchronously.
I have tried various implementations and I think this would be the most appropriate so far.
Unfortunately the following code throws an InvalidOperationException with the message
EndGetResponse can only be called once for each asynchronous operation
I really struggled enough to make this happen and its really vital to the library I build to use the WebRequest like this.
The following code is intend to use in Windows Phone 8 and Windows 8 platforms.
I already understand the async/await pattern and used it, but it is REALLY vital for me to use the synchronous version of the web service request in a part of my library.
The code:
public void ExecuteRequest(string url, string requestData)
{
WebRequest request = WebRequest.Create(new Uri(url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["Header-Key"] = "AKey";
DTOWebRequest webRequestState = new DTOWebRequest
{
Data = requestData,
Request = request
};
ManualResetEventSlim resetEventSlim = new ManualResetEventSlim(false);
// Begin the request using a delegate
request.BeginGetRequestStream(ar =>
{
DTOWebRequest requestDataObj = (DTOWebRequest )ar.AsyncState;
HttpWebRequest requestStream = (HttpWebRequest)requestDataObj.Request;
string data = requestDataObj.Data;
// Convert the string into a byte array.
byte[] postBytes = Encoding.UTF8.GetBytes(data);
try
{
// End the operation
using (Stream endGetRequestStream = requestStream.EndGetRequestStream(ar))
{
// Write to the request stream.
endGetRequestStream.Write(postBytes, 0, postBytes.Length);
}
// Get the response using a delegate
requestStream.BeginGetResponse(result =>
{
DTOWebRequest requestDataObjResult = (DTOWebRequest )ar.AsyncState;
HttpWebRequest requestResult = (HttpWebRequest)requestDataObjResult.Request;
try
{
// End the operation
using (HttpWebResponse response = (HttpWebResponse)requestResult.EndGetResponse(ar)) // Here the exception is thrown.
{
HttpStatusCode rcode = response.StatusCode;
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
// The Response
string responseString = streamRead.ReadToEnd();
if (!string.IsNullOrWhiteSpace(requestDataObjResult.FileName))
{
FileRepository fileRepo = new FileRepository();
fileRepo.Delete(requestDataObjResult.FileName);
}
Debug.WriteLine("Response : {0}", responseString);
}
}
catch (WebException webEx)
{
WebExceptionStatus status = webEx.Status;
WebResponse responseEx = webEx.Response;
Debug.WriteLine(webEx.ToString());
}
resetEventSlim.Set(); // Signal to return handler
}, requestDataObj);
}
catch (WebException webEx)
{
WebExceptionStatus status = webEx.Status;
WebResponse responseEx = webEx.Response;
Debug.WriteLine(webEx.ToString());
}
}, webRequestState);
resetEventSlim.Wait(5000); // Wait either for Set() or a timeout 5 secs.
}
}
Thank you.
You can't do synchronous web calls in Windows Phone and that's why you aren't.
If you were, you'd be calling GetRequestStream instead of BeginGetRequestStram/EndGetRequestStream.
The only reason to be synchronous on Windows Phone is to block the UI which is a very bad idea.
You should use an HttpClient and àsync-await` instead.
But if you really think you should (and can) do asynchronous calls on Windows Phone, you can always try something like this:
public void ExecuteRequest(string url, string requestData)
{
try
{
WebRequest request = WebRequest.Create(new Uri(url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["Header-Key"] = "AKey";
// Convert the string into a byte array.
byte[] postBytes = Encoding.UTF8.GetBytes(requestData);
using (var requestStream = request.EndGetRequestStream(request.BeginGetRequestStream(null, null)))
{
// Write to the request stream.
endGetRequestStream.Write(postBytes, 0, postBytes.Length);
}
using (var response = request.EndGetResponse(request.BeginGetResponse(null, null)))
{
using (var streamRead = new StreamReader(response.GetResponseStream()))
{
// The Response
string responseString = streamRead.ReadToEnd();
if (!string.IsNullOrWhiteSpace(requestDataObjResult.FileName))
{
var fileRepo = new FileRepository();
fileRepo.Delete(request.FileName);
}
Debug.WriteLine("Response : {0}", responseString);
}
}
}
catch (WebException webEx)
{
WebExceptionStatus status = webEx.Status;
WebResponse responseEx = webEx.Response;
Debug.WriteLine(webEx.ToString());
}
}
But I really think you should revise your decision/need.