/// <summary> /// /// </summary> /// <param name="pushRegistration"></param> /// <returns></returns> public async Task<string> CreateOrUpdateRegistrationAsync(PushRegistration pushRegistration) { UserRegistrationResult userRegistrationResult = await RegisterUserAsync(pushRegistration); if (userRegistrationResult == null) { return pushRegistration.RegistrationId; } RegistrationDescription registration = null; switch (pushRegistration.Platform) { case PushPlatform.APNS: registration = new AppleRegistrationDescription(pushRegistration.Handle); break; case PushPlatform.GCM: registration = new GcmRegistrationDescription(pushRegistration.Handle); break; case PushPlatform.WNS: registration = new WindowsRegistrationDescription(pushRegistration.Handle); break; default: //throw new HttpResponseException(HttpStatusCode.BadRequest); throw new Exception(); } registration.RegistrationId = userRegistrationResult.RegistrationId; if (pushRegistration.Tags?.Any() ?? false) { registration.Tags = new HashSet<string>(pushRegistration.Tags); } await notificationHub.CreateOrUpdateRegistrationAsync(registration); return registration.RegistrationId; }
public async Task CreateRegistrationAsync_PassValidGcmNativeRegistration_GetCreatedRegistrationBack() { LoadMockData(); await DeleteAllRegistrationsAndInstallations(); var registration = new GcmRegistrationDescription(_configuration["GcmDeviceToken"]); registration.PushVariables = new Dictionary <string, string>() { { "var1", "value1" } }; registration.Tags = new HashSet <string>() { "tag1" }; var createdRegistration = await _hubClient.CreateRegistrationAsync(registration); Assert.NotNull(createdRegistration.RegistrationId); Assert.NotNull(createdRegistration.ETag); Assert.NotNull(createdRegistration.ExpirationTime); Assert.Contains(new KeyValuePair <string, string>("var1", "value1"), createdRegistration.PushVariables); Assert.Contains("tag1", createdRegistration.Tags); Assert.Equal(registration.GcmRegistrationId, createdRegistration.GcmRegistrationId); RecordTestResults(); }
public async Task<ApiResult> Put(DeviceDto deviceUpdate) { RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = deviceUpdate.RegistrationId; // add check if user is allowed to add these tags registration.Tags = new HashSet<string>(deviceUpdate.Tags); await _hub.CreateOrUpdateRegistrationAsync(registration); return SuccessApiResult(deviceUpdate.RegistrationId); }
// PUT api/register/5 // This creates or updates a registration (with provided channelURI) at the specified id public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate) { RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = id; // add check if user is allowed to add these tags registration.Tags = new HashSet <string>(deviceUpdate.Tags); try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } return(Request.CreateResponse(HttpStatusCode.OK)); }
// PUT api/register/5 // This creates or updates a registration (with provided PNS handle) at the specified id public async void Put(string id, DeviceRegistration deviceUpdate) { // IMPORTANT: add logic to make sure that caller is allowed to register for the provided tags RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = id; registration.Tags = new HashSet<string>(deviceUpdate.Tags); try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } }
public string Serialize(EntityDescription description) { var stringBuilder = new StringBuilder(); var settings = new XmlWriterSettings { OmitXmlDeclaration = true }; // Convert FCM descriptions into their GCM counterparts if (description.GetType().Name == "FcmRegistrationDescription") { description = new GcmRegistrationDescription((FcmRegistrationDescription)description); } if (description.GetType().Name == "FcmTemplateRegistrationDescription") { description = new GcmTemplateRegistrationDescription((FcmTemplateRegistrationDescription)description); } var serializer = GetSerializer(description.GetType().Name); using (var xmlWriter = XmlWriter.Create(stringBuilder, settings)) { serializer.WriteObject(xmlWriter, description); } return(stringBuilder.ToString()); }
public void Serialize(EntityDescription description, XmlWriter writer) { // Convert FCM descriptions into their GCM counterparts if (description.GetType().Name == "FcmRegistrationDescription") { description = new GcmRegistrationDescription((FcmRegistrationDescription)description); } if (description.GetType().Name == "FcmTemplateRegistrationDescription") { description = new GcmTemplateRegistrationDescription((FcmTemplateRegistrationDescription)description); } DataContractSerializer serializer; if (description is RegistrationDescription) { serializer = GetSerializer(typeof(RegistrationDescription).Name); } else { serializer = GetSerializer(description.GetType().Name); } serializer.WriteObject(writer, description); }
public async Task GetRegistrationsByTagAsync_CreateTwoRegistrationsWithTheSameTag_GetCreatedRegistrationsWithRequestedTag() { LoadMockData(); await DeleteAllRegistrationsAndInstallations(); var appleRegistration1 = new AppleRegistrationDescription(_configuration["AppleDeviceToken"], new [] { "tag1" }); var appleRegistration2 = new AppleRegistrationDescription(_configuration["AppleDeviceToken"], new[] { "tag1" }); var gcmRegistration = new GcmRegistrationDescription(_configuration["GcmDeviceToken"]); var createdAppleRegistration1 = await _hubClient.CreateRegistrationAsync(appleRegistration1); var createdAppleRegistration2 = await _hubClient.CreateRegistrationAsync(appleRegistration2); // Create a registration with another channel to make sure that SDK passes correct tag and two registrations will be returned var createdGcmRegistration = await _hubClient.CreateRegistrationAsync(gcmRegistration); var allRegistrations = await _hubClient.GetRegistrationsByTagAsync("tag1", 100); var allRegistrationIds = allRegistrations.Select(r => r.RegistrationId).ToArray(); Assert.Equal(2, allRegistrationIds.Count()); Assert.Contains(createdAppleRegistration1.RegistrationId, allRegistrationIds); Assert.Contains(createdAppleRegistration2.RegistrationId, allRegistrationIds); RecordTestResults(); }
public async Task <HttpStatusCode> Put(string id, DeviceRegistrationContract deviceUpdate) { RegistrationDescription registration; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = id; registration.Tags = new HashSet <string>(deviceUpdate.Tags); try { await _hub.CreateOrUpdateRegistrationAsync(registration); return(HttpStatusCode.OK); } catch (MessagingException e) { var webex = e.InnerException as WebException; if (webex.Status == WebExceptionStatus.ProtocolError) { var response = (HttpWebResponse)webex.Response; if (response.StatusCode == HttpStatusCode.Gone) { // Client will force a refresh for a new id after receiving this message. return(HttpStatusCode.Gone); } } return(HttpStatusCode.InternalServerError); } catch (Exception) { return(HttpStatusCode.InternalServerError); } }
// PUT api/register/5 // This creates or updates a registration (with provided channelURI) at the specified id //there are two ways be registered in the notifications hub //1 is the device directly make the connection //2 the Back-end connects the device public async Task <HttpResponseMessage> Put(HttpRequestMessage req) { string jsonContent = await req.Content.ReadAsStringAsync(); dynamic data = JsonConvert.DeserializeObject(jsonContent); RegistrationDescription registration = null; string platform = data.platform; //handle is the channel uri for the connection with the device, there are different code lines for each OS //Ex. var handle = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); for Windows app string handle = data.handle; switch (platform) { case "mpns": registration = new MpnsRegistrationDescription(handle); break; case "wns": registration = new WindowsRegistrationDescription(handle); break; case "apns": registration = new AppleRegistrationDescription(handle); break; case "gcm": registration = new GcmRegistrationDescription(handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } string id = data.id; registration.RegistrationId = id; string username = data.username; string[] tags = data.tags; // add check if user is allowed to add these tags registration.Tags = new HashSet <string>(tags); //username can be repeated many times due to the devices he has registration.Tags.Add("username:" + username); try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } return(Request.CreateResponse(HttpStatusCode.OK)); }
public Task RegisterGoogle(Guid account_id, string deviceToken) { return(Task.Run(async delegate() { try { NotificationHubClient hubClient = this.HubClient; Account account = this.API.Direct.Accounts.GetById(account_id); string previousRegistrationID = account.push_google; if (!string.IsNullOrEmpty(previousRegistrationID)) { if (await hubClient.RegistrationExistsAsync(previousRegistrationID)) { await hubClient.DeleteRegistrationAsync(previousRegistrationID); } } string accountTag = string.Format(PushAssumptions.TARGET_ACCOUNT_FORMAT, account_id.ToString().ToLower()); var registrations = await hubClient.GetRegistrationsByTagAsync(accountTag, 100); foreach (RegistrationDescription registration in registrations) { if (registration.Tags.Contains("droid")) { await hubClient.DeleteRegistrationAsync(registration); } } List <string> tags = new List <string>(); tags.Add(accountTag); tags.Add("droid"); GcmRegistrationDescription newRegistration = await hubClient.CreateGcmNativeRegistrationAsync(deviceToken, tags); if (newRegistration != null) { this.API.Direct.Accounts.UpdatePushTokenGoogle(account.account_id, newRegistration.RegistrationId); } } catch (Exception ex) { base.IFoundation.LogError(ex); } })); }
/// <summary> /// register device as an asynchronous operation. /// </summary> /// <param name="deviceUpdate">The device update.</param> /// <param name="registrationId">The registration identifier.</param> /// <returns>The Task<System.Boolean>.</returns> private async Task <bool> RegisterDeviceAsync(DeviceInfo deviceUpdate, string registrationId) { bool?isRegistrationIdExpired = false; RegistrationDescription registration; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = registrationId; // the tags can be from the device or from the backEnd storage, it depends from the application requirements registration.Tags = new HashSet <string>(deviceUpdate.Tags); try { await _notificationHubClient.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException messagingException) { isRegistrationIdExpired = IsRegistrationIdExpired(messagingException); if (isRegistrationIdExpired == null) { throw; } } return(isRegistrationIdExpired.Value); }
public async Task RegisterDeviceTags(UserDevice deviceUpdate, string[] tags) { try { RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.PushToken); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.PushToken); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.PushToken); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.PushToken); break; default: throw new Exception("Unrecognized platform."); } registration.RegistrationId = deviceUpdate.RegistrationId; registration.Tags = new HashSet<string>(tags); // Add an extra tag for the platform, in case we want to send // to all users on that platform. registration.Tags.Add("Reop:" + deviceUpdate.Platform); try { await Hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); throw e; } return; } catch (Exception e) { throw e; } }
// PUT api/register/5 // This creates or updates a registration (with provided PNS handle) at the specified id public async Task <IHttpActionResult> Put(string id, DeviceRegistration deviceUpdate) { // IMPORTANT: add logic to make sure that caller is allowed to register for the provided tags RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = id; if (deviceUpdate.Tags != null) { registration.Tags = new HashSet <string>(deviceUpdate.Tags); } try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } return(Ok()); }
// PUT api/register/5 // This creates or updates a registration (with provided channelURI) at the specified id public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate) { RegistrationDescription registration; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = id; var username = deviceUpdate.UserId; registration.Tags = new HashSet <string>(deviceUpdate.Tags) { "username:" + username }; try { await _hub.CreateOrUpdateRegistrationAsync(registration); await SetPnsToUser(deviceUpdate.UserId, deviceUpdate.Platform); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } return(Request.CreateResponse(HttpStatusCode.OK)); }
public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate) { RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = id; var identity = (ClaimsIdentity)User.Identity; var email = identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Email).Value; // add check if user is allowed to add these tags registration.Tags = new HashSet <string>(deviceUpdate.Tags); //registration.Tags.Add("username:" + email); try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } return(Request.CreateResponse(HttpStatusCode.OK)); }
// PUT api/register/5 // Cria ou atualiza um registron (com o channelURI fornecido) no para id public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate) { RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = id; var username = HttpContext.Current.User.Identity.Name; // incluir validação se o usuário pode adicionar essas tags registration.Tags = new HashSet <string>(deviceUpdate.Tags); registration.Tags.Add("username:" + username); try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } return(Request.CreateResponse(HttpStatusCode.OK)); }
public async Task <string> RegisterWithHub(DeviceRegistration deviceUpdate) { string newRegistrationId = null; try { // // make sure there are no existing registrations for this push handle (used for iOS and Android) // if (deviceUpdate.Handle != null) // { // //Azure likes to uppercase the iOS device handles for some reason - no worries tho, I only spent 2 hours tracking this down // if (deviceUpdate.Platform == "iOS") // deviceUpdate.Handle = deviceUpdate.Handle.ToUpper(); // var registrations = await _hub.GetRegistrationsByChannelAsync(deviceUpdate.Handle, 100); // foreach (var reg in registrations) // { // if (newRegistrationId == null) // { // newRegistrationId = reg.RegistrationId; // } // else // { // await _hub.DeleteRegistrationAsync(reg); // } // } // } if (newRegistrationId == null) { newRegistrationId = await _hub.CreateRegistrationIdAsync(); } GcmRegistrationDescription registration = new GcmRegistrationDescription(deviceUpdate.Handle, deviceUpdate.Tags); registration.RegistrationId = newRegistrationId; await _hub.CreateOrUpdateRegistrationAsync(registration); } catch (Exception ex) { throw ex; } return(newRegistrationId); }
/// <summary> /// 以userId更新其裝置PNS的資訊 /// </summary> /// <param name="userId"></param> /// <param name="pns"></param> /// <param name="pnsToken"></param> /// <returns></returns> public async Task <string> updateRegId(string userId, PNS pns, string pnsToken) { string tag = getUserTag(userId); //取得或新建azure regId string regId = await getRegIdAsync(tag); //依pns類型建立註冊描述 RegistrationDescription registration = null; switch (pns) { case PNS.apns: registration = new AppleRegistrationDescription(pnsToken); break; case PNS.gcm: registration = new GcmRegistrationDescription(pnsToken); break; default: break; } try { //填入內容並更新到azure notification hub registration.RegistrationId = regId; registration.Tags = new HashSet <string>(); registration.Tags.Add(D.NTFTAG.EVERYBODY); registration.Tags.Add(tag); await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { Console.WriteLine(e.ToString()); return(null); } return(registration.RegistrationId); }
public async Task <GcmRegistrationDescription> Subsribe(string[] tags, string regId) { GcmRegistrationDescription result = null; //var isRegIdExist = await this.hub.GetRegistrationAsync<GcmRegistrationDescription>(regId); //if (isRegIdExist != null) //{ // await this.hub.DeleteRegistrationAsync(regId); //} if (tags != null) { result = await this.hub.CreateGcmNativeRegistrationAsync(regId, tags); } else { result = await this.hub.CreateGcmNativeRegistrationAsync(regId); } return(result); }
// PUT api/register/5 // This creates or updates a registration (with provided channelURI) at the specified id public async Task <IActionResult> Put(string id, DeviceRegistration deviceUpdate) { RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; } registration.RegistrationId = id; var username = HttpContext.User.Identity.Name; // add check if user is allowed to add these tags registration.Tags = new HashSet <string>(deviceUpdate.Tags); registration.Tags.Add("username:" + username); try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } return(Ok()); }
public async Task GetAllRegistrationsAsync_CreateTwoRegistrations_GetAllCreatedRegistrations() { LoadMockData(); await DeleteAllRegistrationsAndInstallations(); var appleRegistration = new AppleRegistrationDescription(_configuration["AppleDeviceToken"]); var gcmRegistration = new GcmRegistrationDescription(_configuration["GcmDeviceToken"]); var createdAppleRegistration = await _hubClient.CreateRegistrationAsync(appleRegistration); var createdGcmRegistration = await _hubClient.CreateRegistrationAsync(gcmRegistration); var allRegistrations = await _hubClient.GetAllRegistrationsAsync(100); var allRegistrationIds = allRegistrations.Select(r => r.RegistrationId).ToArray(); Assert.Equal(2, allRegistrationIds.Count()); Assert.Contains(createdAppleRegistration.RegistrationId, allRegistrationIds); Assert.Contains(createdGcmRegistration.RegistrationId, allRegistrationIds); RecordTestResults(); }
// PUT api/put/5 // This creates or updates a registration (with provided channelURI) at the specified id public async Task<HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate) { RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = id; var username = HttpContext.Current.User.Identity.Name; // add check if user is allowed to add these tags registration.Tags = new HashSet<string>(deviceUpdate.Tags); registration.Tags.Add("username:" + username); try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } return Request.CreateResponse(HttpStatusCode.OK); }
/// <summary> /// Register device to receive push notifications. /// Registration ID ontained from Azure Notification Hub has to be provided /// Then basing on platform (Android, iOS or Windows) specific /// handle (token) obtained from Push Notification Service has to be provided /// </summary> /// <param name="id"></param> /// <param name="deviceUpdate"></param> /// <returns></returns> public async Task <HubResponse> RegisterForPushNotifications(string id, DeviceRegistration deviceUpdate) { RegistrationDescription registrationDescription = null; switch (deviceUpdate.Platform) { case MobilePlatform.wns: registrationDescription = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case MobilePlatform.apns: registrationDescription = new AppleRegistrationDescription(deviceUpdate.Handle); break; case MobilePlatform.gcm: registrationDescription = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: return(new HubResponse().AddErrorMessage("Please provide correct platform notification service name.")); } registrationDescription.RegistrationId = id; if (deviceUpdate.Tags != null) { registrationDescription.Tags = new HashSet <string>(deviceUpdate.Tags); } try { await _hubClient.CreateOrUpdateRegistrationAsync(registrationDescription); return(new HubResponse()); } catch (MessagingException) { return(new HubResponse().AddErrorMessage("Registration failed because of HttpStatusCode.Gone. PLease register once again.")); } }
public async Task CreateOrUpdateRegistration(string id, DeviceRegistration deviceRegistration) { RegistrationDescription registration; switch (deviceRegistration.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceRegistration.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceRegistration.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceRegistration.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceRegistration.Handle); break; default: throw new ArgumentException("Platform not supported."); } registration.RegistrationId = id; registration.Tags = new HashSet <string>(deviceRegistration.Tags); try { await _hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } }
public async Task <ApiResult> Put(DeviceDto deviceUpdate) { RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = deviceUpdate.RegistrationId; // add check if user is allowed to add these tags registration.Tags = new HashSet <string>(deviceUpdate.Tags); await _hub.CreateOrUpdateRegistrationAsync(registration); return(SuccessApiResult(deviceUpdate.RegistrationId)); }
public async Task <IActionResult> Put([FromRoute] string id, [FromBody] DevicecRegistration deviceUpdate) { RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: return(BadRequest(deviceUpdate)); } registration.RegistrationId = id; registration.Tags = new HashSet <string>(deviceUpdate.Tags); try { await _hub.CreateOrUpdateRegistrationAsync(registration); }catch (MessagingException e) { return(ReturnGoneIfHubResponseIsGone(e)); } return(Ok(id)); }
public async Task <IHttpActionResult> Register([FromBody] DeviceRegistration device) { RegistrationDescription registration = new GcmRegistrationDescription(device.Handle); var registrationId = await CreateRegistrationId(device.Handle); registration.RegistrationId = registrationId; registration.Tags = new HashSet <string>() { device.Tag }; try { await hub.CreateOrUpdateRegistrationAsync(registration); return(Ok()); } catch (MessagingException ex) { return(InternalServerError(ex)); } }
public async Task <string> Upsert(PushRegistration deviceUpdate) { RegistrationDescription desc = null; switch (deviceUpdate.Platform) { case Platform.Windows: desc = new WindowsRegistrationDescription(deviceUpdate.DeviceToken); break; case Platform.iOS: desc = new AppleRegistrationDescription(deviceUpdate.DeviceToken); break; case Platform.Android: desc = new GcmRegistrationDescription(deviceUpdate.DeviceToken); break; default: throw new ArgumentException("Wrong PushChannel"); } string registrationId = deviceUpdate.RegistrationId; if (string.IsNullOrEmpty(registrationId)) { registrationId = await _hub.CreateRegistrationIdAsync(); } desc.RegistrationId = registrationId; desc.Tags = new HashSet <string>(deviceUpdate.Tags); var registration = await _hub.CreateOrUpdateRegistrationAsync(desc); return(registrationId); }
public async Task<HttpStatusCode> Put(string id, DeviceRegistrationContract deviceUpdate) { RegistrationDescription registration; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = id; registration.Tags = new HashSet<string>(deviceUpdate.Tags); try { await _hub.CreateOrUpdateRegistrationAsync(registration); return HttpStatusCode.OK; } catch (MessagingException e) { var webex = e.InnerException as WebException; if (webex.Status == WebExceptionStatus.ProtocolError) { var response = (HttpWebResponse)webex.Response; if (response.StatusCode == HttpStatusCode.Gone) { // Client will force a refresh for a new id after receiving this message. return HttpStatusCode.Gone; } } return HttpStatusCode.InternalServerError; } catch (Exception) { return HttpStatusCode.InternalServerError; } }
/// <summary> /// CSV 形式でアップロードされたファイルを元に登録情報の追加、更新を行います /// </summary> public async Task <HttpResponseMessage> Post() { // マルチパート以外の場合には拒否 if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } // マルチパートデータを読み込む var provider = await Request.Content.ReadAsMultipartAsync(); var content = provider.Contents.FirstOrDefault(p => p.Headers.ContentDisposition.Name == "\"csv\""); // ファイルが見つからない場合にはエラー if (content == null) { throw new HttpResponseException(HttpStatusCode.BadRequest); } RegistrationModel[] records; try { // CSV としてファイルを解析する var csvData = await content.ReadAsStringAsync(); var reader = new StringReader(csvData); var csvReader = new CsvReader(reader); csvReader.Configuration.RegisterClassMap <RegistrationModelMap>(); records = csvReader.GetRecords <RegistrationModel>().ToArray(); } catch (Exception ex) { return(Failure(ex.Message)); } // 予め登録済みのデータがあるかを非同期で一括取得する var registrations = (await Task.WhenAll(records.Where(p => !string.IsNullOrEmpty(p.RegistrationId)).Select(p => _client.GetRegistrationAsync <RegistrationDescription>(p.RegistrationId)))).Where(p => p != null).ToArray(); long insert = 0, update = 0; var targets = new List <RegistrationDescription>(); // 1 レコードごとに追加なのか、更新なのか RegistrationId の有無で処理を行う foreach (var record in records) { var registration = registrations.FirstOrDefault(p => p.RegistrationId == record.RegistrationId); if (registration == null) { switch (record.Platform) { case Platforms.Windows: registration = new WindowsRegistrationDescription(record.Handle); break; case Platforms.WindowsPhone: registration = new MpnsRegistrationDescription(record.Handle); break; case Platforms.Apple: registration = new AppleRegistrationDescription(record.Handle); break; case Platforms.Android: registration = new GcmRegistrationDescription(record.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = await _client.CreateRegistrationIdAsync(); insert += 1; } else { switch (record.Platform) { case Platforms.Windows: ((WindowsRegistrationDescription)registration).ChannelUri = new Uri(record.Handle); break; case Platforms.WindowsPhone: ((MpnsRegistrationDescription)registration).ChannelUri = new Uri(record.Handle); break; case Platforms.Apple: ((AppleRegistrationDescription)registration).DeviceToken = record.Handle; break; case Platforms.Android: ((GcmRegistrationDescription)registration).GcmRegistrationId = record.Handle; break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } update += 1; } registration.Tags = record.Tags; targets.Add(registration); } try { // 処理対象を非同期で一括処理する await Task.WhenAll(targets.Select(p => _client.CreateOrUpdateRegistrationAsync(p))); } catch (Exception ex) { return(Failure(ex.Message)); } // 処理結果を返却 return(Success(string.Format("Imported from CSV : Insert {0}, Update {1}, Total {2}", insert, update, insert + update))); }
// PUT api/register/5 // This creates or updates a registration (with provided channelURI) at the specified id public async Task<HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate,string userid) //ADDED STRING USERID { ApiServices.Log.Info("user id in put request: " + userid + "\t Time: " + DateTime.Now); RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = id; //var username = HttpContext.Current.User.Identity.Name; // add check if user is allowed to add these tags ApiServices.Log.Info("username = "******"\t Time: " + DateTime.Now); registration.Tags = new HashSet<string>(deviceUpdate.Tags); registration.Tags.Add("username:"******"in the try for creating registration\t Time: " + DateTime.Now); await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ApiServices.Log.Error("in the catch\t Time: " + DateTime.Now); ReturnGoneIfHubResponseIsGone(e); } return Request.CreateResponse(HttpStatusCode.OK); }
public async Task <RegistrationResponse> DeviceRegistration( string registrationId, string handle, string platform, string userName) { RegistrationResponse response = new RegistrationResponse(); RegistrationDescription registration = null; switch (platform) { case "mpns": registration = new MpnsRegistrationDescription(handle); break; case "wns": registration = new WindowsRegistrationDescription(handle); break; case "apns": registration = new AppleRegistrationDescription(handle); break; case "gcm": registration = new GcmRegistrationDescription(handle); break; default: response.Errors.Add("No Platform"); response.IsSuccess = false; return(response); } registration.RegistrationId = registrationId; // add check if user is allowed to add these tags registration.Tags = new HashSet <string>(); registration.Tags.Add("username:"******"username:"******"the requested resource is no longer available"); } else { response.Errors.Add("the requested resource is no longer available"); } response.IsSuccess = false; return(response); } throw e; } response.IsSuccess = true; return(response); }
// PUT api/register/5 // This creates or updates a registration (with provided channelURI) at the specified id public async Task <HttpResponseMessage> Put() { string value = await Request.Content.ReadAsStringAsync(); var entidad = System.Web.Helpers.Json.Decode(value); string id = entidad.idhubazure; string[] tag = Convert.ToString(entidad.tag).Split(','); DeviceRegistration deviceUpdate = new DeviceRegistration() { Platform = entidad.platform, Handle = entidad.key, Tags = tag }; RegistrationDescription registration = null; switch (deviceUpdate.Platform) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.Handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.Handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.Handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.Handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } //registration.RegistrationId = id; var username = HttpContext.Current.User.Identity.Name; registration = await hub.GetRegistrationAsync <RegistrationDescription>(entidad.idhubazure); registration.Tags = new HashSet <string>(); registration.Tags.Add("username:"******" ", "").Trim(); registration.Tags.Add(tagString); } try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } return(Request.CreateResponse(HttpStatusCode.OK)); }
// This creates or updates a registration (with provided channelURI) at the specified id public async Task <NotificationRegisterReturn> RegisterDevice(NotificationRegisterInput deviceUpdate) { NotificationRegisterReturn ret = new NotificationRegisterReturn(); ret.success = true; ret.actionRes = ""; if (!ModelState.IsValid) { foreach (ModelState modelState in ModelState.Values) { foreach (ModelError err in modelState.Errors) { ret.actionRes += (err.ErrorMessage + " "); } } ret.success = false; return(ret); } string currUserId = HttpContext.Current.User.Identity.GetUserId(); RegistrationDescription registration = null; using (var db = new ApplicationDbContext()) { var me = await db.Users.FirstOrDefaultAsync(u => u.Id == currUserId); switch (deviceUpdate.DeviceSys) { //case "mpns": // registration = new MpnsRegistrationDescription(deviceUpdate.ChannelURI); // break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.ChannelURI); me.Wns = true; break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.ChannelURI); me.Apns = true; break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.ChannelURI); me.Gcm = true; break; default: ret.success = false; ret.actionRes += "DeviceSys: mpns/wns/apns/gcm"; return(ret); } await db.SaveChangesAsync(); registration.RegistrationId = deviceUpdate.RegistrationId; } // add check if user is allowed to add these tags System.Text.StringBuilder str = new System.Text.StringBuilder(currUserId); str.Append(deviceUpdate.DeviceSys); registration.Tags = new HashSet <string>(); registration.Tags.Add(str.ToString()); // registration.ExpirationTime try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { ReturnGoneIfHubResponseIsGone(e); } return(ret); }
public async Task <HttpResponseMessage> Post([FromBody] ProfileRequest request) { HttpResponseMessage response; try { var profileResponse = new ProfileResponse(); using (DbModel.TechReadyDbContext ctx = new DbModel.TechReadyDbContext()) { var appUser = (from c in ctx.AppUsers where c.AuthProviderName == request.AuthProvider && c.AuthProviderUserId == request.AuthProviderUserId select c).FirstOrDefault(); if (appUser == null) { appUser = new DbModel.AppUser(); ctx.AppUsers.Add(appUser); appUser.RegistrationDateTime = DateTime.Now; } appUser.CityName = request.City.CityName; appUser.Town = request.Town; if (request.Location != null) { appUser.Location = ConvertGeoCode(request.Location); } appUser.AudienceOrgID = request.SelectedAudienceOrgType.AudienceOrgId; appUser.AuthProviderName = request.AuthProvider; appUser.AuthProviderUserId = request.AuthProviderUserId; appUser.Email = request.Email; appUser.FullName = request.FullName; if (appUser.TechnologyTags == null) { appUser.TechnologyTags = new List <DbModel.PrimaryTechnology>(); } foreach (var tech in request.SecondaryTechnologies) { var c = (from t in ctx.PrimaryTechnologies where t.PrimaryTechnologyID == tech.PrimaryTechnologyId select t).FirstOrDefault(); if (c != null) { if (tech.IsSelected) { appUser.TechnologyTags.Add(c); } else { if ( appUser.TechnologyTags.FirstOrDefault( x => x.PrimaryTechnologyID == c.PrimaryTechnologyID) != null) { appUser.TechnologyTags.Remove(c); } } } } ctx.SaveChanges(); if (request.PushEnabled && !string.IsNullOrEmpty(request.PushId)) { //Create/Update if the Platform Changes or Notifications are Enabled if ((appUser.DevicePlatform != request.DevicePlatform) || (appUser.PushEnabled != request.PushEnabled) || string.IsNullOrEmpty(appUser.DeviceId) || appUser.PushId != request.PushId ) { appUser.DeviceId = await hub.CreateRegistrationIdAsync(); RegistrationDescription registration = null; switch (request.DevicePlatform) { case "mpns": registration = new MpnsRegistrationDescription(request.PushId); break; case "wns": registration = new WindowsRegistrationDescription(request.PushId); break; case "apns": registration = new AppleRegistrationDescription(request.PushId); break; case "gcm": registration = new GcmRegistrationDescription(request.PushId); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = appUser.DeviceId; registration.Tags = new HashSet <string>(appUser.TechnologyTags.Select(x => x.PrimaryTech).ToList().Select(x => x.Replace(" ", "_")).ToList()); registration.Tags.Add(request.SelectedAudienceType.AudienceTypeName.Replace(" ", "_")); registration.Tags.Add("userId:" + appUser.AppUserID); if (appUser.FollowedEvents != null) { foreach (var followedEvent in appUser.FollowedEvents) { registration.Tags.Add("eventId:" + followedEvent.EventID.ToString()); } } if (appUser.FollowedSpeakers != null) { foreach (var followedSpeaker in appUser.FollowedSpeakers) { registration.Tags.Add("speakerId:" + followedSpeaker.SpeakerID.ToString()); } } await hub.CreateOrUpdateRegistrationAsync(registration); } } else { if (!string.IsNullOrEmpty(appUser.DeviceId)) { await hub.DeleteRegistrationAsync(appUser.DeviceId); appUser.DeviceId = null; } } appUser.DevicePlatform = request.DevicePlatform; appUser.LastAccessTime = DateTime.Now; appUser.PushEnabled = request.PushEnabled; appUser.PushId = request.PushId; ctx.SaveChanges(); profileResponse.UserId = appUser.AppUserID; } response = this.Request.CreateResponse(HttpStatusCode.OK, profileResponse); response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300)); } catch (Exception ex) { HttpError myCustomError = new HttpError(ex.Message) { { "IsSuccess", false } }; return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, myCustomError)); } return(response); }
public async Task<HttpResponseMessage> Put([FromBody]DeviceRegistration deviceUpdate) { RegistrationDescription registration = null; switch (deviceUpdate.platform.ToLower()) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = deviceUpdate.deviceid; registration.Tags = new HashSet<string>(deviceUpdate.tags); // optionally you could supplement/override the list of client supplied tags here // tags will help you target specific devices or groups of devices depending on your needs try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { //ReturnGoneIfHubResponseIsGone(e); } return Request.CreateResponse(HttpStatusCode.OK); }