WebApi error after enabling the IP address through firewall - android

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

Related

Xamarin.Forms Help optimize load times

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!

How to post list object to cloud firestore firebase in flutter

I have List as
class MyContact {
String userName = "";
List<Phone> phones = List<Phone>();
MyContact({this.userName, this.phones});
}
class Phone {
String phone = "";
Phone({this.phone});
}
and update method
_updateContact() async {
var contacts = (await ContactsService.getContacts()).toList();
List<MyContact> myContacts = List<MyContact>();
contacts.forEach((contact) {
var myContact = MyContact();
myContact.userName = contact.displayName;
contact.phones.forEach((phone) {
myContact.phones.add(Phone(phone: phone.value));
});
myContacts.add(myContact);
});
await Firestore.instance
.collection("contacts")
.document()
.setData(????);
}
Please help me!
I have resolved as follows
class MyContact {
String userName = "";
List<Phone> phones = List<Phone>();
MyContact({this.userName, this.phones});
Map<String, dynamic> toJson() {
return {
"name": userName,
"phones": phones.map((phone) => phone.toJson()).toList(),
};
}
}
class Phone {
String phone = "";
Phone({this.phone});
Map<String, dynamic> toJson() {
return {
"phone": phone,
};
}
}
Method update
_updateContact() async {
var contacts = (await ContactsService.getContacts()).toList();
List<MyContact> myContacts = List<MyContact>();
contacts.forEach((contact) {
List<Phone> phones = List<Phone>();
contact.phones.forEach((phone) {
phones.add(Phone(phone: phone.value));
});
myContacts.add(MyContact(userName: contact.displayName, phones: phones));
});
Map<String, dynamic> map = {
'contact': myContacts.map((myContact) => myContact.toJson()).toList()
};
await Firestore.instance
.collection("contacts")
.document()
.setData(map);
}
Flutter has official document for this master. It recommends to use "json_serializable" that the dart codes are generated automatically by command line
https://flutter.dev/docs/development/data-and-backend/json

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));
}
}
}

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
}
});
};

How to use Individual User Accounts in Azure

I am developing a messaging application for Android and I am using an Azure Web API as my backend which connects to an Azure SQL DB. I am trying to get the service to allow users to log in and proceed through the application with an identity. I want to use Individual User Accounts to do this but I do not know how.
I have been through every piece of documentation on the internet and yet I am still at a loss on how to receive a token from the service and use it to access auhtorised resources.
If someone could please highlight the appropriate methods I need to call from the generated classes as well as methods I should write myself, that would be very helpful!
This is the Account Controller that was generated:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using AcademicAssistant.Models;
using AcademicAssistant.Providers;
using AcademicAssistant.Results;
namespace AcademicAssistant.Controllers
{
[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
private const string LocalLoginProvider = "Local";
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager,
ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
UserManager = userManager;
AccessTokenFormat = accessTokenFormat;
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; }
// GET api/Account/UserInfo
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UserInfo")]
public UserInfoViewModel GetUserInfo()
{
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
return new UserInfoViewModel
{
Email = User.Identity.GetUserName(),
HasRegistered = externalLogin == null,
LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
};
}
// POST api/Account/Logout
[Route("Logout")]
public IHttpActionResult Logout()
{
Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
return Ok();
}
// GET api/Account/ManageInfo?returnUrl=%2F&generateState=true
[Route("ManageInfo")]
public async Task<ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false)
{
IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user == null)
{
return null;
}
List<UserLoginInfoViewModel> logins = new List<UserLoginInfoViewModel>();
foreach (IdentityUserLogin linkedAccount in user.Logins)
{
logins.Add(new UserLoginInfoViewModel
{
LoginProvider = linkedAccount.LoginProvider,
ProviderKey = linkedAccount.ProviderKey
});
}
if (user.PasswordHash != null)
{
logins.Add(new UserLoginInfoViewModel
{
LoginProvider = LocalLoginProvider,
ProviderKey = user.UserName,
});
}
return new ManageInfoViewModel
{
LocalLoginProvider = LocalLoginProvider,
Email = user.UserName,
Logins = logins,
ExternalLoginProviders = GetExternalLogins(returnUrl, generateState)
};
}
// POST api/Account/ChangePassword
[Route("ChangePassword")]
public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword,
model.NewPassword);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
// POST api/Account/SetPassword
[Route("SetPassword")]
public async Task<IHttpActionResult> SetPassword(SetPasswordBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
// POST api/Account/AddExternalLogin
[Route("AddExternalLogin")]
public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken);
if (ticket == null || ticket.Identity == null || (ticket.Properties != null
&& ticket.Properties.ExpiresUtc.HasValue
&& ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow))
{
return BadRequest("External login failure.");
}
ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity);
if (externalData == null)
{
return BadRequest("The external login is already associated with an account.");
}
IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(),
new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey));
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
// POST api/Account/RemoveLogin
[Route("RemoveLogin")]
public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result;
if (model.LoginProvider == LocalLoginProvider)
{
result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId());
}
else
{
result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(),
new UserLoginInfo(model.LoginProvider, model.ProviderKey));
}
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
// GET api/Account/ExternalLogin
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
{
if (error != null)
{
return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
}
if (!User.Identity.IsAuthenticated)
{
return new ChallengeResult(provider, this);
}
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
if (externalLogin == null)
{
return InternalServerError();
}
if (externalLogin.LoginProvider != provider)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
return new ChallengeResult(provider, this);
}
ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
externalLogin.ProviderKey));
bool hasRegistered = user != null;
if (hasRegistered)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
}
else
{
IEnumerable<Claim> claims = externalLogin.GetClaims();
ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
Authentication.SignIn(identity);
}
return Ok();
}
// GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true
[AllowAnonymous]
[Route("ExternalLogins")]
public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false)
{
IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes();
List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>();
string state;
if (generateState)
{
const int strengthInBits = 256;
state = RandomOAuthStateGenerator.Generate(strengthInBits);
}
else
{
state = null;
}
foreach (AuthenticationDescription description in descriptions)
{
ExternalLoginViewModel login = new ExternalLoginViewModel
{
Name = description.Caption,
Url = Url.Route("ExternalLogin", new
{
provider = description.AuthenticationType,
response_type = "token",
client_id = Startup.PublicClientId,
redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
state = state
}),
State = state
};
logins.Add(login);
}
return logins;
}
// POST api/Account/Register
[AllowAnonymous]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
// POST api/Account/RegisterExternal
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("RegisterExternal")]
public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var info = await Authentication.GetExternalLoginInfoAsync();
if (info == null)
{
return InternalServerError();
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
protected override void Dispose(bool disposing)
{
if (disposing && _userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
base.Dispose(disposing);
}
#region Helpers
private IAuthenticationManager Authentication
{
get { return Request.GetOwinContext().Authentication; }
}
private IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
}
if (!result.Succeeded)
{
if (result.Errors != null)
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
if (ModelState.IsValid)
{
// No ModelState errors are available to send, so just return an empty BadRequest.
return BadRequest();
}
return BadRequest(ModelState);
}
return null;
}
private class ExternalLoginData
{
public string LoginProvider { get; set; }
public string ProviderKey { get; set; }
public string UserName { get; set; }
public IList<Claim> GetClaims()
{
IList<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider));
if (UserName != null)
{
claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider));
}
return claims;
}
public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
{
if (identity == null)
{
return null;
}
Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer)
|| String.IsNullOrEmpty(providerKeyClaim.Value))
{
return null;
}
if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
{
return null;
}
return new ExternalLoginData
{
LoginProvider = providerKeyClaim.Issuer,
ProviderKey = providerKeyClaim.Value,
UserName = identity.FindFirstValue(ClaimTypes.Name)
};
}
}
private static class RandomOAuthStateGenerator
{
private static RandomNumberGenerator _random = new RNGCryptoServiceProvider();
public static string Generate(int strengthInBits)
{
const int bitsPerByte = 8;
if (strengthInBits % bitsPerByte != 0)
{
throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits");
}
int strengthInBytes = strengthInBits / bitsPerByte;
byte[] data = new byte[strengthInBytes];
_random.GetBytes(data);
return HttpServerUtility.UrlTokenEncode(data);
}
}
#endregion
}
}
This is the message controller I wrote:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using AcademicAssistant.Models;
namespace AcademicAssistant.Controllers
{
[Authorize]
public class MessagesController : ApiController
{
private AcademicAssistantContext db = new AcademicAssistantContext();
// GET: api/Messages
[Authorize]
public IQueryable<Message> GetMessages()
{
return db.Messages;
}
// GET: api/Messages/5
[Authorize]
[ResponseType(typeof(Message))]
public async Task<IHttpActionResult> GetMessage(int id)
{
Message message = await db.Messages.FindAsync(id);
if (message == null)
{
return NotFound();
}
return Ok(message);
}
// PUT: api/Messages/5
[Authorize]
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutMessage(int id, Message message)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != message.MessageID)
{
return BadRequest();
}
db.Entry(message).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MessageExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Messages
[Authorize]
[ResponseType(typeof(Message))]
public async Task<IHttpActionResult> PostMessage(Message message)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Messages.Add(message);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = message.MessageID }, message);
}
// DELETE: api/Messages/5
[Authorize]
[ResponseType(typeof(Message))]
public async Task<IHttpActionResult> DeleteMessage(int id)
{
Message message = await db.Messages.FindAsync(id);
if (message == null)
{
return NotFound();
}
db.Messages.Remove(message);
await db.SaveChangesAsync();
return Ok(message);
}
[Authorize]
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
[Authorize]
private bool MessageExists(int id)
{
return db.Messages.Count(e => e.MessageID == id) > 0;
}
}
}

Categories

Resources