public bool SendNotification(string url, byte[] message, PushNotificationType target,
                                     PushNotificationPriority priority = PushNotificationPriority.Regular)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = WebRequestMethods.Http.Post;

            request.ContentType   = "text/xml";
            request.ContentLength = message.Length;

            request.Headers["X-MessageID"]         = Guid.NewGuid().ToString();
            request.Headers["X-NotificationClass"] = GetClassNumber(target, priority);

            if (target != PushNotificationType.Raw)
            {
                request.Headers["X-WindowsPhone-Target"] = target == PushNotificationType.Toast ? "toast" : "token";
            }

            using (var requestStream = request.GetRequestStream())
                requestStream.Write(message, 0, message.Length);

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var notificationStatus     = response.Headers["X-NotificationStatus"];
                var subscriptionStatus     = response.Headers["X-SubscriptionStatus"];
                var deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

                Debug.WriteLine(string.Format("Device Connection Status: {0}", deviceConnectionStatus));
                Debug.WriteLine(string.Format("Notification Status: {0}", notificationStatus));
                Debug.WriteLine(string.Format("Subscription Status: {0}", subscriptionStatus));

                return(subscriptionStatus != null && subscriptionStatus.ToLower() == "active");
            }
        }
Ejemplo n.º 2
0
        public bool SendPushToDriver(int userId, int driverId, Notification notf, PushNotificationType type, string key)
        {
            List <UserDevice> userdevices = _dbContext.UserDevices.Where(x1 => x1.Platform == false & x1.IsActive == true && x1.Driver_Id == driverId).ToList();

            Global.objPushNotifications.SendIOSPushNotification(userdevices, OtherNotification: notf, key: key, Type: (int)type);

            _dbContext.Notifications.Add(notf);
            _dbContext.SaveChanges();
            return(true);
        }
Ejemplo n.º 3
0
        public void Send(int userId, PushNotificationType pushNotificationType, object data)
        {
            var connections = OnlineUsers.GetUserConnections(userId);

            if (connections == null)
            {
                return;
            }
            connections.ForEach(connectionId => {
                _context.Clients.Client(connectionId).PushNotification(pushNotificationType, data);
            });
        }
 private PushNotification(
     PushNotificationType type,
     IEnumerable <string> fcmTokens = null,
     string topic = null,
     string title = null,
     string body  = null)
 {
     Type      = type;
     FcmTokens = fcmTokens;
     Topic     = topic;
     Title     = title;
     Body      = body;
 }
Ejemplo n.º 5
0
        public HttpStatusCode SendNotification(string uri, string xml, PushNotificationType type)
        {
            if (_accessToken == null)
            {
                GetAccessToken();
            }

            try
            {
                var contentInBytes = Encoding.UTF8.GetBytes(xml);

                var request = (HttpWebRequest)HttpWebRequest.Create(uri);
                request.ContentType = "text/xml";
                request.Method      = "POST";

                var typeString = "";
                switch (type)
                {
                case PushNotificationType.Tile: typeString = "wns/tile"; break;

                case PushNotificationType.Badge: typeString = "wns/badge"; break;

                case PushNotificationType.Toast: typeString = "wns/toast"; break;

                default: throw new NotImplementedException();
                }

                request.Headers.Add("X-WNS-Type", typeString);
                request.Headers.Add("Authorization", String.Format("Bearer {0}", _accessToken));

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(contentInBytes, 0, contentInBytes.Length);
                requestStream.Close();

                var webResponse = (HttpWebResponse)request.GetResponse();
                return(webResponse.StatusCode);
            }
            catch (WebException webException)
            {
                var exceptionDetails = webException.Response.Headers["WWW-Authenticate"];
                if (exceptionDetails != null && exceptionDetails.Contains("Token expired"))
                {
                    GetAccessToken();
                    return(SendNotification(uri, xml, type));
                }
                throw;
            }
        }
        public List <string> GetUserTokensSubscribedToProtocol(int?protocolId, PushNotificationType notificationTypeId)
        {
            return(CacheHelper.GetOrLoad($"Subscription-{protocolId},{notificationTypeId}",
                                         () =>
            {
                using (
                    var conn = new SqlConnection
                {
                    ConnectionString = ConfigurationManager.AppSettings["ConnectionString"]
                })
                {
                    conn.Open();
                    var cmd =
                        new SqlCommand(@"SELECT TK.Token FROM tblNotificationUserProtocolSubscription PS WITH(NOLOCK) 
                                           JOIN tblNotificationTypeUserSubscription TS WITH(NOLOCK) ON PS.UserID = TS.UserID AND TS.NotificationTypeID = @NotificationTypeID
                                           JOIN tblNotificationToken TK WITH(NOLOCK) ON TS.UserID = TK.UserID
                                           WHERE PS.ProtocolID = @ProtocolID AND Area = @Area", conn);

                    string area;
                    switch (notificationTypeId)
                    {
                    case PushNotificationType.ExpiringInventory:
                        area = "Inventory";
                        break;

                    case PushNotificationType.ShipmentStatusChanged:
                        area = "Shipments";
                        break;

                    default:
                        throw new NotImplementedException($"Unable to get users subscribed to {notificationTypeId}.");
                    }

                    cmd.Parameters.Add(new SqlParameter("@ProtocolID", protocolId));
                    cmd.Parameters.Add(new SqlParameter("@NotificationTypeID", (int)notificationTypeId));
                    cmd.Parameters.Add(new SqlParameter("@Area", area));
                    var rdr = cmd.ExecuteReader();
                    var tokens = new List <string>();
                    while (rdr.Read())
                    {
                        tokens.Add(rdr["Token"].ToString());
                    }
                    return tokens;
                }
            }, 10));
        }
        public NotificationService GetServiceInstance(PushNotificationType pushNotificationType)
        {
            switch (pushNotificationType)
            {
            case PushNotificationType.Apns:
                return(new ApnsService());

            case PushNotificationType.Gcm:
                return(new GcmService());

            case PushNotificationType.WinPush:
                return(new WnsService());

            case PushNotificationType.Pushy:
                return(new ApnsService());
            }
            throw new NullReferenceException();
        }
		public HttpStatusCode SendNotification(string uri, string xml, PushNotificationType type)
		{
			if (accessToken == null)
				GetAccessToken();

			try
			{
				var contentInBytes = Encoding.UTF8.GetBytes(xml);

				var request = (HttpWebRequest)HttpWebRequest.Create(uri);
				request.ContentType = "text/xml";
				request.Method = "POST";

				var typeString = ""; 
				switch (type)
				{
					case PushNotificationType.Tile: typeString = "wns/tile"; break;
					case PushNotificationType.Badge: typeString = "wns/badge"; break;
					case PushNotificationType.Toast: typeString = "wns/toast"; break;
					default: throw new NotImplementedException();
				}

				request.Headers.Add("X-WNS-Type", typeString);
				request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));

				Stream requestStream = request.GetRequestStream();
				requestStream.Write(contentInBytes, 0, contentInBytes.Length);
				requestStream.Close();

				var webResponse = (HttpWebResponse)request.GetResponse();
				return webResponse.StatusCode;
			}
			catch (WebException webException)
			{
				var exceptionDetails = webException.Response.Headers["WWW-Authenticate"];
				if (exceptionDetails != null && exceptionDetails.Contains("Token expired"))
				{
					GetAccessToken();
					return SendNotification(uri, xml, type);
				}
				throw;
			}
		}
Ejemplo n.º 9
0
        public PushNotification(PushNotificationType notificationType, string certFilePath, string certPwd)
        {
            //Reference
            //https://msdn.microsoft.com/en-us/library/system.net.security.sslstream(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

            string _host = "";
            int    _port = 0;

            if (notificationType == PushNotificationType.Development)
            {
                _host = kSandboxPushHost;
                _port = kPushPort;
            }
            else
            {
                _host = kPushHost;
                _port = kPushPort;
            }

            TcpClient                 client      = new TcpClient(_host, _port);
            X509Certificate2          cert        = new X509Certificate2(certFilePath, certPwd);
            X509CertificateCollection certificate = new X509CertificateCollection();

            certificate.Add(cert);

            _sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ServerCertificateValidationCallback), null);
            try
            {
                /*
                 *  When the authentication process, also known as the SSL handshake, succeeds,
                 *  the identity of the server (and optionally, the client) is established and the SslStream can be used by the client and server
                 *  to exchange messages. Before sending or receiving information, the client and server should check the security services
                 *  and levels provided by the SslStream to determine whether the protocol, algorithms, and strengths selected meet their
                 *  requirements for integrity and confidentiality.
                 */
                _sslStream.AuthenticateAsClient(_host, certificate, SslProtocols.Default, false);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception Message: {0} ", e.Message);
                _sslStream.Close();
            }
        }
        private string GetClassNumber(PushNotificationType target, PushNotificationPriority priority = PushNotificationPriority.Regular)
        {
            if (target == PushNotificationType.Tile)
            {
                switch (priority)
                {
                case PushNotificationPriority.Realtime: return("1");

                case PushNotificationPriority.Priority: return("11");

                case PushNotificationPriority.Regular: return("21");
                }
            }
            else if (target == PushNotificationType.Toast)
            {
                switch (priority)
                {
                case PushNotificationPriority.Realtime: return("2");

                case PushNotificationPriority.Priority: return("12");

                case PushNotificationPriority.Regular: return("22");
                }
            }
            else if (target == PushNotificationType.Raw)
            {
                switch (priority)
                {
                case PushNotificationPriority.Realtime: return("3");

                case PushNotificationPriority.Priority: return("13");

                case PushNotificationPriority.Regular: return("23");
                }
            }
            throw new NotImplementedException();
        }
		public bool SendNotification(string url, string text, PushNotificationType target, 
			PushNotificationPriority priority = PushNotificationPriority.Regular)
		{
			return SendNotification(url, Encoding.UTF8.GetBytes(text), target, priority);
		}
Ejemplo n.º 12
0
        public IActionResult AssignRideToDriver(DriverRideAssigningModel model)
        {
            try
            {
                #region Validation
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                #endregion

                Trip ride = _bORide.GetTripById(model.Ride_Id);
                if (ride == null)
                {
                    return(Ok(new CustomResponse <Error> {
                        Message = Global.ResponseMessages.BadRequest, StatusCode = StatusCodes.Status400BadRequest, Result = new Error {
                            ErrorMessage = "Invalid Ride"
                        }
                    }));
                }

                if (ride.Status == TripStatus.AssignedToDriver)
                {
                    return(Ok(new CustomResponse <Error> {
                        Message = Global.ResponseMessages.BadRequest, StatusCode = StatusCodes.Status400BadRequest, Result = new Error {
                            ErrorMessage = "Ride has been assigned to another driver"
                        }
                    }));
                }

                ride.Driver_Id = Convert.ToInt32(User.GetClaimValue("Id"));
                ride.StartTime = DateTime.UtcNow;
                ride.Status    = TripStatus.AssignedToDriver;
                if (!_bORide.UpdateTrip(ride))
                {
                    return(Ok(new CustomResponse <Error> {
                        Message = Global.ResponseMessages.Conflict, StatusCode = StatusCodes.Status409Conflict, Result = new Error {
                            ErrorMessage = Global.ResponseMessages.GenerateInvalid("Failed to assign ride")
                        }
                    }));
                }

                Notification notification = new Notification
                {
                    Title     = "KORSA",
                    Text      = "Rider has accepted your ride.",
                    Entity_Id = ride.Driver_Id,
                    Type      = (int)PushNotificationType.RideAssignedToRider,
                    User_Id   = ride.PrimaryUser_Id.Value
                };
                PushNotificationType type = PushNotificationType.RideAssignedToRider;
                _bORide.SendPushToUser(ride.PrimaryUser_Id.Value, ride.Driver_Id.Value, notification, type, key: AppSettingsProvider.FCMServerKeyUserApp);//Sends Push To Ride User
                TripDTO tripDTO = Mapper.Map <Trip, TripDTO>(ride);
                return(Ok(new CustomResponse <TripDTO> {
                    Message = Global.ResponseMessages.Success, StatusCode = StatusCodes.Status200OK, Result = tripDTO
                }));
            }
            catch (Exception ex)
            {
                return(StatusCode(Error.LogError(ex)));
            }
        }
 public bool SendNotification(string url, string text, PushNotificationType target,
                              PushNotificationPriority priority = PushNotificationPriority.Regular)
 {
     return(SendNotification(url, Encoding.UTF8.GetBytes(text), target, priority));
 }
		private static string GetClassNumber(PushNotificationType target, PushNotificationPriority priority = PushNotificationPriority.Regular)
		{
			if (target == PushNotificationType.Tile)
			{
				switch (priority)
				{
					case PushNotificationPriority.Realtime: return "1";
					case PushNotificationPriority.Priority: return "11";
					case PushNotificationPriority.Regular: return "21";
				}
			}
			else if (target == PushNotificationType.Toast)
			{
				switch (priority)
				{
					case PushNotificationPriority.Realtime: return "2";
					case PushNotificationPriority.Priority: return "12";
					case PushNotificationPriority.Regular: return "22";
				}
			}
			else if (target == PushNotificationType.Raw)
			{
				switch (priority)
				{
					case PushNotificationPriority.Realtime: return "3";
					case PushNotificationPriority.Priority: return "13";
					case PushNotificationPriority.Regular: return "23";
				}
			}
			throw new NotImplementedException();
		}
		public static void SendNotification(string url, string xml, PushNotificationType target, PushNotificationPriority priority = PushNotificationPriority.Regular)
		{
			var message = new UTF8Encoding().GetBytes(xml);

			var request = (HttpWebRequest)WebRequest.Create(url);
			request.Method = WebRequestMethods.Http.Post;

			request.ContentType = "text/xml";
			request.ContentLength = message.Length;

			request.Headers["X-MessageID"] = Guid.NewGuid().ToString();
			request.Headers["X-NotificationClass"] = GetClassNumber(target, priority);

			if (target != PushNotificationType.Raw)
				request.Headers["X-WindowsPhone-Target"] = target == PushNotificationType.Toast ? "toast" : "token";

			using (var requestStream = request.GetRequestStream())
				requestStream.Write(message, 0, message.Length);

			using (var response = (HttpWebResponse)request.GetResponse())
			{
				var notificationStatus = response.Headers["X-NotificationStatus"];
				var subscriptionStatus = response.Headers["X-SubscriptionStatus"];
				var deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

				Debug.WriteLine(string.Format("Device Connection Status: {0}", deviceConnectionStatus));
				Debug.WriteLine(string.Format("Notification Status: {0}", notificationStatus));
				Debug.WriteLine(string.Format("Subscription Status: {0}", subscriptionStatus));
			}
		}
Ejemplo n.º 16
0
        /// <summary>
        /// Converts the enumeration value to the equivalent 'X-WindowsPhone-Target' http header value required by the MPNS.
        /// </summary>
        /// <param name="pushNotificationType">The enumeration value to be converted.</param>
        /// <returns>The converted 'X-WindowsPhone-Target' value'.</returns>
        public static string ToWindowsPhoneTarget(this PushNotificationType pushNotificationType)
        {
            var result = Extensions.windowsPhoneTargetHeaderDictionary[pushNotificationType];

            return(result);
        }
 public PushNotification(string message, PushNotificationType type = PushNotificationType.Info)
 {
     Message = message;
     Type    = type;
 }
Ejemplo n.º 18
0
 public PushNotificationProperties(DeviceType deviceType, PushNotificationType pushNotificationType, string body = "")
 {
     DeviceType           = deviceType;
     PushNotificationType = pushNotificationType;
     Body = body;
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Converts the enumeration value of <see cref="MessagePriority"/> to the equivalent 'X-NotificationClass' http header value required by the MPNS based on the type of push notification.
        /// </summary>
        /// <param name="messagePriority">The priority of the message.</param>
        /// <param name="pushNotificationType">The type of push notification.</param>
        /// <returns>The converted 'X-NotificationClass' value'.</returns>
        public static string ToNotificationClass(this MessagePriority messagePriority, PushNotificationType pushNotificationType)
        {
            var result = Extensions.notificationClassHeaderDictionary[pushNotificationType][messagePriority];

            return(result);
        }