I've created in Xamarin Forms for iOS a HttpClient function to send a picture from the device to my server. The core function is
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fName
};
fileContent.Headers.ContentDisposition.Parameters
.Add(new NameValueHeaderValue("userId", UserId.ToString()));
content.Add(fileContent);
using (var client = new HttpClient()) {
client.DefaultRequestHeaders.Add("authenticationToken", SyncData.Token);
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
// more code
}
}
I'm using System.Net.Http. I tried to use the same function for a project in Android but surprisingly it doesn't work. The problem is in the header: if I inspect fileContent I can see every keys but for webapi on the server FileName is not received.
After some logs, I changed this function adding more client.DefaultRequestHeaders like
client.DefaultRequestHeaders.Add("FileName", fName);
Now the webapi receives FileName param.
Now my question is: what did I wrong?
Personally, I use the Add method on MultipartFormDataContent that accepts a filename.
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(fileBytes);
...
// Use the overload Add method which accepts a file name
content.Add(fileContent, "FileName", fName);
...
I'm not sure if this will solve your problem or not, but it works for me.
Related
I'm basically new to mobile development and stuck for a few weeks because,
I am unable to connect XAMARIN Android app with MQTTT over TLS.
Maybe i am using the wrong library or is it an Xamarin error?
My certificate is a .crt file from m21.cloudmqtt.com.
https://crt.sh/?id=5253106089
First was using System.Net MQTT but they are currently unable to work over TLS.
So i currently i am using MQTTNet, with (for the moment) the default certificate from m21.cloud.com which i have stored in Assets folder.I tested this local with and without a certificate and its working fine.
The MQTTNet Client with cert from local folder is like this, and works like it should:
var caCert = new X509Certificate2("C:/pathtocert.crt");
var source = new CancellationTokenSource().Token;
var token = source;
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
var mqttOptions = new MqttClientOptionsBuilder()
.WithTcpServer(server, port)
.WithClientId(clientId)
.WithCredentials(username, pswd)
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = true,
Certificates = new List<X509Certificate> { caCert }
})
.Build();
mqttClient.ConnectAsync(mqttOptions, token).Wait(token);
To get the Certifcate from Android Assets Folder i used the same client code as above and t et the certificate i used:
using (var assetStream = await Xamarin.Essentials.FileSystem.OpenAppPackageFileAsync("filename.crt"))
using (var memStream = new MemoryStream())
{
assetStream.CopyTo(memStream);
caCert = new X509Certificate(memStream.ToArray());
}
I dont understand why its not working, for now its also okay if the certificate isn't used but it needs to use TLS. But tried, and i still get unauthorized error.
var mqttOptions = new MqttClientOptionsBuilder()
.WithTcpServer(server, port)
.WithClientId(clientId)
.WithCredentials(username, pswd)
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = true,
})
.Build();
Thanks in adnvance.
I have a problem with my app in Xamarin Forms.
The GET request works in debug mode but not in release mode.
The POST request works in both mode.
I test on real device and emulator Android.
The api path is HTTPS and the app has INTERNET permission.
This is the code:
if (IsConnected)
{
string jsonRequest = JsonConvert.SerializeObject(request);
StringContent content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
var Request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(client.BaseAddress + $"api/Servizi/getServizi"),
Content = content
};
var jsonResponse = await client.SendAsync(Request);//.ConfigureAwait(false);
var contents = await jsonResponse.Content.ReadAsStringAsync();
response = await Task.Run(() => JsonConvert.DeserializeObject<ServiziResponse>(contents));
}
In visual Studio Add this line in Android Options
VS19
so i have already made one app that was a test app and it worked just fine using sqlite-net-pcl and i an now making an actual app and i am getting this weird error and i cant figure out why. i found the exact same question already asked on here but it didnt provide any real answer and it was over a year ago.
System.Exception: Something went wrong in the build configuration. This is the bait assembly, which is for referencing by portable libraries, and should never end up part of the app. Reference the appropriate platform assembly instead.
public SQLite.SQLiteConnection GetConnection()
{
var sqliteFilename = "TestDB.db3";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, sqliteFilename);
// Create the connection
var conn = new SQLite.SQLiteConnection(path);//HERE IS WHERE IT THROWS THE EXCEPTION
// Return the database connection
return conn;
}
the app works for every other platform i have tried except android and my test app that worked just fine is using the exact same references and same class as well i just cant figure it out. i have tried referencing the sqlite-net-pcl and made a new class still doesnt work. any help would be greatly appreciated
thank you very much
Here is the one I am using
https://github.com/oysteinkrog/SQLite.Net-PCL
Check you referenced SQLite.Net.Platform.XamarinAndroid in your Android project.
Here is the code which is working fine for me (I also included SQLite.Net.Async-PCL)
public SQLiteAsyncConnection GetConnection()
{
// database name
const string SQLITE_FILENAME = "MyDB.db3";
// Get app folder
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string path = Path.Combine(documentsPath, SQLITE_FILENAME);
var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
var sqliteConnection = new SQLiteConnectionWithLock(plat, new SQLiteConnectionString(path, true)){BusyTimeout = TimeSpan.FromSeconds(5)};
var conn = new SQLiteAsyncConnection(() => sqliteConnection,
TaskScheduler.FromCurrentSynchronizationContext());
// Return the database connection
return conn;
}
Guess this should work:
public SQLiteConnection GetConnection()
{
// database name
const string SQLITE_FILENAME = "MySIT.db3";
// Get app folder
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid(); //important!
string path = Path.Combine(documentsPath, SQLITE_FILENAME);
var conn = new SQLiteConnection(plat, path);
// Return the database connection
return conn;
}
I am new to Xamarin and C# as well. I try to make a Http request to my server with some information.
In general with android Native a uses AsyncTask and HttpClient for that. and build a json object or name value pair, and encrypt it to integrate information with the request.
But when I try to do the same with xamarin I get some problems.
if I try to import the namespace
using System.Net.Http.HttpClient
than my xamarin not have this namespace
Because of the above problem I try to use HttpWebRequest. But when I go for use it with the asyc and await I am not getting any response from server.
I am new to xamarin so I am not sure about async and await keyword.
I read lot of articles but No luck :(
on Click of the Button I call the below Method
public async Task<int> ValidateUser(){
try{
var request = HttpWebRequest.Create (URL);
request.Method = "GET/POST";
String postString = String.Format ("AAA ={0}&BBB={1}&CCC={2}", "111",
"222","333");
byte[] postByte = Encoding.UTF8.GetBytes (postString);
Stream st = request.GetRequestStream ();
//I am reaching here
Console.WriteLine("Check for Validity");
request.ContentLength = postByte.Length;
st.Write (postByte, 0, postByte.Length);
st.Close ();
Task<Stream> contentTask = request.GetRequestStreamAsync();
Stream response = await contentTask;
String str = response.ToString();
// this is not getting printed in Console
Console.WriteLine("=====>>"+str);
}
catch (WebException exception) {
string responseText;
using (var reader = new StreamReader(exception.Response.GetResponseStream())) {
responseText = reader.ReadToEnd ();
Console.WriteLine ("====Dude Error"+responseText);
}
}catch(Exception e){
}
return 1;
}
Any help will be appreciated
Consider using RestSharp, a component created for Xamarin to facilitate web requests. Click here for more info on the component. It will facilitate allot of things about webrequesting ( like serialization, automatic return type detection,... )
Your code would look something like this with restsharp:
public async Task<int> ValidateUser(){
var client = RestClient (URL);
var request = new RestRequest ("AAA ={0}&BBB={1}&CCC={2}", "111",
"222","333");
client.ExecuteAsync (request, response => {
WebApiResponse webApiResponse = new WebApiResponse ();
webApiResponse.Content = response.Content;
webApiResponse.StatusCode = response.StatusCode;
webApiResponse.ResponseStatus = (WebApiResponseStatus)response.ResponseStatus;
return webApiResponse.Content;
});
return -1
}
Using HttpWebRequest is a bad idea, instead it would be better to focus on why you don't have the System.Net.Http.* namespace. Imho the most likely cause is that you didn't add System.Net.Http as a reference to your project.
Here's how you add System.Net.Http.* to your project.
In Visual Studio 2013:
Open the solution
Open the project
Open the Solution Explorer
Right-click on References
Add Reference
Click on 'Search Assemblies'
Type in 'Http'
Select System.Net.Http
Press 'OK'
In Xamarin Studio:
Open the solution
Open the project
Open the Solution Explorer
Right-click on References
Edit References
Type in 'Http'
Select System.Net.Http
Press 'OK'
Afterwards there should be no problems resolving System.Net.Http when 'using System.Net.Http;'
I have my Windows Forms Application in c# 4.0, I wanted to post/send data to an android application. It need to triggered from Windows Forms.
Any one can suggest me the possible ways to do this?
Thanks & Regards.
Use the WebClient class. Depending on the "payload", you can use of of the UploadXXX methods.
For example:
string URL = "..."; //Your url here
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["Username"] = "myusername";
formData["Password"] = "mypassword";
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string Result = Encoding.UTF8.GetString(responseBytes);
Cheers