Example #1
0
        public async Task CreateRegistrationAsync_PassValidMpnsNativeRegistration_GetCreatedRegistrationBack()
        {
            LoadMockData();
            await DeleteAllRegistrationsAndInstallations();

            var registration = new MpnsRegistrationDescription(_configuration["MpnsDeviceToken"]);

            registration.PushVariables = new Dictionary <string, string>()
            {
                { "var1", "value1" }
            };
            registration.Tags = new HashSet <string>()
            {
                "tag1"
            };
            registration.SecondaryTileName = "Tile name";

            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.ChannelUri, createdRegistration.ChannelUri);
            Assert.Equal(registration.SecondaryTileName, createdRegistration.SecondaryTileName);
            RecordTestResults();
        }
    // 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);
      }
    }
Example #3
0
        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 <UpdateRegistrationResponseModel> UpdateHubRegistration(string handle, PlatFormId platform, string registrationId, string userName)
        {
            RegistrationDescription registration;

            switch (platform)
            {
            case PlatFormId.MicrosoftPushNotificationService:
                registration = new MpnsRegistrationDescription(handle);
                break;

            case PlatFormId.WindowsPushNotificationService:
                registration = new WindowsRegistrationDescription(handle);
                break;

            case PlatFormId.ApplePushNotificationService:
                registration = new AppleRegistrationDescription(handle);
                break;

            case PlatFormId.FirebaseCloudMessaging:
                registration = new FcmRegistrationDescription(handle);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(platform));
            }

            registration.RegistrationId = registrationId;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>();
            registration.Tags.Add("username:" + userName);

            try
            {
                var hub = _hubClientFactory.Primary;
                var registrationDescription = await hub.CreateOrUpdateRegistrationAsync(registration);

                return(new UpdateRegistrationResponseModel
                {
                    RegistrationId = registrationDescription.RegistrationId
                });
            }
            catch (MessagingException e)
            {
                var webex = e.InnerException as WebException;
                if (webex.Status == WebExceptionStatus.ProtocolError)
                {
                    var response = (HttpWebResponse)webex.Response;
                    if (response.StatusCode == HttpStatusCode.Gone)
                    {
                        return(null);
                    }
                }

                throw;
            }
        }
        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);
            }
        }
Example #6
0
        // 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;

            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 "fcm":
                registration = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(BadRequest());
            }

            registration.RegistrationId = id;
            var username = HttpContext.User.Identity.Name;
            var nickname = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "nickname")?.Value;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            registration.Tags.Add("username:"******"nickname:" + nickname);

            try
            {
                var hub = _hubClientFactory.Primary;
                var registrationDescription = await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                var webex = e.InnerException as WebException;
                if (webex.Status == WebExceptionStatus.ProtocolError)
                {
                    var response = (HttpWebResponse)webex.Response;
                    if (response.StatusCode == HttpStatusCode.Gone)
                    {
                        return(StatusCode((int)HttpStatusCode.Gone));
                    }
                }
            }

            return(Ok());
        }
Example #7
0
        // 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));
        }
Example #8
0
        public async Task <IActionResult> Put(string id, [FromBody] 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 "fcm":
                registration = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(BadRequest());
            }

            registration.RegistrationId = id;

            var username = User.GetEmail();
            var userId   = User.GetUserId();

            if (string.IsNullOrEmpty(username))
            {
                return(Unauthorized());
            }

            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            // registration.Tags.Add("email:" + username.ToUpper());
            // registration.Tags.Add("userid:" + userId);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Ok());
        }
        /// <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&lt;System.Boolean&gt;.</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);
        }
Example #10
0
        // 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());
        }
Example #11
0
        // 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));
        }
Example #12
0
        // 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 "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 FcmRegistrationDescription(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)
            {
                "username:" + username
            };

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        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;
            }
        }
Example #14
0
        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
        // 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);
        }
        // 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));
        }
Example #17
0
        public async Task <IActionResult> RegisterDevice(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 "fcm":
                registration = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(BadRequest());
            }

            registration.RegistrationId = id;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            registration.Tags.Add("rider:" + deviceUpdate.riderName);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Ok(registration));
        }
        // 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());
        }
        // 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);
        }
Example #20
0
        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 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);
            }
        }
Example #22
0
        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<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);
        }
        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)));
        }
Example #26
0
        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);
        }
Example #27
0
        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));
        }