Xamarin.Forms Help optimize load times - android

I am making an application in Xamarin Forms and I have a Login when loading the application. The case is that when I put the data, I make a call to an API and it returns a series of data in a json.
Then I go through the json, checking that each data exists in my local database (sqlite), if it exists, I update it, if it does not exist, I insert it.
Once it has gone through all the json it loads the following activity, or screen ...
The problem is that it easily takes 10 to 15 seconds to move on to the next activity.
Any idea how to optimize this process? Or, should I modify the API to get less data?
CODE:
Login.xaml.cs
namespace WorkersApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Login : ContentPage
{
public Login()
{
InitializeComponent();
}
public string user = "";
public string password = "";
private async void btnEncript_Clicked(object sender, EventArgs e)
{
if (userEntry.Text != null && passwordEntry.Text != null)
{
user = userEntry.Text;
password = EncriptarMD5.MD5Hash(passwordEntry.Text);
string url = "https://api.com/?f=login&u=" + user + "&pw=" + password;
await GetDataFromApi(url);
}
}
public async Task GetDataFromApi(string url)
{
HttpClient myClient = new HttpClient();
try
{
var response = await myClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
//ERRORES
var error = JsonConvert.DeserializeObject<Errores>(content);
List<string> errror = new List<string>();
foreach (var item in error.error)
{
errror.Add(item.Value);
}
//Tiro error.
if (errror[0] != "0")
{
Preferences.Set("IdError", errror[0]);
Preferences.Set("Nombre", errror[1]);
return;
}
else
{
Preferences.Set("IdError", errror[0]);
Preferences.Set("Nombre", errror[1]);
}
//HOTELES
var hoteles = JsonConvert.DeserializeObject<Hoteles>(content);
List<Model.Hoteles> lista_hoteles = await App.Database.GetHotelesAsync();
List<Model.Bloques> lista_bloques = await App.Database.GetBloquesAsync();
foreach (var item in hoteles.hoteles)
{
Model.Hoteles h = new Model.Hoteles();
h = JsonConvert.DeserializeObject<Model.Hoteles>(item.Value.ToString());
h.ID = item.Key.ToString();
var bloques = JsonConvert.DeserializeObject<Bloques>(item.Value.ToString());
bool existe = false;
foreach (var bloque in bloques.bloques)
{
existe = false;
Model.Bloques b = new Model.Bloques();
b.ID = bloque.Key.ToString();
b.Nombre = bloque.Value.ToString();
b.IDHotel = item.Key.ToString();
foreach (var iLista in lista_bloques)
{
if (b.ID == iLista.ID)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateBloquesAsync(b);
}
else
{
await App.Database.SaveBloquesAsync(b);
}
}
existe = false;
//if exists
foreach (var iLista in lista_hoteles)
{
if (h.ID == iLista.ID)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateHotelesAsync(h);
}
else
{
await App.Database.SaveHotelesAsync(h);
}
}
//SECCIONES
var secciones = JsonConvert.DeserializeObject<Secciones>(content);
List<Model.Seccion> lista_secciones = await App.Database.GetSeccionesAsync();
foreach (var item in secciones.secciones)
{
Model.Seccion s = new Model.Seccion
{
ID = item.Key.ToString(),
Nombre = item.Value
};
bool existe = false;
//if exists
foreach (var iLista in lista_secciones)
{
if (s.ID == iLista.ID)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateSeccionAsync(s);
}
else{
await App.Database.SaveSeccionAsync(s);
}
}
string data = Preferences.Get("IdError", "");
if (data == "0")
{
Application.Current.MainPage = new HomePage();
}
else
{
await DisplayAlert("Error", Preferences.Get("Nombre", ""), "Cerrar");
}
}
}
catch (Exception exc)
{
Console.WriteLine("EXCEPTION:::: " + exc);
await DisplayAlert("Error", exc.ToString(), "Cerrar");
}
}
}
}
HomePage.xaml.cs
namespace WorkersApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HomePage : Shell
{
public IList<Seccion> Secciones { get; set; }
public HomePage()
{
InitializeComponent();
Task.Run(async () =>
Secciones = await App.Database.GetSeccionesAsync()).Wait();
foreach(var item in Secciones)
{
Console.WriteLine(item.Nombre);
switch (item.Nombre)
{
case "Partes":
FlyPartes.IsVisible = true;
//Meter Partes en Parte
string url = "https://api.com/?f=partes.getList";
Task task = GetPartesFromApi(url);
break;
case "Auditorias":
FlyAuditorias.IsVisible = true;
break;
case "Maquinas":
FlyMaquinaria.IsVisible = true;
break;
case "Pisos":
FlyPisos.IsVisible = true;
break;
}
}
}
public async Task GetPartesFromApi(string url)
{
HttpClient myClient = new HttpClient();
try
{
var response = await myClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var error = JsonConvert.DeserializeObject<Errores>(content);
List<string> errror = new List<string>();
foreach (var item in error.error)
{
errror.Add(item.Value);
}
if (errror[0] != "0")
{
Preferences.Set("IdError", errror[0]);
Preferences.Set("Nombre", errror[1]);
return;
}
else
{
Preferences.Set("IdError", errror[0]);
Preferences.Set("Nombre", errror[1]);
}
var partes = JsonConvert.DeserializeObject<Objetos.Partes>(content);
List<Model.Partes> lista = await App.Database.GetPartesAsync();
foreach (var item in partes.partes)
{
Model.Partes p = new Model.Partes();
p = JsonConvert.DeserializeObject<Model.Partes>(item.Value.ToString());
p.ID = item.Key.ToString();
bool existe = false;
//if exists
foreach (var iLista in lista)
{
if (p.ID == iLista.ID)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdatePartesAsync(p);
}
else
{
await App.Database.SavePartesAsync(p);
}
}
}
}
catch (Exception exc)
{
Console.WriteLine("EXCEPTION:::: " + exc);
await DisplayAlert("Error", exc.ToString(), "Cerrar");
}
}
}
}
Partes.xaml.cs
namespace WorkersApp.Pageviews
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Partes : ContentPage
{
public IList<Model.Partes> Partess { get; set; }
public Partes()
{
InitializeComponent();
Task.Run(async () =>
Partess = await App.Database.GetPartesAsync()).Wait();
int contador = 0;
foreach (var item in Partess)
{
Color c = Color.Black;
if (contador % 2 == 0)
{
c = Color.FromRgb(64, 64, 64);
}
var partesBoxClick = new BoxView()
{
WidthRequest = 900,
HeightRequest = 120,
HorizontalOptions = LayoutOptions.Start,
VerticalOptions = LayoutOptions.Start,
BackgroundColor = c,
ClassId = item.ID
};
var partesBoxClick_tap = new TapGestureRecognizer();
partesBoxClick_tap.Tapped += (s, e) =>
{
//OPEN PARTE
GetDatosParteFromApi("https://api.com/?f=partes.get&id= " + partesBoxClick.ClassId, partesBoxClick.ClassId);
};
partesBoxClick.GestureRecognizers.Add(partesBoxClick_tap);
PartesListaView.Children.Add(partesBoxClick, 0, contador);
Color color = Color.Red;
Console.WriteLine("COLOR:::: " + item.Operacion);
switch (item.Operacion)
{
case "nuevo":
color = Color.Red;
break;
case "asignado":
color = Color.GreenYellow;
break;
case "en progreso":
color = Color.Orange;
break;
case "anulado":
color = Color.Gray;
break;
case "en ejecucion":
color = Color.DeepSkyBlue;
break;
case "cerrado":
color = Color.Green;
break;
case "terceros":
color = Color.Firebrick;
break;
}
PartesListaView.Children.Add(new BoxView() { BackgroundColor = color, WidthRequest = 5, HeightRequest = 120, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Start }, 0, contador);
PartesListaView.Children.Add(new Label { Text = item.Titulo, FontSize=16, FontAttributes=FontAttributes.Bold, Padding = new Thickness(10, 0, 0, 0), HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Start }, 0, contador);
PartesListaView.Children.Add(new Label { Text = item.Departamento, Padding = new Thickness(10, 0, 10, 18), HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.End }, 0, contador);
PartesListaView.Children.Add(new Label { Text = item.Hotel, Padding = new Thickness(10, 0, 10, 0), HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.End }, 0, contador);
PartesListaView.Children.Add(new Label { Text = item.Fecha, Padding = new Thickness(10, 0, 10, 18), HorizontalOptions = LayoutOptions.End, VerticalOptions = LayoutOptions.End }, 0, contador);
PartesListaView.Children.Add(new Label { Text = item.Prioridad, Padding = new Thickness(10, 0, 10, 0), HorizontalOptions = LayoutOptions.End, VerticalOptions = LayoutOptions.End }, 0, contador);
contador++;
}
}
public async Task GetDatosParteFromApi(string url, string id)
{
HttpClient myClient = new HttpClient();
try
{
var response = await myClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
//GET ERROR
var error = JsonConvert.DeserializeObject<Errores>(content);
List<string> errror = new List<string>();
foreach (var item in error.error)
{
errror.Add(item.Value);
}
if (errror[0] != "0")
{
Preferences.Set("IdError", errror[0]);
Preferences.Set("Nombre", errror[1]);
return;
}
//GET DATOS
List<string> ids = new List<string>();
List<string> idsh = new List<string>();
var Datos = JsonConvert.DeserializeObject<Parte>(content);
string parte_datos = "";
string parte_fotos = "";
string parte_historico = "";
foreach (var item in Datos.parte)
{
if (item.Key.ToString() == "datos")
{
List<Model.Parte> datosParte = await App.Database.GetDatosParteAsync();
parte_datos = item.Value.ToString();
Model.Parte parte = new Model.Parte();
parte = JsonConvert.DeserializeObject<Model.Parte>(parte_datos);
parte.ID_Parte = id;
bool existe = false;
foreach (var iLista in datosParte)
{
if (parte.ID_Parte == iLista.ID_Parte)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateDatosParteAsync(parte);
}
else
{
await App.Database.SaveDatosParteAsync(parte);
}
}
else if (item.Key.ToString() == "fotos")
{
parte_fotos = item.Value.ToString();
List<Model.Fotos> fotos = await App.Database.GetFotosAsync();
List<Model.Fotos> FotoList = new List<Model.Fotos>();
//foto = JsonConvert.DeserializeObject<Model.Fotos>(parte_fotos);
FotoList = JsonConvert.DeserializeObject<List<Model.Fotos>>(parte_fotos);
foreach(var fotoI in FotoList)
{
Model.Fotos foto = new Model.Fotos();
foto = fotoI;
foto.ID_Parte = id;
bool existe = false;
ids.Add(foto.ID_Foto);
foreach (var iLista in fotos)
{
if (foto.ID_Foto == iLista.ID_Foto)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateFotoAsync(foto);
}
else
{
await App.Database.SaveFotoAsync(foto);
}
}
}
else if (item.Key.ToString() == "historico")
{
parte_historico = item.Value.ToString();
List<Model.Historico> historicos = await App.Database.GetHistoricoAsync();
List<Model.Historico> HistoricoList = new List<Model.Historico>();
HistoricoList = JsonConvert.DeserializeObject<List<Model.Historico>>(parte_historico);
foreach (var historicoI in HistoricoList)
{
Model.Historico historico = new Model.Historico();
historico = historicoI;
historico.idHistorico = id + historico.fechaEvento;
bool existe = false;
idsh.Add(historico.idHistorico);
foreach (var iLista in historicos)
{
if (historico.idHistorico == iLista.idHistorico)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateHistoricoAsync(historico);
}
else
{
await App.Database.SaveHistoricoAsync(historico);
}
}
}
}
string data = Preferences.Get("IdError", "");
if (data == "0")
{
await Navigation.PushAsync(new DatosParte(id, ids, idsh));
}
else
{
await DisplayAlert("Error", Preferences.Get("Nombre", ""), "Cerrar");
}
}
}
catch (Exception exc)
{
Console.WriteLine("EXCEPTION:::: " + exc);
await DisplayAlert("Error", exc.ToString(), "Cerrar");
}
}
private void Filter_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new FiltroPartes());
}
}
}
Thanks for reading.
EDIT:::::
After cleaning the API, now i get fewer Tickes to check if update or save indo local sqlite.
But I just notice I still need to check the whole BBDD to login.
The API now check tickets from last 30 days from curdate and with
operation_state <> "Closed"
I think I'm login (1 call to API to check if user is good)
Then in the HomePage im getting all the tickets (1 call to API to get tickets)
AND THEN. When I click in the Tickets Menu, it loads into the listview. (So another 15 seconds).
I believe i need to remove the API call in HomePage. and add it when I click in Ticket Menu.
Will check in some time. Or tomorrow.
EDIT:
So i checked and i was right, I changed the app to get all the tickets when I tap the Tickets menu.
Thanks for reading.

Cristian, it's normal in mobile app development. According to the amount of data we are getting it takes time to load.
Though as you have mentioned that you are calling service and inserting data if not exist and update if exist, so this data are dynamic and getting changed every time when you call? If not than instead of updating or calling service again, use the data from local database.
If not than You can use monkey cache, that will help you to improve your app performance. But use it only in case of static data.
Another thing instead of getting all data at once from service, try to get only the data that is required and will come in your use, this will also improve your app's performance. And also decrease the amount of internet data it uses.
Refer this for more details: https://heartbeat.fritz.ai/techniques-for-improving-performance-in-a-xamarin-forms-application-b439f2f04156
Also you can remove the images from app and use FontAwesome icons for that.
Hope this will help you in some or other way!

Related

Xamarin.Forms Imagesource issue

I have a view with an image: <Image Source="{Binding MainUrl}"/>
Image binding value : My image source on loading from database
the value of MainUrl variable is stored in an sqlite table.public string LogoUrl { get; set; }
viewmodel :
private string _logoUrl;
public string LogoUrl
{
get { return _logoUrl; }
set
{
SetValue(ref _logoUrl, value);
OnPropertyChanged(nameof(LogoUrl));
}
}
the user has the option to change the image using filepicker :
var file = await FilePicker.PickAsync(options);
if (file == null)
{
return;
}
var stream = await file.OpenReadAsync();
MainUrl = ImageSource.FromStream(() => stream);
LblImportLogo = file.FullPath;
Parameter.LogoUrl = file.FullPath;
when I choose an image with filepicker, this one is well displayed and the the path is saved into sqlite table but when I restart the application, the image is no longer displayed despite the path being well informed (this one is external). the problem is in all platforms, UWP,android and IOS. can you help me find a solution.
Mainpage.xaml.cs :
public MainPage()
{
var parameterStore = new SQLiteParameterStore(DependencyService.Get<ISQLiteDb>());
var pageService = new PageService();
ViewModel = new MainPageViewModel(parameterStore, pageService);
InitializeComponent();
NavigationPage.SetHasBackButton(this, false);
NavigationPage.SetHasNavigationBar(this, false);
}
protected override void OnAppearing()
{
ViewModel.LoadDataCommand.Execute(null);
base.OnAppearing();
}
public MainPageViewModel ViewModel
{
get { return BindingContext as MainPageViewModel; }
set { BindingContext = value; }
}
MainPageViewModel :
......
private ImageSource _mainurl;
public ImageSource MainUrl
{
get { return _mainurl; }
set
{
SetValue(ref _mainurl, value);
OnPropertyChanged(nameof(MainUrl));
}
}
......
private async Task LoadData()
{
var parameters = await _parameterStore.GetAll();
var elts = parameters.Count();
if (elts < 1)
{
//set default values
mainParameter = new Parameter();
mainParameter.LogoUrl = "default.jpg";
MainUrl = mainParameter.LogoUrl;
}
else
{
//set parameters
mainParameter = parameters[0];
MainUrl = ImageSource.FromFile(mainParameter.LogoUrl);
}
}

Xamarin.forms - Background color changes when activity is about to load

I have a activity with a listView that got items which drive us to another activity called Main Chat. The problem resides when I touch one of those items. Before it loads the respective activity, the background color of the main activity changes to green. I've inspected my code but I can't find any sample of code that does that type of behavior. Here's the video of what happen and the following code:
Video: https://files.fm/u/7nt2szdy#/view/20200213_115056.mp4;play
Sample code of the "click item"
async void OnListItemClicked(object o, ItemTappedEventArgs e)
{
try
{
((ListView)o).SelectedItem = null;
var vListItem = e.Item as Classes.ClassConversation.ResultadoConversation;
var getResposta = await Servicos.Servicos.Token(vListItem.institutionId);
if (getResposta)
await Navigation.PushAsync(new Chat.MainChat(vListItem, user2, true));
}
catch (Exception)
{
await DisplayAlert(Languages.AppResources.Notifications, Languages.AppResources.ErrorOccurred, "Ok");
}
}
Sample code of the Main Chat"
public MainChat (Classes.ClassConversation.ResultadoConversation conversation, Classes.ClassUser.Result user, bool Resposta)
{
InitializeComponent();
//Muda a cor do texto e o local da tab no android
UnselectedTabColor = Color.FromHex("#80FFFFFF");
SelectedTabColor = Color.White;
//Muda a cor do toolbar e texto
if (Resposta == true)
{
((NavigationPage)Xamarin.Forms.Application.Current.MainPage).BackgroundColor = (Color)App.Current.Resources["colorPrimary"];
((NavigationPage)Xamarin.Forms.Application.Current.MainPage).BarBackgroundColor = (Color)App.Current.Resources["colorPrimary"];
((NavigationPage)Xamarin.Forms.Application.Current.MainPage).BarTextColor = (Color)App.Current.Resources["white"];
}
if (conversation.OtherUser == null)
{
conversation.OtherUser = new Classes.ClassConversation.User();
if(conversation.user_From.rowKey == user.rowKey)
{
conversation.OtherUser = conversation.user_To;
}
else
{
conversation.OtherUser = conversation.user_From;
}
}
//Set Name and image of the other user and chat title
if (conversation.OtherUser.photoUri != null)
ImageUser.Source = new UriImageSource { CachingEnabled = true, Uri = conversation.OtherUser.photoUri, CacheValidity = new TimeSpan(800000, 0, 0, 0) };
TitleChat.Text = conversation.title;
NameOtherUser.Text = conversation.OtherUser.name;
if(Device.RuntimePlatform != Device.iOS)
Children.Add(new ChatPage(conversation, user));
else
Children.Add(new ChatPageIos(conversation, user));
Children.Add(new Report(conversation, user));
result = conversation;
}

Watson unity android bad recognition

Guys I'm using Unity and Watson to make and vr app that accepts voice commands. I'm using the ExampleStreaming.cs provided with the asset but the recognition is terrible. I change the language model to Portuguese on the code. I'm using Samsung galaxy s7 on gear vr with the mic plugged in. I guess the app is using the cellphone mic and not the plugged one. Any help here.
Here's the code
private int _recordingRoutine = 0;
private string _microphoneID = null;
private AudioClip _recording = null;
private int _recordingBufferSize = 1;
private int _recordingHZ = 22050;
private SpeechToText _service;
public GolemController GolemControllerObj;
void Start()
{
LogSystem.InstallDefaultReactors();
Runnable.Run(CreateService());
}
private IEnumerator CreateService()
{
// Create credential and instantiate service
Credentials credentials = null;
if (!string.IsNullOrEmpty(_username) && !string.IsNullOrEmpty(_password))
{
// Authenticate using username and password
credentials = new Credentials(_username, _password, _serviceUrl);
}
else if (!string.IsNullOrEmpty(_iamApikey))
{
// Authenticate using iamApikey
TokenOptions tokenOptions = new TokenOptions()
{
IamApiKey = _iamApikey,
IamUrl = _iamUrl
};
credentials = new Credentials(tokenOptions, _serviceUrl);
// Wait for tokendata
while (!credentials.HasIamTokenData())
yield return null;
}
else
{
throw new WatsonException("Please provide either username and password or IAM apikey to authenticate the service.");
}
_service = new SpeechToText(credentials);
_service.StreamMultipart = true;
_service.RecognizeModel="pt-BR_BroadbandModel";
Active = true;
StartRecording();
}
public bool Active
{
get { return _service.IsListening; }
set
{
if (value && !_service.IsListening)
{
_service.DetectSilence = true;
_service.EnableWordConfidence = true;
_service.EnableTimestamps = true;
_service.SilenceThreshold = 0.01f;
_service.MaxAlternatives = 0;
_service.EnableInterimResults = true;
_service.OnError = OnError;
_service.InactivityTimeout = -1;
_service.ProfanityFilter = false;
_service.SmartFormatting = true;
_service.SpeakerLabels = false;
_service.WordAlternativesThreshold = null;
_service.StartListening(OnRecognize, OnRecognizeSpeaker);
}
else if (!value && _service.IsListening)
{
_service.StopListening();
}
}
}
private void StartRecording()
{
if (_recordingRoutine == 0)
{
UnityObjectUtil.StartDestroyQueue();
_recordingRoutine = Runnable.Run(RecordingHandler());
}
}
private void StopRecording()
{
if (_recordingRoutine != 0)
{
Microphone.End(_microphoneID);
Runnable.Stop(_recordingRoutine);
_recordingRoutine = 0;
}
}
private void OnError(string error)
{
Active = false;
Log.Debug("ExampleStreaming.OnError()", "Error! {0}", error);
}
private IEnumerator RecordingHandler()
{
Log.Debug("ExampleStreaming.RecordingHandler()", "devices: {0}", Microphone.devices);
_recording = Microphone.Start(_microphoneID, true, _recordingBufferSize, _recordingHZ);
yield return null; // let _recordingRoutine get set..
if (_recording == null)
{
StopRecording();
yield break;
}
bool bFirstBlock = true;
int midPoint = _recording.samples / 2;
float[] samples = null;
while (_recordingRoutine != 0 && _recording != null)
{
int writePos = Microphone.GetPosition(_microphoneID);
if (writePos > _recording.samples || !Microphone.IsRecording(_microphoneID))
{
Log.Error("ExampleStreaming.RecordingHandler()", "Microphone disconnected.");
StopRecording();
yield break;
}
if ((bFirstBlock && writePos >= midPoint)
|| (!bFirstBlock && writePos < midPoint))
{
// front block is recorded, make a RecordClip and pass it onto our callback.
samples = new float[midPoint];
_recording.GetData(samples, bFirstBlock ? 0 : midPoint);
AudioData record = new AudioData();
record.MaxLevel = Mathf.Max(Mathf.Abs(Mathf.Min(samples)), Mathf.Max(samples));
record.Clip = AudioClip.Create("Recording", midPoint, _recording.channels, _recordingHZ, false);
record.Clip.SetData(samples, 0);
_service.OnListen(record);
bFirstBlock = !bFirstBlock;
}
else
{
// calculate the number of samples remaining until we ready for a block of audio,
// and wait that amount of time it will take to record.
int remaining = bFirstBlock ? (midPoint - writePos) : (_recording.samples - writePos);
float timeRemaining = (float)remaining / (float)_recordingHZ;
yield return new WaitForSeconds(timeRemaining);
}
}
yield break;
}
private void OnRecognize(SpeechRecognitionEvent result, Dictionary<string, object> customData)
{
if (result != null && result.results.Length > 0)
{
foreach (var res in result.results)
{
foreach (var alt in res.alternatives)
{
string text = string.Format("{0} ({1}, {2:0.00})\n", alt.transcript, res.final ? "Final" : "Interim", alt.confidence);
Log.Debug("ExampleStreaming.OnRecognize()", text);
ResultsField.text = text;
if(res.final == true)
{
GolemControllerObj.GolemActions(alt.transcript);
}
}
if (res.keywords_result != null && res.keywords_result.keyword != null)
{
foreach (var keyword in res.keywords_result.keyword)
{
Log.Debug("ExampleStreaming.OnRecognize()", "keyword: {0}, confidence: {1}, start time: {2}, end time: {3}", keyword.normalized_text, keyword.confidence, keyword.start_time, keyword.end_time);
}
}
if (res.word_alternatives != null)
{
foreach (var wordAlternative in res.word_alternatives)
{
Log.Debug("ExampleStreaming.OnRecognize()", "Word alternatives found. Start time: {0} | EndTime: {1}", wordAlternative.start_time, wordAlternative.end_time);
foreach(var alternative in wordAlternative.alternatives)
Log.Debug("ExampleStreaming.OnRecognize()", "\t word: {0} | confidence: {1}", alternative.word, alternative.confidence);
}
}
}
}
}
private void OnRecognizeSpeaker(SpeakerRecognitionEvent result, Dictionary<string, object> customData)
{
if (result != null)
{
foreach (SpeakerLabelsResult labelResult in result.speaker_labels)
{
Log.Debug("ExampleStreaming.OnRecognize()", string.Format("speaker result: {0} | confidence: {3} | from: {1} | to: {2}", labelResult.speaker, labelResult.from, labelResult.to, labelResult.confidence));
}
}
}

ionic framework + cordova. WebSocket is not working in the android release version, but the debug version works correctly

With this logs:
WebSocket connection to 'wss://xxxxxx.net/' failed: WebSocket opening handshake was canceled"
"TransportWebSocket.errorHandler - Error {}"
"TransportWebSocket.closeHandler - Error {"code":1006,"text":""}"
Please help with this problem.
sp.external.TransportWebSocket = function () {
var self = this;
var socket = null;
var isOpen = false;
var listSendMsg = [];
this.openHandler = null;
this.closeHandler = null;
this.messageHandler = null;
this.errorHandler = null;
this.serverURL = '';
this.send = function (_data, _highPrioritetFlag) {
utils.logger.debug('TransportWebSocket', 'send', 'Open status:' + isOpen);
_highPrioritetFlag = _highPrioritetFlag || false;
if (isOpen) {
if (_data && typeof _data === 'object') {
try {
socket.send(JSON.stringify(_data));
}
catch (error) {
throw new Error('Invalid JSON stringify');
}
}
else {
throw new Error('The data sent must be an object');
}
}
else {
if (_highPrioritetFlag) {
listSendMsg.unshift(_data);
}
else {
listSendMsg.push(_data);
}
openSocket();
}
};
this.reopen = function () {
utils.logger.debug('TransportWebSocket', 'reopen');
openSocket();
};
this.close = function (_code) {
utils.logger.debug('TransportWebSocket', 'close');
socket.close(_code);
};
function procListMsg() {
utils.logger.debug('TransportWebSocket', 'procListMsg', 'Processing buffer messages, items:' + listSendMsg.length);
if (listSendMsg.length > 0) {
self.send(listSendMsg.shift());
setTimeout(procListMsg, 20);
}
}
function openHandler() {
utils.logger.debug('TransportWebSocket', 'openHandler', 'WebSocket.readyState:' + socket.readyState);
if (socket.readyState === WebSocket.OPEN) {
isOpen = true;
procListMsg();
if (self.openHandler) {
self.openHandler();
}
}
}
function closeHandler(error) {
utils.logger.debug('TransportWebSocket', 'closeHandler', 'Error', {code: error.code, text: error.reason});
isOpen = false;
if (socket.readyState === WebSocket.CLOSED) {
if (self.closeHandler) {
self.closeHandler(error);
}
}
}
function errorHandler(error) {
utils.logger.debug('TransportWebSocket', 'errorHandler', 'Error', {code: error.code, text: error.reason});
isOpen = false;
if (self.errorHandler) {
self.errorHandler(error);
}
}
function messageHandler(e) {
var msg = null;
if (self.messageHandler) {
try {
msg = JSON.parse(e.data);
}
catch (error) {
throw new Error('Invalid JSON format in response: ' + e.data);
}
self.messageHandler(msg);
}
}
function openSocket() {
utils.logger.debug('TransportWebSocket', 'openSocket', 'Opening');
socket = new WebSocket(self.serverURL);
socket.onopen = openHandler;
socket.onclose = closeHandler;
socket.onmessage = messageHandler;
socket.onerror = errorHandler;
}
};
I don't know if you have solved this issue, but for people encountering the same trouble and who find this thread, you may check this cordova "release" behaves differently to "debug" regarding SSL
In short, modify the file that is making the behavior different between debug and release:
platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java
Comment out the content of the method onReceivedSslError and replace it with
handler.proceed();
return;

Node.js- Comapring items from AWS DynamoDB- only lowercases

I want to get Items from my AWS DynamoDB, via Lambda, which satisfy condition:
if (typeof event.keyWord != "undefined") {
var str = event.keyWord;
str = str.toLowerCase();
params.ExpressionAttributeValues[":keyWord"] = {"S": str};
params.FilterExpression = "contains (#nm, :keyWord)";
}
I send string (keyWord) from my android app, then call toLowerCase function on it and compare it with #nm from DB. My question is, how can I call similar function (toLowerCase) on #nm before comparing them? My whole code:
var AWS = require('aws-sdk');
var db = new AWS.DynamoDB();
exports.handler = function(event, context) {
var params = {
TableName: "Events", //"StreamsLambdaTable",
// ProjectionExpression: "locationLat, locationLon",
ProjectionExpression: "ID, description, endDate, imagePath, locationLat, locationLon, #nm, #tp" //specifies the attributes you want in the scan result.
ExpressionAttributeNames: {
"#nm": "name",
"#tp": "type",
},
ExpressionAttributeValues: {
":lower_lon": {"N": event.low_lon},
":higher_lon": {"N": event.high_lon},
":lower_lat": {"N": event.low_lat},
":higher_lat": {"N": event.high_lat}
}
};
if (typeof event.keyWord != "undefined") {
var str = event.keyWord;
str = str.toLowerCase();
params.ExpressionAttributeValues[":keyWord"] = {"S": str};
params.FilterExpression = params.FilterExpression + " and contains (#nm, :keyWord)";
}
db.scan(params, function(err, data) {
if (err) {
console.log(err); // an error occurred
}
else {
data.Items.forEach(function(record) {
console.log(
record.name.S + "");
});
context.succeed(data.Items); // data.Items
}
});
};

Categories

Resources