Related
I have a foreground Service, which updates phonebook every 24h and uploads data from local databse to server every 2 minutes. I'm using MessagingCenter to get the exact time, when the data upload was successful and when the contacts were last updated. Then print this data to labels on the main screen. The problem, is that the labels are always resetting whenever I stop my service, or close and reopen my app.
Is there a way to save labels text, without creating a new database?
Method for sending all data after every call:
public async Task SendData(List<PhoneCall> phoneCalls)
{
Device.BeginInvokeOnMainThread(() =>
{
MessagingCenter.Send<object, string>(this, "Bandyta", DateTime.Now.ToString());
});
if (NetworkCheck.IsInternet())
{
var uri = new Uri("http://mmmmmmmmmmm.aspx");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
foreach (var item in phoneCalls)
{
string json = JsonConvert.SerializeObject(item);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await client.PostAsync(uri, content);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
Device.BeginInvokeOnMainThread(() =>
{
MessagingCenter.Send<object, string>(this, "Sekmingai", DateTime.Now.ToString());
});
}
else
{
await App.Database.SaveLogAsync(new Logs
{
deviceno = item.deviceno,
phoneno = item.phoneno,
direction = item.direction,
dt = item.dt,
action = item.action
});
}
}
}
else
{
foreach (var item in phoneCalls)
{
await App.Database.SaveLogAsync(new Logs
{
deviceno = item.deviceno,
phoneno = item.phoneno,
direction = item.direction,
dt = item.dt,
action = item.action
});
}
}
}
Foreground service:
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
IntentFilter filter = new IntentFilter();
filter.AddAction(TelephonyManager.ActionPhoneStateChanged);
switch (intent.Action)
{
case null:
GetWakelock();
myReceiver = new MyReceiver();
var notif = DependencyService.Get<INotificationHelper>().ReturnNotif();
StartUploadingContactsToServer();
RegisterReceiver(myReceiver, filter);
StartForeground(1001, notif);
break;
case "stopService":
callServiceHelper.UnsubscribeMessages();
UnregisterReceiver(myReceiver);
wl.Release();
callServiceHelper.StopMyService();
break;
}
return StartCommandResult.NotSticky;
}
Label ViewModel class:
public class LabelModel : BindableObject
{
string dataSentSuccessful = "Paskutinį kartą pavyko išsiųsti duomenis sėkmingai: ";
string dataSentTried = "Paskutinį kartą bandyta išsiųsti duomenis: ";
string lastTimeContactsUpdated = "Paskutinį kartą kontaktai buvo atnaujinti: ";
public LabelModel()
{
MessagingCenter.Subscribe<object, string>(this, "Atnaujinti", (sender, args) =>
{
LastTimeContactsUpdated = $"Paskutinį kartą kontaktai buvo atnaujinti: \n {args}";
});
MessagingCenter.Subscribe<object, string>(this, "Sekmingai", (sender, args) =>
{
DataSentSuccessful = $"Paskutinį kartą pavyko išsiųsti duomenis sėkmingai: \n {args}";
});
MessagingCenter.Subscribe<object, string>(this, "Bandyta", (sender, args) =>
{
DataSentTried = $"Paskutinį kartą bandyta išsiųsti duomenis: \n {args}";
});
}
public string DataSentTried
{
get => dataSentTried;
set
{
dataSentTried = value;
OnPropertyChanged(nameof(DataSentTried));
}
}
public string DataSentSuccessful
{
get => dataSentSuccessful;
set
{
dataSentSuccessful = value;
OnPropertyChanged(nameof(DataSentSuccessful));
}
}
public string LastTimeContactsUpdated
{
get => lastTimeContactsUpdated;
set
{
lastTimeContactsUpdated = value;
OnPropertyChanged(nameof(LastTimeContactsUpdated));
}
}
}
MainPage:
public partial class MainPage : ContentPage
{
IContactsHelper contactsHelper = DependencyService.Get<IContactsHelper>();
public MainPage()
{
InitializeComponent();
if (!DependencyService.Get<ICallServiceHelper>().IsMyServiceRunning())
{
BindingContext = new LabelModel();
deviceNoLabel.Text = contactsHelper.GetIdentifier();
}
}
}
MainActivity:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
var permissions = new string[]
{
Manifest.Permission.WakeLock,
Manifest.Permission.ForegroundService,
Manifest.Permission.ReadPhoneState,
Manifest.Permission.ReadCallLog,
Manifest.Permission.ReadContacts,
Manifest.Permission.WriteContacts,
};
ActivityCompat.RequestPermissions(this, permissions, 123);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum]Permission[] grantResults)
{
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 123 && grantResults.Length > 0 && grantResults[0] == Permission.Granted)
{
if (!DependencyService.Get<ICallServiceHelper>().IsMyServiceRunning())
{
DependencyService.Get<ICallServiceHelper>().StartMyService();
}
}
}
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!
I'm calling a WebApi from xamarin forms. I'm not using "localhost" but the actual IP address and have enabled this IP address after seeing some post on stackoverflow about the issue but it didn't work. I'm still getting the errors - System.Net.WebExceptionStatus.ConnectFailure,System.Net.WebExceptionStatus,System.Net.WebExceptionInternalStatus.RequestFatal
The stacktrace error:
{System.Net.WebException: Failed to connect to /223.0.0.1:44321 ---> Java.Net.ConnectException: Failed to connect to /223.0.0.1:44321
at Java.Interop.JniEnvironment+InstanceMethods.CallVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0006e] in <89755ea61d9c4ae0a40ce90b872c9e2d>:0
at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeAbstractVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x00014] in <89755ea61d9c4ae0a40ce90b872c9e2d>:0
at Java.Net.HttpURLConnectionInvoker.Connect () [0x0000a] in <2df86f44c8e946618f31cb3aed952f5b>:0
at Xamarin.Android.Net.AndroidClientHandler+<>c__DisplayClass44_0.b__0 () [0x0007d] in <2df86f44c8e946618f31cb3aed952f5b>:0
at System.Threading.Tasks.Task.InnerInvoke () [0x0000f] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2476
at System.Threading.Tasks.Task.Execute () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2319
--- End of stack trace from previous location where exception was thrown ---
at Xamarin.Android.Net.AndroidClientHandler.DoProcessRequest (System.Net.Http.HttpRequestMessage request, Java.Net.URL javaUrl, Java.Net.HttpURLConnection httpConnection, System.Threading.CancellationToken cancellationToken, Xamarin.Android.Net.AndroidClientHandler+RequestRedirectionState redirectState) [0x0012e] in <2df86f44c8e946618f31cb3aed952f5b>:0
--- End of inner exception stack trace ---
at Xamarin.Android.Net.AndroidClientHandler.DoProcessRequest (System.Net.Http.HttpRequestMessage request, Java.Net.URL javaUrl, Java.Net.HttpURLConnection httpConnection, System.Threading.CancellationToken cancellationToken, Xamarin.Android.Net.AndroidClientHandler+RequestRedirectionState redirectState) [0x0017e] in <2df86f44c8e946618f31cb3aed952f5b>:0
at Xamarin.Android.Net.AndroidClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x002d0] in <2df86f44c8e946618f31cb3aed952f5b>:0
at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) [0x0017e] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:506
at FamilyTreeApp.Pages.UserChildrenTabbedPage.SendURI (System.Uri u, System.Net.Http.HttpContent c) [0x0007f] in C:\Users***\source\repos\FamilyTreeApp\FamilyTreeApp\FamilyTreeApp\Pages\UserChildrenTabbedPage.xaml.cs:211 }
The codes to call the webAPI(on click of Submit button) in UserChildrenxaml.cs
static async Task<string> SendURI(Uri u, HttpContent c)
{
var response = string.Empty;
try {
using (var client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = u,
Content = c
};
HttpResponseMessage result = await client.SendAsync(request);
if (result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString();
}
}
}
catch (Exception ex) {
throw ex;
}
return response;
}
private async void OnSubmit(object sender, EventArgs e)
{
User = new UserInfoTabbedPageViewModel()
{
FirstName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "FirstName").Value,
LastName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "LastName").Value,
Titles = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Titles").Value,
Address1 = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Address1").Value,
Address2 = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Address2").Value,
Age = int.Parse(DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Age").Value.ToString()),
City = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "City").Value,
Zip = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Zip").Value,
Phone = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Phone").Value,
State = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "State").Value,
Country = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Country").Value,
FatherFirstName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "FatherFirstName").Value,
FatherLastName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "FatherLastName").Value,
MotherFirstName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "MotherFirstName").Value,
MotherLastName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "MotherLastName").Value,
Spouse1_FirstName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Spouse1_FirstName").Value,
Spouse1_LastName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Spouse1_LastName").Value,
Spouse2_FirstName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Spouse2_FirstName").Value,
Spouse2_LastName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Spouse2_LastName").Value,
Spouse3_FirstName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Spouse3_FirstName").Value,
Spouse3_LastName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Spouse3_FirstName").Value,
Spouse4_FirstName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Spouse4_FirstName").Value,
Spouse4_LastName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Spouse4_LastName").Value,
Spouse5_FirstName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Spouse5_FirstName").Value,
Spouse5_LastName = DataManager.Instance.Forms1.FirstOrDefault(x => x.Key == "Spouse5_LastName").Value,
Son1_FirstName = User.Son1_FirstName,
Son1_LastName = User.Son1_LastName,
Son2_FirstName = User.Son2_FirstName,
Son2_LastName = User.Son2_LastName,
Son3_FirstName = User.Son3_FirstName,
Son3_LastName = User.Son3_LastName,
Son4_FirstName = User.Son4_FirstName,
Son4_LastName = User.Son4_LastName,
Son5_FirstName = User.Son5_FirstName,
Son5_LastName = User.Son5_LastName,
Son6_FirstName = User.Son6_FirstName,
Son6_LastName = User.Son6_LastName,
Son7_FirstName = User.Son7_FirstName,
Son7_LastName = User.Son7_LastName,
Son8_FirstName = User.Son8_FirstName,
Son8_LastName = User.Son8_LastName,
Son9_FirstName = User.Son9_FirstName,
Son9_LastName = User.Son9_LastName,
Son10_FirstName = User.Son10_FirstName,
Son10_LastName = User.Son10_LastName,
Daughter1_FirstName = User.Daughter1_FirstName,
Daughter1_LastName = User.Daughter1_LastName,
Daughter2_FirstName = User.Daughter2_FirstName,
Daughter2_LastName = User.Daughter2_LastName,
Daughter3_FirstName = User.Daughter3_FirstName,
Daughter3_LastName = User.Daughter3_LastName,
Daughter4_FirstName = User.Daughter4_FirstName,
Daughter4_LastName = User.Daughter4_LastName,
Daughter5_FirstName = User.Daughter5_FirstName,
Daughter5_LastName = User.Daughter5_LastName,
Daughter6_FirstName = User.Daughter6_FirstName,
Daughter6_LastName = User.Daughter6_LastName,
Daughter7_FirstName = User.Daughter7_FirstName,
Daughter7_LastName = User.Daughter7_LastName,
Daughter8_FirstName = User.Daughter8_FirstName,
Daughter8_LastName = User.Daughter8_LastName,
Daughter9_FirstName = User.Daughter9_FirstName,
Daughter9_LastName = User.Daughter9_LastName,
Daughter10_FirstName = User.Daughter10_FirstName,
Daughter10_LastName = User.Daughter10_LastName
};
Uri u = new Uri("http://223.0.0.1:44321/api/FamilyTree/Save");
string strPayload = JsonConvert.SerializeObject(User);
HttpContent c = new StringContent(strPayload, Encoding.UTF8, "application/json");
var t = await Task.Run(() => SendURI(u, c));
}
internal class RestHttpClient
{
public HttpResponseMessage ResponseMessage = new HttpResponseMessage();
public async void SendRequestAsync(string adaptiveUri, string xmlRequest)
{
using (HttpClient httpClient = new HttpClient())
{
StringContent httpConent = new StringContent(xmlRequest, Encoding.UTF8);
try
{
ResponseMessage = await httpClient.PostAsync(adaptiveUri, httpConent);
}
catch (Exception ex)
{
ResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
ResponseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex);
}
}
}
}
WebApi -FamilyTreeController
using FamilyTreeAPI.DTO;
using FamilyTreeAPI.Models;
using Microsoft.AspNetCore.Cors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.SessionState;
namespace FamilyTreeAPI.Controllers
{
[RoutePrefix("api/FamilyTree")]
public class FamilyTreeController : ApiController, IRequiresSessionState
{
[Route("GetAllUsers")]
[HttpGet]
[EnableCors]
public IHttpActionResult GetAllUsers()
{
IList<UserDTO> students = null;
using (var ctx = new FamilyTreeDBEntities())
{
students = ctx.FamilyTreeMasters
.Select(s => new UserDTO()).ToList<UserDTO>();
}
if (students.Count == 0)
{
return NotFound();
}
return Ok(students);
}
[Route("GetUser")]
[HttpGet]
[EnableCors]
public IHttpActionResult GetUser(int UserId)
{
IList<UserDTO> users = null;
using (var ctx = new FamilyTreeDBEntities())
{
users = ctx.FamilyTreeMasters.Where(w => w.UserID == UserId).Select(s => new UserDTO()).ToList<UserDTO>();
// students = ctx.FamilyTreeMasters.Where(w=>w.Address2=="hhh").Select(s => new UserDTO()
// {
// Id = s.StudentID,
// FirstName = s.FirstName,
// LastName = s.LastName,
//}).ToList<UserDTO>();
}
if (users.Count == 0)
{
return NotFound();
}
return Ok(users);
}
//Get action methods of the previous section
[Route("Save")]
[HttpPost]
[EnableCors]
public IHttpActionResult Save(UserDTO user)
{
if (!ModelState.IsValid)
return BadRequest("Invalid data.");
using (var ctx = new FamilyTreeDBEntities())
{
ctx.FamilyTreeMasters.Add(new FamilyTreeMaster()
{
MyPosition = 1,
MyParentPosition=1,
Title = user.Title,
FirstName = user.FirstName,
LastName = user.LastName,
Phone = user.Phone,
Age = user.Age,
Profession = user.Profession,
Address1 = user.Address1,
Address2 = user.Address2,
Zip = user.Zip,
City = user.City,
Country = user.Country,
State = user.State,
FatherFirstName = user.FatherFirstName,
FatherLastName = user.FatherLastName,
MotherFirstName = user.MotherFirstName,
MotherLastName = user.MotherLastName,
Spouse1_FirstName = user.Spouse1_FirstName,
Spouse1_LastName = user.Spouse1_LastName,
Spouse2_FirstName = user.Spouse2_FirstName,
Spouse2_LastName = user.Spouse2_LastName,
Spouse3_FirstName = user.Spouse3_FirstName,
Spouse3_LastName = user.Spouse3_LastName,
Spouse4_FirstName = user.Spouse4_FirstName,
Spouse4_LastName = user.Spouse4_LastName,
Spouse5_FirstName = user.Spouse5_FirstName,
Spouse5_LastName = user.Spouse5_LastName,
Son1_FirstName = user.Son1_FirstName,
Son1_LastName = user.Son1_LastName,
Son2_FirstName = user.Son2_FirstName,
Son2_LastName = user.Son2_LastName,
Son3_FirstName = user.Son3_FirstName,
Son3_LastName = user.Son3_LastName,
Son4_FirstName = user.Son4_FirstName,
Son4_LastName = user.Son4_LastName,
Son5_FirstName = user.Son5_FirstName,
Son5_LastName = user.Son5_LastName,
Son6_FirstName = user.Son6_FirstName,
Son6_LastName = user.Son6_LastName,
Son7_FirstName = user.Son7_FirstName,
Son7_LastName = user.Son7_LastName,
Son8_FirstName = user.Son8_FirstName,
Son8_LastName = user.Son8_LastName,
Son9_FirstName = user.Son9_FirstName,
Son9_LastName = user.Son9_LastName,
Son10_FirstName = user.Son10_FirstName,
Son10_LastName = user.Son10_LastName,
Daughter1_FirstName = user.Daughter1_FirstName,
Daughter1_LastName = user.Daughter1_LastName,
Daughter2_FirstName = user.Daughter2_FirstName,
Daughter2_LastName = user.Daughter2_LastName,
Daughter3_FirstName = user.Daughter3_FirstName,
Daughter3_LastName = user.Daughter3_LastName,
Daughter4_FirstName = user.Daughter4_FirstName,
Daughter4_LastName = user.Daughter4_LastName,
Daughter5_FirstName = user.Daughter5_FirstName,
Daughter5_LastName = user.Daughter5_LastName,
Daughter6_FirstName = user.Daughter6_FirstName,
Daughter6_LastName = user.Daughter6_LastName,
Daughter7_FirstName = user.Daughter7_FirstName,
Daughter7_LastName = user.Daughter7_LastName,
Daughter8_FirstName = user.Daughter8_FirstName,
Daughter8_LastName = user.Daughter8_LastName,
Daughter9_FirstName = user.Daughter9_FirstName,
Daughter9_LastName = user.Daughter9_LastName,
Daughter10_FirstName = user.Daughter10_FirstName,
Daughter10_LastName = user.Daughter10_LastName
}) ;
ctx.SaveChanges();
}
return Ok();
}
[Route("Update")]
[HttpGet]
[EnableCors]
public IHttpActionResult Put(UserDTO user)
{
if (!ModelState.IsValid)
return BadRequest("Not a valid model");
using (var ctx = new FamilyTreeDBEntities())
{
var existingStudent = ctx.FamilyTreeMasters.Where(s => s.UserID == user.UserID)
.FirstOrDefault<FamilyTreeMaster>();
if (existingStudent != null)
{
existingStudent.FirstName = user.FirstName;
existingStudent.LastName = user.LastName;
ctx.SaveChanges();
}
else
{
return NotFound();
}
}
return Ok();
}
[Route("Delete")]
[HttpGet]
[EnableCors]
public IHttpActionResult Delete(int userID)
{
if (userID <= 0)
return BadRequest("Not a valid student id");
using (var ctx = new FamilyTreeDBEntities())
{
var user = ctx.FamilyTreeMasters
.Where(s => s.UserID == userID)
.FirstOrDefault();
ctx.Entry(user).State = System.Data.Entity.EntityState.Deleted;
ctx.SaveChanges();
}
return Ok();
}
}
}
RouteConfig
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace FamilyTreeAPI
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "CreateUser",
url: "{controller}/{action}/{id}",
defaults: new { controller = "FamilyTree", action = "Save", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "GetUser",
url: "{controller}/{action}/{id}",
defaults: new { controller = "FamilyTree", action = "GetUser", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "UpdateUser",
url: "{controller}/{action}/{id}",
defaults: new { controller = "FamilyTree", action = "Update", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "DeleteUser",
url: "{controller}/{action}/{id}",
defaults: new { controller = "FamilyTree", action = "Delete", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Here are the FamilyTreeAPI's property Web where I created a virtual directory and the error in the QuickWatch from thrown exception
here is the controller - its a tabs moving page data are loaded first time itself . but only display while reload?
.controller('TestCntrl', function($scope, $state, $route, $window, Chats, $rootScope, $cordovaToast, $location, $ionicSlideBoxDelegate, $window, $ionicGesture, WebService, $localStorage) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});
$scope.Height = $window.innerHeight - 30;
$scope.chats = Chats.all();
$scope.remove = function(chat) {
Chats.remove(chat);
};
$scope.nextSlide = function() {
$ionicSlideBoxDelegate.next();
};
//controller for category types for products.
$route.reload();
WebService.invokeService('home', 'POST', 'http://' + $rootScope.ip + 'php/products_category.php')
.success(function(data) {
$route.reload();
$scope.productCategories = data.productCategories;
console.log("PRODUCT CATEGORIES ", $scope.productCategories);
var data = {
category_id: $localStorage.category.c_id,
product_category: $scope.productCategories[0].product_category
}
var jsonStr = angular.toJson(data);
WebService.invokeService('home', 'POST', 'http://' + $rootScope.ip + 'php/productsList.php', jsonStr)
.success(function(data) {
// $scope.productsList = data.productsList;
$scope.productsListd = data.productsList;
console.log($scope.productsListd);
// $window.location.reload();
// location.reload(true);
$route.reload();
})
.error(function(data) {
$cordovaToast.showLongCenter('Please Check Your Data Connection!');
});
})
.error(function(data) {
$cordovaToast.showLongCenter('Please Check Your Data Connection!');
});
$scope.myActiveSlide = 0;
$scope.reportSlideChanged = function(slideNum) {
console.log('SlideNum = ' + slideNum);
// switch(slideNum) {
// case 0:
var data = {
category_id: $localStorage.category.c_id,
product_category: $scope.productCategories[slideNum].product_category
}
var jsonStr = angular.toJson(data);
WebService.invokeService('home', 'POST', 'http://' + $rootScope.ip + 'php/productsList.php', jsonStr)
.success(function(data) {
$scope.productsList = data.productsList;
console.log($scope.productsList);
// $window.location.reload();
// window.location.reload(true);
$route.reload();
})
.error(function(data) {
$cordovaToast.showLongCenter('Please Check Your Data Connection!');
});
}
$scope.productDetailsPage = function(product) {
$localStorage.product_Details = product;
$state.go('productDesc');
}
})
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;