How to get result value from WebAPI in Xamarin - xamarin

public async Task<Customer> GetCustomersAsync(string id)
{
var prod = new Customer();
HttpClient client = new HttpClient();
string url = "https://xxxxxx.com/api/Customers/" + id;
client.BaseAddress = new Uri(url);
HttpResponseMessage response = await client.GetAsync("");
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
prod = JsonConvert.DeserializeObject<Customer>(content);
}
return await Task.FromResult(prod);
}
Class Customer(Models)
public class Customer
{
public string CodeRandom { get; set; }
public string NameUs { get; set; }
}
I do make a call to the API to get the results. However I can't get the return result when .Result
This is how I do it:
var infocustomer = customerRepository.GetCustomersAsync(userrating);
string nameus = infocustomer.Result.NameUs;
When I debug, nameus exits by itself. Please give me any solution. Thank you

instead of this
string content = response.Content.ReadAsStringAsync().Result;
do this
string content = await response.Content.ReadAsStringAsync();
and then just
return prod;

Related

How to get Auth code in api call post on ruby on rails app from wix api website?

I'm trying to developing a dashboard website for a wix application and I need to connect the website to the wix application.
I have a problem with an api (post) call. I have to fill in several information including the auth code that I don't know where to find.
Here is an image to illustrate the process :
I don't really know what is the wix app marker install, but for the authorization request I did this
$url_oauth = "https://www.wix.com/oauth/access"
response = RestClient::Request.execute(url: $url_oauth, method: :post, body:{grant_type: "authorization_code",client_id:"APP_ID", client_secret:"Secret_key", code:"{Can not find what is this value}"})
#data = JSON.parse(response)
render json: response
Here is the documentation :
Could you help how and where to find this Auth code ?
You will need to make an intermediate web service that will accept webhooks from WIX.
I'll show you the example of C# ASP.Net Core.
STEP 1:
We are waiting for a token from WIX and if it is received, we make a redirect.
private const string AppID = "";
private const string ApiKey = "";
private const string UrlAccess = "https://www.wix.com/oauth/access";
HttpGet("WaitToken")]
public ActionResult GetToken([FromQuery] string token = "")
{
try
{
if (string.IsNullOrWhiteSpace(token))
{
string message = "Your message";
ModelState.AddModelError("TokenNotCorrect", message);
return BadRequest(ModelState);
}
string paramUrl = #"https://your web service/OAuth/api/check/WaitAuthCode";
string urlRedirect = $#"https://www.wix.com/installer/install?token={token}&appId={AppID}&redirectUrl={paramUrl}";
return RedirectPermanent(urlRedirect);
}
catch (WebException ex)
{
ModelState.AddModelError("GetTokenException", ex.Message);
return BadRequest(ModelState);
}
}
STEP 2:
We are waiting for the Auth Code to be received, provided that the user has confirmed the installation of the application.
[HttpGet("WaitAuthCode")]
public async Task<ActionResult> GetAuthCodeAsync([FromQuery] string code = "", string state = "", string instanceId = "")
{
try
{
if (string.IsNullOrWhiteSpace(code))
{
string message = "your message";
ModelState.AddModelError("AuthCodeNotCorrect", message);
return BadRequest(ModelState);
}
var token = new Token(code);
if (!GetAccessToken(ref token))
return BadRequest("your message RefreshToken");
var tokenBase = new TokenBase
{
AppID = instanceId,
Token = token.RefreshToken
};
db.Tokens.Add(tokenBase);
if(await db.SaveChangesAsync() == 0)
return BadRequest("your message");
string urlRedirect = $"https://www.wix.com/installer/token-received?access_token={token.AccessToken}";
return RedirectPermanent(urlRedirect);
}
catch (WebException ex)
{
ModelState.AddModelError("GetAuthCodeException", ex.Message);
return BadRequest(ModelState);
}
}
The AuthCode is valid for 10 minutes, we send a request to receive a Refresh Token. This token must be kept at home, as it will be required in the future to obtain an Access Token.
private bool GetAccessToken(ref Token token)
{
try
{
string json = JsonConvert.SerializeObject(token, Formatting.Indented);
var client = new RestClient(UrlAccess);
var request = new RestRequest();
request.Method = Method.POST;
request.AddHeader("Content-Type", "application/json");
request.AddParameter(string.Empty, json, "application/json", ParameterType.RequestBody);
var response = client.Post(request);
if (response == null)
return false;
token = JsonConvert.DeserializeObject<Token>(response.Content);
if (string.IsNullOrWhiteSpace(token.RefreshToken))
return false;
return !string.IsNullOrWhiteSpace(token.AccessToken);
}
catch (Exception ex)
{
return false;
}
}
Getting an Access Token from a client application:
[HttpGet("WaitAccessToken")]
public async Task<ActionResult<string>> GetAccessToken([FromQuery] string instance = "", string apiKey = "")
{
string message;
var tokenBase = await db.Tokens.FirstOrDefaultAsync(x => x.AppID == instance);
if (tokenBase == null)
{
message = "Your message";
ModelState.AddModelError("AppIdNotFound", message);
return NotFound(ModelState);
}
var token = new Token
{
GrantType = "refresh_token",
RefreshToken = tokenBase.Token
};
if (!GetAccessToken(ref token))
{
message = $"Your message";
ModelState.AddModelError("NotCorrectAccessToken", message);
return BadRequest(ModelState);
}
return new ObjectResult(token.AccessToken);
}
Model Token:
public class Token
{
public Token() { }
public Token(string code) { Code = code; }
[JsonProperty("grant_type")]
public string GrantType { get; set; } = "authorization_code";
[JsonProperty("client_id")]
public string ClientID { get; set; } = "";
[JsonProperty("client_secret")]
public string ClientSecret { get; set; } = "";
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("refresh_token", NullValueHandling = NullValueHandling.Ignore)]
public string RefreshToken { get; set; }
[JsonProperty("access_token", NullValueHandling = NullValueHandling.Ignore)]
public string AccessToken { get; set; }
}
Model Instance:
public class Instance
{
[JsonProperty("instanceId")]
public string InstanceId { get; set; }
[JsonProperty("appDefId")]
public string AppDefId { get; set; }
[JsonProperty("signDate")]
public DateTime SignDate { get; set; }
[JsonProperty("uid")]
public string Uid { get; set; }
[JsonProperty("permissions")]
public string Permissions { get; set; }
[JsonProperty("demoMode")]
public bool DemoMode { get; set; }
[JsonProperty("siteOwnerId")]
public string SiteOwnerId { get; set; }
[JsonProperty("siteMemberId")]
public string SiteMemberId { get; set; }
[JsonProperty("expirationDate")]
public DateTime ExpirationDate { get; set; }
[JsonProperty("loginAccountId")]
public string LoginAccountId { get; set; }
}
Don't forget that to get an Access Token, you will need the application ID on the site where it is installed.
[HttpGet("WixInfo")]
public ActionResult GetWixInfo([FromQuery] string instance = "")
{
try
{
string message;
var base64 = instance.Split(".");
if (base64.Length != 2)
{
message = "Your message";
ModelState.AddModelError("InstanceNotCorrect", message);
return BadRequest(ModelState);
}
var base64EncodedBytes = Convert.FromBase64String(base64[1]);
string json = Encoding.Default.GetString(base64EncodedBytes);
var info = JsonConvert.DeserializeObject<Instance>(json);
message = $"Your message.AppID: {info.InstanceId}";
return Ok(message);
}
catch (Exception ex)
{
ModelState.AddModelError("GetWixInfoException", ex.Message);
return BadRequest(ModelState);
}
}
When a WIX application is launched by a user, you can get the ID of the running application.

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 use await in asp.net webapi post method

I am using entity framework and asp.net web API. I want to make the following method async but I do not know where to use await in following code.
[HttpPost]
public async Task<IHttpActionResult> CreateAccount([FromUri]string fullname, string email, string cnic,string username,string password, string logrol )
{
using (var entity = new Smock_DBEntities())
{
Person pr = new Person();
pr.Full_Name = fullname;
pr.Email = email;
pr.CNIC = cnic;
entity.Persons.Add(pr);
entity.SaveChanges();
int prID = entity.Persons.Where(per => per.CNIC == cnic).Select(per => per.Person_ID).First();
Login log = new Login();
log.Person_ID = prID;
log.Username = username;
log.Password = password;
log.Login_Role = logrol;
entity.Logins.Add(log);
entity.SaveChanges();
return Ok();
}
}
Putting it as an answer with possible places(3 places) where you can put await in your code snippet.
[HttpPost]
public async Task<IHttpActionResult> CreateAccount([FromUri]string fullname, string email, string cnic,string username,string password, string logrol )
{
using (var entity = new Smock_DBEntities())
{
Person pr = new Person();
pr.Full_Name = fullname;
pr.Email = email;
pr.CNIC = cnic;
entity.Persons.Add(pr);
await entity.SaveChangesAsync();
int prID = await entity.Persons.Where(per => per.CNIC == cnic).Select(per => per.Person_ID).FirstAsync();
Login log = new Login();
log.Person_ID = prID;
log.Username = username;
log.Password = password;
log.Login_Role = logrol;
entity.Logins.Add(log);
await entity.SaveChangesAsync();
return Ok();
}
}

Not able to access Request.Headers in BeginExecuteCore() method of Basecontroller MVC4

Can any one please help me? I am trying to implement localization in my mvc 4 WebApi application. I want to show the culture specific pages to the user on the basis of
"User-Locale" passed in the Request headers.
What I have done is, I am having a LinkedAccountModel class as shown below -
public class LinkedAccountModel
{
public string Id { get; set; }
[Required(ErrorMessageResourceType = typeof(LanguageResources.Resource), ErrorMessageResourceName = "DomainNameRequired")]
[DataType(DataType.Password)]
[Display(Name = "DomainName", ResourceType = typeof(LanguageResources.Resource))]
public string DomainName { get; set; }
[Required(ErrorMessageResourceType = typeof(LanguageResources.Resource), ErrorMessageResourceName = "UserNameRequired")]
[Display(Name = "UserName", ResourceType = typeof(LanguageResources.Resource))]
public string UserName { get; set; }
[Required(ErrorMessageResourceType = typeof(LanguageResources.Resource), ErrorMessageResourceName = "PasswordRequired")]
[DataType(DataType.Password)]
[Display(Name = "Password", ResourceType = typeof(LanguageResources.Resource))]
public string Password { get; set; }
[Required(ErrorMessageResourceType = typeof(LanguageResources.Resource), ErrorMessageResourceName = "ServerNameRequired")]
[Display(Name = "ServerName", ResourceType = typeof(LanguageResources.Resource))]
public string ServerName { get; set; }
[Required]
public long UserId { get; set; }
}
========================================================================
With this, I am having an ExchangeAccountSetupController which uses this model. This controller is implemented by the BaseController. My ExchangeAccountSetupController looks like as follows-
public class ExchangeAccountSetupController : BaseController
{
private PersistenceManagerAsync _persistenceManager;
public async Task<ActionResult> New(string sessionToken)
{
if (string.IsNullOrEmpty(sessionToken))
{
ViewBag.Title = LanguageResources.Resource.AccountConfigurationFailed;
ViewBag.ErrorMessage = LanguageResources.Resource.UnableToProcessRequest;
return View("Message");
}
_persistenceManager = new PersistenceManagerAsync(null);
var token = await _persistenceManager.RetrieveAsync<SessionToken>(string.Format("{0}|{1}", sessionToken.Substring(0, 10), sessionToken));
if (token == null)
{
ViewBag.Title = LanguageResources.Resource.AccountConfigurationFailed;
ViewBag.ErrorMessage = LanguageResources.Resource.UnableToProcessRequest;
return View("Message");
}
_persistenceManager = new PersistenceManagerAsync(token);
var user = new User { UserId = token.UserId };
var linkedAccount = await LinkedAccountManager.RetrieveLinkedAccount(_persistenceManager, user, "Exchange");
var linkedAccountModel = new LinkedAccountModel { UserId = token.UserId };
var existingUser = await _persistenceManager.RetrieveAsync<User>(user.PartitionKey, user.RowKey);
if (linkedAccount != null)
{
ViewBag.Title = LanguageResources.Resource.ChangePassword;
linkedAccountModel.DomainName = linkedAccount.DomainName;
linkedAccountModel.UserName = linkedAccount.UserName;
if (!string.IsNullOrEmpty(linkedAccount.Url))
linkedAccountModel.ServerName = new Uri(linkedAccount.Url).Host;
return View("New", linkedAccountModel);
}
ViewBag.Title = LanguageResources.Resource.ConfigureNewExchangeAccount; //default title.
return View("New", linkedAccountModel);
}
========================================================================
My BaseController looks like as follows -
public class BaseController : Controller
{
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
string currentLocale = string.Empty;
if (Request.Headers["User-Locale"] == null || string.IsNullOrEmpty(Request.Headers["User-Locale"]))
currentLocale = "en-US";
else
currentLocale = Request.Headers["User-Locale"];
// Modify current thread's cultures
string[] localeKeys = currentLocale.Split('-');
if (localeKeys[0].Equals("en"))
currentLocale = "en-US";
else if (localeKeys[0].Equals("nl"))
currentLocale = "nl-NL";
else
currentLocale = "en-US";
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(currentLocale);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
return base.BeginExecuteCore(callback, state);
}
}
========================================================================
My client application is in Dotnet only. I am sending a request to the "ExchangeAccountSetupController" controller's New() Action.
Here is the client application code where I am adding headers in my HttpClient Request-
var client = new HttpClient();
client.Timeout = new TimeSpan(1, 1, 1);
client.DefaultRequestHeaders.Add("User-Locale", "nl-NL");
var webResponse = httpClient.GetAsync(RestServiceUrl.GetLinkedAccountProviderUrl(accountProviderName)).Result;
if (webResponse.StatusCode != HttpStatusCode.OK)
return null;
var url = JsonConvert.DeserializeObject<string>(webResponse.Content.ReadAsStringAsync().Result);
return url;
My problem is that whenever I send a request from my client, the request reached to BaseController successfully.But I cannot access that "User-Locale" in the current Request object under BeginExecuteCore() method. I cannot access the "User-Locale" header from the Request object. I did not get any thing in Request.Headers["User-Locale"].It give me null.
Please tell me if I am doing anything wrong.Even I am not sure whether I can access that header under BeginExecuteCore() method or not .Any suggestions are highly appreciated.
There is no User-Locale header defined in HTTP. You are probably looking for the Accept-Language header.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
From MVC Web API you can get a hold of it with
Request.Headers.AcceptLanguage.
You can also get a parsed list of languages with this property
HttpContext.Current.Request.UserLanguages
Please note that the list is NOT sorted, contrary to what the documentation says.
http://msdn.microsoft.com/en-us/library/system.web.httprequest.userlanguages(v=vs.110).aspx

Not able to send the Toast Push notification in wp7

I always get the 404 error.Below is my complete code for sending the push notification of type Toast from the wcf service.Anything wrong with the message ?
string channelURI = "http://db3.notify.live.net/throttledthirdparty/01.00/AgAAAAQUZm52OjBEMTRBNDEzQjc4RUFBRTY";
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(channelURI);
//Indicate that you'll send toast notifications!
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
sendNotificationRequest.Method = "POST";
sendNotificationRequest.Headers.Add("X-MessageID",Guid.NewGuid().ToString());
if (string.IsNullOrEmpty(message)) return "empty cannot be sent";
//send it
var msg = string.Format("sample toast message", "Toast Message", "This is from server");
byte[] notificationMessage = Encoding.UTF8.GetBytes(msg);
sendNotificationRequest.ContentLength = notificationMessage.Length;
//Push data to stream
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
//Get reponse for message sending
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
return notificationStatus;
this code may help you
private static byte[] prepareToastPayload(string text1, string text2)
{
MemoryStream stream = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, Encoding = Encoding.UTF8 };
XmlWriter writer = XmlTextWriter.Create(stream, settings);
writer.WriteStartDocument();
writer.WriteStartElement("wp", "Notification", "WPNotification");
writer.WriteStartElement("wp", "Toast", "WPNotification");
writer.WriteStartElement("wp", "Text1", "WPNotification");
writer.WriteValue(text1);
writer.WriteEndElement();
writer.WriteStartElement("wp", "Text2", "WPNotification");
writer.WriteValue(text2);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
byte[] payload = stream.ToArray();
return payload;
}
private void SendMessage(Uri channelUri, byte[] payload, NotificationType notificationType, SendNotificationToMPNSCompleted callback)
{
//Check the length of the payload and reject it if too long
if (payload.Length > MAX_PAYLOAD_LENGTH)
throw new ArgumentOutOfRangeException(
"Payload is too long. Maximum payload size shouldn't exceed " + MAX_PAYLOAD_LENGTH.ToString() + " bytes");
try
{
//Create and initialize the request object
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(channelUri);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "text/xml; charset=utf-8";
request.ContentLength = payload.Length;
request.Headers[MESSAGE_ID_HEADER] = Guid.NewGuid().ToString();
request.Headers[NOTIFICATION_CLASS_HEADER] = ((int)notificationType).ToString();
if (notificationType == NotificationType.Toast)
request.Headers[WINDOWSPHONE_TARGET_HEADER] = "toast";
else if (notificationType == NotificationType.Token)
request.Headers[WINDOWSPHONE_TARGET_HEADER] = "token";
request.BeginGetRequestStream((ar) =>
{
//Once async call returns get the Stream object
Stream requestStream = request.EndGetRequestStream(ar);
//and start to write the payload to the stream asynchronously
requestStream.BeginWrite(payload, 0, payload.Length, (iar) =>
{
//When the writing is done, close the stream
requestStream.EndWrite(iar);
requestStream.Close();
//and switch to receiving the response from MPNS
request.BeginGetResponse((iarr) =>
{
using (WebResponse response = request.EndGetResponse(iarr))
{
//Notify the caller with the MPNS results
OnNotified(notificationType, (HttpWebResponse)response, callback);
}
},
null);
},
null);
},
null);
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
//Notify client on exception
OnNotified(notificationType, (HttpWebResponse)ex.Response, callback);
}
throw;
}
}
protected void OnNotified(NotificationType notificationType, HttpWebResponse response, SendNotificationToMPNSCompleted callback)
{
CallbackArgs args = new CallbackArgs(notificationType, response);
if (null != callback)
callback(args);
}
public class CallbackArgs
{
public CallbackArgs(NotificationType notificationType, HttpWebResponse response)
{
this.Timestamp = DateTimeOffset.Now;
this.MessageId = response.Headers[NotificationSenderUtility.MESSAGE_ID_HEADER];
this.ChannelUri = response.ResponseUri.ToString();
this.NotificationType = notificationType;
this.StatusCode = response.StatusCode;
this.NotificationStatus = response.Headers[NotificationSenderUtility.NOTIFICATION_STATUS_HEADER];
this.DeviceConnectionStatus = response.Headers[NotificationSenderUtility.DEVICE_CONNECTION_STATUS_HEADER];
this.SubscriptionStatus = response.Headers[NotificationSenderUtility.SUBSCRIPTION_STATUS_HEADER];
}
public DateTimeOffset Timestamp { get; private set; }
public string MessageId { get; private set; }
public string ChannelUri { get; private set; }
public NotificationType NotificationType { get; private set; }
public HttpStatusCode StatusCode { get; private set; }
public string NotificationStatus { get; private set; }
public string DeviceConnectionStatus { get; private set; }
public string SubscriptionStatus { get; private set; }
}
public enum NotificationType
{
Token = 1,
Toast = 2,
Raw = 3
}

Resources