public dynamic SaveEvent(Event CM) { using (LystenEntities db = new LystenEntities()) { if (CM.Id > 0) { var Event = db.Events.Where(x => x.Id == CM.Id).FirstOrDefault(); Event.ModifiedDate = System.DateTime.Now; Event.Description = CM.Description; Event.Title = CM.Title; Event.CategoryId = CM.CategoryId; Event.IsActive = CM.IsActive; Event.Location = CM.Location; db.Entry(Event).State = EntityState.Modified; db.SaveChanges(); return(new { Id = CM.Id, Status = "Update" }); } else { if (db.Events.Any(x => x.Title == (CM.Title).Trim())) { CM.Id = db.Events.Where(x => x.Title == (CM.Title).Trim()).Select(x => x.Id).FirstOrDefault(); return(new { Id = CM.Id, Status = "Exists" }); } else { CM.IsActive = true; CM.CreatedDate = System.DateTime.Now; CM.CreatedBy = 1; db.Events.Add(CM); db.SaveChanges(); return(new { Id = CM.Id, Status = "Insert" }); } } } }
public dynamic SaveCallingPriceMaster(CallingPriceMaster viewModel) { using (LystenEntities db = new LystenEntities()) { if (viewModel.Id > 0) { var callingPrice = db.CallingPriceMasters.Where(x => x.Id == viewModel.Id).FirstOrDefault(); callingPrice.ModifiedDate = System.DateTime.Now; callingPrice.Name = viewModel.Name; callingPrice.Description = viewModel.Description; callingPrice.Price = viewModel.Price; callingPrice.Time = viewModel.Time; callingPrice.ModifiedDate = DateTime.Now; db.Entry(callingPrice).State = EntityState.Modified; db.SaveChanges(); return(new { Id = viewModel.Id, Status = "Update" }); } else { if (db.Categories.Any(x => x.Name == (viewModel.Name).Trim())) { viewModel.Id = db.Categories.Where(x => x.Name == (viewModel.Name).Trim()).Select(x => x.Id).FirstOrDefault(); return(new { Id = viewModel.Id, Status = "Exists" }); } else { viewModel.IsActive = true; viewModel.CreatedDate = DateTime.Now; viewModel.ModifiedDate = DateTime.Now; db.CallingPriceMasters.Add(viewModel); db.SaveChanges(); return(new { Id = viewModel.Id, Status = "Insert" }); } } } }
public object MarkAsVerified(int id) { using (LystenEntities db = new LystenEntities()) { var User = db.User_Master.Where(x => x.Id == id).FirstOrDefault(); if (User.IsVerified == null || User.IsVerified == false) { User.IsVerified = true; } db.Entry(User).State = EntityState.Modified; db.SaveChanges(); try { Helpers.EmailHelper.SendEmail(User.Email, User.UserName, User.Password); } catch { } return(new { Id = 1, Status = User.IsActive }); } }
public override void OnActionExecuting(HttpActionContext filterContext) { if (filterContext.Request.Headers.Authorization == null) { filterContext.Response = filterContext.Request.CreateResponse((new { AuthorizeStatus = HttpStatusCode.Unauthorized, ReasonPhrase = "Token Validation Failed", Code = HttpStatusCode.Unauthorized, Version = HttpVersion.Version10 })); } else { if (filterContext.Request.Headers.Authorization.Scheme.ToLower().Contains(Token)) { var tokenValue = filterContext.Request.Headers.Authorization.Parameter; if (tokenValue != null) { LystenEntities _db = new LystenEntities(); var chkToken = _db.AppAccessTokens.AsEnumerable().Where(top => top.AuthToken == Token).FirstOrDefault(); if (checkToken(tokenValue)) { } else { filterContext.Response = filterContext.Request.CreateResponse((new { AuthorizeStatus = HttpStatusCode.Unauthorized, ReasonPhrase = "Token Validation Failed", Code = HttpStatusCode.Unauthorized, Version = HttpVersion.Version10 })); } } } else { filterContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Token Not Sent", StatusCode = HttpStatusCode.Unauthorized, Version = HttpVersion.Version10 }; } } base.OnActionExecuting(filterContext); }
public void sendMsgUser(int GroupId, bool Check, string devicetocken, string Body, string groupname, string senderfullname) { 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) { Console.WriteLine("Authentication failed"); client.Close(); 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; strmsgbody = senderfullname + " sent a message in " + groupname + "."; Debug.WriteLine("during testing via device!"); System.Web.HttpContext.Current.Server.MapPath("APNSduringdevice.txt"); string ImagePath = ""; string Name = ""; string baseURL = HttpContext.Current.Request.Url.Authority; baseURL += (WebConfigurationManager.AppSettings["groupimagepath"]).Replace("~", ""); bool IsMember = false; bool IsOwner = false; string GroupIdString = ""; payload = "{\"aps\":{\"alert\":\"" + strmsgbody + "\",\"badge\":" + totunreadmsg.ToString() + ",\"sound\":\"mailsent.wav\"},\"nav\":{\"type\":\"" + Check.ToString() + "\",\"typeID\":" + GroupIdString + ",\"image\":\"" + ImagePath + "\",\"name\":\"" + name + "\",\"IsMember\":\"" + IsMember.ToString() + "\",\"IsOwner\":\"" + IsOwner.ToString() + "\"},\"acme1\":\"bar\",\"acme2\":42}"; if (Check) { using (LystenEntities db = new LystenEntities()) { Group G = db.Groups.Where(x => x.Id == GroupId).FirstOrDefault(); if (G != null) { if (G.Image != null) { ImagePath = G.Image = baseURL + G.Image; name = G.Name; } } var obj = db.User_Master.Where(x => x.DeviceToken == devicetocken).FirstOrDefault(); if (obj != null) { var data = db.UserGroupMappings.Where(x => x.GroupId == GroupId && x.UserId == obj.Id).FirstOrDefault(); if (data != null) { IsMember = true; IsOwner = false; } else { if (G.CreatorId == obj.Id) { IsMember = true; IsOwner = true; } } } GroupIdString = Convert.ToString(G.Id); payload = "{\"aps\":{\"alert\":\"" + strmsgbody + "\",\"badge\":" + totunreadmsg.ToString() + ",\"sound\":\"mailsent.wav\"},\"nav\":{\"type\":\"" + Check.ToString() + "\",\"typeID\":" + GroupIdString + ",\"image\":\"" + ImagePath + "\",\"name\":\"" + G.Name + "\",\"IsMember\":\"" + IsMember.ToString() + "\",\"IsOwner\":\"" + IsOwner.ToString() + "\"},\"acme1\":\"bar\",\"acme2\":42}"; } } //else //{ // GroupIdString = Convert.ToString(GroupId); // Exception ex = new Exception("Testing 1"); // CommonServices.ErrorLogging(ex); // baseURL = HttpContext.Current.Request.Url.Authority; // baseURL += (WebConfigurationManager.AppSettings["userimagepath"]).Replace("~", ""); // using (LystenEntities db = new LystenEntities()) // { // Exception ex2 = new Exception("Testing 2"); // CommonServices.ErrorLogging(ex2); // 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(); // Exception ex23asdasd2 = new Exception(name); // CommonServices.ErrorLogging(ex23asdasd2); // Exception ex232 = new Exception("Testing 3"); // CommonServices.ErrorLogging(ex232); // } // payload = "{\"aps\":{\"alert\":\"" + strmsgbody + "\",\"badge\":" + totunreadmsg.ToString() + ",\"sound\":\"mailsent.wav\"},\"nav\":{\"type\":\"" + Check.ToString() + "\",\"typeID\":" + GroupIdString + ",\"image\":\"" + ImagePath + "\",\"name\":\"" + name + "\",\"IsMember\":\"" + ImagePath + "\",\"IsOwner\":\"" + 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(); Debug.WriteLine("This is being sent...\n\n"); Debug.WriteLine(array); try { sslStream.Write(array); sslStream.Flush(); } catch { Debug.WriteLine("Write failed buddy!!"); System.Web.HttpContext.Current.Server.MapPath("Writefailed.txt"); } client.Close(); Debug.WriteLine("Client closed."); System.Web.HttpContext.Current.Server.MapPath("APNSSuccess.txt"); }
public override void OnOpen() { try { clients.Add(this); if (this.WebSocketContext.RequestUri.Query.Split(',')[1].Split(':').Contains("GroupId")) { var GroupId = this.WebSocketContext.RequestUri.Query.Split(',')[1].Split(':')[1]; var UserId = this.WebSocketContext.RequestUri.Query.Split(',')[0].Split(':')[1]; using (LystenEntities db = new LystenEntities()) { int gid = Convert.ToInt32(GroupId); int uid = Convert.ToInt32(UserId); //var obj = db.Groups.Where(x => x.Id == gid).FirstOrDefault(); //if (obj.GroupTypeId == 1) //{ // if (!db.Groups.Any(x => x.CreatorId == uid && x.Id == gid)) // { // if (!db.UserGroupMappings.Any(x => x.UserId == uid && x.GroupId == gid)) // { // UserGroupMapping ugm = new UserGroupMapping() // { // GroupId = gid, // UserId = uid // }; // db.UserGroupMappings.Add(ugm); // db.SaveChanges(); // } // } //} WebSocketSessionDb webs = new WebSocketSessionDb(); if (db.WebSocketSessionDbs.Any(x => x.GroupID == gid && x.UserId == uid)) { webs = db.WebSocketSessionDbs.Where(x => x.GroupID == gid && x.UserId == uid).FirstOrDefault(); webs.GroupID = Convert.ToInt32(GroupId); webs.UserId = Convert.ToInt32(UserId); webs.SessionId = this.WebSocketContext.SecWebSocketKey; db.Entry(webs).State = EntityState.Modified; db.SaveChanges(); } else { webs.GroupID = Convert.ToInt32(GroupId); webs.UserId = Convert.ToInt32(UserId); webs.SessionId = this.WebSocketContext.SecWebSocketKey; db.WebSocketSessionDbs.Add(webs); db.SaveChanges(); } } } else { var ReceiptionId = this.WebSocketContext.RequestUri.Query.Split(',')[1].Split(':')[1]; var UserId = this.WebSocketContext.RequestUri.Query.Split(',')[0].Split(':')[1]; using (LystenEntities db = new LystenEntities()) { int rid = Convert.ToInt32(ReceiptionId); int uid = Convert.ToInt32(UserId); WebSocketSessionDb webs = new WebSocketSessionDb(); if (db.WebSocketSessionDbs.Any(x => x.RecipientId == rid && x.UserId == uid)) { webs = db.WebSocketSessionDbs.Where(x => x.RecipientId == rid && x.UserId == uid).FirstOrDefault(); webs.RecipientId = Convert.ToInt32(rid); webs.UserId = Convert.ToInt32(UserId); webs.SessionId = this.WebSocketContext.SecWebSocketKey; db.Entry(webs).State = EntityState.Modified; db.SaveChanges(); } else { webs.RecipientId = Convert.ToInt32(rid); webs.UserId = Convert.ToInt32(UserId); webs.SessionId = this.WebSocketContext.SecWebSocketKey; db.WebSocketSessionDbs.Add(webs); db.SaveChanges(); } } } } catch (Exception ex) { CommonServices.ErrorLogging(ex); } }
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); } }
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); } }
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); } }
public dynamic getinboxmessage(int UserId, int Count) { int skip = Count * 10; MainInboxMessageModel Minbox = new MainInboxMessageModel(); List <InboxMessageModel> InboxUser = new List <InboxMessageModel>(); string baseURL = HttpContext.Current.Request.Url.Authority; baseURL += (WebConfigurationManager.AppSettings["userimagepath"]).Replace("~", ""); var TotalCount = 0; using (LystenEntities db = new LystenEntities()) { var userdataTimeZone = db.User_Master.Where(x => x.Id == UserId).Select(x => x.TimeZone).FirstOrDefault(); List <int> Ids = new List <int>(); var obj = db.MessageRequests.Where(x => x.FromUserId == UserId || x.ToUserId == UserId).ToList(); foreach (var item in obj) { if (!Ids.Contains(item.ToUserId.Value) && item.ToUserId.Value != UserId) { Ids.Add(item.ToUserId.Value); } if (!Ids.Contains(item.FromUserId.Value) && item.FromUserId.Value != UserId) { Ids.Add(item.FromUserId.Value); } } if (obj.Count > 0) { TotalCount = Ids.ToList().Count; var data = Ids.ToList().Skip(skip).Take(10); foreach (var item in data) { //var obj123 = db.MessageRecipients.Where(x => x.RecipientId == UserId || x.Message.CreatorId == UserId && x.RecipientGroupId == null).Select(x => new { x.User_Master.UserName }).OrderBy(x => x.UserName).ToList(); var newdatttt = db.User_Master.Where(x => x.Id == item).FirstOrDefault(); var datess = db.MessageRecipients.Where(x => x.User_Master.Id == UserId && x.Message.CreatorId == item || x.User_Master.Id == item && x.Message.CreatorId == UserId).OrderByDescending(x => x.Id).Select(x => x.Message.CreatedDate.Value).FirstOrDefault(); InboxMessageModel newModel = new InboxMessageModel() { Id = newdatttt.Id, Image = US.GetFavouriteImage(baseURL, newdatttt.Id), CreatorName = newdatttt.FullName == null ? "" : newdatttt.FullName, IsAccept = db.MessageRequests.Where(t => t.FromUserId == UserId && t.ToUserId == item || t.FromUserId == item && t.ToUserId == UserId).FirstOrDefault() == null ? false : db.MessageRequests.Where(t => t.FromUserId == UserId && t.ToUserId == item || t.FromUserId == item && t.ToUserId == UserId).Select(y => y.IsAccept).FirstOrDefault(), IsReject = db.MessageRequests.Where(t => t.FromUserId == UserId && t.ToUserId == item || t.FromUserId == item && t.ToUserId == UserId).FirstOrDefault() == null ? false : db.MessageRequests.Where(t => t.FromUserId == UserId && t.ToUserId == item || t.FromUserId == item && t.ToUserId == UserId).Select(y => y.IsReject).FirstOrDefault(), IsRequested = db.MessageRequests.Where(t => t.FromUserId == UserId && t.ToUserId == item || t.FromUserId == item && t.ToUserId == UserId).FirstOrDefault() == null ? false : db.MessageRequests.Where(t => t.FromUserId == UserId && t.ToUserId == item || t.FromUserId == item && t.ToUserId == UserId).Select(y => y.IsRequested).FirstOrDefault(), //CreatedDate = db1.CreatedDate.Value.Date == DateTime.Now.Date ? "Today " + Convert.ToDateTime((db1.CreatedDate)).ToString("HH:mm") : Convert.ToDateTime((db1.CreatedDate)).ToString("dd MMM, yyyy HH:mm"), CreatedDate = datess == null ? System.DateTime.UtcNow : datetimeset(userdataTimeZone, datess), //CreatedDate = datess.Date == DateTime.Now.Date ? "Today " + Convert.ToDateTime((datess)).ToString("HH:mm") : Convert.ToDateTime(datess).ToString("dd MM yyyy HH:mm"), Message = db.MessageRecipients.Where(x => x.User_Master.Id == UserId && x.Message.CreatorId == item || x.User_Master.Id == item && x.Message.CreatorId == UserId).OrderByDescending(x => x.Id).Select(x => x.Message.Body).FirstOrDefault() == null ? "" : db.MessageRecipients.Where(x => x.User_Master.Id == UserId && x.Message.CreatorId == item || x.User_Master.Id == item && x.Message.CreatorId == UserId).OrderByDescending(x => x.Id).Select(x => x.Message.Body).FirstOrDefault(), IsWaiting = false }; var data123 = db.MessageRequests.Where(t => t.FromUserId == UserId && t.ToUserId == item).FirstOrDefault(); if (data123 == null) { if (newModel.IsAccept.Value) { newModel.IsRequested = false; newModel.IsWaiting = false; } else if (newModel.IsReject.Value) { newModel.IsRequested = false; newModel.IsWaiting = false; } else { newModel.IsRequested = true; newModel.IsWaiting = false; } } else { newModel.IsRequested = false; newModel.IsWaiting = true; } InboxUser.Add(newModel); } } } Minbox.InboxUser = InboxUser; Minbox.TotalCount = TotalCount; return(Minbox); }
public 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()) { 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; string strmsgbody = ""; int totunreadmsg = 20; string Checkbool = ""; //if (IsAccept==1) //{ // Checkbool = "Accrpted"; //} //else //{ // Checkbool = "Rejected"; //} //strmsgbody = "Call request has been" + Checkbool; //payload = "{\"aps\":{\"alert\":\"" + strmsgbody + "\",\"badge\":" + totunreadmsg.ToString() + ",\"sound\":\"mailsent.wav\"},\"call\":{\"CallType\":\"" + IsAccept.ToString() == "1" ? "1" : "2" + "\",\"name\":\"" + name + "\"},\"acme1\":\"bar\",\"acme2\":42}"; if (IsAccept == 1) { Checkbool = "Accepted"; } else { Checkbool = "Rejected"; } strmsgbody = "Message request has been " + Checkbool; payload = "{\"aps\":{\"alert\":\"" + strmsgbody + "\",\"badge\":" + totunreadmsg.ToString() + ",\"sound\":\"mailsent.wav\"},\"inbox\":{},\"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 dynamic getalleventsbyCategoryId(int CategoryId, int Count, string Search, string Location) { using (LystenEntities db = new LystenEntities()) { if (Location == null) { Location = ""; } int skip = Count * 10; string baseURL = HttpContext.Current.Request.Url.Authority; baseURL += (WebConfigurationManager.AppSettings["eventimagepath"]).Replace("~", ""); if (Search == "" || Search == null) { if (Location == "") { var obj = (from dbs in db.Events where dbs.IsActive == true && dbs.CategoryId == CategoryId select dbs).OrderBy(x => x.CreatedDate).Skip(skip).Take(10).ToList(); return((from dbs in obj select new EventViewModel() { Id = dbs.Id, Description = dbs.Description, CategoryName = dbs.Category.Name, Location = dbs.Location, CreatedDate = string.Format("{0:f}", dbs.CreatedDate), Image = dbs.Image == null ? "" : dbs.Image == "" ? "" : baseURL + dbs.Image, Title = dbs.Title, CategoryId = dbs.CategoryId.Value, }).ToList()); } else { var obj = (from dbs in db.Events where dbs.IsActive == true && dbs.CategoryId == CategoryId select dbs).Where(x => x.Location.ToLower().Contains(Location.ToLower())).OrderBy(x => x.CreatedDate).Skip(skip).Take(10).ToList(); return((from dbs in obj select new EventViewModel() { Id = dbs.Id, Description = dbs.Description, CategoryName = dbs.Category.Name, Location = dbs.Location, CreatedDate = string.Format("{0:f}", dbs.CreatedDate), Image = dbs.Image == null ? "" : dbs.Image == "" ? "" : baseURL + dbs.Image, Title = dbs.Title, CategoryId = dbs.CategoryId.Value, }).ToList()); } } else { if (Location == "") { var obj = (from dbs in db.Events where dbs.IsActive == true && dbs.CategoryId == CategoryId select dbs).OrderBy(x => x.CreatedDate).Skip(skip).Take(10).Where(x => x.Title.ToLower().Contains(Search.ToLower()) || x.Description.ToLower().Contains(Search.ToLower())).ToList(); return((from dbs in obj select new EventViewModel() { Id = dbs.Id, Description = dbs.Description, CategoryName = dbs.Category.Name, Location = dbs.Location, CreatedDate = string.Format("{0:f}", dbs.CreatedDate), Image = dbs.Image == null ? "" : dbs.Image == "" ? "" : baseURL + dbs.Image, Title = dbs.Title, CategoryId = dbs.CategoryId.Value }).ToList()); } else { var obj = (from dbs in db.Events where dbs.IsActive == true && dbs.CategoryId == CategoryId select dbs).Where(x => x.Location.ToLower().Contains(Location.ToLower())).OrderByDescending(x => x.CreatedDate).Skip(skip).Take(10).Where(x => x.Title.ToLower().Contains(Search.ToLower()) || x.Description.ToLower().Contains(Search.ToLower())).ToList(); return((from dbs in obj select new EventViewModel() { Id = dbs.Id, Description = dbs.Description, CategoryName = dbs.Category.Name, Location = dbs.Location, CreatedDate = string.Format("{0:f}", dbs.CreatedDate), Image = dbs.Image == null ? "" : dbs.Image == "" ? "" : baseURL + dbs.Image, CategoryId = dbs.CategoryId.Value, Title = dbs.Title }).ToList()); } } } }
public dynamic getallevents(int Count, string Search) { using (LystenEntities db = new LystenEntities()) { int skip = Count * 10; string baseURL = HttpContext.Current.Request.Url.Authority; baseURL += (WebConfigurationManager.AppSettings["eventimagepath"]).Replace("~", ""); var data = db.Categories.Where(x => x.IsActive == true).OrderBy(x => x.Name).Skip(skip).Take(10).ToList(); List <EventMainModel> MainEMM = new List <EventMainModel>(); if (Search == "" || Search == null) { foreach (var item in data) { EventMainModel EMM = new EventMainModel(); var obj = (from dbs in db.Events where dbs.IsActive == true && dbs.CategoryId == item.Id select dbs).OrderByDescending(x => x.CreatedDate).FirstOrDefault(); if (obj != null) { EMM.Title = obj.Title == null ? "" : obj.Title; EMM.Id = obj.Id; EMM.Description = obj.Description == null ? "" : obj.Description; EMM.Location = obj.Location == null ? "" : obj.Location; EMM.CreatedDate = string.Format("{0:f}", obj.CreatedDate); EMM.Image = obj.Image == null ? "" : obj.Image == "" ? "" : baseURL + obj.Image; EMM.CategoryName = item.Name == null ? "" : item.Name; EMM.CategoryId = item.Id; EMM.CategoryImageForEvent = getcategoryimageforevent(item.Id); } else { EMM.Title = ""; EMM.Id = 0; EMM.Description = ""; EMM.Location = ""; EMM.CreatedDate = ""; EMM.Image = ""; EMM.CategoryName = item.Name == null ? "" : item.Name; EMM.CategoryId = item.Id; EMM.CategoryImageForEvent = getcategoryimageforevent(item.Id); } MainEMM.Add(EMM); } return(MainEMM); } else { foreach (var item in data) { EventMainModel EMM = new EventMainModel(); var obj = (from dbs in db.Events where dbs.IsActive == true && dbs.CategoryId == item.Id select dbs).OrderByDescending(x => x.CreatedDate).Where(x => x.Title.ToLower().Contains(Search.ToLower()) || x.Description.ToLower().Contains(Search.ToLower())).FirstOrDefault(); if (obj != null) { EMM.Title = obj.Title == null ? "" : obj.Title; EMM.Id = obj.Id; EMM.Description = obj.Description == null ? "" : obj.Description; EMM.Location = obj.Location == null ? "" : obj.Location; EMM.CreatedDate = string.Format("{0:f}", obj.CreatedDate); EMM.Image = obj.Image == null ? "" : obj.Image == "" ? "" : baseURL + obj.Image; EMM.CategoryName = item.Name == null ? "" : item.Name; EMM.CategoryId = item.Id; } else { EMM.Title = ""; EMM.Id = 0; EMM.Description = ""; EMM.Location = ""; EMM.CreatedDate = ""; EMM.Image = ""; EMM.CategoryName = item.Name == null ? "" : item.Name; EMM.CategoryId = item.Id; } MainEMM.Add(EMM); } return(MainEMM); } } }
public async Task <ResultClass> newRegisterUser(User_Master um) { using (LystenEntities db = new LystenEntities()) { if (string.IsNullOrEmpty(um.Password)) { um.Password = um.UserName + "@2018"; } var pwd = SecutiryServices.EncodePasswordToBase64(um.Password); var result = (from um23 in db.User_Master where um23.Email.ToUpper() == um.Email.ToUpper() && um23.Password == pwd select um23 ).FirstOrDefault(); um.Password = pwd; var model = new { }; if (result != null) { objresult.Code = (int)HttpStatusCode.Found; objresult.Msg = ap.UserEMailExist; objresult.Data = model; } else { if (db.User_Master.Any(x => x.UserName.ToLower().Trim() == um.UserName.ToLower().Trim())) { objresult.Code = (int)HttpStatusCode.Found; objresult.Msg = ap.UserNameExist; objresult.Data = model; (objresult.AccessToken) = ""; return(objresult); } um.Displayname = um.FullName; um.DeviceType = um.DeviceType; um.IsLogin = true; um.IsDisclaimer = false; um.RoleId = um.RoleId; um.PostalCode = um.PostalCode; um.Skill = um.Skill; um.SSN = um.SSN; um.IsVerified = false; um.DateOfBirth = um.DateOfBirth; um.TimeZone = um.TimeZone; um.Address = um.Address; um.CityId = um.CityId; um.StateId = um.StateId; um.CountryId = um.CountryId; db.User_Master.Add(um); db.SaveChanges(); objresult.Code = (int)HttpStatusCode.OK; objresult.Msg = ap.Success; objresult.Data = AutoMapper.Mapper.Map <UserViewModel>(um); objresult.Data.Favourite = new List <ProfileFavourite>() { }; } (objresult.AccessToken) = ""; if (objresult.Code == (int)HttpStatusCode.OK) { TokenDetails objToken = await generatToken(um.Email, um.Password, um.DeviceToken); (objresult.AccessToken) = objToken.access_token; var obj = AutoMapper.Mapper.Map <UserViewModel>(objresult.Data); Add_UpdateToken(obj.Id, objToken, 1, um.DeviceType); } return(objresult); } }
public object AddUserToGroup(UserGroupViewModel gVM) { List <MessageModel> Messages = new List <MessageModel>(); using (LystenEntities db = new LystenEntities()) { UserGroupMapping UGM = new UserGroupMapping(); if (gVM.IsAdded == "1") { var obj = gVM.UsersId.Split(','); foreach (var item in obj) { int id = Convert.ToInt32(item); if (!db.UserGroupMappings.Any(x => x.UserId == id && x.GroupId == gVM.GroupId)) { UGM = new UserGroupMapping() { GroupId = gVM.GroupId, UserId = Convert.ToInt16(item) }; db.UserGroupMappings.Add(UGM); db.SaveChanges(); var group = db.Groups.Where(x => x.Id == gVM.GroupId).FirstOrDefault(); var userdetail = db.User_Master.Where(x => x.Id == UGM.UserId).FirstOrDefault(); if (group.GroupTypeId == 2) { if (userdetail.DeviceToken != null && userdetail.DeviceToken != "") { if (userdetail.DeviceType == "Android") { Helpers.NotificationHelper.sendMsgGroup(userdetail.Id, userdetail.DeviceToken, group.User_Master.FullName, group.Name, group.Id); } else { sendMsgGroup(userdetail.Id, userdetail.DeviceToken, group.User_Master.FullName, group.Name); } } } } } } else if (gVM.IsAdded == "0") { var obj = gVM.UsersId.Split(','); foreach (var item in obj) { int id = Convert.ToInt32(item); if (db.UserGroupMappings.Any(x => x.UserId == id && x.GroupId == gVM.GroupId)) { UGM = db.UserGroupMappings.Where(x => x.UserId == id && x.GroupId == gVM.GroupId).FirstOrDefault(); if (UGM != null) { db.Entry(UGM).State = EntityState.Deleted; db.SaveChanges(); } } } } else if (gVM.IsAdded == "2") { var obj = gVM.UsersId.Split(','); foreach (var item in obj) { int id = Convert.ToInt32(item); if (db.UserGroupMappings.Any(x => x.UserId == id && x.GroupId == gVM.GroupId)) { UGM = db.UserGroupMappings.Where(x => x.UserId == id && x.GroupId == gVM.GroupId).FirstOrDefault(); if (UGM != null) { db.Entry(UGM).State = EntityState.Deleted; db.SaveChanges(); } } } foreach (var item in obj) { int id = Convert.ToInt32(item); var newgroupdata = db.UserGroupMappings.Where(x => x.GroupId == gVM.GroupId).Select(x => x.Id).ToList(); var msgRdata = db.MessageRecipients.Where(x => x.RecipientGroupId == gVM.GroupId).ToList(); if (msgRdata.Count > 0) { foreach (var itemss in msgRdata) { var msgdata = db.Messages.Where(x => x.Id == itemss.MessageId).FirstOrDefault(); if (msgdata != null) { db.Entry(msgdata).State = EntityState.Deleted; db.SaveChanges(); } var Mdata = db.MessageRecipients.Where(x => x.Id == itemss.Id).FirstOrDefault(); if (Mdata != null) { db.Entry(Mdata).State = EntityState.Deleted; db.SaveChanges(); } } } foreach (var itemss in newgroupdata) { UGM = db.UserGroupMappings.Where(x => x.Id == itemss).FirstOrDefault(); if (UGM != null) { db.Entry(UGM).State = EntityState.Deleted; db.SaveChanges(); } } if (db.WebSocketSessionDbs.Any(x => x.GroupID == gVM.GroupId)) { var websocket = db.WebSocketSessionDbs.Where(x => x.GroupID == gVM.GroupId).FirstOrDefault(); db.Entry(websocket).State = EntityState.Deleted; db.SaveChanges(); } if (db.Groups.Any(x => x.Id == gVM.GroupId && x.CreatorId == id)) { var objdata = db.Groups.Where(x => x.Id == gVM.GroupId && x.CreatorId == id).FirstOrDefault(); db.Entry(objdata).State = EntityState.Deleted; db.SaveChanges(); } } } return(UGM); } }
public dynamic GetCategoryList(int UserId) { List <GroupListViewModel> groupList = new List <GroupListViewModel>(); using (LystenEntities db = new LystenEntities()) { var categoryList = new List <GroupListViewModel>(); categoryList = db.UserCategoryMappings.Where(x => x.UserId == UserId).Select(x => new GroupListViewModel() { CategoryId = x.CategoryId == null ? 0 : x.CategoryId.Value, CategoryName = x.Category.Name, UserId = x.UserId == null ? 0 : x.UserId.Value, }).ToList(); string baseURL = HttpContext.Current.Request.Url.Authority; baseURL += (WebConfigurationManager.AppSettings["groupimagepath"]).Replace("~", ""); foreach (var category in categoryList) { List <GroupViewModel> model = new List <GroupViewModel>(); var allgroup = db.Groups.Where(x => x.GroupTypeId == 1 && x.IsActive == true).OrderByDescending(x => x.Id).ToList(); var group = db.Groups.Where(x => x.CategoryId == category.CategoryId && x.GroupTypeId == 2 && x.CreatorId == UserId && x.IsActive == true).OrderByDescending(x => x.Id).ToList(); if (group.Count == 0) { var data = db.UserGroupMappings.Where(x => x.Group.CategoryId == category.CategoryId && x.Group.GroupTypeId == 2 && x.UserId == UserId && x.Group.IsActive == true).OrderByDescending(x => x.GroupId).Select(x => x.Group).Distinct().ToList(); foreach (var item in data) { GroupViewModel groupmodel = new GroupViewModel(); if (item.CategoryId == category.CategoryId) { groupmodel.Id = item.Id; if (item.Image == null || item.Image == "") { groupmodel.Image = ""; } else { groupmodel.Image = baseURL + item.Image; } groupmodel.Name = item.Name == null ? "" : item.Name; groupmodel.CreatorId = Convert.ToString(item.CreatorId); groupmodel.GroupTypeId = Convert.ToString(item.GroupTypeId); groupmodel.CategoryId = Convert.ToString(item.CategoryId); groupmodel.IsOwner = 0; groupmodel.IsMember = 0; var obbbbb = db.UserGroupMappings.Where(x => x.GroupId == item.Id && x.UserId == UserId).FirstOrDefault(); if (obbbbb != null) { groupmodel.IsMember = 1; } if (item.CreatorId == UserId) { groupmodel.IsOwner = 1; } model.Add(groupmodel); } } } foreach (var item in group) { GroupViewModel groupmodel = new GroupViewModel(); if (item.CategoryId == category.CategoryId) { groupmodel.Id = item.Id; if (item.Image == null || item.Image == "") { groupmodel.Image = ""; } else { groupmodel.Image = baseURL + item.Image; } groupmodel.Name = item.Name == null ? "" : item.Name; groupmodel.CreatorId = Convert.ToString(item.CreatorId); groupmodel.GroupTypeId = Convert.ToString(item.GroupTypeId); groupmodel.CategoryId = Convert.ToString(item.CategoryId); groupmodel.IsOwner = 0; groupmodel.IsMember = 0; var obbbbb = db.UserGroupMappings.Where(x => x.GroupId == item.Id && x.UserId == UserId).FirstOrDefault(); if (obbbbb != null) { groupmodel.IsMember = 1; } if (item.CreatorId == UserId) { groupmodel.IsOwner = 1; groupmodel.IsMember = 1; } model.Add(groupmodel); } } foreach (var item in allgroup) { GroupViewModel groupmodel = new GroupViewModel(); if (item.CategoryId == category.CategoryId) { groupmodel.Id = item.Id; if (item.Image == null || item.Image == "") { groupmodel.Image = ""; } else { groupmodel.Image = baseURL + item.Image; } groupmodel.Name = item.Name == null ? "" : item.Name; groupmodel.CreatorId = Convert.ToString(item.CreatorId); groupmodel.GroupTypeId = Convert.ToString(item.GroupTypeId); groupmodel.CategoryId = Convert.ToString(item.CategoryId); groupmodel.IsOwner = 0; groupmodel.IsMember = 0; var obbbbb = db.UserGroupMappings.Where(x => x.GroupId == item.Id && x.UserId == UserId).FirstOrDefault(); if (obbbbb != null) { groupmodel.IsMember = 1; } if (item.CreatorId == UserId) { groupmodel.IsOwner = 1; groupmodel.IsMember = 1; } model.Add(groupmodel); } } category.GroupList = new List <GroupViewModel>(); category.GroupList = model; } groupList = categoryList; } return(groupList.Select(x => new { UserId = UserId, Category = groupList }).FirstOrDefault()); }
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 dynamic messagerequest(MessageRequestModel MM) { using (LystenEntities db = new LystenEntities()) { MessageRequest MR = new MessageRequest(); if (db.MessageRequests.Any(x => x.FromUserId == MM.MRUserId && x.ToUserId == MM.UserId || x.FromUserId == MM.UserId && x.ToUserId == MM.MRUserId)) { MR = db.MessageRequests.Where(x => x.FromUserId == MM.MRUserId && x.ToUserId == MM.UserId || x.FromUserId == MM.UserId && x.ToUserId == MM.MRUserId).FirstOrDefault(); if (MM.IsAccept == 0) { MR.IsAccept = false; MR.IsReject = true; MR.IsRequested = false; db.Entry(MR).State = EntityState.Modified; db.SaveChanges(); if (MR.User_Master.DeviceToken != null) { if (MR.User_Master.DeviceType == "Android") { Helpers.NotificationHelper.sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master.DeviceToken); } else { sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master.DeviceToken); } } else if (MR.User_Master1.DeviceToken != null) { if (MR.User_Master1.DeviceType == "Android") { Helpers.NotificationHelper.sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master1.DeviceToken); } else { sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master1.DeviceToken); } } } else { MR.IsAccept = true; MR.IsReject = false; MR.IsRequested = false; db.Entry(MR).State = EntityState.Modified; db.SaveChanges(); if (MR.User_Master.DeviceToken != null) { if (MR.User_Master.DeviceType == "Android") { Helpers.NotificationHelper.sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master.DeviceToken); } else { sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master.DeviceToken); } } else if (MR.User_Master1.DeviceToken != null) { if (MR.User_Master1.DeviceType == "Android") { Helpers.NotificationHelper.sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master1.DeviceToken); } else { sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master1.DeviceToken); } } } } else { if (MM.IsAccept == 0) { MR.FromUserId = MM.MRUserId; MR.ToUserId = MM.UserId; MR.IsAccept = false; MR.IsReject = true; MR.IsRequested = false; db.MessageRequests.Add(MR); db.SaveChanges(); if (MR.User_Master.DeviceToken != null) { if (MR.User_Master.DeviceType == "Android") { Helpers.NotificationHelper.sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master.DeviceToken); } else { sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master.DeviceToken); } } else if (MR.User_Master1.DeviceToken != null) { if (MR.User_Master1.DeviceType == "Android") { Helpers.NotificationHelper.sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master1.DeviceToken); } else { sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master1.DeviceToken); } } } else { MR.FromUserId = MM.MRUserId; MR.ToUserId = MM.UserId; MR.IsAccept = false; MR.IsReject = true; MR.IsRequested = false; db.MessageRequests.Add(MR); db.SaveChanges(); if (MR.User_Master.DeviceToken != null) { if (MR.User_Master.DeviceType == "Android") { Helpers.NotificationHelper.sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master.DeviceToken); } else { sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master.DeviceToken); } } else if (MR.User_Master1.DeviceToken != null) { if (MR.User_Master1.DeviceType == "Android") { Helpers.NotificationHelper.sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master1.DeviceToken); } else { sendMsgCallAccept(0, MR.ToUserId.Value, MR.User_Master1.DeviceToken); } } } } return(MR); } }
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 { } }
public static bool SendEmail(string Email, string UserName, string Password) { using (LystenEntities db = new LystenEntities()) { try { var template = db.EmailTemplates.Where(x => x.SystemName == "system.account.verification").FirstOrDefault(); var emailaccount = db.EmailAccounts.FirstOrDefault(); var _password = SecutiryServices.DecodeFrom64(Password); MailMessage mailMsg = new MailMessage(); mailMsg.To.Add(new MailAddress(Email, "")); mailMsg.From = new MailAddress(emailaccount.EmailId, "Lysten"); //mailMsg.To.Add(new MailAddress(Email, "Mitaja Corp.")); //mailMsg.From = new MailAddress("*****@*****.**", "Mitaja Corp."); mailMsg.Subject = template.Subject; string body = template.Body; body = body.Replace("{Username}", UserName); body = body.Replace("{Password}", _password); mailMsg.IsBodyHtml = true; mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html)); SmtpClient smtpClient = new SmtpClient(emailaccount.SMTPRelay, Convert.ToInt32(emailaccount.Port)); System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(emailaccount.EmailId, emailaccount.Password); smtpClient.Credentials = credentials; smtpClient.EnableSsl = Convert.ToBoolean(emailaccount.EnableSSL); ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; smtpClient.Send(mailMsg); } catch (Exception ex) { throw ex; } } //try //{ // MailMessage mailMsg = new MailMessage(); // mailMsg.To.Add(new MailAddress(Email, UserName)); // mailMsg.From = new MailAddress("*****@*****.**", "Lysten"); // //mailMsg.To.Add(new MailAddress(Email, "Mitaja Corp.")); // //mailMsg.From = new MailAddress("*****@*****.**", "Mitaja Corp."); // mailMsg.Subject = "Account Verified"; // string body = ""; // body = "--> Thank you for registering as Service Provider with Lysten. Please login with your below credentials: <br/><br/>"; // body=body+ "<br/>UserName: "******"<br/>Password: "******"<br/>If you have any questions, please contact us xxxx @xx.com"; // body = body + "<br/>Registration confirmation email should be sent to the service provider once admin will approve the user from the admin panel."; // body = body + "<br/>Random password for the service provider should be generate and will pass in the email."; // mailMsg.IsBodyHtml = true; // mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html)); // SmtpClient smtpClient = new SmtpClient("*****@*****.**", 465); // System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("*****@*****.**", "Testing.Mitaja1"); // smtpClient.Credentials = credentials; // smtpClient.EnableSsl = true; // ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) // { return true; }; // smtpClient.Send(mailMsg); //} //catch //{ //} return(true); }
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(); }
public dynamic SaveUser(UserModel objUM) { using (LystenEntities db = new LystenEntities()) { if (objUM.Id > 0) { var user = db.User_Master.Where(x => x.Id == objUM.Id).FirstOrDefault(); var sendflag = false; if (user.Password != objUM.Password) { sendflag = true; } //user.Email = objUM.Email; user.Password = objUM.Password; user.Address = objUM.Address; user.CountryId = objUM.Country; user.StateId = objUM.State; user.CityId = objUM.City; user.Phone = objUM.Phone; user.Mobile = objUM.Mobile; user.Displayname = objUM.Displayname; user.IsActive = true; user.Modifydate = System.DateTime.Now; db.Entry(user).State = EntityState.Modified; db.SaveChanges(); if (sendflag == true) { ES.SendToUser(user); } return(new { Id = user.Id, Status = "Update" }); } else { if (db.User_Master.Any(x => x.Email == (objUM.Email).Trim())) { objUM.Id = db.User_Master.Where(x => x.Email == (objUM.Email).Trim()).Select(x => x.Id).FirstOrDefault(); return(new { Id = objUM.Id, Status = "Exists" }); } else { User_Master user = new User_Master(); user.Email = objUM.Email; user.Password = objUM.Password; user.Address = objUM.Address; user.CountryId = objUM.Country; user.StateId = objUM.State; user.CityId = objUM.City; user.Phone = objUM.Phone; user.Mobile = objUM.Mobile; user.Displayname = objUM.Displayname; user.IsActive = true; user.Createdate = System.DateTime.Now; user.Modifydate = System.DateTime.Now; user.Createdby = 1; db.User_Master.Add(user); db.SaveChanges(); ES.SendToUser(user); return(new { Id = user.Id, Status = "Insert" }); } } } }
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; }