Are these ZIORepository and Controller for mvc correct? - model-view-controller

Repository
namespace AgenziaMatrimoniale.DataAccess {
public class AgenziaMatrimonialeRepository
{
private readonly string _connectionString = ConfigurationManager.ConnectionStrings["AgenziaMatrimonialeConnectionString"].ConnectionString;
public List<Candidato> FindSimple(int? id, string sesso, string citta)
{
List<Candidato> result = new List<Candidato>();
string query = "SELECT * FROM Candidato";
using (var connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var dbId = Convert.ToInt32(reader["Id"]);
var dbNome = Convert.ToString(reader["Nome"]);
var dbCognome = Convert.ToString(reader["Cognome"]);
var dbSesso = Convert.ToString(reader["Sesso"]);
var dbCitta = Convert.ToString(reader["Citta"]);
var dbProfessione = Convert.ToString(reader["Professione"]);
var dbDescrizione = Convert.ToString(reader["Descrizione"]);
if (id.HasValue && dbId == id)
{
AggiungiCandidatoAiRisultati(result, dbId, dbNome, dbCognome, dbSesso, dbCitta, dbProfessione, dbDescrizione);
}
else if (!id.HasValue
&& (string.IsNullOrEmpty(sesso) || dbSesso==sesso)
&& (string.IsNullOrEmpty(citta)|| dbCitta.ToLower().Contains(citta.ToLower())))
{
AggiungiCandidatoAiRisultati(result, dbId, dbNome, dbCognome, dbSesso, dbCitta, dbProfessione, dbDescrizione);
}
}
reader.Close();
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("Errore applicativo: {0}", ex.Message));
throw ex;
}
}
return result;
}
public Candidato FindCandidato(int id)
{
List<Candidato> candidati = FindSimple(id, null, null);
if (candidati.Count == 1)
{
return candidati[0];
}
return null;
}
Controller
namespace AgenziaMatrimoniale.Controllers
{
public class CandidatoController : Controller
{
private readonly AgenziaMatrimonialeRepository _repository;
public CandidatoController()
{
_repository = new AgenziaMatrimonialeRepository();
}
public ActionResult Index(string sesso, string citta)
{
List<Candidato> candidati = _repository.FindSimple(null, sesso, citta);
List<SelectListItem> sessi= new List<SelectListItem> {
new SelectListItem { Text = "Maschio", Value = "M" },
new SelectListItem { Text = "Femmina", Value = "F" }
};
ViewBag.sesso = sessi;
return View(candidati);
}
public ActionResult Details(int id)
{
Candidato candidato = _repository.FindCandidato(id);
return View(candidato);
}
}
}

It depends...if you're trying to fill a table with data collected from a DB and possibly filter that data....then you are doing just fine.
You remind me this little piece of code that's just VERY similar.
using Prova1.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Web;
namespace Prova1.DataAccess
{
public class ProvaRepository
{
private readonly string _connectionString = ConfigurationManager.ConnectionStrings["StringConnectionName"].ConnectionString;
public List<Modello> Find(int? id, string filtro1, string filtro2)
{
List<Modello> result = new List<Modello>();
string query = "SELECT * FROM Tabella";
using (var connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var dbId = Convert.ToInt32(reader["Id"]);
var dbCampo1 = Convert.ToString(reader["Campo1"]);
var dbCampo2 = Convert.ToString(reader["Campo2"]);
var dbCampo3 = Convert.ToString(reader["Campo3"]);
Modello modello = new Modello();
if (id.HasValue && dbId == id)
{
AddModello(result, dbId, dbCampo1, dbCampo2, dbCampo3, modello);
}
else if (!id.HasValue
&& (string.IsNullOrEmpty(filtro1) || dbCampo1.ToLower().Contains(filtro1.ToLower()))
&& (string.IsNullOrEmpty(filtro2) || dbCampo2.ToLower().Contains(filtro2.ToLower()))
)
{
AddModello(result, dbId, dbCampo1, dbCampo2, dbCampo3, modello);
}
}
reader.Close();
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("Errore Applicativo {0}: ", ex.Message));
throw ex;
}
}
return result;
}
private static void AddModello(List<Modello> result, int dbId, string dbCampo1, string dbCampo2, string dbCampo3, Modello modello)
{
modello.Id = dbId;
modello.Campo1 = dbCampo1;
modello.Campo2 = dbCampo2;
modello.Campo3 = dbCampo3;
result.Add(modello);
}
public Modello FindDetail(int id)
{
List<Modello> modello = Find(id, null, null);
if (modello.Count == 1)
{
return modello[0];
}
return null;
}
}
}
Edit: I forgot the Controller
using Prova1.DataAccess;
using Prova1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Prova1.Controllers
{
public class ProvaController : Controller
{
private readonly ProvaRepository _repository;
public ProvaController()
{
_repository = new ProvaRepository();
}
// GET: Prova
public ActionResult Index(string filtro1, string filtro2)
{
List<Modello> modelli = _repository.Find(null, filtro1, filtro2);
return View(modelli);
}
public ActionResult Detail(int id)
{
Modello modello = _repository.FindDetail(id);
return View(modello);
}
}
}

Related

how to save a picker value to the web api using the mvvm properties in the command?

I have a xamarin forms application and would like to save some values ​​that I got from the picker via the web api. The objective is to save this value as well as the other properties in the web api that is linked to the sql server database, but I have issues in how to reference the value selected in the picker through mvvm. I can load the data from the picker but I just don't know how to save these values ​​by referencing the picker in mvvm.
UsuarioModel Class
This is the model class, it has the CodPerfil property which is the foreign key that should be stored in my web api database and must correspond to the value that will be selected in the picker.
public class UsuarioModel
{
public int CodUsuario { get; set; }
public string Nome { get; set; }
public string Senha { get; set; }
public int Telefone { get; set; }
public DateTime DataRegisto { get; set; }
public bool Estado { get; set; }
public int CodPerfil { get; set; }
}
PerfilModel Class
public class PerfilModel
{
public int CodPerfil { get; set; }
public string Titulo { get; set; }
}
Web API Controller to Insert Data
public IHttpActionResult Registo(UsuarioModel usuario)
{
connection();
SqlCommand cmd = new SqlCommand("SpAddNewUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Nome", usuario.Nome);
cmd.Parameters.AddWithValue("#Senha", usuario.Senha);
cmd.Parameters.AddWithValue("#Telefone", usuario.Telefone);
cmd.Parameters.AddWithValue("#CodPerfil", usuario.CodPerfil);
conn.Open();
cmd.ExecuteNonQuery();
return Ok();
}
Web API Controller to Get Data for Picker in Xamarin
public IEnumerable<PerfilModel> GetPerfisApp()
{
List<PerfilModel> perfilModels = new List<PerfilModel>();
connection();
SqlCommand cmd = new SqlCommand("SpGetPerfilApp", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
PerfilModel perfil = new PerfilModel();
perfil.CodPerfil = Convert.ToInt32(reader["CodPerfil"]);
perfil.Titulo = reader["Titulo"].ToString();
perfilModels.Add(perfil);
}
conn.Close();
return perfilModels;
}
ViewModel Class
public class AddRegistoUsuarioViewModel : BaseViewModel
{
ApiServices _apiServices = new ApiServices();
string _nome;
public string Nome
{
get
{
return _nome;
}
set
{
if (value != null)
{
_nome = value;
OnPropertyChanged();
}
}
}
string _senha;
public string Senha
{
get
{
return _senha;
}
set
{
if (value != null)
{
_senha = value;
OnPropertyChanged();
}
}
}
int _telefone;
public int Telefone
{
get
{
return _telefone;
}
set
{
_telefone = value;
OnPropertyChanged();
}
}
int _codperfil;
public int CodPerfil
{
get
{
return _codperfil;
}
set
{
_codperfil = value;
OnPropertyChanged();
}
}
public string Message { get; set; }
public ICommand Registar
{
get
{
return new Command(async () =>
{
var usuario = new UsuarioModel
{
Nome = Nome,
Senha = Senha,
Telefone = Telefone,
CodPerfil = SelectedPerfil.CodPerfil
};
await _apiServices.RegistoUsuarioAsync(usuario);
});
}
}
public AddRegistoUsuarioViewModel()
{
GetPerfisApp();
}
public async void GetPerfisApp()
{
using (var client = new HttpClient())
{
var uri = "https://webapiigarbage-ff4.conveyor.cloud/api/Usuario/PerfisApp";
var result = await client.GetStringAsync(uri);
var PerfilList = JsonConvert.DeserializeObject<List<PerfilModel>>(result);
Perfis = new ObservableCollection<PerfilModel>(PerfilList);
}
}
PerfilModel _selectedPerfil;
public PerfilModel SelectedPerfil
{
get
{
return _selectedPerfil;
}
set
{
if (SelectedPerfil != value)
{
_selectedPerfil = value;
OnPropertyChanged();
}
}
}
ObservableCollection<PerfilModel> _perfis;
public ObservableCollection<PerfilModel> Perfis
{
get
{
return _perfis;
}
set
{
_perfis = value;
OnPropertyChanged();
}
}
}
API Service Class
I tried to use this form: CodPerfil = SelectedPerfil.CodPerfil
But I was not successful.
public async Task RegistoUsuarioAsync(UsuarioModel usuario)
{
var client = new HttpClient();
var json = JsonConvert.SerializeObject(usuario);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("https://mywebsite/api/Usuario/Registo", content);
}
RegisterPage.xaml.cs
public RegisterPage()
{
InitializeComponent();
BindingContext = new RegistoUsuarioViewModel();
}
RegisterPage.xaml
<Entry Placeholder="Nome de Usuário"
x:Name="NomeEntry" />
<Picker x:Name="PerfilPicker" Title="Selecione o seu Perfil" FontSize="Large" HorizontalOptions="Center"
ItemsSource="{Binding Perfis}"
ItemDisplayBinding="{Binding Titulo}"
SelectedItem="{Binding SelectedPerfil}" />
<Entry Placeholder="Número de Telemóvel"
x:Name="TelefoneEntry"
Keyboard="Telephone"/>
<Entry Placeholder="Senha" x:Name="SenhaEntry" IsPassword="True"/>
<Button Text="Registar"
TextColor="White"
BackgroundColor="#07E3B0"
x:Name="ButtonLogin"
Command="{Binding Registar}"/>
I would be grateful if someone could help me.
thanks for the tips. what happened was that the viewmodel that was being binded in the Register.xaml.cs class was not the one that contained the Register command. I solve the 'problem' by replacing the viewmodel and it worked!
RegisterPage.xaml.cs
public RegisterPage()
{
InitializeComponent();
BindingContext = new AddRegistoUsuarioViewModel();
}

Sign-in user via remote services and about TokenAuthController

I need to sign-in the user using only remote services. I think using TokenAuthController in Web.Core application
I really can't understand why the snippet given below doesn't work. I have added a new method called Login in TokenAuthController .
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.MultiTenancy;
using Abp.Runtime.Security;
using Abp.UI;
using Abp.Web.Models;
using Microsoft.AspNetCore.Authorization;
using TSE.DergiAbone.Authentication.External;
using TSE.DergiAbone.Authentication.JwtBearer;
using TSE.DergiAbone.Authorization;
using TSE.DergiAbone.Authorization.Users;
using TSE.DergiAbone.Identity;
using TSE.DergiAbone.Models.TokenAuth;
using TSE.DergiAbone.MultiTenancy;
namespace TSE.DergiAbone.Controllers
{
[Route("api/[controller]/[action]")]
public class TokenAuthController : DergiAboneControllerBase
{
private readonly LogInManager _logInManager;
private readonly SignInManager _signInManager;
private readonly ITenantCache _tenantCache;
private readonly AbpLoginResultTypeHelper _abpLoginResultTypeHelper;
private readonly TokenAuthConfiguration _configuration;
private readonly IExternalAuthConfiguration _externalAuthConfiguration;
private readonly IExternalAuthManager _externalAuthManager;
private readonly UserRegistrationManager _userRegistrationManager;
public TokenAuthController(
LogInManager logInManager,
SignInManager signInManager,
ITenantCache tenantCache,
AbpLoginResultTypeHelper abpLoginResultTypeHelper,
TokenAuthConfiguration configuration,
IExternalAuthConfiguration externalAuthConfiguration,
IExternalAuthManager externalAuthManager,
UserRegistrationManager userRegistrationManager)
{
_logInManager = logInManager;
_tenantCache = tenantCache;
_abpLoginResultTypeHelper = abpLoginResultTypeHelper;
_configuration = configuration;
_externalAuthConfiguration = externalAuthConfiguration;
_externalAuthManager = externalAuthManager;
_userRegistrationManager = userRegistrationManager;
_signInManager = signInManager;
}
***[HttpPost]
public virtual async Task<JsonResult> Login(string UserName, string password,bool IsPersistent )
{
var loginResult = await GetLoginResultAsync(UserName, password, GetTenancyNameOrNull());
//var result = await _signInManager.SignInAsync(loginResult.Identity, IsPersistent);
var result = await _signInManager.PasswordSignInAsync(UserName, password, true, false);
if (result.Succeeded)
{
long bak= User.Identity.GetUserId().Value;
string res = "User signed in";
}
await UnitOfWorkManager.Current.SaveChangesAsync();
bool chk = User.Identity.IsAuthenticated;
return Json(new Abp.Web.Models.AjaxResponse { TargetUrl = "" });
}***
[HttpPost]
public async Task<AuthenticateResultModel> Authenticate([FromBody] AuthenticateModel model)
{
var loginResult = await GetLoginResultAsync(
model.UserNameOrEmailAddress,
model.Password,
GetTenancyNameOrNull()
);
//var chk = _logInManager.LoginAsync("jimycarbonare#gmail.com", "123qwe", "TSEDergi").Result;
//var chk2 = _logInManager.Login("jimycarbonare#gmail.com", "123qwe", "TSEDergi");
//var name = User.Identity.Name;
//bool bak0 = User.IsInRole("admin");
//var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
//var loginResult = await GetLoginResultAsync("jimycarbonare#gmail.com", "123qwe", "TSEDergi");
//await _signInManager.SignInAsync(loginResult.Identity, model.RememberClient);//_logInManager.LoginAsync("jimycarbonare#gmail.com", "123qwe", "TSEDergi").Result;
//var name = User.Identity.Name;
//bool bak0 = User.IsInRole("admin");
var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
return new AuthenticateResultModel
{
AccessToken = accessToken,
EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
UserId = loginResult.User.Id
};
}
[HttpGet]
public List<ExternalLoginProviderInfoModel> GetExternalAuthenticationProviders()
{
return ObjectMapper.Map<List<ExternalLoginProviderInfoModel>>(_externalAuthConfiguration.Providers);
}
[HttpPost]
public async Task<ExternalAuthenticateResultModel> ExternalAuthenticate([FromBody] ExternalAuthenticateModel model)
{
var externalUser = await GetExternalUserInfo(model);
var loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull());
switch (loginResult.Result)
{
case AbpLoginResultType.Success:
{
var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
return new ExternalAuthenticateResultModel
{
AccessToken = accessToken,
EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds
};
}
case AbpLoginResultType.UnknownExternalLogin:
{
var newUser = await RegisterExternalUserAsync(externalUser);
if (!newUser.IsActive)
{
return new ExternalAuthenticateResultModel
{
WaitingForActivation = true
};
}
// Try to login again with newly registered user!
loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull());
if (loginResult.Result != AbpLoginResultType.Success)
{
throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
loginResult.Result,
model.ProviderKey,
GetTenancyNameOrNull()
);
}
return new ExternalAuthenticateResultModel
{
AccessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity)),
ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds
};
}
default:
{
throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
loginResult.Result,
model.ProviderKey,
GetTenancyNameOrNull()
);
}
}
}
private async Task<User> RegisterExternalUserAsync(ExternalAuthUserInfo externalUser)
{
var user = await _userRegistrationManager.RegisterAsync(
externalUser.Name,
externalUser.Surname,
externalUser.EmailAddress,
externalUser.EmailAddress,
Authorization.Users.User.CreateRandomPassword(),
true
);
user.Logins = new List<UserLogin>
{
new UserLogin
{
LoginProvider = externalUser.Provider,
ProviderKey = externalUser.ProviderKey,
TenantId = user.TenantId
}
};
await CurrentUnitOfWork.SaveChangesAsync();
return user;
}
private async Task<ExternalAuthUserInfo> GetExternalUserInfo(ExternalAuthenticateModel model)
{
var userInfo = await _externalAuthManager.GetUserInfo(model.AuthProvider, model.ProviderAccessCode);
if (userInfo.ProviderKey != model.ProviderKey)
{
throw new UserFriendlyException(L("CouldNotValidateExternalUser"));
}
return userInfo;
}
private string GetTenancyNameOrNull()
{
if (!AbpSession.TenantId.HasValue)
{
return null;
}
return _tenantCache.GetOrNull(AbpSession.TenantId.Value)?.TenancyName;
}
[HttpPost]
public AbpLoginResult<Tenant, User> GetLoginResult2Async(string usernameOrEmailAddress, string password, string tenancyName)
{
var loginResult = _logInManager.LoginAsync(usernameOrEmailAddress, password, tenancyName).Result;
switch (loginResult.Result)
{
case AbpLoginResultType.Success:
return loginResult;
default:
throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName);
}
}
private async Task<AbpLoginResult<Tenant, User>> GetLoginResultAsync(string usernameOrEmailAddress, string password, string tenancyName)
{
var loginResult = await _logInManager.LoginAsync(usernameOrEmailAddress, password, tenancyName);
switch (loginResult.Result)
{
case AbpLoginResultType.Success:
return loginResult;
default:
throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName);
}
}
private string CreateAccessToken(IEnumerable<Claim> claims, TimeSpan? expiration = null)
{
var now = DateTime.UtcNow;
var jwtSecurityToken = new JwtSecurityToken(
issuer: _configuration.Issuer,
audience: _configuration.Audience,
claims: claims,
notBefore: now,
expires: now.Add(expiration ?? _configuration.Expiration),
signingCredentials: _configuration.SigningCredentials
);
return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}
private static List<Claim> CreateJwtClaims(ClaimsIdentity identity)
{
var claims = identity.Claims.ToList();
var nameIdClaim = claims.First(c => c.Type == ClaimTypes.NameIdentifier);
// Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
claims.AddRange(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, nameIdClaim.Value),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
});
return claims;
}
private string GetEncrpyedAccessToken(string accessToken)
{
return SimpleStringCipher.Instance.Encrypt(accessToken, AppConsts.DefaultPassPhrase);
}
}
}
I am getting a reasonable loginResult. And PasswordSignInAsync method returns with success. At that point I conclude the sign in process is OK. But after when I check User.Identity. I see it is null. Same is valid for the SignInAsync method.All I wanna do is sign-in the user only using the remote services. Thank you all..
I solved the problem as given below:
Change the httpost login method in AccountController of Web.Mvc application as below
[HttpPost]
[UnitOfWork]
public virtual async Task<JsonResult> Login(LoginViewModel loginModel, string returnUrl = "", string returnUrlHash = "")
{
var claims = GetClaims(loginModel.UsernameOrEmailAddress, loginModel.Password);
if (claims == null)//giriş yapılamadı
{
return Json(new AjaxResponse { TargetUrl = "" });
}
else
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name,
ClaimTypes.Role);
foreach (var claim in claims)
{
identity.AddClaim(new Claim(claim.type, claim.value));
}
//AbpSession.UserId=18;
//// Authenticate using the identity
//var principal = new ClaimsPrincipal(identity);
//await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });
//bool chk = User.Identity.IsAuthenticated;
////bool bak = User.Identity.IsAuthenticated;
//bool bak2 = User.IsInRole("Admin");
//return RedirectToAction("Index", "Home");
await _signInManager.SignInAsync(identity, loginModel.RememberMe);
await UnitOfWorkManager.Current.SaveChangesAsync();
bool bak = User.Identity.IsAuthenticated;
var bakl = AbpSession.UserId;
}
returnUrl = NormalizeReturnUrl(returnUrl);
if (!string.IsNullOrWhiteSpace(returnUrlHash))
{
returnUrl = returnUrl + returnUrlHash;
}
return Json(new AjaxResponse { TargetUrl = returnUrl });
}
Create GetClaims method in AccountController of Web.Mvc application
protected List<ClaimRootObject> GetClaims(string UserName, string Password)
{
using (var client = new HttpClient())
{
string reqString = "http://localhost:21021/api/" + "TokenAuth/GetClaims/GetClaims?UserName=" + UserName + "&password=" + Password + "&TenantName=Default";
//string reqString = "http://localhost:81/api/TokenAuth/GetClaims/GetClaims?UserName=admin&password=123qwe&TenantName=TSEDergi";
HttpResponseMessage response = client.GetAsync(reqString).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
// Get the response
var JsonString = response.Content.ReadAsStringAsync();
// Deserialise the data (include the Newtonsoft JSON Nuget package if you don't already have it)
//List<Claim> deserialized = JsonConvert.DeserializeObject<List<Claim>>(JsonString.Result);
List<ClaimRootObject> deserialized = JsonConvert.DeserializeObject<List<ClaimRootObject>>(JsonString.Result);
if (deserialized != null)
{
return deserialized;
}
}
else
{
}
}
return null;
}
Create the required objects
public class ClaimRootObject
{
public string issuer { get; set; }
public string originalIssuer { get; set; }
public Properties properties { get; set; }
public Subject subject { get; set; }
public string type { get; set; }
public string value { get; set; }
public string valueType { get; set; }
}
public class Properties
{
}
public class Subject
{
public string authenticationType { get; set; }
public bool isAuthenticated { get; set; }
public object actor { get; set; }
public object bootstrapContext { get; set; }
public List claims { get; set; }
public object label { get; set; }
public string name { get; set; }
public string nameClaimType { get; set; }
public string roleClaimType { get; set; }
}
And last step, modify your startup class of Web.Mvc project to enable cookie authentication.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// MVC
services.AddMvc(
options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())
);
#region cookieAuthentication
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
#endregion cookieAuthentication
IdentityRegistrar.Register(services);
AuthConfigurer.Configure(services, _appConfiguration);
services.AddScoped();
services.AddSignalR();
// Configure Abp and Dependency Injection
return services.AddAbp(
// Configure Log4Net logging
options => options.IocManager.IocContainer.AddFacility(
f => f.UseAbpLog4Net().WithConfig("log4net.config")
)
);
}
That's all. Then you can log in a user into the application using only remote services..

Xamarin MVVM passing data to other view

I want to pass the data to another view page. So far I can get the data I need to pass. My problem is how do I pass the data in MVVM. I used Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(), true); When I add contactId inside DatabaseSyncPage() an error occurs. "The error is 'DatabaseSyncPage' does not contain a constructor that takes 1 arguments"
My code:
LoginPageViewModel.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Input;
using TBSMobileApplication.Data;
using TBSMobileApplication.View;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace TBSMobileApplication.ViewModel
{
public class LoginPageViewModel : INotifyPropertyChanged
{
void OnProperyChanged(string PropertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
public string username;
public string password;
public string Username
{
get { return username; }
set
{
username = value;
OnProperyChanged(nameof(Username));
}
}
public string Password
{
get { return password; }
set
{
password = value;
OnProperyChanged(nameof(Password));
}
}
public class LoggedInUser
{
public string ContactID { get; set; }
}
public ICommand LoginCommand { get; set; }
public LoginPageViewModel()
{
LoginCommand = new Command(OnLogin);
}
public void OnLogin()
{
if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
{
MessagingCenter.Send(this, "Login Alert", Username);
}
else
{
var current = Connectivity.NetworkAccess;
if (current == NetworkAccess.Internet)
{
var link = "http://192.168.1.25:7777/TBS/test.php?User=" + Username + "&Password=" + Password;
var request = HttpWebRequest.Create(string.Format(#link));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
}
else
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
{
MessagingCenter.Send(this, "Http", Username);
}
else
{
var result = JsonConvert.DeserializeObject<List<LoggedInUser>>(content);
var contactId = result[0].ContactID;
Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage { myId = contactId }, true);
}
}
}
}
else
{
MessagingCenter.Send(this, "Not Connected", Username);
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
DatabaseSyncPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TBSMobileApplication.View
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DatabaseSyncPage : ContentPage
{
public int myId { get; set; }
public DatabaseSyncPage ()
{
InitializeComponent ();
DisplayAlert("Message", Convert.ToString(myId), "ok");
}
}
}
If you want to send the int. First declare that in your DatabaseSyncPage
Like below
public partial class DatabaseSyncPage : ContentPage
{
public DatabaseSyncPage( int Id)
{
}
}
& when you are pushing your page in your code else block do like this
if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
{
MessagingCenter.Send(this, "Http", Username);
}
else
{
var result = JsonConvert.DeserializeObject<List<LoggedInUser>>(content);
var contactId = result[0].ContactID;
Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(contactId), true);
}
I'm assuming that contactID is an int.
Create an additional constructor in your DatabaseSyncPage:
public DatabaseSyncPage (int contactID)
{
// TODO: Do something with your id
}
But this passes the data to the page, not the page model.
Are you using any kind of framework? It would probably be worth looking into that.
You can use xamrin.plugins.settings nuget package.

Extending webapi 2.1's help page to include additional data

I found a pretty dated post from Yao at microsoft advanced help page customizations
I have tried to implement the steps however I am unable to get my custom comment to display within the help documentation.
Within my
XmlDocumentationProvider.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using System.Xml.XPath;
namespace MyApp.Areas.HelpPage
{
/// <summary>
/// A custom <see cref="IDocumentationProvider"/> that reads the API documentation from an XML documentation file.
/// </summary>
public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider
{
private XPathNavigator _documentNavigator;
private const string TypeExpression = "/doc/members/member[#name='T:{0}']";
private const string MethodExpression = "/doc/members/member[#name='M:{0}']";
private const string PropertyExpression = "/doc/members/member[#name='P:{0}']";
private const string FieldExpression = "/doc/members/member[#name='F:{0}']";
private const string ParameterExpression = "param[#name='{0}']";
/// <summary>
/// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
/// </summary>
/// <param name="documentPath">The physical path to XML document.</param>
public XmlDocumentationProvider(string documentPath)
{
if (documentPath == null)
{
throw new ArgumentNullException("documentPath");
}
XPathDocument xpath = new XPathDocument(documentPath);
_documentNavigator = xpath.CreateNavigator();
}
public string GetDocumentation(HttpControllerDescriptor controllerDescriptor)
{
XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType);
return GetTagValue(typeNode, "summary");
}
public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
return GetTagValue(methodNode, "summary");
}
public virtual string GetActionTypes(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
return GetTagValue(methodNode, "action");
}
public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor)
{
ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor;
if (reflectedParameterDescriptor != null)
{
XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor);
if (methodNode != null)
{
string parameterName = reflectedParameterDescriptor.ParameterInfo.Name;
XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName));
if (parameterNode != null)
{
return parameterNode.Value.Trim();
}
}
}
return null;
}
public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
return GetTagValue(methodNode, "returns");
}
public string GetDocumentation(MemberInfo member)
{
string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name);
string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression;
string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName);
XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression);
return GetTagValue(propertyNode, "summary");
}
public string GetDocumentation(Type type)
{
XPathNavigator typeNode = GetTypeNode(type);
return GetTagValue(typeNode, "summary");
}
private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor)
{
ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
if (reflectedActionDescriptor != null)
{
string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo));
return _documentNavigator.SelectSingleNode(selectExpression);
}
return null;
}
private static string GetMemberName(MethodInfo method)
{
string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name);
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != 0)
{
string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray();
name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames));
}
return name;
}
private static string GetTagValue(XPathNavigator parentNode, string tagName)
{
if (parentNode != null)
{
XPathNavigator node = parentNode.SelectSingleNode(tagName);
if (node != null)
{
return node.Value.Trim();
}
}
return null;
}
private XPathNavigator GetTypeNode(Type type)
{
string controllerTypeName = GetTypeName(type);
string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName);
return _documentNavigator.SelectSingleNode(selectExpression);
}
private static string GetTypeName(Type type)
{
string name = type.FullName;
if (type.IsGenericType)
{
// Format the generic type name to something like: Generic{System.Int32,System.String}
Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
string genericTypeName = genericType.FullName;
// Trim the generic parameter counts from the name
genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray();
name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames));
}
if (type.IsNested)
{
// Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax.
name = name.Replace("+", ".");
}
return name;
}
public interface ICustomCommentProvider
{
string GetCustomComment(HttpActionDescriptor actionDescriptor);
}
public virtual string GetCustomComment(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
if (methodNode != null)
{
XPathNavigator returnsNode = methodNode.SelectSingleNode("customcomment");
if (returnsNode != null)
{
return returnsNode.Value.Trim();
}
}
return null;
}
}
}
I have modifie
public interface ICustomCommentProvider
{
string GetCustomComment(HttpActionDescriptor actionDescriptor);
}
public virtual string GetCustomComment(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
if (methodNode != null)
{
XPathNavigator returnsNode = methodNode.SelectSingleNode("customcomment");
if (returnsNode != null)
{
return returnsNode.Value.Trim();
}
}
return null;
}
I have updated the
HelpPageModel.cs
to include
public string CustomMessage { get; set; }
Last thing I have updated is the GenerateApiModel
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
var responseDocProvider =
config.Services.GetDocumentationProvider() as XmlDocumentationProvider.ICustomCommentProvider;
if (responseDocProvider != null)
{
apiModel.CustomMessage = responseDocProvider.GetCustomComment(apiDescription.ActionDescriptor);
}
Everytime I run the application responseDocProvider is null. Is there anything sticking out that looks like I have done it wrong?
Help on the problem would be very much appreciated
You would need to set the documentation provider. You can uncomment the following piece of code present under Areas\HelpPage\App_Start\HelpPageConfig.cs
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
ANSWER FROM COMMENT (Kiran Challa):
but that would not work right..as your type is not implementing that interface and you are trying to cast to it...change the
XmlDocumentationProvider
to implementing the ICustomCommentProvider interface
and do a
var responseDocProvider =config.Services.GetDocumentationProvider() as ICustomCommentProvider;

Weird and Annoying IsolatedStorageError

Update
I added the piece of code/function that normally throws the error.
can someone please help.
Before I begin, I have spent over 20+ hours researching this issue.
I am developing a windows phone app and I keep getting a lot of IsolatedStorage Exceptions, especially "Operation not supported on IsolatedStorageFileStream".
The Scenario
I have an object that has a ProfilePictureUrl as a property, every time I create an instance of the object I download the profile image from the web, then I will store that image to the Isolated storage.
Sample Code
foreach(String url in urls)
{
var profile = new MyClass()
{
ProfilePictureURL = url
};
profile.DownloadProfilePictureToLocalStorage(() =>
{
completed(profile);
}, (ex) => { incomplete(ex); });
}
The Code that throws the Exception
if (isoFile.FileExists(saveAs))
isoFile.DeleteFile(saveAs);
using (var isoFileStream = isoFile.CreateFile(saveAs))
{
var width = wb.PixelWidth;
var height = wb.PixelHeight;
Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
This is inside the DownloadImageToIsolatedStorage function in the LocalStorageManager class.
Here is the class that manages my IsolatedStorage storing
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Media.Imaging;
namespace Classes.Managers
{
public delegate void GetImageCompletedDelegate(BitmapImage bmp);
public delegate void GetImageNotCompletedDelegate(Exception ex);
public delegate void SaveImageCompletedDelegate();
public delegate void SaveImageNotCompletedDelegate(Exception ex);
public delegate void DeleteImageCompletedDelegate();
public delegate void DeleteImageNotCompletedDelegate(Exception ex);
class LocalStorageManager
{
private static readonly LocalStorageManager _instance = new LocalStorageManager();
public static LocalStorageManager Instance
{
get
{
return _instance;
}
}
private bool m_IsBusy;
public bool IsBusy
{
get { return m_IsBusy; }
private set { m_IsBusy = value; }
}
private void GetImageFromIsolatedStorage(String name, GetImageCompletedDelegate completed, GetImageNotCompletedDelegate notCompleted)
{
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
BitmapImage img = new BitmapImage();
if (isoFile.FileExists(name))
{
using (IsolatedStorageFileStream fileStream = isoFile.OpenFile(name, FileMode.Open, FileAccess.Read))
{
img.SetSource(fileStream);
}
}
completed(img);
}
}
catch (Exception ex) { notCompleted(ex); }
}
public void DownloadImageToIsolatedStorage(String url, string saveAs, SaveImageCompletedDelegate completed, SaveImageNotCompletedDelegate notCompleted)
{
try
{
this.IsBusy = true;
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.BeginGetResponse((callback) =>
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
HttpWebResponse response = (HttpWebResponse)httpRequest.EndGetResponse(callback);
var bi = new BitmapImage();
bi.SetSource(response.GetResponseStream());
var wb = new WriteableBitmap(bi);
if (isoFile.FileExists(saveAs))
isoFile.DeleteFile(saveAs);
using (var isoFileStream = isoFile.CreateFile(saveAs))
{
var width = wb.PixelWidth;
var height = wb.PixelHeight;
Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
this.IsBusy = false;
completed();
}
});
}, null);
}
catch (Exception e) { this.IsBusy = false; notCompleted(e); }
}
public void MoveFile(String source, String destination)
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.FileExists(source))
{
isoFile.MoveFile(source, destination);
}
}
}
private void WriteImageStreamToIsolatedStorage(Stream imageStream, string saveAs, SaveImageCompletedDelegate completed, SaveImageNotCompletedDelegate notCompleted)
{
try
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(saveAs))
isolatedStorage.DeleteFile(saveAs);
var fileStream = isolatedStorage.CreateFile(saveAs);
imageStream.CopyTo(fileStream);
fileStream.Close();
/*
BitmapImage bmp = null;
bmp.SetSource(imageStream);
var writeableBMP = new WriteableBitmap(bmp);
writeableBMP.SaveJpeg(fileStream, writeableBMP.PixelWidth, writeableBMP.PixelHeight, 0, 100);
fileStream.Close();*/
}
completed();
}
catch (Exception ex) { notCompleted(ex); }
}
private void DeleteImageFromIsolatedStorage(string imageName, DeleteImageCompletedDelegate completed, DeleteImageNotCompletedDelegate notCompleted)
{
try
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(imageName))
isolatedStorage.DeleteFile(imageName);
completed();
}
}
catch (Exception e) { notCompleted(e); }
}
}
}
Here is the class for my objects
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Media.Imaging;
using System.Runtime.Serialization;
using System.IO.IsolatedStorage;
using System.Net;
namespace Classes.Model
{
public class MyClass : INotifyPropertyChanged
{
private string m_ProfilePictureURL;
public string ProfilePictureURL
{
get { return m_ProfilePictureURL; }
set
{
if (m_ProfilePictureURL == value)
return;
m_ProfilePictureURL = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("ProfilePictureURL"));
}
}
[IgnoreDataMember]
public BitmapImage LocalProfilePicture
{
get
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(isoFile.OpenFile("ProfilePic_" + this.UUID, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite));
return bitmapImage;
}
catch (Exception ex)
{
isoFile.Dispose();
return null;
}
}
}
}
public void DownloadProfilePictureToLocalStorage(SaveImageCompletedDelegate completed, SaveImageNotCompletedDelegate notCompleted)
{
// Wait till its no longer busy
while (LocalStorageManager.Instance.IsBusy) ;
if (!String.IsNullOrWhiteSpace(this.ProfilePictureURL) && !String.IsNullOrWhiteSpace(this.UUID))
{
LocalStorageManager.Instance.DownloadImageToIsolatedStorage(this.ProfilePictureURL, "ProfilePic_" + this.UUID, () =>
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("LocalProfilePicture"));
completed();
}, (ex) => { notCompleted(ex); });
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}

Resources