WebView.loadUrl raising UnsupportedOperationException - android-webview

This exception raising only in android 5.1 (Samsung galaxy J3 2016)
Log:
Caused by java.lang.UnsupportedOperationException
java.util.Collections$SingletonMap$1$1.remove (Collections.java:355)
java.util.AbstractMap.remove (AbstractMap.java:397)
org.chromium.android_webview.AwContents.loadUrl (AwContents.java:1594)
org.chromium.android_webview.AwContents.loadUrl (AwContents.java:1458)
com.android.webview.chromium.WebViewChromium.loadUrl (WebViewChromium.java:496)
android.webkit.WebView.loadUrl (WebView.java:862)
I don't have this device, I receive a ton of such exceptions from my crashlytics report.
My WebView settings is below:
settings.loadWithOverviewMode = true
settings.useWideViewPort = true
#SuppressLint("SetJavaScriptEnabled")
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
webViewClient = WebViewClient()
And I am loading URL with extra headers provided:
val extraHeaders = mapOf("Referer" to "https://my.site.url")
webView.loadUrl(state.url, extraHeaders)

Ok, I found a problem:
In source code of AwContents in loadUrl method you can find such block:
final String REFERER = "referer";
Map<String, String> extraHeaders = params.getExtraHeaders();
if (extraHeaders != null) {
for (String header : extraHeaders.keySet()) {
if (REFERER.equals(header.toLowerCase(Locale.US))) {
params.setReferrer(new Referrer(extraHeaders.remove(header), 1));
params.setExtraHeaders(extraHeaders);
break;
}
}
}
interesting thing is extraHeaders.remove(header) because I'm creating immutable map, this causing throwing UnsupportedOperationException.
Made this change:
val extraHeaders = mutableMapOf("Referer" to "https://my.site.url")

Related

Strange issue when no breakpoint is set when calling SslStream.AuthenticateAsServer

I am adding some code to a legacy application running .net 4.5.2. I copied some code from .net 4.8 solution for decrypting the Ssl Stream. My Code works fine when I have a breakpoint right on or right after SslStream.AuthenticateAsServer. if I statement "return sslStream"
public SslStream DecrtyptStream(TcpClient client)
{
bool clientCertificateRequired = false;
SslStream sslStream = null;
if (gTLS_CertEnable == "Yes")
{
clientCertificateRequired = true;
sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(_validateServerCertificate));
}
else
{
sslStream = new SslStream(client.GetStream(), false);
}
sslStream.ReadTimeout = 60000;
sslStream.WriteTimeout = 5000;
if (gTLS_Ver == "TLS1.0")
{
sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls, true);
}
else if (gTLS_Ver == "TLS1.1")
{
sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls11, true);
}
else
{
//https://stackoverflow.com/questions/38236302/the-client-and-server-cannot-communicate-because-they-do-not-possess-a-common-a
sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls12, true);
}
return sslStream;
}
When I remove the breakpoint I get this error:
The client and server cannot communicate, because they do not possess
a common algorithm.
So as shown in a stackoverflow post I changed it to
sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls11 | SslProtocols.Tls | SslProtocols.Tls12, true);
I get this error message:
The supplied message is incomplete. The signature was not verified
But still if I add a breakpoint, this error does not happen.

Can two ASP . NET Core 5.0 web api cause "The content may be already have been read by another component" errpr 400 if they accessed same db be4?

My API was as follows:
[HttpPut("{id}")]
public async Task<ActionResult<HomeContextModel>> EditHomeContext(int id, string title, string context, string subcontext, IFormFile imageFile)
{
HomeContextModel homeContextModel = await _context.HomeContext.Include(x => x.Image).Include(x => x.Button).Include(x => x.Logo).ThenInclude(y => y.Image)
.FirstOrDefaultAsync(m => m.Context_Id == id);
//HomeContextModel homeContextModel = await GetHomeContextModel(id);
if (homeContextModel == null)
{
return BadRequest("Context Id cannot be null");
}
if (imageFile != null)
{
ImageModel imageModel = homeContextModel.Image;
if (imageModel != null)
{
string cloudDomain = "https://privacy-web.conveyor.cloud";
string uploadPath = _webHostEnvironment.WebRootPath + "\\Images\\";
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
string filePath = uploadPath + imageFile.FileName;
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await imageFile.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
using (var memoryStream = new MemoryStream())
{
await imageFile.CopyToAsync(memoryStream);
imageModel.Image_Byte = memoryStream.ToArray();
}
imageModel.ImagePath = cloudDomain + "/Images/" + imageFile.FileName;
imageModel.Modify_By = "CMS Admin";
imageModel.Modity_dt = DateTime.Now;
//_context.Update(imageModel);
}
}
homeContextModel.Title = title;
homeContextModel.Context = context;
homeContextModel.SubContext = subcontext;
_context.Entry(homeContextModel).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!HomeContextModelExists(homeContextModel.Context_Id))
{
return NotFound();
}
else
{
throw;
}
}
return Ok("Home Context Edit Successfully");
}
It's an API for the Content Management System (CMS) to change the content of the Homepage using a Flutter webpage that make put request onto this API.
Everything works fine. In the last few days, where I tested and tested again during the development. So before today, I've wrapped up them and submitted to the necessary place (It's a university FYP).
Until now it cause me this error when I was using this to prepare my presentation:
Error 400 failed to read the request form Unexpected end of stream ..."
After all the tested I tried:
Internet solutions
restore the database
repair Microsoft VS 2019 (As this issue was fixed before after I
updated my VS 2019 from 16.8. to the latest 16.11.7)
Use the ASP .NET file which didn't caused this issue before
Then I realized it may be because of I used another older ASP file to accessed the same database before. Does this really cause this matter?
If yes, then now how should I solved it, with the action I already done (listed as above)?
EDIT: Additional description to the situation
The above API I set breakpoint before, on the first line, using Swagger to test it.
It turns out that it didn't go into the API and straightaway return the error 400
REST API can have parameters in at least two ways:
As part of the URL-path
(i.e. /api/resource/parametervalue)
As a query argument
(i.e. /api/resource?parameter=value)
You are passing your parameters as a query instead of a path as indicated in your code. And that is why it is not executing your code and returning 400.

Power BI REST API ExportToFileInGroup Not Working

I am able to programmatically log in to the PowerBI Client, gather my Workspaces as well as get a specific Report from a specific Workspace. I need to programmatically render that report to a .pdf or .xlsx file. Allegedly this is possible with the ExportToFileInGroup/ExportToFileInGroupAsync methods. I even created a very simple report without any parameters. I can embed this using the sample app from here. So that at least tells me that I have what I need setup in the backend. But it fails when I try to run the ExportToFileInGroupAsync method (errors below code.)
My Code is:
var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(new string[] {
PowerBiScopes.ReadReport,
PowerBiScopes.ReadDataset,
});
var userInfo = await graphServiceClient.Me.Request().GetAsync();
var userName = userInfo.Mail;
AuthDetails authDetails = new AuthDetails {
UserName = userName,
AccessToken = accessToken,
};
var credentials = new TokenCredentials($"{accessToken}", "Bearer");
PowerBIClient powerBIClient = new PowerBIClient(credentials);
var groups = await powerBIClient.Groups.GetGroupsAsync();
var theGroup = groups.Value
.Where(x => x.Name == "SWIFT Application Development")
.FirstOrDefault();
var groupReports = await powerBIClient.Reports.GetReportsAsync(theGroup.Id);
var theReport = groupReports.Value
.Where(x => x.Name == "No Param Test")
.FirstOrDefault();
var exportRequest = new ExportReportRequest {
Format = FileFormat.PDF,
};
string result = "";
try {
var response = await powerBIClient.Reports.ExportToFileInGroupAsync(theGroup.Id, theReport.Id, exportRequest);
result = response.ReportId.ToString();
} catch (Exception e) {
result = e.Message;
}
return result;
It gets to the line in the try block and then throws the following errors:
An error occurred while sending the request.
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
UPDATE
Relating to #AndreyNikolov question, here is our Embedded capacity:
After this was implemented, no change. Same exact error.
Turns out the issue was on our side, more specifically, security/firewall settings. Here is the exact quote from our networking guru.
"After some more investigation we determined that our firewall was causing this issue when it was terminating the SSL connection. We were able to add a bypass for the URL and it is now working as expected."

GenerateAppearances = true; System.NullReferenceException

Got some legacy code using iTextSharp.
All documents have GenerateAppearances set to true regardless. and now its triggering an exception.
Took the basic code out and placed it into a Console app, same thing, Used a generic PDF (http://www.pdf995.com/samples/pdf.pdf) of the net same thing.
This is using version 5.5.12
class Program
{
static void Main(string[] args)
{
var reader = new PdfReader(#"C:\Users\me\Desktop\pdf.pdf");
var outStream = new MemoryStream();
var stamper = new PdfStamper(reader, outStream);
stamper.AcroFields.GenerateAppearances = true; <--- usually true before setting
stamper.FormFlattening = true;
}
}
An unhandled exception of type 'System.NullReferenceException' occurred in itextsharp.dll
Additional information: Object reference not set to an instance of an object.
Thanks
After years of production, I just changed it from:
if (stamper.AcroFields != null)
{
f.GenerateAppearances = true;
foreach(var field in f.Fields)
{
f.SetField(field.Key, f.GetField(field.Key));
}
stamper.FormFlattening = true;
}
to
if (stamper.AcroFields != null && stamper.AcroFields.GenerateAppearances == true)
I encounter the same issues as below:
When I set AcroFields.GenerateAppearances = true
an unhandled exception of type 'System.NullReferenceException' occurred in itextsharp.dll
Additional information: Object reference not set to an instance of an object.
I debugged this code and found that AcroFields is not null. but NullReferenceException still occourred.
After inverstigating, I found that the format of PDF file is aspose xfa rather than acroforms. So I solved this issue by converting the format of PDF from aspose xfa to acroforms.

Xamarin.Forms Consume Rest Service

I'm new to Xamarin and developing native apps in general (I have made html5 apps in the past).
I have started on a Xamarin.Forms project and I'm trying to contact a REST like API (need to GET an URL which will return a json array).
Normally from C# I would use RestSharp and perform this call using the RestClient.
I'm not having any luck installing that package from Xamarin Studio though, but I have got the Microsoft HTTP Libraries installed.
I'm pretty sure this is a very trivial task to perform, I just haven't been able to adapt the samples I have found online to work for me.
Anyone who could post how this is done please (remember I'm new to this so don't expect me to understand everything that is different from say a normal console app)?
It is easy with HTTP Client and JSON.NET here is a example of a GET:
public async Task<List<Appointment>> GetDayAppointments(DateTime day)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + App.apiToken);
//Your url.
string resourceUri = ApiBaseAddress;
HttpResponseMessage result = await client.GetAsync (resourceUri, CancellationToken.None);
if (result.IsSuccessStatusCode) {
try {
return GetDayAppointmentsList(result);
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
} else {
if(TokenExpired(result)){
App.SessionExpired = true;
App.ShowLogin();
}
return null;
}
return null;
}
private List<Appointment> GetDayAppointmentsList(HttpResponseMessage result){
string content = result.Content.ReadAsStringAsync ().Result;
JObject jresponse = JObject.Parse (content);
var jarray = jresponse ["citas"];
List<Appointment> AppoinmentsList = new List<Appointment> ();
foreach (var jObj in jarray) {
Appointment newApt = new Appointment ();
newApt.Guid = (int)jObj ["id"];
newApt.PatientId = (string)jObj ["paciente"];
newApt.Name = (string)jObj ["nombre"];
newApt.FatherLstName = (string)jObj ["paterno"];
newApt.MotherLstName = (string)jObj ["materno"];
string strStart = (string)jObj ["horaIni"];
TimeSpan start;
TimeSpan.TryParse (strStart, out start);
newApt.StartDate = start;
string strEnd = (string)jObj ["horaFin"];
TimeSpan end;
TimeSpan.TryParse (strEnd, out end);
newApt.EndDate = end;
AppoinmentsList.Add (newApt);
}
return AppoinmentsList;
}
I use System.Net.WebClient and our asp.net WebAPI interface:
public string GetData(Uri uri)
{//uri like "https://webapi.main.cz/api/root"
string ret = "ERROR";
try
{
using (WebClient webClient = new WebClient())
{
//You can set webClient.Headers there
webClient.Encoding = System.Text.Encoding.UTF8;
ret = webClient.DownloadString(uri));//Test some data received
//In ret you can have JSON string
}
}
catch (Exception ex) { ret = ex.Message; }
return ret;
}
4
public string SendData(Uri uri, byte[] data)
{//uri like https://webapi.main.cz/api/PostCheckLicence/
string ret = "ERROR";
try
{
using (WebClient webClient = new WebClient())
{
webClient.Headers[HttpRequestHeader.Accept] = "application/octet-stream";
webClient.Headers[HttpRequestHeader.ContentType] = "text/bytes";
webClient.Encoding = System.Text.Encoding.ASCII;
byte[] result = webClient.UploadData(uri, data);
ret = Encoding.ASCII.GetString(result);
if (ret.Contains("\"ResultWebApi\":\"OK"))
{//In ret you can have JSON string
}
else
{
}
}
}
catch (Exception ex) { ret = ex.Message; }
return ret;
}
x
I've some examples in my Github repo. Just grab the classes there and give them a try. The API is really easy to use:
await new Request<T>()
.SetHttpMethod(HttpMethod.[Post|Put|Get|Delete].Method) //Obligatory
.SetEndpoint("http://www.yourserver.com/profilepic/") //Obligatory
.SetJsonPayload(someJsonObject) //Optional if you're using Get or Delete, Obligatory if you're using Put or Post
.OnSuccess((serverResponse) => {
//Optional action triggered when you have a succesful 200 response from the server
//serverResponse is of type T
})
.OnNoInternetConnection(() =>
{
// Optional action triggered when you try to make a request without internet connetion
})
.OnRequestStarted(() =>
{
// Optional action triggered always as soon as we start making the request i.e. very useful when
// We want to start an UI related action such as showing a ProgressBar or a Spinner.
})
.OnRequestCompleted(() =>
{
// Optional action triggered always when a request finishes, no matter if it finished successufully or
// It failed. It's useful for when you need to finish some UI related action such as hiding a ProgressBar or
// a Spinner.
})
.OnError((exception) =>
{
// Optional action triggered always when something went wrong it can be caused by a server-side error, for
// example a internal server error or for something in the callbacks, for example a NullPointerException.
})
.OnHttpError((httpErrorStatus) =>
{
// Optional action triggered when something when sending a request, for example, the server returned a internal
// server error, a bad request error, an unauthorize error, etc. The httpErrorStatus variable is the error code.
})
.OnBadRequest(() =>
{
// Optional action triggered when the server returned a bad request error.
})
.OnUnauthorize(() =>
{
// Optional action triggered when the server returned an unauthorize error.
})
.OnInternalServerError(() =>
{
// Optional action triggered when the server returned an internal server error.
})
//AND THERE'S A LOT MORE OF CALLBACKS THAT YOU CAN HOOK OF, CHECK THE REQUEST CLASS TO MORE INFO.
.Start();
And there's a couple of examples.
For all my Xamarin Forms app I use Tiny.RestClient.
It's easy to get it and easy to use it.
You have to download this nuget.
And after it just very easy to use it :
var client = new TinyRestClient(new HttpClient(), "http://MyAPI.com/api");
var cities = client.
GetRequest("City").
AddQueryParameter("id", 2).
AddQueryParameter("country", "France").
ExecuteAsync<City>> ();
Hopes that helps.