public HttpResponseMessage Post([FromBody] BaseRequest request)
 {
     if (!ModelState.IsValid)
     {
         return(Request.CreateResponse(HttpStatusCode.BadRequest));
     }
     try
     {
         var groupDetails = NeeoGroup.GetUserGroupsDetails(new NeeoUser(request.Uid.Trim()));
         if (groupDetails.Count > 0)
         {
             return(Request.CreateResponse(HttpStatusCode.OK, groupDetails));
         }
         return(Request.CreateResponse(HttpStatusCode.NoContent));
     }
     catch (ApplicationException applicationException)
     {
         return(Request.CreateErrorResponse((HttpStatusCode)Convert.ToInt16(applicationException.Message), NeeoDictionaries.HttpStatusCodeDescriptionMapper[Convert.ToInt16(applicationException.Message)]));
     }
     catch (Exception exception)
     {
         Logger.LogManager.CurrentInstance.ErrorLogger.LogError(System.Reflection.MethodBase.GetCurrentMethod().GetType(), exception.Message, exception);
         return(Request.CreateResponse(HttpStatusCode.InternalServerError));
     }
 }
        private void SendGroupImNotification(NotificationModel notificationModel)
        {
            if (NeeoUtility.IsNullOrEmpty(notificationModel.SenderID) || notificationModel.RID == 0 ||
                NeeoUtility.IsNullOrEmpty(notificationModel.RName) || NeeoUtility.IsNullOrEmpty(notificationModel.Alert) ||
                notificationModel.MessageType == null)
            {
                throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
            }

            List <NeeoUser> lstgroupParticipant = NeeoGroup.GetGroupParticipants(notificationModel.RID,
                                                                                 notificationModel.SenderID, (int)notificationModel.MessageType);

            if (lstgroupParticipant.Count == 0)
            {
                return;
            }

            var taskUpdateOfflineCount = Task.Factory.StartNew(() =>
            {
                const string delimeter = ",";
                LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Group participants - " + JsonConvert.SerializeObject(lstgroupParticipant), System.Reflection.MethodBase.GetCurrentMethod().Name);
                IEnumerable <string> userList = from item in lstgroupParticipant
                                                where item.PresenceStatus == Presence.Offline
                                                select item.UserID;
                string userString = string.Join(delimeter, userList);

                //lstgroupParticipant.Where(i => i.PresenceStatus == Presence.Offline).Select(a => a.UserID)
                //    .Aggregate((current, next) => current + delimeter + next);

                LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "User list - " + userString, System.Reflection.MethodBase.GetCurrentMethod().Name);
                if (NeeoUtility.IsNullOrEmpty(userString))
                {
                    return;
                }
                var dbManager = new DbManager();
                dbManager.UpdateUserOfflineCount(userString, delimeter);
            });

            var taskSendiOSNotification = Task.Factory.StartNew(() =>
            {
                var iosUserList =
                    lstgroupParticipant.Where(
                        x =>
                        x.DevicePlatform == DevicePlatform.iOS && x.PresenceStatus == Presence.Offline).ToList();

                _services.ApnsService.Send(iosUserList, notificationModel);
            });

            var taskSendAndroidNotification = Task.Factory.StartNew(() =>
            {
                var androidUserList =
                    lstgroupParticipant.Where(
                        x =>
                        x.DevicePlatform == DevicePlatform.Android && x.PresenceStatus == Presence.Offline).ToList();

                _services.GcmService.Send(androidUserList, notificationModel);
            });

            Task.WaitAll(taskUpdateOfflineCount, taskSendiOSNotification, taskSendAndroidNotification);
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="uID"></param>
        /// <param name="gID"></param>
        public void DeleteGroupIcon(string uID, string gID)
        {
            #region log user request and response

            /***********************************************
            *  To log user request
            ***********************************************/
            if (_logRequestResponse)
            {
                LogManager.CurrentInstance.InfoLogger.LogInfo(
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name + "===>" +
                    "Request ===> senderID : " + uID + ", groupID : " + gID);
            }

            #endregion

            //#region Verify User
            //var request = OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            //string keyFromClient = request.Headers["key"];
            //if (NeeoUtility.AuthenticateUserRequest(uID, keyFromClient))
            //{
            //    #endregion

            ulong temp = 0;

            if (NeeoUtility.IsNullOrEmpty(uID) || !ulong.TryParse(uID, out temp) ||
                NeeoUtility.IsNullOrEmpty(gID))
            {
                NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.InvalidArguments);
            }
            else
            {
                uID = uID.Trim();
                gID = gID.ToLower();
                try
                {
                    NeeoGroup.DeleteGroupIcon(groupID: gID, userID: uID);
                }
                catch (Exception exception)
                {
                    LogManager.CurrentInstance.ErrorLogger.LogError(
                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
                        System.Reflection.MethodBase.GetCurrentMethod().Name, exception);
                    NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.ServerInternalError);
                }
            }
            //}
            //else
            //{
            //    NeeoUtility.SetServiceResponseHeaders((CustomHttpStatusCode) HttpStatusCode.Unauthorized);

            //}
        }
Example #4
0
        private LibNeeo.IO.File GetRequestedFile(FileRequest fileRequest)
        {
            switch (fileRequest.FileCategory)
            {
            case FileCategory.Shared:
                return(SharedMedia.GetMedia(fileRequest.Name, fileRequest.MediaType));

            case FileCategory.Group:
                return(NeeoGroup.GetGroupIcon(fileRequest.Name));

            default:
                return(null);
            }
        }
Example #5
0
        public HttpResponseMessage Post([FromBody] UploadGroupIconRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
            LogRequest(request);
            ulong temp = 0;

            request.Uid = request.Uid.Trim();
            request.gID = request.gID.ToLower();
            try
            {
                var file = new LibNeeo.IO.File()
                {
                    Info = new NeeoFileInfo()
                    {
                        Creator   = request.Uid,
                        MimeType  = MimeType.ImageJpeg,
                        MediaType = MediaType.Image
                    },
                    Data = request.data,
                };
                if (NeeoGroup.SaveGroupIcon(request.Uid, request.gID.ToLower(), file))
                {
                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.InternalServerError));
                }
            }
            catch (ApplicationException appExp)
            {
                return(SetCustomResponseMessage("", (HttpStatusCode)(CustomHttpStatusCode)(Convert.ToInt32(appExp.Message))));
            }
            catch (Exception exception)
            {
                LogManager.CurrentInstance.ErrorLogger.LogError(
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name, exception);
                return(SetCustomResponseMessage("", (HttpStatusCode)CustomHttpStatusCode.ServerInternalError));
            }
        }
Example #6
0
        public HttpResponseMessage Delete(string uId, string gID)
        {
            #region log user request and response

            /***********************************************
            *  To log user request
            ***********************************************/
            if (_logRequestResponse)
            {
                LogManager.CurrentInstance.InfoLogger.LogInfo(
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name + "===>" +
                    "Request ===> senderID : " + uId + ", groupID : " + gID);
            }

            #endregion

            ulong temp = 0;

            if (NeeoUtility.IsNullOrEmpty(uId) || !ulong.TryParse(uId, out temp) ||
                NeeoUtility.IsNullOrEmpty(gID))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
            else
            {
                uId = uId.Trim();
                gID = gID.ToLower();
                try
                {
                    NeeoGroup.DeleteGroupIcon(groupID: gID, userID: uId);
                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                catch (Exception exception)
                {
                    LogManager.CurrentInstance.ErrorLogger.LogError(
                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
                        System.Reflection.MethodBase.GetCurrentMethod().Name, exception);

                    return(Request.CreateResponse(HttpStatusCode.InternalServerError));
                }
            }
        }
Example #7
0
        private LibNeeo.IO.File GetRequestedFile(string fileID, FileCategory fileCategory, MediaType mediaType)
        {
            string filePath = null;

            switch (fileCategory)
            {
            case FileCategory.Shared:
                return(SharedMedia.GetMedia(fileID, mediaType));

                break;

            case FileCategory.Group:
                return(NeeoGroup.GetGroupIcon(fileID));

                break;

            default:
                return(null);
            }
        }
Example #8
0
        public HttpResponseMessage Get([FromUri] GetGroupIconRequest request)
        {
            LogRequest(request);
            ulong temp = 0;

            if (NeeoUtility.IsNullOrEmpty(request.Uid) || !ulong.TryParse(request.Uid, out temp) ||
                NeeoUtility.IsNullOrEmpty(request.gID))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
            else
            {
                request.Uid = request.Uid.Trim();
                request.gID = request.gID.ToLower();
                try
                {
                    if (NeeoGroup.GroupIconExists(request.gID.ToLower()))
                    {
                        string url =
                            NeeoUrlBuilder.BuildFileUrl(ConfigurationManager.AppSettings[NeeoConstants.FileServerUrl], request.gID,
                                                        FileCategory.Group, MediaType.Image);
                        return(RedirectServiceToUrl(url));
                    }
                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotFound));
                    }
                }
                catch (Exception exception)
                {
                    LogManager.CurrentInstance.ErrorLogger.LogError(
                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name, exception);
                    return(Request.CreateResponse(HttpStatusCode.InternalServerError));
                }
            }
        }
Example #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="uID"></param>
        /// <param name="gID"></param>
        /// <param name="reqType"></param>
        public void GetGroupIcon(string uID, string gID, string reqType = "GET")
        {
            #region log user request and response

            /***********************************************
            *  To log user request
            ***********************************************/
            if (_logRequestResponse)
            {
                LogManager.CurrentInstance.InfoLogger.LogInfo(
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name + "===>" +
                    "Request ===> senderID : " + uID + ", groupID : " + gID);
            }

            #endregion

            //      #region Verify User
            //var request = OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            //string keyFromClient = request.Headers["key"];
            //if (NeeoUtility.AuthenticateUserRequest(uID, keyFromClient))
            //{
            //    #endregion
            ulong temp = 0;

            if (NeeoUtility.IsNullOrEmpty(uID) || !ulong.TryParse(uID, out temp) ||
                NeeoUtility.IsNullOrEmpty(gID))
            {
                NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.InvalidArguments);
            }
            else
            {
                uID = uID.Trim();
                gID = gID.ToLower();
                try
                {
                    if (!NeeoGroup.GroupIconExists(gID))
                    {
                        NeeoUtility.SetServiceResponseHeaders((CustomHttpStatusCode)HttpStatusCode.NotFound);
                    }
                    else
                    {
                        string url =
                            NeeoUrlBuilder.BuildFileUrl(ConfigurationManager.AppSettings[NeeoConstants.FileServerUrl], gID,
                                                        FileCategory.Group, MediaType.Image);
                        RedirectServiceToUrl(url);
                    }
                }
                catch (Exception exception)
                {
                    LogManager.CurrentInstance.ErrorLogger.LogError(
                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name, exception);
                    NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.ServerInternalError);
                }
            }
            //}
            //else
            //{
            //    NeeoUtility.SetServiceResponseHeaders((CustomHttpStatusCode)HttpStatusCode.Unauthorized);

            //}
        }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="uID"></param>
        /// <param name="data"></param>
        /// <param name="gID"></param>
        public void UploadGroupIcon(string uID, string data, string gID)
        {
            ulong temp = 0;

            uID = (uID != null) ? uID.Trim() : uID;

            #region log user request and response

            /***********************************************
            *  To log user request
            ***********************************************/
            if (_logRequestResponse)
            {
                LogManager.CurrentInstance.InfoLogger.LogInfo(
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name + "===>" +
                    "Request ===> senderID : " + uID + ", groupID : " + gID);
            }

            #endregion
            // #region Verify User
            //var request = OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            //string keyFromClient = request.Headers["key"];
            //if (NeeoUtility.AuthenticateUserRequest(uID, keyFromClient))
            //{
            //    #endregion


            if (NeeoUtility.IsNullOrEmpty(uID) || !ulong.TryParse(uID, out temp) ||
                NeeoUtility.IsNullOrEmpty(data) ||
                NeeoUtility.IsNullOrEmpty(gID))
            {
                NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.InvalidArguments);
            }
            else
            {
                gID = gID.ToLower();
                try
                {
                    var file = new LibNeeo.IO.File()
                    {
                        Info = new NeeoFileInfo()
                        {
                            Creator   = uID,
                            MimeType  = MimeType.ImageJpeg,
                            MediaType = MediaType.Image
                        },
                        Data = data,
                    };
                    if (!NeeoGroup.SaveGroupIcon(uID, gID.ToLower(), file))
                    {
                        NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.ServerInternalError);
                    }
                }
                catch (ApplicationException appExp)
                {
                    NeeoUtility.SetServiceResponseHeaders((CustomHttpStatusCode)(Convert.ToInt32(appExp.Message)));
                }
                catch (Exception exception)
                {
                    LogManager.CurrentInstance.ErrorLogger.LogError(
                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, System.Reflection.MethodBase.GetCurrentMethod().Name, exception);
                    NeeoUtility.SetServiceResponseHeaders(CustomHttpStatusCode.ServerInternalError);
                }
            }
            //}
            //else
            //{
            //    NeeoUtility.SetServiceResponseHeaders((CustomHttpStatusCode) HttpStatusCode.Unauthorized);

            //}
        }
        /// <summary>
        /// Sends notifications to the specified device token and device platform .
        /// </summary>
        /// <param name="notification">An enum specifying the notification type.</param>
        public void SendNotification(Models.Notification notification)
        {
            int            badgeCount = 0;
            ulong          tempNumber;
            const string   delimeter = ",";
            DevicePlatform devicePlatform;
            string         deviceToken = null;

            switch (notification.NType)
            {
            case NotificationType.Im:
                #region IM notfication

                if (_notificationMsgLength == 0)
                {
                    _notificationMsgLength = Convert.ToUInt16(ConfigurationManager.AppSettings[NotificationConstants.NotificationMsgLength]);
                }
                if (!NeeoUtility.IsNullOrEmpty(notification.DToken) && notification.Dp != null && notification.IMTone != null &&
                    !NeeoUtility.IsNullOrEmpty(notification.Alert) && !NeeoUtility.IsNullOrEmpty(notification.SenderID) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber) &&
                    notification.Badge != 0)
                {
                    NeeoUser receiver = new NeeoUser(notification.ReceiverID)
                    {
                        DeviceToken     = notification.DToken.Trim(),
                        ImTone          = notification.IMTone.GetValueOrDefault(),
                        OfflineMsgCount = notification.Badge,
                        DevicePlatform  = notification.Dp.GetValueOrDefault(),
                        PnSource        = notification.PnSource.HasValue ? notification.PnSource.Value : PushNotificationSource.Default
                    };

                    if (notification.Alert.Length > _notificationMsgLength)
                    {
                        notification.Alert = notification.Alert.Substring(0, _notificationMsgLength) + "...";
                    }

                    if (receiver.DevicePlatform == DevicePlatform.iOS)
                    {
                        _push.QueueNotification(new AppleNotification(receiver.DeviceToken)
                                                .WithAlert(notification.Alert)
                                                .WithBadge(receiver.OfflineMsgCount)
                                                .WithSound(receiver.ImTone.GetDescription())
                                                .WithCustomItem(NotificationConstants.NotificationID, NotificationType.Im.ToString("D"))
                                                .WithCustomItem(NotificationConstants.SenderID, notification.SenderID));
                    }
                    else if (receiver.DevicePlatform == DevicePlatform.Android)
                    {
                        Dictionary <string, string> payload = new Dictionary <string, string>()
                        {
                            { "alert", notification.Alert },
                            { NotificationConstants.NotificationID, NotificationType.Im.ToString("D") },
                            { NotificationConstants.SenderID, notification.SenderID }
                        };
                        switch (receiver.PnSource)
                        {
                        case PushNotificationSource.Default:
                            _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiver.DeviceToken)
                                                    .WithJson(JsonConvert.SerializeObject(payload)));
                            break;

                        case PushNotificationSource.Pushy:
                            var pushyRequest = new PushyPushRequest(payload, new string[] { receiver.DeviceToken });
                            PushyClient.SendPush(pushyRequest);
                            break;
                        }
                    }
                    else if (receiver.DevicePlatform == DevicePlatform.WindowsMobile)
                    {
                        var    alertParts           = notification.Alert.Split(new[] { ':' }, 2);
                        string notificationMeta     = string.Format("/NeeoPivot.xaml?PhoneNumber={0}&PushNotificationType={1}", notification.SenderID, NotificationType.Im.ToString("D"));
                        var    winToastNotification = new WindowsToastNotification()
                                                      .WithLaunch(notificationMeta)
                                                      .AsToastText02(alertParts[0].Trim(), alertParts[1].Trim())
                                                      .ForChannelUri(receiver.DeviceToken);
                        var customAudio = new CustomToastAudio()
                        {
                            CustomSource = "ms-appx:///Assets/Sounds/beep.wav"
                        };
                        winToastNotification.Audio = customAudio;
                        _push.QueueNotification(winToastNotification);
                        _push.QueueNotification(new WindowsBadgeNumericNotification().WithBadgeNumber(receiver.OfflineMsgCount).ForChannelUri(receiver.DeviceToken));
                    }
                    else
                    {
                        //do nothing
                    }
                }
                else
                {
                    throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                }
                break;
                #endregion

            case NotificationType.Call:
                #region Incoming sip call notification

                if (_incomingCallingMsgText == null)
                {
                    _incomingCallingMsgText = ConfigurationManager.AppSettings[NotificationConstants.IncomingCallingMsgText];
                }

                if (!NeeoUtility.IsNullOrEmpty(notification.CallerID) && ulong.TryParse(notification.CallerID, out tempNumber) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber))
                {
                    // Get the name of the user from data base.
                    DbManager dbManager = new DbManager();
                    var       userInfo  = dbManager.GetUserInforForNotification(notification.ReceiverID, notification.CallerID, false);
                    NeeoUser  receiver  = new NeeoUser(notification.ReceiverID)
                    {
                        CallingTone    = (CallingTone)Convert.ToInt16(userInfo[NeeoConstants.ReceiverCallingTone]),
                        DevicePlatform = (DevicePlatform)Convert.ToInt16(userInfo[NeeoConstants.ReceiverUserDeviceplatform]),
                    };

                    if (!NeeoUtility.IsNullOrEmpty(userInfo[NeeoConstants.ReceiverDeviceToken]) && !NeeoUtility.IsNullOrEmpty(userInfo[NeeoConstants.CallerName]))
                    {
                        receiver.DeviceToken = userInfo[NeeoConstants.ReceiverDeviceToken].Trim();
                        receiver.PnSource    =
                            (PushNotificationSource)Convert.ToInt32(userInfo[NeeoConstants.PushNotificationSource]);
                    }
                    else
                    {
                        throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                    }

                    if (receiver.DevicePlatform == DevicePlatform.iOS)
                    {
                        if (_actionKeyText == null)
                        {
                            _actionKeyText = ConfigurationManager.AppSettings[NotificationConstants.ActionKeyText];
                        }
                        if (_iosIncomingCallingTone == null)
                        {
                            _iosIncomingCallingTone =
                                ConfigurationManager.AppSettings[NotificationConstants.IosIncomingCallingTone];
                        }

                        _push.QueueNotification(new AppleNotification(receiver.DeviceToken)
                                                .WithAlert(_incomingCallingMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName]), "", _actionKeyText, new List <object>()
                        {
                        })
                                                .WithSound(receiver.CallingTone.GetDescription())
                                                .WithCustomItem(NotificationConstants.NotificationID, NotificationType.Call.ToString("D"))
                                                .WithCustomItem(NotificationConstants.Timestamp, DateTime.UtcNow.ToString(NeeoConstants.TimestampFormat)));
                    }
                    else if (receiver.DevicePlatform == DevicePlatform.Android)
                    {
                        Dictionary <string, string> payload = new Dictionary <string, string>()
                        {
                            { "alert", _incomingCallingMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName]) },
                            { NotificationConstants.NotificationID, NotificationType.Call.ToString("D") },
                            { NotificationConstants.Timestamp, DateTime.UtcNow.ToString(NeeoConstants.TimestampFormat) },
                            { NotificationConstants.CallerID, notification.CallerID }
                        };
                        switch (receiver.PnSource)
                        {
                        case PushNotificationSource.Default:
                            _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiver.DeviceToken)
                                                    .WithJson(JsonConvert.SerializeObject(payload)));
                            break;

                        case PushNotificationSource.Pushy:
                            var pushyRequest = new PushyPushRequest(payload, new string[] { receiver.DeviceToken });
                            PushyClient.SendPush(pushyRequest);
                            break;
                        }
                    }
                    else
                    {
                        // do nothing
                    }
                }
                else
                {
                    throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                }
                break;
                #endregion

            case NotificationType.Mcr:
                #region Mcr notification

                if (_mcrMsgText == null)
                {
                    _mcrMsgText = ConfigurationManager.AppSettings[NotificationConstants.McrMsgText];
                }

                if (!NeeoUtility.IsNullOrEmpty(notification.CallerID) && ulong.TryParse(notification.CallerID, out tempNumber) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber) && notification.McrCount != 0)
                {
                    DbManager dbManager = new DbManager();
                    var       userInfo  = dbManager.GetUserInforForNotification(notification.ReceiverID, notification.CallerID, true, notification.McrCount);

                    NeeoUser receiver = new NeeoUser(notification.ReceiverID)
                    {
                        DevicePlatform = (DevicePlatform)Convert.ToInt16(userInfo[NeeoConstants.ReceiverUserDeviceplatform]),
                    };

                    if (!NeeoUtility.IsNullOrEmpty(userInfo[NeeoConstants.ReceiverDeviceToken]))
                    {
                        receiver.DeviceToken = userInfo[NeeoConstants.ReceiverDeviceToken].Trim();
                        receiver.PnSource    =
                            (PushNotificationSource)Convert.ToInt32(userInfo[NeeoConstants.PushNotificationSource]);
                    }
                    else
                    {
                        throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                    }
                    badgeCount = Convert.ToInt32(userInfo[NeeoConstants.OfflineMessageCount]);
                    if (receiver.DevicePlatform == DevicePlatform.iOS)
                    {
                        if (_iosApplicationMcrTone == null)
                        {
                            _iosApplicationMcrTone =
                                ConfigurationManager.AppSettings[NotificationConstants.IosApplicationMcrTone];
                        }
                        _push.QueueNotification(new AppleNotification(receiver.DeviceToken)
                                                .WithAlert(_mcrMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName]))
                                                .WithBadge(badgeCount)
                                                .WithSound(_iosApplicationMcrTone)
                                                .WithCustomItem(NotificationConstants.NotificationID, NotificationType.Mcr.ToString("D"))
                                                .WithCustomItem(NotificationConstants.CallerID, notification.CallerID));
                    }
                    else if (receiver.DevicePlatform == DevicePlatform.Android)
                    {
                        Dictionary <string, string> payload = new Dictionary <string, string>()
                        {
                            { "alert", _mcrMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName]) },
                            { NotificationConstants.NotificationID, NotificationType.Mcr.ToString("D") },
                            { NotificationConstants.CallerID, notification.CallerID }
                        };
                        switch (receiver.PnSource)
                        {
                        case PushNotificationSource.Default:
                            _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiver.DeviceToken)
                                                    .WithJson(JsonConvert.SerializeObject(payload)));
                            break;

                        case PushNotificationSource.Pushy:
                            var pushyRequest = new PushyPushRequest(payload, new string[] { receiver.DeviceToken });
                            PushyClient.SendPush(pushyRequest);
                            break;
                        }
                    }
                    else
                    {
                        //do nothing
                    }
                }
                else
                {
                    throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                }
                break;
                #endregion

            case NotificationType.GroupIm:
                #region Group notification
                if (!NeeoUtility.IsNullOrEmpty(notification.SenderID) && notification.RID != 0 && !NeeoUtility.IsNullOrEmpty(notification.RName) && !NeeoUtility.IsNullOrEmpty(notification.Alert) && notification.MessageType != null)
                {
                    List <NeeoUser> lstgroupParticipant = NeeoGroup.GetGroupParticipants(notification.RID,
                                                                                         notification.SenderID, (int)notification.MessageType);
                    if (lstgroupParticipant.Count > 0)
                    {
                        var taskUpdateOfflineCount = Task.Factory.StartNew(() =>
                        {
                            LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Group participants - " + JsonConvert.SerializeObject(lstgroupParticipant), System.Reflection.MethodBase.GetCurrentMethod().Name);
                            IEnumerable <string> userList = from item in lstgroupParticipant
                                                            where item.PresenceStatus == Presence.Offline
                                                            select item.UserID;
                            string userString = string.Join(delimeter, userList);

                            //lstgroupParticipant.Where(i => i.PresenceStatus == Presence.Offline).Select(a => a.UserID)
                            //    .Aggregate((current, next) => current + delimeter + next);

                            LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "User list - " + userString, System.Reflection.MethodBase.GetCurrentMethod().Name);
                            if (!NeeoUtility.IsNullOrEmpty(userString))
                            {
                                DbManager dbManager = new DbManager();
                                dbManager.UpdateUserOfflineCount(userString, delimeter);
                            }
                        });
                        var taskScheduleNotifications = Task.Factory.StartNew(() =>
                        {
                            Parallel.ForEach(lstgroupParticipant, item =>
                                             //foreach (var item in lstgroupParticipant)
                            {
                                if (!NeeoUtility.IsNullOrEmpty(item.DeviceToken) && item.DeviceToken != "-1" &&
                                    item.PresenceStatus == Presence.Offline)
                                {
                                    if (item.DevicePlatform == DevicePlatform.iOS)
                                    {
                                        _push.QueueNotification(new AppleNotification(
                                                                    item.DeviceToken.Trim())
                                                                .WithAlert(notification.Alert)
                                                                .WithBadge(item.OfflineMsgCount + 1)
                                                                .WithSound(item.ImTone.GetDescription())
                                                                .WithCustomItem(NotificationConstants.NotificationID,
                                                                                NotificationType.GroupIm.ToString("D"))
                                                                .WithCustomItem(NotificationConstants.RoomID, notification.RName));
                                    }
                                    else if (item.DevicePlatform == DevicePlatform.Android)
                                    {
                                        Dictionary <string, string> payload = new Dictionary <string, string>()
                                        {
                                            { "alert", notification.Alert },
                                            { NotificationConstants.NotificationID, NotificationType.GroupIm.ToString("D") },
                                            { NotificationConstants.RoomID, notification.RName }
                                        };
                                        switch (item.PnSource)
                                        {
                                        case PushNotificationSource.Default:
                                            _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(item.DeviceToken)
                                                                    .WithJson(JsonConvert.SerializeObject(payload)));
                                            break;

                                        case PushNotificationSource.Pushy:
                                            var pushyRequest = new PushyPushRequest(payload, new string[] { item.DeviceToken });
                                            PushyClient.SendPush(pushyRequest);
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        //do nothing
                                    }
                                }
                            });
                        });
                        taskUpdateOfflineCount.Wait();
                        taskScheduleNotifications.Wait();
                    }
                }
                else
                {
                    throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                }
                break;
                #endregion

            case NotificationType.GroupInvite:
                #region Group invitation notification

                if (!NeeoUtility.IsNullOrEmpty(notification.DToken) && notification.Dp != null && notification.IMTone != null &&
                    !NeeoUtility.IsNullOrEmpty(notification.Alert) && !NeeoUtility.IsNullOrEmpty(notification.RName) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber))
                {
                    NeeoUser receiver = new NeeoUser(notification.ReceiverID)
                    {
                        DeviceToken     = notification.DToken.Trim(),
                        ImTone          = notification.IMTone.GetValueOrDefault(),
                        OfflineMsgCount = notification.Badge,
                        DevicePlatform  = notification.Dp.GetValueOrDefault(),
                        PnSource        = notification.PnSource.HasValue ? notification.PnSource.Value : PushNotificationSource.Default
                    };

                    if (receiver.DevicePlatform == DevicePlatform.iOS)
                    {
                        _push.QueueNotification(new AppleNotification(receiver.DeviceToken)
                                                .WithAlert(notification.Alert)
                                                .WithBadge(receiver.OfflineMsgCount)
                                                .WithSound(receiver.ImTone.GetDescription())
                                                .WithCustomItem(NotificationConstants.NotificationID,
                                                                NotificationType.GroupIm.ToString("D"))
                                                .WithCustomItem(NotificationConstants.RoomID, notification.RName));
                    }
                    else if (receiver.DevicePlatform == DevicePlatform.Android)
                    {
                        Dictionary <string, string> payload = new Dictionary <string, string>()
                        {
                            { "alert", notification.Alert },
                            { NotificationConstants.NotificationID, NotificationType.GroupIm.ToString("D") },
                            { NotificationConstants.RoomID, notification.RName }
                        };

                        switch (receiver.PnSource)
                        {
                        case PushNotificationSource.Default:
                            _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiver.DeviceToken)
                                                    .WithJson(JsonConvert.SerializeObject(payload)));
                            break;

                        case PushNotificationSource.Pushy:
                            var pushyRequest = new PushyPushRequest(payload, new string[] { receiver.DeviceToken });
                            PushyClient.SendPush(pushyRequest);
                            break;
                        }
                    }
                    else
                    {
                        //do nothing
                    }
                }
                else
                {
                    throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                }
                break;
                #endregion
            }
        }
        /// <summary>
        /// Sends notifications to the specified device token and device platform .
        /// </summary>
        /// <param name="notification">An enum specifying the notification type.</param>
        public void SendNotification(Notification notification)
        {
            int            badgeCount = 0;
            ulong          tempNumber;
            const string   delimeter = ",";
            DevicePlatform devicePlatform;
            string         deviceToken = null;

            switch (notification.NType)
            {
            case NotificationType.Im:
                #region IM notfication

                if (_notificationMsgLength == 0)
                {
                    _notificationMsgLength = Convert.ToUInt16(ConfigurationManager.AppSettings[NotificationConstants.NotificationMsgLength]);
                }
                if (!NeeoUtility.IsNullOrEmpty(notification.DToken) && notification.Dp != null && notification.IMTone != null &&
                    !NeeoUtility.IsNullOrEmpty(notification.Alert) && !NeeoUtility.IsNullOrEmpty(notification.SenderID) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber) &&
                    notification.Badge != 0)
                {
                    NeeoUser receiver = new NeeoUser(notification.ReceiverID)
                    {
                        DeviceToken     = notification.DToken,
                        ImTone          = notification.IMTone.GetValueOrDefault(),
                        OfflineMsgCount = notification.Badge,
                        DevicePlatform  = notification.Dp.GetValueOrDefault()
                    };

                    if (notification.Alert.Length > _notificationMsgLength)
                    {
                        notification.Alert = notification.Alert.Substring(0, _notificationMsgLength) + "...";
                    }

                    if (receiver.DevicePlatform == DevicePlatform.iOS)
                    {
                        _push.QueueNotification(new AppleNotification(receiver.DeviceToken)
                                                .WithAlert(notification.Alert)
                                                .WithBadge(receiver.OfflineMsgCount)
                                                .WithSound(receiver.ImTone.ToString("G").Replace('_', '.'))
                                                .WithCustomItem(NotificationConstants.NotificationID, NotificationType.Im.ToString("D"))
                                                .WithCustomItem(NotificationConstants.SenderID, notification.SenderID));
                    }
                    else if (receiver.DevicePlatform == DevicePlatform.Android)
                    {
                        //_push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiver.DeviceToken)
                        // .WithJson("{\"alert\":\"" + notification.Alert + "\"}"));
                    }
                    else
                    {
                        //do nothing
                    }
                }
                else
                {
                    throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                }
                break;
                #endregion

            case NotificationType.IncomingSipCall:
                #region Incoming sip call notification
                if (_incomingCallingMsgText == null)
                {
                    _incomingCallingMsgText = ConfigurationManager.AppSettings[NotificationConstants.IncomingCallingMsgText];
                }

                if (!NeeoUtility.IsNullOrEmpty(notification.CallerID) && ulong.TryParse(notification.CallerID, out tempNumber) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber))
                {
                    // Get the name of the user from data base.
                    DbManager dbManager = new DbManager();
                    var       userInfo  = dbManager.GetUserInforForNotification(notification.ReceiverID, notification.CallerID, false);

                    devicePlatform = (DevicePlatform)Convert.ToInt16(userInfo[NeeoConstants.ReceiverUserDeviceplatform]);
                    if (!NeeoUtility.IsNullOrEmpty(userInfo[NeeoConstants.ReceiverDeviceToken]) && !NeeoUtility.IsNullOrEmpty(userInfo[NeeoConstants.CallerName]))
                    {
                        deviceToken = userInfo[NeeoConstants.ReceiverDeviceToken];
                    }
                    else
                    {
                        throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                    }

                    if (devicePlatform == DevicePlatform.iOS)
                    {
                        if (_actionKeyText == null)
                        {
                            _actionKeyText = ConfigurationManager.AppSettings[NotificationConstants.ActionKeyText];
                        }
                        if (_iosIncomingCallingTone == null)
                        {
                            _iosIncomingCallingTone =
                                ConfigurationManager.AppSettings[NotificationConstants.IosIncomingCallingTone];
                        }
                        Console.WriteLine("device token : " + deviceToken + " alert  : " +
                                          _incomingCallingMsgText.Replace("[" + NeeoConstants.CallerName + "]",
                                                                          userInfo[NeeoConstants.CallerName]));
                        _push.QueueNotification(new AppleNotification(deviceToken)
                                                .WithAlert(_incomingCallingMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName]), "", _actionKeyText, new List <object>()
                        {
                        })
                                                .WithSound(_iosIncomingCallingTone)
                                                .WithCustomItem(NotificationConstants.NotificationID, NotificationType.IncomingSipCall.ToString("D"))
                                                .WithCustomItem(NotificationConstants.Timestamp, DateTime.UtcNow.ToString(NeeoConstants.TimestampFormat)));
                    }
                    else if (devicePlatform == DevicePlatform.Android)
                    {
                        _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(deviceToken)
                                                .WithJson("{\"alert\":\"" + _incomingCallingMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName]) + "\"}"));
                    }
                    else
                    {
                        // do nothing
                    }
                }
                else
                {
                    throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                }
                break;
                #endregion

            case NotificationType.Mcr:
                #region Mcr notification

                if (_mcrMsgText == null)
                {
                    _mcrMsgText = ConfigurationManager.AppSettings[NotificationConstants.McrMsgText];
                }

                if (!NeeoUtility.IsNullOrEmpty(notification.CallerID) && ulong.TryParse(notification.CallerID, out tempNumber) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber) && notification.McrCount != 0)
                {
                    DbManager dbManager = new DbManager();
                    var       userInfo  = dbManager.GetUserInforForNotification(notification.ReceiverID, notification.CallerID, true, notification.McrCount);

                    devicePlatform = (DevicePlatform)Convert.ToInt16(userInfo[NeeoConstants.ReceiverUserDeviceplatform]);
                    if (!NeeoUtility.IsNullOrEmpty(userInfo[NeeoConstants.ReceiverDeviceToken]))
                    {
                        deviceToken = userInfo[NeeoConstants.ReceiverDeviceToken];
                    }
                    else
                    {
                        throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                    }
                    badgeCount = Convert.ToInt32(userInfo[NeeoConstants.OfflineMessageCount]);
                    if (devicePlatform == DevicePlatform.iOS)
                    {
                        if (_iosApplicationMcrTone == null)
                        {
                            _iosApplicationMcrTone =
                                ConfigurationManager.AppSettings[NotificationConstants.IosApplicationMcrTone];
                        }
                        _push.QueueNotification(new AppleNotification(deviceToken)
                                                .WithAlert(_mcrMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName]))
                                                .WithBadge(badgeCount)
                                                .WithSound(_iosApplicationMcrTone)
                                                .WithCustomItem(NotificationConstants.NotificationID, NotificationType.Mcr.ToString("D"))
                                                .WithCustomItem(NotificationConstants.CallerID, notification.CallerID));
                    }
                    else if (devicePlatform == DevicePlatform.Android)
                    {
                        _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(deviceToken)
                                                .WithJson("{\"alert\":\"" + _mcrMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName]) + "\"}"));
                    }
                    else
                    {
                        //do nothing
                    }
                }
                else
                {
                    throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                }
                break;
                #endregion

            case NotificationType.GIm:
                #region Group notification
                if (!NeeoUtility.IsNullOrEmpty(notification.SenderID) && notification.RID != 0 && !NeeoUtility.IsNullOrEmpty(notification.RName) && !NeeoUtility.IsNullOrEmpty(notification.Alert))
                {
                    List <NeeoUser> lstgroupParticipant = NeeoGroup.GetGroupParticipants(notification.RID,
                                                                                         notification.SenderID, 1);
                    if (lstgroupParticipant.Count > 0)
                    {
                        var taskUpdateOfflineCount = Task.Factory.StartNew(() =>
                        {
                            LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Group participants - " + JsonConvert.SerializeObject(lstgroupParticipant), System.Reflection.MethodBase.GetCurrentMethod().Name);
                            IEnumerable <string> userList = from item in lstgroupParticipant
                                                            where item.PresenceStatus == Presence.Offline
                                                            select item.UserID;
                            string userString = string.Join(delimeter, userList);

                            //lstgroupParticipant.Where(i => i.PresenceStatus == Presence.Offline).Select(a => a.UserID)
                            //    .Aggregate((current, next) => current + delimeter + next);

                            LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "User list - " + userString, System.Reflection.MethodBase.GetCurrentMethod().Name);
                            if (!NeeoUtility.IsNullOrEmpty(userString))
                            {
                                DbManager dbManager = new DbManager();
                                dbManager.UpdateUserOfflineCount(userString, delimeter);
                            }
                        });
                        var taskScheduleNotifications = Task.Factory.StartNew(() =>
                        {
                            Parallel.ForEach(lstgroupParticipant, item =>
                                             //foreach (var item in lstgroupParticipant)
                            {
                                if (item.DevicePlatform == DevicePlatform.iOS)
                                {
                                    if (!NeeoUtility.IsNullOrEmpty(item.DeviceToken) && item.DeviceToken != "-1" &&
                                        item.PresenceStatus == Presence.Offline)
                                    {
                                        _push.QueueNotification(new AppleNotification(
                                                                    item.DeviceToken)
                                                                .WithAlert(notification.Alert)
                                                                .WithBadge(item.OfflineMsgCount + 1)
                                                                .WithSound(item.ImTone.ToString("G").Replace('_', '.'))
                                                                .WithCustomItem(NotificationConstants.NotificationID, NotificationType.GIm.ToString("D"))
                                                                .WithCustomItem(NotificationConstants.RoomID, notification.RName));
                                    }
                                }
                                else if (item.DevicePlatform == DevicePlatform.Android)
                                {
                                    //_push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(deviceToken)
                                    // .WithJson("{\"alert\":\"" + notificationMsg + "\",\"badge\":" + bageCount + ",\"sound\":\"sound.caf\"}"));
                                }
                                else
                                {
                                    //do nothing
                                }
                            });
                        });
                        taskUpdateOfflineCount.Wait();
                        taskScheduleNotifications.Wait();
                    }
                }
                else
                {
                    throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                }
                break;
                #endregion

            case NotificationType.GInvite:
                #region Group invitation notification

                if (!NeeoUtility.IsNullOrEmpty(notification.DToken) && notification.Dp != null && notification.IMTone != null &&
                    !NeeoUtility.IsNullOrEmpty(notification.Alert) && !NeeoUtility.IsNullOrEmpty(notification.RName) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber))
                {
                    NeeoUser receiver = new NeeoUser(notification.ReceiverID)
                    {
                        DeviceToken     = notification.DToken,
                        ImTone          = notification.IMTone.GetValueOrDefault(),
                        OfflineMsgCount = notification.Badge,
                        DevicePlatform  = notification.Dp.GetValueOrDefault()
                    };

                    if (receiver.DevicePlatform == DevicePlatform.iOS)
                    {
                        _push.QueueNotification(new AppleNotification(receiver.DeviceToken)
                                                .WithAlert(notification.Alert)
                                                .WithBadge(receiver.OfflineMsgCount)
                                                .WithSound(receiver.ImTone.ToString("G").Replace('_', '.'))
                                                .WithCustomItem(NotificationConstants.NotificationID,
                                                                NotificationType.GIm.ToString("D"))
                                                .WithCustomItem(NotificationConstants.RoomID, notification.RName));
                    }
                    else if (receiver.DevicePlatform == DevicePlatform.Android)
                    {
                        //_push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(deviceToken)
                        // .WithJson("{\"alert\":\"" + notificationMsg + "\",\"badge\":" + bageCount + ",\"sound\":\"sound.caf\"}"));
                    }
                    else
                    {
                        //do nothing
                    }
                }
                else
                {
                    throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D"));
                }
                break;
                #endregion
            }
        }