示例#1
0
        public void appServer_NewMessageReceived(WebSocketSession session, string message)
        {
            try
            {
                ResultClass result = new ResultClass();

                string baseURL = (WebConfigurationManager.AppSettings["WebSiteUrl"]);
                baseURL += (WebConfigurationManager.AppSettings["userimagepath"]).Replace("~", "");

                var Message = message.Split(',')[2].Split(':')[1];
                var UserId  = message.Split(',')[0].Split(':')[1];
                var GroupId = message.Split(',')[1].Split(':')[1];

                int GId = Convert.ToInt32(GroupId);
                int Uid = Convert.ToInt32(UserId);


                List <WebSocketSessionDb> list = new List <WebSocketSessionDb>();
                MessageModel MessagesModel     = new MessageModel();
                using (LystenEntities db = new LystenEntities())
                {
                    Message ms = new Message()
                    {
                        Body            = Message,
                        CreatedDate     = System.DateTime.Now,
                        ParentMessageId = 0,
                        CreatorId       = Uid
                    };
                    db.Messages.Add(ms);
                    db.SaveChanges();

                    MessageRecipient MR = new MessageRecipient()
                    {
                        RecipientGroupId = GId,
                        RecipientId      = null,
                        MessageId        = ms.Id,
                        IsRead           = false
                    };
                    db.MessageRecipients.Add(MR);
                    db.SaveChanges();


                    int gid = Convert.ToInt32(GroupId);
                    list = db.WebSocketSessionDbs.Where(x => x.GroupID == gid).ToList();

                    MessagesModel = new MessageModel()
                    {
                        MessageId        = ms.Id,
                        Body             = ms.Body,
                        RecipientGroupId = GId,
                        CreatorId        = Uid,
                        IsRead           = false,
                        CreatedDate      = Convert.ToDateTime(ms.CreatedDate).ToString("dd MM yyyy HH:MM"),
                        Image            = US.GetFavouriteImage(baseURL, Uid),
                        CreatorName      = db.User_Master.Where(y => y.Id == Uid).Select(y => y.FullName).FirstOrDefault() == null ? "" : db.User_Master.Where(y => y.Id == Uid).Select(y => y.FullName).FirstOrDefault(),
                        ParentMessageId  = 0,
                        ExpiryDate       = System.DateTime.Now,
                        RecipientId      = 0
                    };
                    result.Code = (int)HttpStatusCode.OK;
                    result.Msg  = ap.Success;
                    result.Data = MessagesModel;
                }
                var json = new JavaScriptSerializer().Serialize(result);
                foreach (var item in list)
                {
                    if (item.UserId.Value != Uid)
                    {
                        foreach (WebSocketSession session1 in appServer.GetAllSessions().Where(x => x.SessionID == item.SessionId))
                        {
                            session1.Send(json);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CommonServices.ErrorLogging(ex);
            }
        }
示例#2
0
        public static void sendMsgCallAccept(int IsAccept, int Id, string devicetocken)
        {
            string ImagePath = "";
            string name      = "";
            string baseURL   = HttpContext.Current.Request.Url.Authority;

            baseURL += (WebConfigurationManager.AppSettings["userimagepath"]).Replace("~", "");
            using (LystenEntities db = new LystenEntities())
            {
                ApiUserServices US = new ApiUserServices();

                ImagePath = US.GetFavouriteImage(baseURL, Id);
                name      = db.User_Master.Where(x => x.Id == Id).Select(x => x.FullName).FirstOrDefault() == null ? "" : db.User_Master.Where(x => x.Id == Id).Select(x => x.FullName).FirstOrDefault();
            }

            string response;

            try
            {
                // From: https://console.firebase.google.com/project/x.y.z/settings/general/android:x.y.z

                // Projekt-ID: x.y.z
                // Web-API-Key: A...Y (39 chars)
                // App-ID: 1:...:android:...

                // From https://console.firebase.google.com/project/x.y.z/settings/
                // cloudmessaging/android:x,y,z
                // Server-Key: AAAA0...    ...._4

                // string serverKey = "AIzaSyA8TnixTCgxdJgIiL8o_DPDZHrwSBxh6mg"; // Something very long
                string     senderId     = Convert.ToString(Id); //"959844890015";
                string     deviceId     = devicetocken;         //"fNV1nvahRcQ:APA91bG8NH4CVIFfGhuNnHyrCuxWja6pcNsGBLZUIvuNlbakeOw_xsr0jz-dFetsJq0IxhHpO2nDiXlPgQrgJGQrQJAQztch5jKZBAgVOEj3O4cqN8LKG1fRk66jbVqcRIzCanleo40M"; // Also something very long,
                int        totunreadmsg = 20;                   // topic notification
                WebRequest tRequest     = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                string     Checkbool    = "";
                string     strmsgbody   = "";
                if (IsAccept == 1)
                {
                    Checkbool = "Accepted";
                }
                else
                {
                    Checkbool = "Rejected";
                }
                strmsgbody           = "Message request has been " + Checkbool;
                tRequest.Method      = "post";
                tRequest.ContentType = "application/json";
                var data = new
                {
                    to   = deviceId,
                    data = new
                    {
                        body  = strmsgbody,
                        title = "Message",
                        Id    = Id,
                        Type  = "Message"
                                //sound = "Enabled",
                                // Icon = ImagePath,
                    }
                };

                var    serializer = new JavaScriptSerializer();
                var    json       = serializer.Serialize(data);
                Byte[] byteArray  = Encoding.UTF8.GetBytes(json);
                tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
                tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
                tRequest.ContentLength = byteArray.Length;

                using (Stream dataStream = tRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    using (WebResponse tResponse = tRequest.GetResponse())
                    {
                        using (Stream dataStreamResponse = tResponse.GetResponseStream())
                        {
                            using (StreamReader tReader = new StreamReader(dataStreamResponse))
                            {
                                String sResponseFromServer = tReader.ReadToEnd();
                                response = sResponseFromServer;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                response = ex.Message;
            }

            // return response;
        }
示例#3
0
        public override void OnMessage(string message)
        {
            try
            {
                ResultClassForNonAuth result = new ResultClassForNonAuth();
                string baseURL = (WebConfigurationManager.AppSettings["WebSiteUrl"]);
                baseURL += (WebConfigurationManager.AppSettings["userimagepath"]).Replace("~", "");
                if (message.Split(',')[1].Split(':').Contains("GroupId"))
                {
                    var Message = message.Split(',')[2].Split(':')[1];
                    var UserId  = message.Split(',')[0].Split(':')[1];
                    var GroupId = message.Split(',')[1].Split(':')[1];

                    int GId       = Convert.ToInt32(GroupId);
                    int Uid       = Convert.ToInt32(UserId);
                    var groupname = "";

                    List <WebSocketSessionDb> list = new List <WebSocketSessionDb>();
                    MessageModel MessagesModel     = new MessageModel();
                    using (LystenEntities db = new LystenEntities())
                    {
                        groupname = db.Groups.Where(x => x.Id == GId).Select(x => x.Name).FirstOrDefault();
                        Message ms = new Message()
                        {
                            Body            = Message,
                            CreatedDate     = DateTime.UtcNow,
                            ParentMessageId = 0,
                            CreatorId       = Uid
                        };
                        db.Messages.Add(ms);
                        db.SaveChanges();

                        MessageRecipient MR = new MessageRecipient()
                        {
                            RecipientGroupId = GId,
                            RecipientId      = null,
                            MessageId        = ms.Id,
                            IsRead           = false
                        };
                        db.MessageRecipients.Add(MR);
                        db.SaveChanges();


                        int gid = Convert.ToInt32(GroupId);
                        list = db.WebSocketSessionDbs.Where(x => x.GroupID == gid).ToList();



                        var userdataTimeZone = db.User_Master.Where(x => x.Id == Uid).Select(x => x.TimeZone).FirstOrDefault();
                        var ddd = DateTime.UtcNow;
                        if (userdataTimeZone != null && userdataTimeZone != "")
                        {
                            Instant instant = Instant.FromDateTimeUtc(ms.CreatedDate.Value);
                            IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
                            var usersTimezoneId    = userdataTimeZone; //just an example
                            var usersTimezone      = timeZoneProvider[usersTimezoneId];
                            var usersZonedDateTime = instant.InZone(usersTimezone);
                            ddd = usersZonedDateTime.ToDateTimeUnspecified();
                        }



                        MessagesModel = new MessageModel()
                        {
                            MessageId        = ms.Id,
                            Body             = ms.Body,
                            RecipientGroupId = GId,
                            CreatorId        = Uid,
                            IsRead           = false,
                            CreatedDate      = ddd.Date == DateTime.UtcNow.Date ? "Today " + Convert.ToDateTime((ddd)).ToString("HH:mm") : Convert.ToDateTime(ddd).ToString("dd MM yyyy HH:mm"),

                            //CreatedDate = Convert.ToDateTime(ms.CreatedDate).ToString("dd MM yyyy HH:MM"),
                            Image           = US.GetFavouriteImage(baseURL, Uid),
                            CreatorName     = db.User_Master.Where(y => y.Id == Uid).Select(y => y.FullName).FirstOrDefault() == null ? "" : db.User_Master.Where(y => y.Id == Uid).Select(y => y.FullName).FirstOrDefault(),
                            ParentMessageId = 0,
                            ExpiryDate      = System.DateTime.Now,
                            RecipientId     = 0
                        };
                        result.Code = (int)HttpStatusCode.OK;
                        result.Msg  = ap.Success;
                        result.Data = MessagesModel;
                    }
                    var json = new JavaScriptSerializer().Serialize(result);
                    foreach (var item in list)
                    {
                        foreach (var data in clients.Where(x => x.WebSocketContext.SecWebSocketKey == item.SessionId))
                        {
                            clients.SingleOrDefault(r => ((WebSocketHandler)r).WebSocketContext.SecWebSocketKey == item.SessionId).Send(json);
                        }
                        using (LystenEntities db = new LystenEntities())
                        {
                            var obj        = db.User_Master.Where(x => x.Id == item.UserId.Value).FirstOrDefault();
                            var sendername = db.User_Master.Where(x => x.Id == Uid).Select(x => x.FullName).FirstOrDefault();

                            if (obj != null)
                            {
                                if (obj.DeviceToken != null)
                                {
                                    try
                                    {
                                        sendMsgUser(GId, true, obj.DeviceToken, Message, groupname, sendername);
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    var Message      = message.Split(',')[2].Split(':')[1];
                    var UserId       = message.Split(',')[0].Split(':')[1];
                    var ReceiptionId = message.Split(',')[1].Split(':')[1];

                    int RId = Convert.ToInt32(ReceiptionId);
                    int Uid = Convert.ToInt32(UserId);


                    List <WebSocketSessionDb> list = new List <WebSocketSessionDb>();
                    MessageModel MessagesModel     = new MessageModel();
                    var          SenderFullName    = "";

                    using (LystenEntities db = new LystenEntities())
                    {
                        SenderFullName = db.User_Master.Where(x => x.Id == Uid).Select(x => x.FullName).FirstOrDefault();

                        if (!db.MessageRequests.Any(x => x.ToUserId == RId && x.FromUserId == Uid || x.FromUserId == RId && x.ToUserId == Uid))
                        {
                            MessageRequest M1R = new MessageRequest();
                            M1R.ToUserId    = Convert.ToInt32(RId);
                            M1R.FromUserId  = Convert.ToInt32(Uid);
                            M1R.IsAccept    = false;
                            M1R.IsReject    = false;
                            M1R.IsRequested = true;
                            db.MessageRequests.Add(M1R);
                            db.SaveChanges();
                            var obj = db.User_Master.Where(x => x.Id == M1R.ToUserId).FirstOrDefault();


                            if (obj.DeviceToken != null || obj.DeviceToken != "")
                            {
                                try
                                {
                                    if (obj.DeviceType == "Android")
                                    {
                                        Helpers.NotificationHelper.sendMsgUserRequest(obj.Id, obj.DeviceToken, 0, SenderFullName);
                                    }
                                    else
                                    {
                                        sendMsgUserRequest(obj.Id, obj.DeviceToken, 0, SenderFullName);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    CommonServices.ErrorLogging(ex);
                                }
                            }
                        }
                        Message ms = new Message()
                        {
                            Body            = Message,
                            CreatedDate     = DateTime.UtcNow,
                            ParentMessageId = 0,
                            CreatorId       = Uid
                        };
                        db.Messages.Add(ms);
                        db.SaveChanges();
                        MessageRecipient MR = new MessageRecipient()
                        {
                            RecipientGroupId = null,
                            RecipientId      = RId,
                            MessageId        = ms.Id,
                            IsRead           = false
                        };
                        db.MessageRecipients.Add(MR);
                        db.SaveChanges();
                        list = db.WebSocketSessionDbs.Where(x => x.RecipientId == RId && x.UserId == Uid || (x.RecipientId == Uid && x.UserId == RId)).ToList();


                        var userdataTimeZone = db.User_Master.Where(x => x.Id == Uid).Select(x => x.TimeZone).FirstOrDefault();
                        var ddd = DateTime.UtcNow;
                        if (userdataTimeZone != null && userdataTimeZone != "")
                        {
                            Instant instant = Instant.FromDateTimeUtc(ms.CreatedDate.Value);
                            IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
                            var usersTimezoneId    = userdataTimeZone; //just an example
                            var usersTimezone      = timeZoneProvider[usersTimezoneId];
                            var usersZonedDateTime = instant.InZone(usersTimezone);
                            ddd = usersZonedDateTime.ToDateTimeUnspecified();
                        }
                        try
                        {
                            MessagesModel = new MessageModel()
                            {
                                MessageId        = ms.Id,
                                Body             = ms.Body,
                                RecipientGroupId = 0,
                                CreatorId        = Uid,
                                IsRead           = false,

                                CreatedDate = ddd.Date == DateTime.UtcNow.Date ? "Today " + Convert.ToDateTime((ddd)).ToString("HH:mm") : Convert.ToDateTime(ddd).ToString("dd MM yyyy HH:mm"),


                                //CreatedDate = ms.CreatedDate.Value.Date == DateTime.Now.Date ? "Today " + Convert.ToDateTime((ms.CreatedDate.Value)).ToString("HH:mm") : Convert.ToDateTime(ms.CreatedDate.Value).ToString("dd MM yyyy HH:mm"),

                                //CreatedDate = Convert.ToDateTime(ms.CreatedDate).ToString("dd MM yyyy HH:MM"),
                                Image           = US.GetFavouriteImage(baseURL, Uid),
                                CreatorName     = db.User_Master.Where(y => y.Id == Uid).Select(y => y.FullName).FirstOrDefault() == null ? "" : db.User_Master.Where(y => y.Id == Uid).Select(y => y.FullName).FirstOrDefault(),
                                ParentMessageId = 0,
                                ExpiryDate      = System.DateTime.Now,
                                RecipientId     = RId
                            };
                        }
                        catch (Exception ex)
                        {
                            CommonServices.ErrorLogging(ex);
                        }
                        result.Code = (int)HttpStatusCode.OK;
                        result.Msg  = ap.Success;
                        result.Data = MessagesModel;
                    }
                    try
                    {
                        var json = new JavaScriptSerializer().Serialize(result);
                        foreach (var item in list)
                        {
                            foreach (var data in clients.Where(x => x.WebSocketContext.SecWebSocketKey == item.SessionId))
                            {
                                clients.SingleOrDefault(r => ((WebSocketHandler)r).WebSocketContext.SecWebSocketKey == item.SessionId).Send(json);
                            }
                            using (LystenEntities db = new LystenEntities())
                            {
                                var obj = db.User_Master.Where(x => x.Id == item.RecipientId.Value).FirstOrDefault();


                                if (obj != null)
                                {
                                    //if (obj.DeviceToken != null)
                                    //{
                                    //    sendMsgEventsssss(item.UserId.Value, obj.DeviceToken, Message, SenderFullName);
                                    //}

                                    try
                                    {
                                        if (obj.DeviceToken != null)
                                        {
                                            if (obj.DeviceType == "Android")
                                            {
                                                Helpers.NotificationHelper.sendMsgEventsssss(item.UserId.Value, obj.DeviceToken, Message, SenderFullName, MessagesModel.MessageId);
                                            }
                                            else
                                            {
                                                sendMsgEventsssss(item.UserId.Value, obj.DeviceToken, Message, SenderFullName);
                                                //sendMsgUserRequest(obj.Id, obj.DeviceToken, 0, SenderFullName);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        CommonServices.ErrorLogging(ex);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        CommonServices.ErrorLogging(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                CommonServices.ErrorLogging(ex);
            }
        }
示例#4
0
        public static void sendMsgPreCalling(int Id, string devicetocken, string Status, string Fullname)
        {
            string ImagePath = "";
            string name      = "";
            string baseURL   = HttpContext.Current.Request.Url.Authority;

            baseURL += (WebConfigurationManager.AppSettings["userimagepath"]).Replace("~", "");
            using (LystenEntities db = new LystenEntities())
            {
                ApiUserServices US = new ApiUserServices();

                ImagePath = US.GetFavouriteImage(baseURL, Id);
                name      = db.User_Master.Where(x => x.Id == Id).Select(x => x.FullName).FirstOrDefault() == null ? "" : db.User_Master.Where(x => x.Id == Id).Select(x => x.FullName).FirstOrDefault();
            }

            string response;

            try
            {
                // From: https://console.firebase.google.com/project/x.y.z/settings/general/android:x.y.z

                // Projekt-ID: x.y.z
                // Web-API-Key: A...Y (39 chars)
                // App-ID: 1:...:android:...

                // From https://console.firebase.google.com/project/x.y.z/settings/
                // cloudmessaging/android:x,y,z
                // Server-Key: AAAA0...    ...._4

                //string serverKey = "AIzaSyA8TnixTCgxdJgIiL8o_DPDZHrwSBxh6mg"; // Something very long
                string senderId = Convert.ToString(Id); //"959844890015";
                string deviceId = devicetocken;         //"fNV1nvahRcQ:APA91bG8NH4CVIFfGhuNnHyrCuxWja6pcNsGBLZUIvuNlbakeOw_xsr0jz-dFetsJq0IxhHpO2nDiXlPgQrgJGQrQJAQztch5jKZBAgVOEj3O4cqN8LKG1fRk66jbVqcRIzCanleo40M"; // Also something very long,
                                                        // topic notification
                WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                //string Checkbool = "";

                string strmsgbody   = "";
                int    totunreadmsg = 20;
                if (Status == "TO")
                {
                    strmsgbody = "You have a call from " + Fullname + " in 15 minutes.be ready!";
                }
                else
                {
                    strmsgbody = "Your calling time is in 15 minutes.be ready!";
                }


                var data = new
                {
                    to   = deviceId,
                    data = new
                    {
                        body  = strmsgbody,//"Greetings",
                        title = "Calling Request",
                        Type  = "Call",
                        //sound = "Enabled",
                        Id = Id,
                        //Icon = ImagePath,
                    }
                };
                //strmsgbody = "Message request has been " + Checkbool;
                tRequest.Method      = "post";
                tRequest.ContentType = "application/json";

                //var payload = "{\"aps\":{\"alert\":\"" + strmsgbody + "\",\"badge\":" + totunreadmsg.ToString() + ",\"sound\":\"mailsent.wav\"},\"event\":{\"EventID\":\"" + EventId + "\"},\"acme1\":\"bar\",\"acme2\":42}";
                var    serializer = new JavaScriptSerializer();
                var    json       = serializer.Serialize(data);
                Byte[] byteArray  = Encoding.UTF8.GetBytes(json);
                tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
                tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
                tRequest.ContentLength = byteArray.Length;

                using (Stream dataStream = tRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    using (WebResponse tResponse = tRequest.GetResponse())
                    {
                        using (Stream dataStreamResponse = tResponse.GetResponseStream())
                        {
                            using (StreamReader tReader = new StreamReader(dataStreamResponse))
                            {
                                String sResponseFromServer = tReader.ReadToEnd();
                                response = sResponseFromServer;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                response = ex.Message;
            }
            //string ImagePath = "";
            //string name = "";
            //var certificatePath = HostingEnvironment.MapPath("~/Lysten-DevB.p12");


            //int port = 2195;
            //String hostname = (WebConfigurationManager.AppSettings["ApnsEnvironment"]);
            ////String hostname = "gateway.push.apple.com";

            //string certificatePassword = "";

            //X509Certificate2 clientCertificate = new X509Certificate2(certificatePath, certificatePassword, X509KeyStorageFlags.MachineKeySet);
            //X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);


            //TcpClient client = new TcpClient(hostname, port);

            //SslStream sslStream = new SslStream(
            //                client.GetStream(),
            //                false,
            //                new RemoteCertificateValidationCallback(ValidateServerCertificate),
            //                null
            //);
            //try
            //{
            //    sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
            //}
            //catch (AuthenticationException ex)
            //{
            //    client.Close();
            //    Exception Eccsssas12 = new Exception("Athentication Failed");
            //    CommonServices.ErrorLogging(Eccsssas12);
            //    System.Web.HttpContext.Current.Server.MapPath("~/Authenticationfailed.txt");
            //    return;
            //}

            ////// Encode a test message into a byte array.
            //MemoryStream memoryStream = new MemoryStream();
            //BinaryWriter writer = new BinaryWriter(memoryStream);
            //writer.Write((byte)0);  //The command
            //writer.Write((byte)0);  //The first byte of the deviceId length (big-endian first byte)
            //writer.Write((byte)32); //The deviceId length (big-endian second byte)
            //byte[] b0 = HexString2Bytes(devicetocken);
            //WriteMultiLineByteArray(b0);
            //writer.Write(b0);
            //String payload;
            //string strmsgbody = "";
            //int totunreadmsg = 20;
            //if (Status == "TO")
            //{
            //    strmsgbody = "You have a call from " + Fullname + " in 15 minutes.be ready!";
            //}
            //else
            //{
            //    strmsgbody = "Your calling time is in 15 minutes.be ready!";
            //}
            //payload = "{\"aps\":{\"alert\":\"" + strmsgbody + "\",\"badge\":" + totunreadmsg.ToString() + ",\"sound\":\"mailsent.wav\"},\"acme1\":\"bar\",\"acme2\":42}";
            //writer.Write((byte)0); //First byte of payload length; (big-endian first byte)
            //writer.Write((byte)payload.Length);     //payload length (big-endian second byte)
            //byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
            //writer.Write(b1);
            //writer.Flush();

            //byte[] array = memoryStream.ToArray();
            //try
            //{
            //    sslStream.Write(array);
            //    sslStream.Flush();
            //}
            //catch
            //{
            //}
            //client.Close();
        }
示例#5
0
        public static void sendMsgUserRequest(int GroupId, string devicetocken, int Id, string SenderFullName)
        {
            string ImagePath = "";
            string Name      = "";
            string response  = "";

            try
            {
                string baseURL = HttpContext.Current.Request.Url.Authority;
                baseURL += (WebConfigurationManager.AppSettings["groupimagepath"]).Replace("~", "");
                //string serverKey = "AIzaSyA8TnixTCgxdJgIiL8o_DPDZHrwSBxh6mg"; // Something very long
                //string response = "";

                baseURL  = HttpContext.Current.Request.Url.Authority;
                baseURL += (WebConfigurationManager.AppSettings["userimagepath"]).Replace("~", "");
                using (LystenEntities db = new LystenEntities())
                {
                    ApiUserServices US = new ApiUserServices();

                    ImagePath = US.GetFavouriteImage(baseURL, GroupId);
                    Name      = db.User_Master.Where(x => x.Id == GroupId).Select(x => x.FullName).FirstOrDefault() == null ? "" : db.User_Master.Where(x => x.Id == GroupId).Select(x => x.FullName).FirstOrDefault();
                }
                string     deviceId     = devicetocken;
                WebRequest tRequest     = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                string     strmsgbody   = SenderFullName + " sent you a message request.";
                int        totunreadmsg = 20;
                var        data         = new
                {
                    to   = deviceId,
                    data = new
                    {
                        body  = strmsgbody,//"Greetings",
                        title = SenderFullName,
                        Type  = "Group",
                        //sound = "Enabled",
                        Id = GroupId,
                        //Icon = ImagePath,
                    }
                };
                string payload    = "{\"aps\":{\"alert\":\"" + strmsgbody + "\",\"badge\":" + totunreadmsg.ToString() + ",\"sound\":\"mailsent.wav\"},\"inbox\":{},\"acme1\":\"bar\",\"acme2\":42}";
                var    serializer = new JavaScriptSerializer();
                var    json       = serializer.Serialize(data);
                Byte[] byteArray  = Encoding.UTF8.GetBytes(json);
                tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
                //tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
                tRequest.ContentLength = byteArray.Length;

                using (Stream dataStream = tRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    using (WebResponse tResponse = tRequest.GetResponse())
                    {
                        using (Stream dataStreamResponse = tResponse.GetResponseStream())
                        {
                            using (StreamReader tReader = new StreamReader(dataStreamResponse))
                            {
                                String sResponseFromServer = tReader.ReadToEnd();
                                response = sResponseFromServer;
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
示例#6
0
        public static string SendPushNotification(int Id, string devicetocken, int QuestionId, string commentuser, string questionname)
        {
            string response;

            try
            {
                string ImagePath = "";
                string name      = "";
                string baseURL   = HttpContext.Current.Request.Url.Authority;
                baseURL += (WebConfigurationManager.AppSettings["userimagepath"]).Replace("~", "");
                using (LystenEntities db = new LystenEntities())
                {
                    ApiUserServices US = new ApiUserServices();

                    ImagePath = US.GetFavouriteImage(baseURL, Id);
                    name      = db.User_Master.Where(x => x.Id == Id).Select(x => x.FullName).FirstOrDefault() == null ? "" : db.User_Master.Where(x => x.Id == Id).Select(x => x.FullName).FirstOrDefault();
                }
                // From: https://console.firebase.google.com/project/x.y.z/settings/general/android:x.y.z

                // Projekt-ID: x.y.z
                // Web-API-Key: A...Y (39 chars)
                // App-ID: 1:...:android:...

                // From https://console.firebase.google.com/project/x.y.z/settings/
                // cloudmessaging/android:x,y,z
                // Server-Key: AAAA0...    ...._4

                //string serverKey = "AAAA33s2tZ8:APA91bFKBFRMEacmRGZCvdiZ4bq-kjqyzmogX-lAqzl0sWzsSlU0ainu_RE2ATmQDC8PlF2YaFhSqBmfR5FXCBXHN3kLM0gGzHojCwuyP7tEhd0b5WYZVq-XTLbJPZGSOZy_svenV1Hl";//"AIzaSyA8TnixTCgxdJgIiL8o_DPDZHrwSBxh6mg"; // Something very long
                string senderId = Convert.ToString(Id); //"959844890015";
                string deviceId = devicetocken;         //"fNV1nvahRcQ:APA91bG8NH4CVIFfGhuNnHyrCuxWja6pcNsGBLZUIvuNlbakeOw_xsr0jz-dFetsJq0IxhHpO2nDiXlPgQrgJGQrQJAQztch5jKZBAgVOEj3O4cqN8LKG1fRk66jbVqcRIzCanleo40M"; // Also something very long,
                                                        // topic notification
                WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");

                tRequest.Method      = "post";
                tRequest.ContentType = "application/json";
                var data = new
                {
                    to   = deviceId,
                    data = new
                    {
                        body  = commentuser,//"Greetings",
                        title = questionname,
                        //sound = "Enabled",
                        //icon = ImagePath,
                        Id   = QuestionId,
                        Type = "Question",
                    }
                };
                string totunreadmsg = "20";
                string payload      = "{\"aps\":{\"alert\":\"" + commentuser + "\",\"badge\":" + totunreadmsg + ",\"sound\":\"mailsent.wav\"},\"acme1\":\"bar\",\"acme2\":42}";
                var    serializer   = new JavaScriptSerializer();
                var    json         = serializer.Serialize(data);
                Byte[] byteArray    = Encoding.UTF8.GetBytes(json);
                tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
                tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
                tRequest.ContentLength = byteArray.Length;

                using (Stream dataStream = tRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    using (WebResponse tResponse = tRequest.GetResponse())
                    {
                        using (Stream dataStreamResponse = tResponse.GetResponseStream())
                        {
                            using (StreamReader tReader = new StreamReader(dataStreamResponse))
                            {
                                String sResponseFromServer = tReader.ReadToEnd();
                                response = sResponseFromServer;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                response = ex.Message;
            }

            return(response);
        }
        public void sendMsg(int Id, string devicetocken, bool IsAccept, bool IsReject)
        {
            string ImagePath  = "";
            string name       = "";
            string strmsgbody = "";

            strmsgbody = "Hey There!";
            if (IsAccept)
            {
                strmsgbody += "Calling request accepted.";
            }

            if (IsReject)
            {
                strmsgbody += "Calling request rejected.";
            }
            string baseURL = HttpContext.Current.Request.Url.Authority;

            baseURL += (WebConfigurationManager.AppSettings["userimagepath"]).Replace("~", "");
            using (LystenEntities db = new LystenEntities())
            {
                ImagePath = US.GetFavouriteImage(baseURL, Id);
                name      = db.User_Master.Where(x => x.Id == Id).Select(x => x.FullName).FirstOrDefault() == null ? "" : db.User_Master.Where(x => x.Id == Id).Select(x => x.FullName).FirstOrDefault();
            }

            int    port     = 2195;
            String hostname = (WebConfigurationManager.AppSettings["ApnsEnvironment"]);
            //String hostname = "gateway.push.apple.com";

            string certificatePath = System.Web.HttpContext.Current.Server.MapPath("~/Lysten-DevB.p12");

            string certificatePassword = "";

            X509Certificate2           clientCertificate      = new X509Certificate2(certificatePath, certificatePassword, X509KeyStorageFlags.MachineKeySet);
            X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);


            TcpClient client = new TcpClient(hostname, port);

            SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null
                );

            try
            {
                sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
            }
            catch (AuthenticationException ex)
            {
                client.Close();
                Exception Eccsssas12 = new Exception("Athentication Failed");
                CommonServices.ErrorLogging(Eccsssas12);
                System.Web.HttpContext.Current.Server.MapPath("~/Authenticationfailed.txt");
                return;
            }

            //// Encode a test message into a byte array.
            MemoryStream memoryStream = new MemoryStream();
            BinaryWriter writer       = new BinaryWriter(memoryStream);

            writer.Write((byte)0);  //The command
            writer.Write((byte)0);  //The first byte of the deviceId length (big-endian first byte)
            writer.Write((byte)32); //The deviceId length (big-endian second byte)
            byte[] b0 = HexString2Bytes(devicetocken);
            WriteMultiLineByteArray(b0);
            writer.Write(b0);
            String payload;
            int    totunreadmsg = 20;

            payload = "{\"aps\":{\"alert\":\"" + strmsgbody + "\",\"badge\":" + totunreadmsg.ToString() + ",\"sound\":\"mailsent.wav\"},\"call\":{\"CallType\":\"" + IsAccept.ToString() == "true" ? "1" : "2" + "\",\"name\":\"" + name + "\"},\"acme1\":\"bar\",\"acme2\":42}";
            writer.Write((byte)0);              //First byte of payload length; (big-endian first byte)
            writer.Write((byte)payload.Length); //payload length (big-endian second byte)
            byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
            writer.Write(b1);
            writer.Flush();

            byte[] array = memoryStream.ToArray();
            try
            {
                sslStream.Write(array);
                sslStream.Flush();
            }
            catch
            {
            }
            client.Close();
        }
        public async Task <ResultClass> PostLoginAuthenticationAsync(UserMasterModel objtblusermaster)
        {
            try
            {
                using (LystenEntities db = new LystenEntities())
                {
                    string baseURL = HttpContext.Current.Request.Url.Authority;
                    baseURL += (WebConfigurationManager.AppSettings["userimagepath"]).Replace("~", "");

                    //db.Configuration.LazyLoadingEnabled = false;
                    var pwd = SecutiryServices.EncodePasswordToBase64(objtblusermaster.Password);

                    User_Master result = (from um23 in db.User_Master
                                          where um23.Email.ToUpper() == objtblusermaster.UserNameorEmail.ToUpper() && um23.Password == pwd
                                          select um23
                                          ).FirstOrDefault();
                    if (result == null)
                    {
                        result = (from um23 in db.User_Master
                                  where um23.UserName.ToUpper() == objtblusermaster.UserNameorEmail.ToUpper() && um23.Password == pwd
                                  select um23
                                  ).FirstOrDefault();
                    }
                    var model = new
                    {
                    };
                    if (result != null)
                    {
                        var id = result.Id;
                        if (result.IsActive == true)
                        {
                            objresult.Code = (int)HttpStatusCode.OK;
                            objresult.Msg  = ap.Success;
                            //var user = result;
                            objresult.Data = AutoMapper.Mapper.Map <UserViewLoginModel>(result);
                            User_Master obj = result;//db.User_Master.Where(x => x.Id == id).FirstOrDefault();
                            obj.SessionId       = null;
                            obj.IsLogin         = true;
                            obj.DeviceType      = objtblusermaster.DeviceType;
                            obj.DeviceToken     = objtblusermaster.DeviceToken;
                            obj.TimeZone        = objtblusermaster.TimeZone;
                            db.Entry(obj).State = EntityState.Modified;
                            db.SaveChanges();
                            objresult.Data.Image = US.GetFavouriteImage(baseURL, result.Id);
                        }
                        else
                        {
                            objresult.Code = (int)HttpStatusCode.Accepted;
                            objresult.Msg  = ap.LoginUserIsNotActive;
                            //var user = result;
                            objresult.Data = AutoMapper.Mapper.Map <UserViewLoginModel>(result);
                        }
                    }
                    else if (result == null)
                    {
                        objresult.Code        = (int)HttpStatusCode.NotFound;
                        objresult.Msg         = ap.LoginUserInvalid;
                        objresult.Data        = model;
                        objresult.AccessToken = "";
                    }
                    else
                    {
                        objresult.Code = (int)HttpStatusCode.Accepted;
                        objresult.Msg  = ap.LoginUserIsNotActive;
                        result.Image   = US.GetFavouriteImage(baseURL, result.Id);

                        objresult.Data = AutoMapper.Mapper.Map <UserViewLoginModel>(result);
                    }

                    if (objresult.Code == (int)HttpStatusCode.OK)
                    {
                        TokenDetails objToken = await generatToken((result.Email), (result.Password), (result.DeviceToken));

                        //User_Master obj1 = db.User_Master.Where(x => x.Id == result.Id).FirstOrDefault();
                        //obj1.DeviceType = objtblusermaster.DeviceType;
                        ////obj.DeviceToken = objtblusermaster.DeviceToken;
                        //db.Entry(obj1).State = EntityState.Modified;
                        //db.SaveChanges();
                        (objresult.AccessToken) = objToken.access_token;
                        var obj = objresult.Data as UserViewLoginModel;
                        Add_UpdateToken(obj.Id, objToken, 1, objtblusermaster.DeviceType);
                    }
                    //if (updatetoken)
                    //{
                    //    (objresult.Data as UserViewModel).AccessToken = accessToken;
                    //}
                    //else
                    //{
                    //    (objresult.Data as UserViewModel).AccessToken = "";
                    //}
                    //db.Configuration.LazyLoadingEnabled = true;
                    return(objresult);
                }
            }
            catch (Exception ex)
            {
                objresult.Code        = (int)HttpStatusCode.NotAcceptable;
                objresult.Msg         = Convert.ToString(ex.Message);
                objresult.Data        = "";
                objresult.AccessToken = "";
                return(objresult);
            }
        }