Message box shows before all data insert in iot hub c# - c#

I have CSV file. I read that CSV file and that csv file data converts to json then that json will upload in Iot hub.
That CSV file may contains 1400 to 5000 records. After inserting all records I will show the message like Data inserted successfully
Here when one single row got inserted that message showing popup. It's did not wait for all records getting insert.
private async Task DataSendstoAzureIotHub(string jsonserv, string deviceID)
{
DeviceClient s_deviceClient;
Console.WriteLine("upload time start" + DateTime.Now);
try
{
if (registryManager == null)
{
registryManager = RegistryManager.CreateFromConnectionString(s_connectionString01);
}
else
{
Device device = await registryManager.GetDeviceAsync(deviceID);
if (device != null)
{
string s_connectionStringNew = "*";
s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionStringNew, Microsoft.Azure.Devices.Client.TransportType.Amqp);
s_deviceClient.OpenAsync();
string messageString = "";
messageString = jsonserv;
var message = new Message(Encoding.UTF8.GetBytes(messageString));
message.Properties.Add("southnorth_msgid", "com.intel.wsn.sensorData");
Task task = s_deviceClient.SendEventAsync(message);
await task;
s_deviceClient.CloseAsync();
await Task.Delay(10);
}
else
{
device = await registryManager.AddDeviceAsync(new Device(deviceID));
string s_connectionStringNew = "*";
s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionStringNew, Microsoft.Azure.Devices.Client.TransportType.Amqp);
string messageString = "";
messageString = jsonserv;
var message = new Message(Encoding.UTF8.GetBytes(messageString));
message.Properties.Add("southnorth_msgid", "com.intel.wsn.sensorData");
Task task = s_deviceClient.SendEventAsync(message);
await Task.Delay(1000 * 10);
}
}
Console.WriteLine("File Upload time end " + DateTime.Now);
}
catch (Exception ex)
{
Log.Error(ex);
}
}

Related

Why is my BLE device data FFFFFFF from config index?

Basically, I am supposed to retrieve a value from a Bluetooth LE skincare device. Among the services that the device has, the device has a configuration service, with two characteristics: one for reading/writing data, and another characteristic for reading and writing the configuration value.
I have the document that shows all the UUID's, their characteristics, properties, values etc. The configuration indexes are all listed in the file too, and preprogrammed in the device.
Goal: This is where I am stuck. One of the config indexes has a value of 12. I have to write the config index to the characteristic, and then in return, the program will read the data corresponding to the configuration index, and print the data on the terminal. I sent a value as 0C (12 in hex), and ended up with FFFFFFFFFFFFFFFFFFFF. It has to be a different value.
How can I achieve this goal?
This is the code that I have so far:
while (true)
{
if (device == null)
{
Thread.Sleep(200);
}
else
{
Console.WriteLine("Press any key to pair the device.");
Console.ReadKey();
Console.WriteLine();
BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.Id);
Console.WriteLine("Attempting to pair with device");
GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();
if (result.Status == GattCommunicationStatus.Success)
{
var services = result.Services;
foreach (var service in services)
{
if (service.Uuid.ToString() == configSvc)
{
GattCharacteristicsResult charactiristicResult = await service.GetCharacteristicsAsync();
if (charactiristicResult.Status == GattCommunicationStatus.Success)
{
var characteristics = charactiristicResult.Characteristics;
foreach (var characteristic in characteristics)
{
GattReadResult rResult = await characteristic.ReadValueAsync();
GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
if (properties.HasFlag(GattCharacteristicProperties.Write))
{
var writer = new DataWriter();
GattCommunicationStatus wResult = await characteristic.WriteValueAsync(writer.DetachBuffer());
if (characteristic.Uuid.ToString() == configIdxCt)
{
int psCalVal = 12;
//var startCommand = Encoding.ASCII.GetBytes(psCalVal.ToString());
//Console.WriteLine(startCommand[0]);
writer.WriteByte(0xc0);
if (wResult == GattCommunicationStatus.Success)
{
Console.WriteLine("message sent successfully");
}
else
{
Console.WriteLine("Error encountered on writing to characteristic!");
}
}
}
if(properties.HasFlag(GattCharacteristicProperties.Read))
{
if (rResult.Status == GattCommunicationStatus.Success)
{
if (characteristic.Uuid.ToString() == configValCt)
{
var reader = DataReader.FromBuffer(rResult.Value);
byte[] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(input);
//Console.WriteLine(input[0]);
Console.WriteLine("Data: ");
string psCArrayWDash = BitConverter.ToString(input) + " ";
string psCArray = psCArrayWDash.Replace("-", "").ToLower();
Console.WriteLine(psCArray);
}
if (characteristic.Uuid.ToString() == measurementCt)
{
Console.WriteLine("Read");
var reader = DataReader.FromBuffer(rResult.Value);
byte[] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(input);
Console.WriteLine("Data: ");
for (int i = 0; i < input.Length; i++)
Console.WriteLine(input[i].ToString() + " ");
}
}
else
Console.WriteLine("ERROR");
}
}
}
}
}
}
else
Console.WriteLine("Please, make sure the device is connected, and try again.");
}
}
deviceWatcher.Stop();

Error during transfering Bytes xamarin forms

I try to upload at least 30 pictures to a web server but my program catch errors.
They appear randomly, sometimes at the first image, sometimes third etc.
{System.Net.Http.HttpRequestException: Error while copying content to a stream. ---> System.IO.IOException: Unable to write data to the transport connection: Connection reset by peer. ---> System.Net.Sockets.SocketException: Connection reset by peer
at System.Net.Sockets.Socket.EndSend (System.IAsyncResult asyncResult) [0x0000c] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/mcs/class/referencesource/System/net/System/Net/Sockets/Socket.cs:3874
at System.Net.Sockets.NetworkStream.EndWrite (System.IAsyncResult asyncResult) [0x00057] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/mcs/class/referencesource/System/net/System/Net/Sockets/NetworkStream.cs:1043
--- End of inner exception stack trace ---
OR
Read error: ssl=0x7e46332e08: I/O error during system call, Connection reset by peer
I explain you the process : I got an array with image path and I created a loop to upload each image on my web server.
public async void LaunchImagesUpload()
{
for (int i = startIndex; i < picturesToDisplay.Count; i++)
{
try
{
await UploadSinglePicture(i);
}
catch (Exception e)
{
if(e.Message.Equals("The operation was canceled."))
{
hasErrors = true;
}
else if(e.Message.Equals("Error while copying content to a stream."))
{
// Sometimes program goes here
hasErrors = true;
}
else
{
// Sometimes program goes here
currentPictureGrid.ActivateCancelledMode("error , retry please");
hasErrors = true;
}
}
}
}
Here is the http call
public static async Task<string> CreateUploadTask(string file, string id, string user_id, string user_login)
{
string requestResult = "";
var cont = new MultipartFormDataContent();
var image = new StreamContent(File.OpenRead(file));
image.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = "imageToUpload.jpeg" };
image.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
cont.Add(image);
string id_level = id
string uri = // private uri
using (var client = new HttpClient())
{
var response = await client.PostAsync(uri, cont);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
return "error";
}
requestResult = response.Content.ReadAsStringAsync().Result;
Console.WriteLine("DATA FINAL" + requestResult);
}
return requestResult;
}
How can I upload multiple image. Do I made a mistake. There is another way to uplad pictures thank's in advance
UPDATE
I used breakpoint to see when appear error and I added a handler.HttpSendProgress to see the transfer and error appear during transfer
Here is the nuew CreateUploadTask function
public static async Task<string> CreateUploadTask(string file, string vtour_id, string user_id, string user_login)
{
string requestResult = "";
HttpContent fileStreamContent = new StreamContent(File.OpenRead(file));
await Task.Delay(500);
fileStreamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = "imageToUpload.jpeg" };
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
string boundary = "---8393774hhy37373773";
using (var formData = new MultipartFormDataContent(boundary))
{
handler.HttpSendProgress += (s, e) =>
{
// error is here because I display transfer and not all Bytes are transfered
float prog = (float)e.BytesTransferred / (float)File.OpenRead(file).Length;
prog = prog > 1 ? 1 : prog;
if (prog > .99)
{
currentPictureGrid.ActivateTreatmentMode();
Console.WriteLine("IMAGE IMPORT --------- Transfert -------- Mode 'en cours de traitement' activé");
}
else
{
Console.WriteLine("step 0");
byteTransferedBeforeBug = (float)e.BytesTransferred;
byteTotalBeforeBug = (float)File.OpenRead(file).Length;
currentPictureGrid.UpdateUploadRate((float)e.BytesTransferred, (float)File.OpenRead(file).Length);
}
};
formData.Add(fileStreamContent);
string id_level = (jsoncontent != null && jsoncontent.GetValue(currentPath.ToString())["floor"].ToString() != null ? jsoncontent.GetValue(currentPath.ToString())["floor"].ToString() : "0");
var response = await client.PostAsync(MY_PRIVATE_URL, formData);
requestResult = response.Content.ReadAsStringAsync().Result.ToString();
Console.WriteLine("DATA RESULT : " + requestResult);
}
return requestResult;
}

How to close SQLite Connection in Xamarin Forms?

I have a code the gets data from my server. Every data will be inserted in my local database (SQLite Database) one by one. Every once in a whole I am getting these two errors. My codes below is where the exception are always appearing.
SQLite.SQLiteException: Busy
SQLite.SQLiteException: database is locked
What is/are the cause(s) why I always get these exceptions?
Update:
I added await conn.CloseAsync(); in every end of the code is that correct?
here is my first code, it will inquire to the server if there were updates and if there are updates it will insert or replace(update) the data in my local database:
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
string apifile = "sync-retailer-outlet-server-update-api.php";
var lastchecked = Preferences.Get("retaileroutletchangelastcheck", String.Empty, "private_prefs");
int count = 0;
var uri = new Uri(string.Format("http://" + domain + "/TBSApp/app_api/" + apifile + "?Host=" + host + "&Database=" + database + "&ContactID=" + contact + "&LastChecked=" + lastchecked, string.Empty));
try
{
SyncStatus("Getting retailer outlet data from server");
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(content))
{
var dataresult = JsonConvert.DeserializeObject<List<RetailerGroupData>>(content, settings);
var datacount = dataresult.Count;
for (int i = 0; i < datacount; i++)
{
SyncStatus("Saving retailer outlet server update to local database (" + (count + 1) + " out of " + dataresult.Count + ")");
var item = dataresult[i];
var retailerCode = item.RetailerCode;
var insertdata = new RetailerGroupTable
{
RetailerCode = retailerCode
};
await conn.InsertOrReplaceAsync(insertdata);
count++;
}
}
}
}
catch (Exception ex)
{
Crashes.TrackError(ex);
}
await conn.CloseAsync();
Here is the other code that creates the local database table everytime the StartPage is loaded.
public async void CreateTableAsync()
{
try
{
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
if (conn != null)
{
try
{
await conn.CreateTableAsync<UserTable>();
await conn.CreateTableAsync<ContactsTable>();
await conn.CreateTableAsync<ActivityTable>();
await conn.CreateTableAsync<CAFTable>();
await conn.CreateTableAsync<RetailerGroupTable>();
await conn.CreateTableAsync<UserEmailTable>();
await conn.CreateTableAsync<UserLogsTable>();
await conn.CreateTableAsync<SubscriptionTable>();
await conn.CreateTableAsync<ProvinceTable>();
await conn.CreateTableAsync<TownTable>();
}
catch (Exception ex)
{
Console.Write("Creating table error " + ex.Message);
}
}
}
catch (Exception ex)
{
Crashes.TrackError(ex);
await DisplayAlert("Application Error", "Error:\n\n" + ex.Message.ToString() + "\n\n Please contact your administrator", "Ok");
}
}
await conn.CloseAsync();
using (SQLiteConnection connection = db.GetConnection())
{
// Do whatever you want to do with your active connection
}
Note that you cannot reuse that connection outside the scope of the using block and have to get a new connection the same way the next time you want to access your database.
According to your description and code, I assume you use async-style inserts and are on different threads and thus an insert is timing out waiting for the lock of a different insert to complete. You can use synchronous inserts to avoid this condition.

StorageProgress Report function is not called by GetFileAsync

I'm trying to download resources file for my game from Firebase Storage, and to show downloading progress. But I came to strange behavior of GetFileAsync function. The Report function of StorageProgress is not called periodically during file downloading how it is described in reference. Report function is called during saving to disk, after the file is placed into memory(downloaded). What I'm doing wrong?
string resourcesURL = "URL_TO_RESOURCE_FILE"; // https://firebasestorage.googleapis.com/......
public void UpdateProgress(float val)
{
labelProgress.text = Mathf.RoundToInt(val * 100f) + "%";
circleProgress.fillAmount = val;
}
void OnDownloadClick()
{
SetDownloadingView();
string saveToPath = GetParentFolder() + "/resources.bin";
StorageReference fileRef = FirebaseBackend.Instance.GetStorage().GetReferenceFromUrl(resourcesURL);
StorageProgress<Firebase.Storage.DownloadState> progressHandler = new StorageProgress<Firebase.Storage.DownloadState>(state =>
{
Debug.Log(String.Format ("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
UpdateProgress(state.BytesTransferred / state.TotalByteCount);
});
Task dwnTask = fileRef.GetFileAsync
(
saveToPath,
progressHandler,
CancellationToken.None
);
dwnTask.ContinueWith(resultTask =>
{
if (!resultTask.IsFaulted && !resultTask.IsCanceled)
{
ResetView();
Debug.Log("Download finished!");
}
else
{
ResetView();
Debug.Log("Download fail!");
}
});
}
Unity version is 5.5.0f3
Firebase Unity SDK version is 3.0.1
You may not be doing anything wrong at all.
According to this post, this is a Firebase bug that is to be addressed in the next Firebase update.
Try with an IEnumerator, this is my code with the storage progress working:
protected IEnumerator downloadObject(string target_file, string target_path, int item_index)
{
if (target_file != "")
{
FirebaseStorage storage = FirebaseStorage.DefaultInstance;
string local_url = target_path.Replace("\\", "/").Replace("//", "/");
StorageReference storage_ref =
storage.GetReferenceFromUrl(FB_Conf.gsURL + target_file);
Task task = null;
try
{
task = storage_ref.GetFileAsync(local_url,
new Firebase.Storage.StorageProgress<DownloadState>((DownloadState state) =>
{
// called periodically during the download
long tbyte = state.TotalByteCount;
file_progress = (float)state.BytesTransferred / (float)tbyte;
}), CancellationToken.None);
}
catch (Exception exc)
{
Debug.Log("Get file async error: " + exc.Message);
}
if (task != null)
{
yield return new WaitUntil(() => task.IsCompleted);
task.ContinueWith((resultTask) =>
{
if ((resultTask.IsFaulted) || (resultTask.IsCanceled))
{
error_count++;
string msg = (resultTask.IsCanceled) ? "Download error." : "";
if ((resultTask.Exception != null) &&
(resultTask.Exception.InnerExceptions.Count > 0) &&
(resultTask.Exception.InnerExceptions[0] is Firebase.Storage.StorageException))
msg = ((Firebase.Storage.StorageException)resultTask.Exception.InnerExceptions[0]).HttpResultCode.ToString();
else if (resultTask.Exception != null)
msg = resultTask.Exception.Message;
}
});
}
else
{
error_count++;
}
}
}

Null Point Exception happening in the HttpClient.GetAsync methode

I'm working on a Xamarin.Forms application in which I'm downloading some data from the server and showing them on the screen. This data is downloaded every 5-10 seconds in order to keep the application updated. My code for the data download looks like this:
public async Task<List<string>> RefreshProgressPageAsync()
{
var uri = new Uri(string.Format("http://someurladdress1"));
List<string> returnValue = new List<string>();
try
{
var response = await client.GetAsync(uri);
string allResult = string.Empty;
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
string[] valuePartsArray = result.Split(',');
string id = valuePartsArray[0].Substring(valuePartsArray[0].IndexOf(':') + 1);
string name = valuePartsArray[1].Substring(valuePartsArray[1].IndexOf(':') + 1);
string value = valuePartsArray[2].Substring(valuePartsArray[2].IndexOf(':') + 1);
returnValue.Add(string.Format("{0}|{1}|{2}", id, name, value));
}
uri = new Uri(string.Format("http://someurladdress2"));
response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
string[] valuePartsArray = result.Split(',');
string id = valuePartsArray[0].Substring(valuePartsArray[0].IndexOf(':') + 1);
string name = valuePartsArray[1].Substring(valuePartsArray[1].IndexOf(':') + 1);
string value = valuePartsArray[2].Substring(valuePartsArray[2].IndexOf(':') + 1);
returnValue.Add(string.Format("{0}|{1}|{2}", id, name, value));
}
return returnValue;
}
catch (Exception ex)
{
Debug.WriteLine(#" ERROR {0}", ex.Message);
return new List<string>();
}
}
Client is the HttpClient. There are two calls for the client because I want to download two different set of data in one RefreshProgressPageAsync call.
Now my problem with this is when second await client.GetAsync(uri) happens, I get a null point exception somewhere in the GetAsynch call, which is not caught by the try-catch block. I do have a workaround by not parsing the string and instead send it as is, but my question is what could cause this NullPointException?

Categories