Getting update issue in recent times in Android xamarin - xamarin.forms

Installed version and Appstore version seems to be same but in last few days we are facing force update in our app randomly
var version = await Task.Run(async () =>
{
var uri = new Uri($"https://play.google.com/store/apps/details?id={PackageName}&hl=en");
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Get, uri))
{
request.Headers.TryAddWithoutValidation("Accept", "text/html");
request.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
request.Headers.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
using (var response = await client.SendAsync(request).ConfigureAwait(false))
{
try
{
response.EnsureSuccessStatusCode();
var responseHTML = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var rx = new Regex(#"(?<=""htlgb"">)(\d{1,3}\.\d{1,3}\.{0,1}\d{0,3})(?=<\/span>)", RegexOptions.Compiled);
MatchCollection matches = rx.Matches(responseHTML);
return matches.Count > 0 ? matches[0].Value : "Unknown";
}
catch
{
return "Error";
}
}
}
}
);
When matches returns unknown because matches count sometime getting 0 values Can anyone facing this issue and how could resolve this issue. Thanks Advance.

Related

How can I make proper request for the Identity Server Token Endpoint?

I tried to send an api call to the identity server via .net 6 console application.
Here is the request:
public static async Task<WorkflowResponse> PostRequestToIdentityAsync()
{
var url = "http://didentity/connect/token";
IdentityRequestDataVM identityRequestDataVM = new IdentityRequestDataVM();
identityRequestDataVM.username = "csm";
identityRequestDataVM.password = "MjAyMjox";
identityRequestDataVM.grant_type = "password";
identityRequestDataVM.scope = "m_gln m_msd";
string jsonString = JsonConvert.SerializeObject(identityRequestDataVM);
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Content = new StringContent(jsonString),
Headers =
{
{"X-Login","override"}
}
};
var user = "gclt";
var password = "glsrt";
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes($"{user}:{password}")));
HttpResponseMessage message = await httpClient.SendAsync(request);
if (message.StatusCode == System.Net.HttpStatusCode.OK)
{
var contents = await message.Content.ReadAsStringAsync();
WorkflowResponse workflowResponse = JsonConvert.DeserializeObject<WorkflowResponse>(contents);
return workflowResponse;
}
else
{
throw new Exception(await message.Content.ReadAsStringAsync());
}
}
}
But, it returned 400 err code (Bad request), is there any mistake in the code snippet ?
It is working fine with postman.

How to send file with HttpClient post in xamarin forms

I want to send file through post request using httpclient
this what i tried but file didn't sent , when i tried in postman it works fine
string Url = $"http://ataprojects.net/test/products.php?request_type=add&company_name={BaseService.Company}&name={product.name}&barcode={product.barcode}&buy_price={product.buy_price}&sell_price={product.sell_price}";
try
{
using (HttpClient client = new HttpClient())
{
var content = new MultipartFormDataContent();
content.Headers.ContentType.MediaType = "multipart/form-data";
content.Add(new StreamContent(product._mediaFile.GetStream()),
"image",
product.image);
var response = client.PostAsync(Url, content).Result;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
var contentdata = await response.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<AddProductReturnModel>(contentdata);
return Items;
}
else
{
return null;
}
}
}
what's the problem ?
Try This Code
var content = new MultipartFormDataContent();
content.Add(new StreamContent(product._mediaFile.GetStream()),
"\"file\"",
$"\"{product._mediaFile.Path}\"");

esp8266 byethost Error get request

Good morning, I want to send data by get through esp8266, I have a qualifying account in byethost and I also have a hosting account paid with another hosting provider, but with byethost I get the following error:
AT+CIPSTART="TCP","ahorrodeenergy.byethost17.com",80
AT+CIPSEND=67
GET /inserta.php HTTP/1.1
Host:ahorrodeenergy.byethost17.com/inserta.php"
+IPD,1080:HTTP/1.1 200 OK
Server: nginx
Date: Fri, 10 Mar 2017 01:30:09 GMT
Content-Type: text/html
Content-Length: 851
Connection: keep-alive
Vary: Accept-Encoding
Expires: THu, 01 Jan 1970 00:00:01 GMT
Cache-Control: no-cache
And returns: This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support
Spoof the User-Agent string. It probably tries to identify your browser by that, and then tries to figure out if you have JavaScript enabled. It could then try to use more active tests, like inserting a piece of JavaScript and expect a page to be called with the result of the computation of that javascript, in a challenge-and-response manner. But I think a User-Agent spoof should just work fine. Do the following:
AT+CIPSTART="TCP","ahorrodeenergy.byethost17.com",80
AT+CIPSEND=154
GET /inserta.php HTTP/1.1
Host: ahorrodeenergy.byethost17.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0
+IPD,1080: ..
(number in CIPSEND assumes \r\nbeing used as newline)
Based on the this awnser, the problem is testcookie-nginx-module which is used by byethost, and here the solution:
/*
Author: Moien007
Source: https://gist.github.com/moien007/06656aa4032c45b629a507dd4dcb6fd6
Description:
Bypass testcookie-nginx-module bot protection
Web host providers like Byethost uses that module so...
*/
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Net;
using System.Net.Http;
namespace Gist
{
class CustomWebClient
{
const string TestCookieSign = "aes.js";
public static byte[] Get(string url)
{
var address = new Uri(url);
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler))
{
var content = client.GetAsync(address).WaitResult().Content;
var script = content.ReadAsStringAsync().WaitResult();
if (!script.Contains(TestCookieSign))
{
return content.ReadAsByteArrayAsync().WaitResult();
}
var test = Decrypt(script);
cookieContainer.Add(new Cookie("__test", test) { Domain = address.Host });
content = client.GetAsync(address).WaitResult().Content;
if (content.ReadAsStringAsync().WaitResult().Contains(TestCookieSign))
{
throw new Exception();
}
return content.ReadAsByteArrayAsync().WaitResult();
}
}
public static byte[] Post(string url, byte[] data)
{
var address = new Uri(url);
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler))
using (var post = new ByteArrayContent(data))
{
var content = client.PostAsync(address, post).WaitResult().Content;
var script = content.ReadAsStringAsync().WaitResult();
if (!script.Contains(TestCookieSign))
{
return content.ReadAsByteArrayAsync().WaitResult();
}
var test = Decrypt(script);
cookieContainer.Add(new Cookie("__test", test) { Domain = address.Host });
content = client.PostAsync(address, post).WaitResult().Content;
if (content.ReadAsStringAsync().WaitResult().Contains(TestCookieSign))
{
throw new Exception();
}
return content.ReadAsByteArrayAsync().WaitResult();
}
}
static string Decrypt(string script)
{
var split = script.Split(new[] { "toNumbers(\"", "\")" }, StringSplitOptions.RemoveEmptyEntries)
.Where(s => s.Length == 32)
.ToArray();
if (split.Length != 3)
throw new Exception();
var key = StringToByteArray(split[0]);
var iv = StringToByteArray(split[1]);
var bytesIn = StringToByteArray(split[2]);
var aes = Aes.Create();
aes.Padding = PaddingMode.None;
aes.Mode = CipherMode.CBC;
aes.BlockSize = 128;
aes.KeySize = 128;
aes.Key = key;
aes.IV = iv;
var decrypter = aes.CreateDecryptor();
var decrypted = decrypter.TransformFinalBlock(bytesIn, 0, bytesIn.Length);
decrypter.Dispose();
aes.Dispose();
return BitConverter.ToString(decrypted).Replace("-", "").ToLower();
}
static byte[] StringToByteArray(string hex) // Taken from https://stackoverflow.com/a/321404/9248173
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
}
static class ExtensionMethods
{
public static T WaitResult<T>(this Task<T> task)
{
task.Wait();
return task.Result;
}
}
}

Result of the "R Script" without ColumnNames

I'm going crazy!
I'm using Azure Machine Learning and R Script. I deploy it as Web Service. I use sample code based on HttpClient.
using (var client = new HttpClient())
{
var scoreRequest = new
{
Inputs = new Dictionary<string, StringTable>() {
{
"input1",
new StringTable()
{
ColumnNames = new string[] {
"experts_estimates",
"experts_share_of_unique_information",
"avg_correlation",
"point_a",
"point_b",
"is_export_mode"
},
Values = new string[,] {
{
expertsEstimatesStr,
expertsShareOfUniqueInformationStr,
avgCorrelationStr,
pointAStr,
pointBStr,
isExportModeStr
},
}
}
},
},
GlobalParameters = new Dictionary<string, string>()
{
}
};
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
client.BaseAddress = new Uri(apiUrl);
// WARNING: The 'await' statement below can result in a deadlock
// if you are calling this code from the UI thread of an ASP.Net application.
// One way to address this would be to call ConfigureAwait(false)
// so that the execution does not attempt to resume on the original context.
// For instance, replace code such as:
// result = await DoSomeTask()
// with the following:
// result = await DoSomeTask().ConfigureAwait(false)
HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
return result;
}
else
{
// Print the headers - they include the requert ID and the timestamp,
// which are useful for debugging the failure
var headers = response.Headers.ToString();
string responseContent = await response.Content.ReadAsStringAsync();
throw new Exception(responseContent, new Exception(headers));
}
}
and when I run code from Visual Studio I get:
but when I run code from Azure App Service I get:
Any ideas?
One solution is adding "edit metadata" module inside the model and rename the output columns. It'll be easy than using the code to name the columns.

asp.net Web API file upload fileData empty

I'm using any one of several examples found all over the place to do a file upload with .net Web API. The files get stored to the server, but the fileData object on the provider always returns empty. Code below.
var url = "api/Documents/fileUpload";
var xhr = new XMLHttpRequest();
var file = document.getElementById("inputFile").files[0];
var formData = new FormData();
formData.append('file', file);
xhr.open("POST", url, true);
xhr.responseType = "text";
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
console.log("photoUpload xhr", xhr);
var responseTypeAsJSON = JSON.parse(xhr.responseText);
currentPhoto.responseText = xhr.responseText;
if (responseTypeAsJSON.result == "SUCCESS") {
currentPhoto.status = "SUCCESSfully uploaded";
}
else {
currentPhoto.status = responseTypeAsJSON.result;
alert(responseTypeAsJSON.message);
}
PhotoClear();
// console.log(currentPhoto);
// console.log("xhr done: ", xhr);
}
}
xhr.send(formData);
// console.log("xhr sent: ", xhr);
CONTROLLER TO RECEIVE:
[HttpPost]
[ActionName("fileUpload")]
public Task<HttpResponseMessage> fileUpload()
{
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
var task = request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(o =>
{
string file1 = provider.FileData.First().LocalFileName.ToString();
// this is the file name on the server where the file was saved
return new HttpResponseMessage()
{
Content = new StringContent("File uploaded.")
};
}
);
return task;
}
Here is the request from Chrome. When I debug the provider, the keys of the form data are empty as well. Yet the file gets put into the AppData
Request URL:http://localhost:4231/api/Documents/fileUpload
Request Headersview source
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarycuGegdEDmBsR0mMl
Origin:http://localhost:4231
Referer:http://localhost:4231/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Request Payload
------WebKitFormBoundarycuGegdEDmBsR0mMl
Content-Disposition: form-data; name="testInfo"
some info here for testing
------WebKitFormBoundarycuGegdEDmBsR0mMl
Content-Disposition: form-data; name="file"; filename="irislogo.png"
Content-Type: image/png
------WebKitFormBoundarycuGegdEDmBsR0mMl--
I was running into this exact issue and a small code change fixed the issue.
The line:
var provider = new MultipartFormDataStreamProvider(root);
Should be:
var provider = new MultipartFileStreamProvider(root);
I also had this issue; here is the solution:
public async Task<HttpResponseMessage> Save()
{
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
// provider.FileData will contain your data...
// you can also send form data which will be in provider.FormData
}

Resources