Xamarin Forms: IOS adhoc crashes but debug works - c#

I have a very strange problem, I programmed an app that triggers a webservice and gives me a response back. This also works on android and IOS (in debug mode) but when I install the app via adhoc it still works but when I press the button that triggers the webservice the app freezes and you have to restart it but it always stops at the same place.
I have found out with a lot of commenting and commenting out that the error happens in the marked place. In debug mode everything works as it should.
Here is the code that will be executed.
IsMYSite(strLink);
if (gotResponse)
{
gotResponse = false;
DetailPage.MYPages.Add(new MYPage { Title = portal, Link = strLink, Username = "", Password = "", IsVisible = false, CompanyImage = ImageLink });
App.Current.Properties["MYPages"] = JsonConvert.SerializeObject(DetailPage.MYPages);
App.Current.Properties["LastPortal"] = strLink;
Navigation.PopAsync(true);
LinkURL.TextColor = Color.Black;
}
else
{
LinkURL.TextColor = Color.Red;
}
public async void IsMYSite(String url)
{
try
{
String linkonly = url;
url += "/api/" + CultureInfo.CurrentUICulture.ThreeLetterWindowsLanguageName;
string strpost = "";
StringContent str = new StringContent(strpost, Encoding.UTF8, "application/x-www-form-urlencoded");
var client = new System.Net.Http.HttpClient();
client.Timeout = new TimeSpan(0, 0, 6);
client.BaseAddress = new Uri(url);
var response = await client.GetAsync(new Uri(url));
Dictionary<string, string> result = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);
portal = result["PortalTitle"];
if (result["LoginLogo_Path"].StartsWith("~"))
{
StringBuilder str2 = new StringBuilder(result["LoginLogo_Path"]);
str2.Remove(0, 1);
ImageLink = linkonly + str2.ToString();
gotResponse = true;
}
}
catch
{
}
}

Related

How to use an information sent on httpResponse?

I am learning about making requests to an api using my backend and when i make this i receive a response with some informations i want to use but i don't know how to use this.
Let me clarify this for you.
I HAVE THIS CODE TO MAKE THE REQUEST
try
{
//Set Basic Auth
var userPagarme = test_key;
var password = "";
var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userPagarme}:{password}"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var clienteToAdd = new PagarmeCliente()
{
Name = registerUser.Name,
Code = registerUser.Code,
Document = registerUser.Document,
Type = registerUser.Type,
Document_Type = registerUser.Document_Type,
Birthdate = registerUser.Birthdate,
Email = registerUser.Email,
Gender = registerUser.Gender,
Address = new PagarmeClienteEndereco()
{
city = registerUser.City,
country = registerUser.Country,
line_1 = registerUser.Line_1,
line_2 = registerUser.Line_2,
state = registerUser.State,
zip_code = registerUser.Zip_Code
},
Phones = new PagarmeClienteTelefone()
{
mobile_phone = new PagarmeClienteTelefoneMobile()
{
area_code = registerUser.Mobile_phone_area_code,
country_code = registerUser.Mobile_phone_country_code,
number = registerUser.Mobile_phone_number
},
}
};
var jsonString = JsonConvert.SerializeObject(clienteToAdd);
HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
this.responseBodyJSON = JsonConvert.DeserializeObject(responseBody); // I have created this prop as an OBJ to receive the obj that was sent. I don't know if it is correct
}
catch (HttpRequestException e)
{
return BadRequest("\nException Caught - Message :{0} " + e.Message);
}
That is what i have in this responseBodyJSON and i want to use this property ID to insert on my database but if i make something like this below it doesn't work:
string idThatIWant = responseBodyJSON.id... or something like that.
var jsonString = JsonConvert.SerializeObject(clienteToAdd);
HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);
You converted your model to JSON but you didn't use that jsonString. This could be the cause of the problem.
var respBody = JsonConvert.DeserializeObject<PagarmeCliente>(responseBody);
respBody.ID should be available if the class PagarmeCliente has the ID field you wanted populated.

Jira REST API returning HTML

I am trying to access the Jira rest API via C#. For that I am using the Windows.Web.Http.HttpClient. But all I get as a return value is HTML.
I am calling the following URL: https://jira.atlassian.com/rest/api/latest/field/
Little Edit
When I call the url from a browser it works fine, just the call from the HttpClient doesn't work.
Here is my code:
public async Task<IRestResponse> Execute(RestRequest request) {
var restResponse = new RestResponse();
var client = new HttpClient();
var req = new HttpRequestMessage(request.Method, new Uri(BaseUrl, UriKind.RelativeOrAbsolute));
foreach (var item in request.headers) {
req.Headers[item.Key] = item.Value;
}
req.Headers.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
if (this.Authenticator != null)
req.Headers["Authorization"] = this.Authenticator.GetHeader();
var res = await client.SendRequestAsync(req);
restResponse.Content = await res.Content.ReadAsStringAsync();
restResponse.StatusCode = res.StatusCode;
restResponse.StatusDescription = res.ReasonPhrase;
if (!res.IsSuccessStatusCode) {
restResponse.ErrorMessage = restResponse.Content;
restResponse.ResponseStatus = ResponseStatus.Error;
} else if (res.StatusCode == HttpStatusCode.RequestTimeout) {
restResponse.ResponseStatus = ResponseStatus.TimedOut;
} else if (res.StatusCode == HttpStatusCode.None) {
restResponse.ResponseStatus = ResponseStatus.None;
} else {
restResponse.ResponseStatus = ResponseStatus.Completed;
}
return restResponse;
}
I just found my problem, I don't add the relative path anywhere. It just calls the BaseUrl meaning https://jira.atlassian.com/ that explains why I get the HTML page.

Adaptive Payments giving Exception on Web Server in c#

I am working on Delayed Chained Payments Module in Adaptive Payments in Paypal. I am Using AdaptivePaymentsCoreSdk for it and it is working fine on LocalHost as well as one web Server. All working is going Fine. But when I Deploy my application on another Server than On Service.Pay I am Getting an Exception. Exception is as Follows:-
PayPal.Exception.ConnectionException: Invalid HTTP response The underlying connection was closed: An unexpected error occurred on a receive.
at PayPal.HttpConnection.Execute(String payLoad, HttpWebRequest httpRequest)
at PayPal.APIService.MakeRequestUsing(IAPICallPreHandler apiCallHandler)
at PayPal.BasePayPalService.Call(IAPICallPreHandler apiCallHandler)
at PayPal.AdaptivePayments.AdaptivePaymentsService.Pay(PayRequest payRequest, String apiUserName)
at PayPal.AdaptivePayments.AdaptivePaymentsService.Pay(PayRequest payRequest)
at Payme101.Controllers.HomeController.Order_Pay(Order_Pay single) in d:\Completed\Payme10\Payme101\Payme101\Controllers\HomeController.cs:line 2404
My Code is As Follows:-
PayRequest request = new PayRequest();
RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
ReceiverList receiverList = new ReceiverList();
request.requestEnvelope = requestEnvelope;
Receiver receiver1 = new Receiver();
receiver1.amount = 10;
receiver1.email = "Primary Email ID";
receiver1.primary = true;
receiver1.invoiceId = str;
Receiver receiver2 = new Receiver();
receiver2.amount = 8;
receiver2.email = SellerMail;
receiver2.primary = false;
receiver2.invoiceId = str;
receiverList.receiver.Add(receiver1);
receiverList.receiver.Add(receiver2);
request.receiverList = receiverList;
request.actionType = "PAY_PRIMARY";
request.currencyCode = "USD";
request.returnUrl = "http://ServerIP/Home/complete/?payKey=${payKey}";
request.cancelUrl = "http://ServerIP/Home/cancel?payKey=${payKey}";
//request.returnUrl = "http://localhost:1735/Home/complete/?payKey=${payKey}";
//request.cancelUrl = "http://localhost:1735/Home/cancel?payKey=${payKey}";
AdaptivePaymentsService service = null;
PayResponse response = null;
try
{
Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();
service = new AdaptivePaymentsService(configurationMap);
response = service.Pay(request);
}
catch (Exception ex)
{
//Here I am getting Exception.
return RedirectToAction("Order_Pay2", "Home", new { id = ex.ToString() });
}
Dictionary<string, string> responseValues = new Dictionary<string, string>();
string redirectUrl = null;
if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
{
redirectUrl = "https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_ap-payment&paykey=" + response.payKey;
return Redirect(redirectUrl);
}
Can Anybody tell me what I am doing wrong and What should i change to Remove this Exception And Make Payment Successfull.
Thanks in Advance...

Get request after a put or a post shows previous data instead of modified data?

The problem is that I do a GET request in the constructor(I call upon the method so every time that you enter the page the data is newly get from the database) and it gets the data from the database in a proper way. But after I modify the data and go back to page the data is still unmodified. The data changes in the database so the modify works but the GET request seems to get old data that is no longer in the database. How is this happening and how can I fix this? Thanks in advance!
public void getUserData()
{
RestClient client = new RestClient("http://localhost:8080/GigShare/webresources");
var request = new RestRequest("/user/{username}", Method.GET);
request.AddUrlSegment("username", "" + user.userName);
client.ExecuteAsync(request, response =>
{
getYourCarpools();
System.Diagnostics.Debug.WriteLine(modifyName.Text);
userget = (User) JsonConvert.DeserializeObject<User>(response.Content);
System.Diagnostics.Debug.WriteLine("GET");
System.Diagnostics.Debug.WriteLine(userget.name);
modifyName.Text = userget.Name;
modifySurname.Text = userget.surName;
modifyUsername.Text = userget.userName;
modifyTown.Text = userget.town;
modifyStreetName.Text = userget.streetName;
modifyHomenumber.Text = userget.homeNumber;
modifyProvince.Text = userget.province;
modifyEmail.Text = userget.email;
modifyCarBrand.Text = userget.car.brand;
modifyFuelType.Text = userget.car.fuelType;
modifySeats.Text = "" + userget.car.seats;
modifyavarageConsumption.Text = "" + userget.car.averageConsumption;
getCarData();
});
}
private void btnModifyCreateAccount_Click(object sender, RoutedEventArgs e)
{
User outputUser = dataFromUser();
var client = new RestClient()
{
BaseUrl = "http://localhost:8080/GigShare/webresources",
Authenticator = new HttpBasicAuthenticator("" + user.userId, user.password)
};
var request = new RestRequest("/user/id/{id}", Method.PUT);
request.AddUrlSegment("id", "" + user.userId);
request.RequestFormat = DataFormat.Json;
request.AddBody(outputUser);
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.NoContent)
{
// getUserData();
// NavigationService.Navigate(new Uri("/Views/NewlyAdded.xaml", UriKind.Relative));
System.Diagnostics.Debug.WriteLine("PUT");
}
else
{
System.Diagnostics.Debug.WriteLine("failmode");
}
});
}

How to click a button in an webpage

I'm using these code to download a file from the server.
The link of the server from where I need to download the file is:
http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx
var forms = new NameValueCollection();
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = ExtractVariable(s, "__VIEWSTATE");
forms["mTbdate"] = "12/22/2011";
forms["__EVENTVALIDATION"] = __EVENTVALIDATION;
forms["mImgBtnGo"] = "?";
forms["__EVENTTARGET"] = "btnLink_Excel";
webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
var responseData = webClient.UploadValues(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms);
System.IO.File.WriteAllBytes(#"c:\11152011.csv", responseData);
Its downloading the file of the given date in the textbox which is default in the website now.
I need to click a button called mImgBtnGo before, to download the file of the given date
in the mTbdate.
I don't know what I should do to click the button called mImgBtnGo .
What I should write here
forms["mImgBtnGo"] = "?";
using fiddler I think this is what you want:
class Program
{
static string Extract(string s, string tag)
{
var startTag = String.Format("id=\"{0}\" value=\"", tag);
var eaPos = s.IndexOf(startTag) + startTag.Length ;
var eaPosLast = s.IndexOf('"', eaPos);
return s.Substring(eaPos, eaPosLast-eaPos);
}
static void Main(string[] args)
{
WebClient webClient = new WebClient();
var firstResponse = webClient.DownloadString(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx");
var forms = new NameValueCollection();
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = Extract(firstResponse, "__VIEWSTATE");
forms["mTbdate"] = "12/22/2011";
forms["__EVENTVALIDATION"] = Extract(firstResponse, "__EVENTVALIDATION");
forms["mImgBtnGo.x"] = "10";
forms["mImgBtnGo.y"] = "10";
forms["ScriptManager1"] = "MupdPnl|mImgBtnGo";
// forms["__EVENTTARGET"] = "btnLink_Excel";
webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
String secondResponse = UTF8Encoding.UTF8.GetString(
webClient.UploadValues(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms)
);
forms = new NameValueCollection();
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = Extract(secondResponse, "__VIEWSTATE");
forms["mTbdate"] = "12/22/2011";
forms["__EVENTVALIDATION"] = Extract(secondResponse, "__EVENTVALIDATION");
// forms["mImgBtnGo"] = "?";
forms["__EVENTTARGET"] = "btnLink_Excel";
webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
var responseData = webClient.UploadValues(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms);
System.IO.File.WriteAllBytes(#"c:\prj\11152011.csv", responseData);
}
}

Categories