Undefined - ajax method error - ajax

I looked most of questions like this and i tried a lot of methods to solve the problem but i couldn't.
var kullaniciAdi = '<%= Session["kullanici"] %>';
alert(kullaniciAdi);
$.ajax({
url: "http://localhost:63000/GetInfoService.asmx/GetInfos",
type: "POST",
dataType:'json',
data: JSON.stringify({ kullaniciAdi: kullaniciAdi }),
contentType: "application/json; charset=windows-1254",
success: function (infos) {
var items = infos.d;
$jQuery.each(items, function (index, val) {
$("div#adSoyad").html('<h1>' + val[index].ad + " " + val[index].soyad + '</h1>');
$("div#fotograf").html('<img src="' + val[index].fotograf + '" class="img-responsive">');
});
},
error: function (e) {
alert(e.leader);
}
});
it's not working no matter what i did. i tried to turn index to 0 or remove them nothing worked.
here is my service that i have been calling:
public class GetInfoService : System.Web.Services.WebService
{
[WebMethod]
public List<kullaniciBilgileri> GetInfos(string kullaniciAd)
{
List<kullaniciBilgileri> infos = new List<kullaniciBilgileri>();
try
{
SqlConnection conn = new SqlConnection("Data Source=.\\SQLExpress; Initial Catalog=twitter;Integrated Security=SSPI");
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT ad,soyad,fotograf FROM tblKullanici WHERE kullaniciAdi = #kullaniciAd");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#kullaniciAd", kullaniciAd);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
var kullanici = new kullaniciBilgileri
{
ad = dr["ad"].ToString(),
soyad = dr["soyad"].ToString(),
fotograf = dr["fotograf"].ToString()
};
infos.Add(kullanici);
}
return infos;
}
catch (SoapException se)
{
throw se;
}
}
public class kullaniciBilgileri
{
public string ad { get; set; }
public string soyad { get; set; }
public string fotograf { get; set; }
}
}
and for more information this method my login and home page. maybe there are mistakes that i've made.
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetSessionValue(string kullaniciAd)
{
HttpContext.Current.Session["kullanici"] = kullaniciAd;
return kullaniciAd;
}
}
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.Session["kullanici"] == null)
{
Response.Redirect("Login.aspx");
}
}
}
sorry for my English :)

Related

Unable to open asset URL: file:///android_asset/www/sf.min.js xamarin forms

While developing xamarin forms custom webview, when I try to load URL from assets folder, getting below error
[AndroidProtocolHandler] Unable to open asset URL: file:///android_asset/www/sf.min.js
This is my code
ChatbotView.xaml file
<controls:HybridWebView
x:Name="webView"
Uri="TestWebPage.html"
Margin="10"
BackgroundColor="Red"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" />
This is ChatbotViewModel and HybridWebView class
public class ChatbotViewModel: BaseViewModel
{
public UrlWebViewSource SourceContent { get; set; }
public ChatbotViewModel()
{
var source = new UrlWebViewSource();
var baseUrl = DependencyService.Get<IBaseUrl>().Get();
string filePathUrl = Path.Combine(baseUrl, "TestWebPage.html");
source.Url = filePathUrl;
SourceContent = source;
}
}
public interface IBaseUrl { string Get(); }
public class HybridWebView : WebView
{
Action<string> action;
public static readonly BindableProperty UriProperty = BindableProperty.Create(
propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(HybridWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
public void RegisterAction(Action<string> callback)
{
action = callback;
}
public void Cleanup()
{
action = null;
}
public void InvokeAction(string data)
{
if (action == null || data == null)
{
return;
}
action.Invoke(data);
}
}
This is HybridWebViewRenderer, JavascriptWebViewClient and JSBridge class
public class HybridWebViewRenderer : WebViewRenderer
{
const string JavascriptFunction = "function Chat1(data){jsBridge.invokeAction(data);}";
Context _context;
public HybridWebViewRenderer(Context context) : base(context)
{
_context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
Control.RemoveJavascriptInterface("jsBridge");
((HybridWebView)Element).Cleanup();
}
if (e.NewElement != null)
{
Control.SetWebViewClient(new JavascriptWebViewClient(this, $"javascript: {JavascriptFunction}"));
Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
Control.Settings.AllowFileAccess = true;
Control.Settings.JavaScriptEnabled = true;
Control.Settings.SetAppCacheMaxSize(100000000);
Control.Settings.AllowFileAccessFromFileURLs = true;
Control.Settings.AllowUniversalAccessFromFileURLs = true;
Control.Settings.AllowContentAccess = true;
Control.SetWebChromeClient(new WebChromeClient());
Control.SetWebViewClient(new WebViewClient());
var myUlr2 = $"file:///android_asset/TestWebPage.html";
Control.LoadUrl(myUlr2);
}
}
public class JavascriptWebViewClient : FormsWebViewClient
{
string _javascript;
public JavascriptWebViewClient(HybridWebViewRenderer renderer, string javascript) : base(renderer)
{
_javascript = javascript;
}
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
base.OnPageFinished(view, url);
view.EvaluateJavascript(_javascript, null);
}
}
public class JSBridge : Java.Lang.Object
{
readonly WeakReference<HybridWebViewRenderer> hybridWebViewRenderer;
public JSBridge(HybridWebViewRenderer hybridRenderer)
{
hybridWebViewRenderer = new WeakReference<HybridWebViewRenderer>(hybridRenderer);
}
[JavascriptInterface]
[Export("invokeAction")]
public void InvokeAction(string data)
{
HybridWebViewRenderer hybridRenderer;
if (hybridWebViewRenderer != null && hybridWebViewRenderer.TryGetTarget(out hybridRenderer))
{
((HybridWebView)hybridRenderer.Element).InvokeAction(data);
}
}
}
}
Below is TestWebpage.html file. This file is accessing one of JavaScript file from assets folder
<script type='text/javascript' src='file:///android_asset/www/sf.min.js'></script>
sf.min.js is not getting loaded and throwing error.
<html>
<body>
<button onclick="Chat1()">Submit</button>
<script type='text/javascript' src='file:///android_asset/www/sf.min.js'></script>
<script type='text/javascript'>
function Chat1() {
var initESW = function (gslbBaseURL) {
embedded_svc.settings.displayHelpButton = true; //Or false
embedded_svc.settings.language = ''; //For example, enter 'en' or 'en-US'
embedded_svc.settings.enabledFeatures = ['LiveAgent'];
embedded_svc.settings.entryFeature = 'LiveAgent';
embedded_svc.init(
'https://ulr.my.salesforce.com',
'https://ulr.force.com/visualforce',
gslbBaseURL,
'00D7a00000055uj',
'US_Universities',
{
'baseLiveAgentContentURL': 'https://c.la3-c1cs-cdg.salesforceliveagent.com/content',
'deploymentId': '720008Oqg',
'buttonId': '5730PID',
'baseLiveAgentURL': 'https://d.la3-c1cs-cdg.salesforceliveagent.com/chat',
'eswLiveAgentDevName': 'EmbeddedServiceLiveAgent_Parent0000000jLUAQ_17d9a605e8e',
'isOfflineSupportEnabled': false
}
);
};
if (!window.embedded_svc) {
var s = document.createElement('script');
console.log("Control here1")
var sdxMin = 'https://ulr.salesforce.com/embeddedservice/5.0/esw.min.js/'
console.log("Control here2")
s.src = sdxMin;
console.log("Control here3")
s.onload = function () {
initESW(null);
}
document.body.appendChild(s);
}
else {
initESW('https://service.force.com');
}
}
</script>
</body>
</html>
doc.microsoft webview, this I have followed for development. How can I fix this error ?
Edit 1 : Screenshot of Assets folder
From my perspective,you haven't put the sf.min.js file under Assets/www/sf.min.js folder.When compiling the TestWebpage.html, the system can't detect the js file as a result of the error "[AndroidProtocolHandler] Unable to open asset URL: file:///android_asset/www/sf.min.js".

Xamarin Forms consuming Web Service

I'm new in mobile apps and now developing an app with xamarin forms. There is a website which i developed with django (sqlite3 db), and now i'am trying to consume data from it and display in my mobile app in listvew. Any thoughts how to achieve it. I've tried this but it doesn't work. Should i use rest api?
public class LandingViewModel : INotifyPropertyChanged
{
private List<Dishes> _menuList { set; get; }
public List<Dishes> MenuList
{
get
{
return _menuList;
}
set
{
if(value != _menuList)
{
_menuList = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public LandingViewModel()
{
GetDataAsync();
}
private async void GetDataAsync()
{
HttpClient client = new HttpClient();
var response = await client.GetAsync("https://mysite.ru/project/");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var menu = JsonConvert.DeserializeObject<List<Dishes>>(content);
MenuList = new List<Dishes>(menu);
}
}
models:
public class Dishes
{
public int id { get; set; }
public string description { get; set; }
public string image { get; set; }
public DateTime published { get; set; }
}
my database in django:
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.TextField(blank=True)),
('image', models.ImageField(blank=True, upload_to='pictures/')),
('published', models.DateTimeField(verbose_name='publishing date')),
],
),
]
i solved the problem
in postgresql database allowed remote connection: in postgresql.conf replaced line listen_addresses = 'localhost' with listen_addresses = '*'
allowed tcp\ip connection on port 5432
in my web api established connection width db
NpgsqlConnection connection;
public string _name;
public string _description;
public string _image;
private readonly MenuContext _context;
public MenuController(MenuContext context)
{
_context = context;
string connectionString = "Server=server; Port=5432; User Id=user;
Password=password; Database=database";
try
{
connection = new NpgsqlConnection(connectionString);
connection.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
NpgsqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM table";
try
{
NpgsqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
_name = reader[1].ToString();
_image = reader[2].ToString();
_description = reader[3].ToString();
_context.Menus.Add(new Menu { name = _name, description =
_description, image = "https://mysite.ru/media/" + _image });
_context.SaveChanges();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
// GET: api/Menu
[HttpGet]
public async Task<ActionResult<IEnumerable<Menu>>> GetMenus()
{
return await _context.Menus.ToListAsync();
}
code in my app:
private async void GetDataAsync()
{
HttpClient httpClient = new HttpClient();
var content = await httpClient.GetStringAsync("https://locahost/api/Menu");
var menu = JsonConvert.DeserializeObject<List<Dishes>>(content);
MenuList = new ObservableCollection<Dishes>(menu);
}
and then displayed it in listview

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..

How to unregister a client from Push Notifications?

I'm working on an Xamarin.Forms app with Azure Notifications Hub and Androud GCM. Now when I user is registered I register him to the notifications:
I have an interface:
public interface IPushNotificationService
{
void Register();
void UnRegister();
}
And in the Android project I implemented the interface as:
public class PushNotificationService : IPushNotificationService
{
public PushNotificationService() { }
public void Register()
{
RegisterWithGCM();
}
public void UnRegister()
{
try
{
GcmClient.UnRegister(MainActivity.instance);
}
catch (Exception e)
{
Log.Verbose(PushHandlerBroadcastReceiver.TAG, "ERROR while UnRegistering - " + e.Message);
}
}
private void RegisterWithGCM()
{
try
{
// Check to ensure everything's setup right
GcmClient.CheckDevice(MainActivity.instance);
GcmClient.CheckManifest(MainActivity.instance);
// Register for push notifications
UnRegister();
Log.Verbose(PushHandlerBroadcastReceiver.TAG, "Registering...");
GcmClient.Register(MainActivity.instance, Constants.SenderID);
}
catch (Java.Net.MalformedURLException)
{
Log.Verbose(PushHandlerBroadcastReceiver.TAG, "ERROR - There was an error creating the client. Verify the URL.");
}
catch (Exception e)
{
Log.Verbose(PushHandlerBroadcastReceiver.TAG, "ERROR - " + e.Message);
CreateAndShowDialog("Cannot register to push notification. Please try to run the app again.", "Error");
}
}
private void CreateAndShowDialog(String message, String title)
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.instance);
builder.SetMessage(message);
builder.SetTitle(title);
builder.Create().Show();
}
}
I also has the GcmService as listen in the Azure MSDN sites:
[assembly: Permission(Name = "#PACKAGE_NAME#.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "#PACKAGE_NAME#.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
[assembly: UsesPermission(Name = "android.permission.INTERNET")]
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
namespace MyApp.Droid
{
[BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "#PACKAGE_NAME#" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "#PACKAGE_NAME#" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "#PACKAGE_NAME#" })]
public class PushHandlerBroadcastReceiver : GcmBroadcastReceiverBase<GcmService>
{
public static string[] SENDER_IDS = new string[] { "XXXXX" };
public static string TAG = "PUSH_NOTIFICATIONS";
}
[Service]
public class GcmService : GcmServiceBase
{
public static string RegistrationID { get; private set; }
private NotificationHub Hub { get; set; }
public GcmService()
: base(PushHandlerBroadcastReceiver.SENDER_IDS) { }
protected override void OnRegistered(Context context, string registrationId)
{
Log.Verbose(PushHandlerBroadcastReceiver.TAG, "GCM Registered: " + registrationId);
RegistrationID = registrationId;
Hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString,
context);
try
{
Hub.UnregisterAll(registrationId);
Hub.Unregister();
}
catch (Exception ex)
{
Log.Error(PushHandlerBroadcastReceiver.TAG, ex.Message);
}
var userId = Settings.UserId;
if (! String.IsNullOrWhiteSpace(userId))
{
Log.Verbose(PushHandlerBroadcastReceiver.TAG, "Registering user_id: " + userId);
var tags = new List<string>() { userId };
try
{
Hub.Register(registrationId, tags.ToArray());
}
catch (Exception ex)
{
Log.Error(PushHandlerBroadcastReceiver.TAG, ex.Message);
}
}
}
protected override void OnMessage(Context context, Intent intent)
{
Log.Info(PushHandlerBroadcastReceiver.TAG, "GCM Message Received!");
var msg = new StringBuilder();
if (intent != null && intent.Extras != null)
{
foreach (var key in intent.Extras.KeySet())
msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());
}
string message = intent.Extras.GetString("message");
if (!string.IsNullOrEmpty(message))
{
createNotification("New Message", message);
return;
}
Log.Error(PushHandlerBroadcastReceiver.TAG, "Unknown message details: " + msg);
}
void createNotification(string title, string desc)
{
//Create notification
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
//Create an intent to show ui
var uiIntent = new Intent(this, typeof(MainActivity));
//Use Notification Builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
//Create the notification
//we use the pending intent, passing our ui intent over which will get called
//when the notification is tapped.
var notification = builder.SetContentIntent(PendingIntent.GetActivity(this, 0, uiIntent, 0))
.SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
.SetTicker(title)
.SetContentTitle(title)
.SetContentText(desc)
//.AddAction(new NotificationCompat.Action())
//Set the notification sound
.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
//Auto cancel will remove the notification once the user touches it
.SetAutoCancel(true).Build();
//Show the notification
notificationManager.Notify(1, notification);
}
protected override void OnUnRegistered(Context context, string registrationId)
{
Log.Info(PushHandlerBroadcastReceiver.TAG, "Unregistered RegisterationId : " + registrationId);
try
{
Hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString,
context);
Hub.Unregister();
if (!String.IsNullOrWhiteSpace(registrationId))
Hub.UnregisterAll(registrationId);
}
catch (Exception e)
{
Log.Error(PushHandlerBroadcastReceiver.TAG, "Error while unregistering: " + e.Message);
}
}
protected override void OnError(Context context, string errorId)
{
Log.Error(PushHandlerBroadcastReceiver.TAG, "GCM Error: " + errorId);
}
}
}
Now when a user logged in to the app I call:
DependencyService.Get<IPushNotificationService>().Register();
And when he logged out I call:
Now when a user logged in to the app I call:
DependencyService.Get<IPushNotificationService>().UnRegister();
What I'm doing wrong here? When a user logged out I see in the debug that all the Unregister methods are called but the user still getting new messages.
Thanks,
Seif.
Maybe the problem is in the line:
Hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString,
context);
You are creating a new object of NotificationHub that might not be referencing the initial connection.
You could try creating a field NotificationHub _hub; set its value in the registering step; and use this field on the unregistering step:
_hub.Unregister();
if (!string.IsNullOrWhiteSpace(registrationId))
_hub.UnregisterAll(registrationId);
disclaimer: did not try this solution. Hope it helps.

Are these ZIORepository and Controller for mvc correct?

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

Resources