Not able to send the Toast Push notification in wp7 - windows-phone-7

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
}

Related

How to enable multiple consumers for Apache.NMS.AMQP clients?

Would like to know how to enable multiple consumers for Apache.NMS.AMQP client. Have tried with multiple sessions for same queue with different consumer - but the listener is only getting called for one consumer per queue.
Below is the sample code. Ignore the connection per queue as I thought that might be the cause, but doesn't work. Given consumer one name -ConsumerName to identify consumer being called.
var queueClientLogger = loggerFactory.CreateLogger<QueueClient>();
var queueClient1 = new QueueClient(queueClientLogger, "Q/test1");
await queueClient1.InitializeAsync();
var queueClient2 = new QueueClient(queueClientLogger, "Q/test1");
await queueClient2.InitializeAsync();
var queueClient3 = new QueueClient(queueClientLogger, "Q/test2");
await queueClient3.InitializeAsync();
-----------------------------------------------
internal class QueueClient : IDisposable
{
private readonly ILogger<QueueClient> logger;
private IMessageConsumer consumer;
private bool disposedValue;
#region constructor
public QueueClient(ILogger<QueueClient> logger, string queueName)
{
this.logger = logger;
QueueName = queueName;
ConsumerName = $"{QueueName}-{Guid.NewGuid()}";
}
#endregion
#region Properties
internal string? QueueName { get; private set; }
internal string ConsumerName { get; private set; }
internal Apache.NMS.ISession Session { get; private set; }
internal Apache.NMS.IConnection Connection { get; private set; }
#endregion
#region Methods
internal async Task InitializeAsync()
{
string brokerUri = $"amqp://localhost:5672"; // Default port
NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);
Connection = await factory.CreateConnectionAsync();
await Connection.StartAsync();
Session = await Connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);
Apache.NMS.IDestination dest = await Session.GetQueueAsync(QueueName);
consumer = await Session.CreateConsumerAsync(dest);
consumer.Listener += Consumer_Listener;
}
private void Consumer_Listener(Apache.NMS.IMessage message)
{
logger.LogInformation($"{ConsumerName}: Message from queue - {QueueName}");
Thread.Sleep(1000);
string content = string.Empty;
if (message is ITextMessage)
{
ITextMessage? txtMsg = message as ITextMessage;
content = txtMsg?.Text ?? "";
}
else if (message is IBytesMessage)
{
IBytesMessage? bytesMsg = message as IBytesMessage;
if (bytesMsg == null)
{
content = $"NULL message received";
}
else
{
content = Encoding.UTF8.GetString(bytesMsg.Content);
}
}
else
{
content = "Unexpected message type: " + message.GetType().Name;
}
logger.LogInformation($"{content}");
}
//Ignore IDosposable code
}

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 can I wait end to work async callback HttpWebRequest on Windows Phone 7?

Sorry, it's questions already was on stackoverflow, but I don't found answer. Maybe it's classic, but I can't understand, how to solve this problem :(
I have Singletone class for working with web service:
public sealed class GYAccessService
{
static GYAccessService instance = null;
static readonly object padlock = new object();
public string Atoken { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string Uid { get; set; }
const string UrlRequest = "http://site.html";
private GYAccessService()
{
}
public static GYAccessService Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new GYAccessService();
}
return instance;
}
}
}
public void sendPost(string postData)
{
PostData = "request=" + postData;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UrlRequest);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Accept = "application/json";
webRequest.AllowAutoRedirect = true;
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(getRequestStreamCallback), webRequest);
}
private void getRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(getResponseCallback), webRequest);
}
private void getResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(Response)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ServiceResponse));
ServiceResponse res = (ServiceResponse)serializer.ReadObject(stream);
// I want to return res in main thread
}
}
catch (WebException e)
{
// Error treatment
ServiceResponse err = new ServiceResponse();
err.Message = e.Message;
}
}
public string getRequestString(string model, string method, Params parametrs, string auth = null)
{
Function func = new Function();
func.Model = model;
func.Method = method;
func.Params = parametrs;
ServiceRequest req = new ServiceRequest() { Function = func };
string json = JsonConvert.SerializeObject(req);
ServiceResponse deserializedProduct = JsonConvert.DeserializeObject<ServiceResponse>(json);
return json;
}
}
I have call sendPost() in main thread, I want to return response in this function.
GYAccessService gy = GYAccessService.Instance;
gy.sendPost(postData);
//I want to use the response here
But in WP 7 HttpWebRequest has not GetResponse, only BeginGetResponse. I use callback and don't know how can I return response from callback. I put up with it, I can set property response my Singletone and get it after end async callback, but I don't know how can I block async callback. It's really problem, I try to use WaitOne()/Set() - don't help me, my app just frozen. I try to use IAsyncResult handle, but not success. How can I wait end to work async callback? Thanks in advance!
You need to use the EndGetResponse method and process the result in it. It is asynchronous, so you will not be able to immediately get the result after you call gy.sendPost(postData);, you have to use it as a call back.
If I may suggest, there is a simpler way for such HTTP calls, use RestSharp. It is a great and easy to use library that also works with Windows Phone.

How to post image data from j2me to ASP.net MVC 3?

I'm making a j2me mobile application which can post images (as byte[]) and other simple data (strings, ints, floats, etc) on a ASP.net MVC 3 website. Currently the application and website are nearly done, except the part where the app can post the image data on the website.
Here is the datamodel I'd like to post to the website (j2me):
public class DataModel {
private String description = null;
private float latitude = 0;
private float longitude = 0;
private long timestamp = 0;
private String userName = null;
private byte[] imageData = null;
private String contentType = null;
// getters and setters...
}
This is the model my website expects (ASP.net MVC3 C#):
public class Model
{
public string Description { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public long Timestamp { get; set; }
public string UserName { get; set; }
public byte[] Image { get; set; }
}
This is the (simplified) code I use to send the data (j2me):
InputStream in = null;
OutputStream out = null;
// url contains all the simple data
String encodedUrl = UrlEncoder.encodeUrl(url);
this.connection = (HttpConnection)Connector.open(encodedUrl);
byte[] imageData = DataModel.getImageData();
this.connection.setRequestMethod(HttpConnection.POST);
this.connection.setRequestProperty("Content-Length", imageData.length + "");
out = this.connection.openOutputStream();
out.write(imageData);
int responseCode = this.connection.getResponseCode();
if(responseCode != HttpConnection.HTTP_OK) {
throw new IOException("Transmission failed as server responded with response code: " + responseCode);
}
// process response here...
I've found some sollutions online for handling a post request from a j2me application which doens't do what I want and it's in VB. But maybe there's some useful code in there, which should be placed in the page-load event:
' the stream will be ASCII encoded'
Dim ascii As ASCIIEncoding = New ASCIIEncoding
'Get ASCII into reg. string here'
strmContent = ascii.GetString(strArr)
Label1.Text = strArr.ToString()
'write the received data to a text file'
Dim FILE_NAME As String = "C:\\NP\\received.txt"
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine(strmContent)
objWriter.WriteLine()
objWriter.Close()
I have no clue how I can receive the image data on my website. What code do I need to put in my Controller Action to be able to receive all the data? Do I need to change anything in my application code?
I'm splitting up the simple data from the image data. Is that even the right way to work here?
Thanks alot!
I am not an expert of j2me but you could simply make a multipart/form-data request as shown in this article which allows you to send files in addition to simple values in an HTTP request. So your code will look something along the lines of:
byte[] fileBytes = DataModel.getImageData();
Hashtable params = new Hashtable();
params.put("Description", "some description");
params.put("Latitude", "5");
params.put("Longitude", "6");
params.put("Timestamp", "123");
params.put("UserName", "john smith");
HttpMultipartRequest req = new HttpMultipartRequest(
"http://example.com/home/upload",
params,
"Image", "original_filename.png", "image/png", fileBytes
);
byte[] response = req.send();
Then on your ASP.NET MVC side your view model will simply look like this:
public class MyViewModel
{
public string Description { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public long Timestamp { get; set; }
public string UserName { get; set; }
public HttpPostedFileBase Image { get; set; }
}
and your controller action:
[HttpPost]
public ActionResult Upload(MyViewModel model)
{
...
}
And here's the HttpMultipartRequest code (in case Nokia's site goes down):
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class HttpMultipartRequest
{
static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
byte[] postBytes = null;
String url = null;
public HttpMultipartRequest(String url, Hashtable params, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
{
this.url = url;
String boundary = getBoundaryString();
String boundaryMessage = getBoundaryMessage(boundary, params, fileField, fileName, fileType);
String endBoundary = "\r\n--" + boundary + "--\r\n";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(boundaryMessage.getBytes());
bos.write(fileBytes);
bos.write(endBoundary.getBytes());
this.postBytes = bos.toByteArray();
bos.close();
}
String getBoundaryString()
{
return BOUNDARY;
}
String getBoundaryMessage(String boundary, Hashtable params, String fileField, String fileName, String fileType)
{
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
Enumeration keys = params.keys();
while(keys.hasMoreElements())
{
String key = (String)keys.nextElement();
String value = (String)params.get(key);
res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")
.append("\r\n").append(value).append("\r\n")
.append("--").append(boundary).append("\r\n");
}
res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(fileType).append("\r\n\r\n");
return res.toString();
}
public byte[] send() throws Exception
{
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestMethod(HttpConnection.POST);
OutputStream dout = hc.openOutputStream();
dout.write(postBytes);
dout.close();
int ch;
is = hc.openInputStream();
while ((ch = is.read()) != -1)
{
bos.write(ch);
}
res = bos.toByteArray();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
return res;
}
}

Resources