public IActionResult SendMessage(long id, [FromBody] MessagePost message)
        {
            User current = new UserController(_context, _configuration).GetCurrentUser(HttpContext.User);
            User second  = _context.Users.Find(id);

            if (second == null)
            {
                return(BadRequest("No user with such id"));
            }
            if (!(current.Dialogues.Contains(second) && second.Dialogues.Contains(current)))
            {
                return(Conflict());
            }

            _context.Messages.Add(new Message
            {
                Content   = message.Content,
                Date      = DateTime.Now,
                IsRead    = false,
                Sender    = current,
                Recipient = second,
            });
            _context.SaveChanges();

            return(Ok());
        }
        public override Task OnConnected()
        {
            //Interlocked.Increment(ref _usersCount);

            User user = db.Users.First(r => r.Email == HttpContext.Current.User.Identity.Name);

            user.ConnectionId    = Context.ConnectionId;
            db.Entry(user).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();

            return(base.OnConnected());
        }
Example #3
0
 public int Create(Chat chat)
 {
     db.Chats.Add(chat);
     db.SaveChanges();
     //TODO: ↑
     return(chat.Id);
 }
 public static void Initialize()
 {
     using (MessengerContext db = new MessengerContext())
     {
         db.Database.Initialize(false);
         db.SaveChanges();
     }
 }
Example #5
0
        public IActionResult Signup([FromBody] UserSignup signupForm)
        {
            if (_context.Users.Any(u => u.UserName == signupForm.UserName))
            {
                return(BadRequest("Username is busy"));
            }
            string hashedPassword = GetHash(signupForm.Password);

            _context.Users.Add(new User
            {
                UserName = signupForm.UserName,
                Name     = signupForm.Name,
                Password = hashedPassword,
            });
            _context.SaveChanges();

            return(Ok());
        }
Example #6
0
        public ActionResult Create([Bind(Include = "UserId,UserName,UserEmail,UserPassword,UserImage")] User user, HttpPostedFileBase file)
        {
            if (file != null)
            {
                string pic = System.IO.Path.GetFileName(file.FileName);
                // string path = System.IO.Path.Combine(Server.MapPath("~/images/profile"), pic);
                //  file.SaveAs(pic);

                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    file.InputStream.CopyTo(ms);
                    user.UserImage = ms.GetBuffer();
                }
            }
            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();
                return(RedirectToAction("Login"));
            }

            return(View(user));
        }
 public bool DeleteMessage(int mailID)
 {
     using (var db = new MessengerContext())
     {
         var  mails = from u in db.Mails where u.Id == mailID select u;
         Mail mail  = mails.FirstOrDefault();
         db.Mails.Remove(mail);
         int i = db.SaveChanges();
         if (i == 1)
         {
             return(true);
         }
     }
     return(false);
 }
Example #8
0
        CreateMessageAsync(Messages message)
        {
            if (string.IsNullOrWhiteSpace(message.Topic) ||
                string.IsNullOrWhiteSpace(message.Message) ||
                string.IsNullOrWhiteSpace(message.Receiver) ||
                string.IsNullOrWhiteSpace(message.Sender))
            {
                throw new Exception("One or more fields are empty for sending a message.");
            }

            if (message.Topic.Length > 30)
            {
                throw new Exception("The topic must not be longer than 30 characters.");
            }
            _messageContext.Messages.Add(message);
            _messageContext.SaveChanges();
        }
Example #9
0
        public void SendMessage(ViewMessage message)
        {
            using (MessengerContext context = new MessengerContext())
            {
                message.DispatchTime = DateTime.Now;
                Message m = (Message)message;
                context.Messages.Add(m);
                context.SaveChanges();
            }

            int groupId = message.GroupId;
            List <ViewMessage> messages = GetMessages(groupId);

            _clients.Where(c => c.Value.Groups
                           .FirstOrDefault(g => g.GroupId == groupId) != null)
            .ToList().ForEach(a => a.Key.Send(groupId, messages));
        }
        private void DoConnect()
        {
            string login    = Context.Request.Headers["login"];
            string password = Context.Request.Headers["password"];
            User   user     = null;

            using (var db = new MessengerContext())
            {
                var login_qout    = string.Format(@"""{0}""", login);
                var password_qout = string.Format(@"""{0}""", password);

                var users = db.Users.SqlQuery("select * from  messengerbd.users where binary Login = "******"  and binary  Password = "******"";
                        user_to_result.Login    = "";
                        Clients.Others.singedIn(user_to_result);
                        Clients.Caller.singIn(user);
                        FromUsers.TryAdd(Context.ConnectionId, userName);
                        ToUsers.TryAdd(userName, Context.ConnectionId);
                    }
                    else
                    {
                        Clients.Caller.Exception("error in db when change status");
                    }
                }
                else
                {
                    string firstName = Context.Request.Headers["first_name"];
                    string LastName  = Context.Request.Headers["last_name"];
                    if (firstName == null && LastName == null)
                    {
                        Clients.Caller.singIn(null);
                    }
                    addNewUser(firstName, login, password, LastName);
                }
            }
        }
Example #11
0
        public void SaveImage(Image image)
        {
            Image dbEntry = _context.Image
                            .FirstOrDefault(p => p.Id == image.Id);

            if (dbEntry != null)
            {
                dbEntry.UserID     = image.UserID;
                dbEntry.ImageData  = image.ImageData;
                dbEntry.ImageTitle = image.ImageTitle;
            }
            else
            {
                _context.Image.Add(image);
            }

            _context.SaveChanges();
        }
 //
 // GET: /Home/
 public bool NewMessage(int senderID, int receiverID, string Text)
 {
     using (var db = new MessengerContext())
     {
         var sender        = from u in db.Users where u.Id == senderID select u;
         var receiver      = from u in db.Users where u.Id == receiverID select u;
         var sender_user   = sender.FirstOrDefault();
         var receiver_user = receiver.FirstOrDefault();
         if (sender_user != null && receiver_user != null)
         {
             var mes = new Mail {
                 receiver = receiver_user, sender = sender_user, Text = Text, Time = DateTime.Now
             };
             db.Mails.Add(mes);
             db.SaveChanges();
             return(true);
         }
     }
     return(false);
 }
        private void SaveIncomingMessage(MessageInformation message)
        {
            try
            {
                // Set this to blank to save database space
                message.RawMessage = string.Empty;
                message.DataBytes  = null;

                IncomingMessage msg = new IncomingMessage()
                {
                    MsgContent = EntityHelper.ToCommonRepresentation <MessageInformation>(message)
                };
                database.IncomingMesages.Add(msg);
                database.SaveChanges();
            }
            catch (Exception ex)
            {
                logger.Error("Failed to save message", ex);
            }
        }
        //public bool DeleteMessage(int mailID)
        //{
        //    using (var db = new MessengerContext())
        //    {
        //        var mails = from u in db.Mails where u.Id == mailID select u;
        //        Mail mail = mails.FirstOrDefault();
        //        db.Mails.Remove(mail);
        //        int i = db.SaveChanges();
        //        if (i == 1) return true;
        //    }
        //    return false;
        //}
        public Mail NewMessage(int senderID, int receiverID, string Text)
        {
            Mail message = null;

            using (var db = new MessengerContext())
            {
                var sender        = from u in db.Users where u.Id == senderID select u;
                var receiver      = from u in db.Users where u.Id == receiverID select u;
                var sender_user   = sender.FirstOrDefault();
                var receiver_user = receiver.FirstOrDefault();
                if (sender_user != null && receiver_user != null)
                {
                    var belarus = TimeZoneInfo.ConvertTime(DateTime.Now,
                                                           TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time"));
                    message = new Mail {
                        receiver = receiver_user, sender = sender_user, Text = Text, Time = belarus
                    };
                    db.Mails.Add(message);
                    db.SaveChanges();
                    //Clients.User(receiver_user.Login).UpdateMessage(message);

                    try
                    {
                        var user = ToUsers.Where(x => x.Key == receiver_user.Login);
                        if (user == null)
                        {
                            Clients.Caller.noUser();
                        }
                        else
                        {
                            Clients.Client(user.First().Value).UpdateMessage(message);
                            Clients.User(receiver_user.Login).UpdateMessage(message);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            return(message);
        }
        private string setChanges(string FirstName, string LastName, byte[] photo)
        {
            var id    = Context.ConnectionId;
            var users = ToUsers.Where(x => x.Value == id).ToList();
            var user  = users.First();

            try
            {
                using (var db = new MessengerContext())
                {
                    var login      = user.Key;
                    var login_qout = string.Format(@"""{0}""", login);
                    var users_db   = db.Users.SqlQuery("select * from  messengerbd.users where binary Login = "******"ok");
                        }
                        else
                        {
                            return("error in SaveChanges");
                        }
                    }
                    else
                    {
                        return("user is null");
                    }
                }
            }
            catch (Exception)
            {
                return("exception(no user in hub)");
            }
        }
 public bool addNewUser(string FirstName, string login, string password, string LastName)
 {
     using (var db = new MessengerContext())
     {
         var  users = from u in db.Users where u.Login == login select u;
         User user_ = users.FirstOrDefault();
         if (user_ == null)
         {
             User user = new User {
                 FirstName = FirstName, LastName = LastName, Login = login, Password = password
             };
             db.Users.Add(user);
             int i = db.SaveChanges();
             if (i == 1)
             {
                 return(true);
             }
         }
     }
     return(false);
 }
        public override Task OnDisconnected(bool stopCalled)
        {
            using (var db = new MessengerContext())
            {
                var users = ToUsers.Where(x => x.Value == Context.ConnectionId).ToList();
                var user  = users.First();
                try
                {
                    {
                        var login      = user.Key;
                        var login_qout = string.Format(@"""{0}""", login);
                        var users_db   = db.Users.SqlQuery("select * from  messengerbd.users where binary Login = "******"no user found in db when disconect");
                        }
                    }
                }
                catch (Exception e)
                {
                    Clients.Caller.Ecxeption("no user found in ToUsers when delete");
                }
            }
            string id = Context.ConnectionId;

            Clients.Others.Offline("id " + id);
            FromUsers.TryRemove(id, out userName);
            ToUsers.TryRemove(userName, out id);
            return(base.OnDisconnected(stopCalled));
        }
Example #18
0
        public void Register(User user)
        {
            var callback = OperationContext.Current.GetCallbackChannel <IMessengerServiceCallback>();

            using (MessengerContext context = new MessengerContext())
            {
                if (context.Users.ToList().Exists(u => u.Login == user.Login))
                {
                    throw new Exception("Пользователь с таким логином уже существует!");
                }
                else if (context.Users.ToList().Exists(u => u.Email == user.Email))
                {
                    throw new Exception("Пользователь с таким адресом электронной почты уже существует!");
                }
                else if (context.Users.ToList().Exists(u => u.Phone == user.Phone))
                {
                    throw new Exception("Пользователь с таким номером мобильного телефона уже существует!");
                }
                context.Users.Add(user);
                context.SaveChanges();
            }
            callback.Message("Регистрация прошла успешно!");
        }
 public bool DeleteUser(int userID, string password)
 {
     using (var db = new MessengerContext())
     {
         //db.Database.ExecuteSqlCommand("TRUNCATE TABLE [Users]");
         var  users = from u in db.Users where u.Id == userID && u.Password == password select u;
         User user  = users.FirstOrDefault();
         if (user != null)
         {
             string str = string.Format("DELETE FROM Users WHERE Id = {0}", userID);
             db.Database.ExecuteSqlCommand("SET FOREIGN_KEY_CHECKS=0");
             db.Users.Remove(user);
             db.Database.ExecuteSqlCommand("SET FOREIGN_KEY_CHECKS=1");
             //db.Users.Remove(user);
             int i = db.SaveChanges();
             if (i == 1)
             {
                 return(true);
             }
         }
     }
     return(false);
 }
 public User addNewUser(string FirstName, string login, string password, string LastName)
 {
     using (var db = new MessengerContext())
     {
         var  users = from u in db.Users where u.Login == login select u;
         User user_ = users.FirstOrDefault();
         if (user_ == null)
         {
             User user = new User {
                 FirstName = FirstName, LastName = LastName, Login = login, Password = password
             };
             db.Users.Add(user);
             int i = db.SaveChanges();
             if (i == 1)
             {
                 var user_to_result = new User();
                 user_to_result          = user;
                 user_to_result.Password = "";
                 user_to_result.Login    = "";
                 FromUsers.TryAdd(Context.ConnectionId, userName);
                 ToUsers.TryAdd(userName, Context.ConnectionId);
                 Clients.Others.updateUsers(user_to_result);
                 Clients.Caller.singed_Up(user);
                 return(user);
             }
             else
             {
                 Clients.Caller.Exception("error in db when add new user " + login);
             }
         }
         else
         {
             Clients.Caller.Exception("error in db  (has already such user " + login);
         }
     }
     return(null);
 }
Example #21
0
        public static void SeedTestUser(MessengerContext db)
        {
            var user = new User
            {
                Name               = "testuser",
                UserName           = "******",
                NormalizedUserName = "******"
            };

            var passwordHasher = new PasswordHasher <User>();
            var hash           = passwordHasher.HashPassword(user, "password");

            user.PasswordHash = hash;

            var userStore = new UserStore <User>(db);

            userStore.CreateAsync(user);

            var user2 = new User
            {
                Name               = "testuser2",
                UserName           = "******",
                NormalizedUserName = "******"
            };

            var passwordHasher2 = new PasswordHasher <User>();
            var hash2           = passwordHasher.HashPassword(user, "password");

            user2.PasswordHash = hash2;

            var userStore2 = new UserStore <User>(db);

            userStore.CreateAsync(user2);

            db.SaveChanges();
        }
Example #22
0
 private void BtSave_Click(object sender, RoutedEventArgs e)
 {
     Context.SaveChanges();
 }
Example #23
0
 public void Save()
 {
     db.SaveChanges();
 }
 public ActionResult Registration(User newUser)
 {
     DataBase.Users.Add(newUser);
     DataBase.SaveChanges();
     return(View("Main"));
 }
        /// <summary>
        /// Does the work.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void DoWork(object sender, ElapsedEventArgs e)
        {
            bool isDataConnectionAvailable = false;

            try
            {
                // Disable and wait until finish execution
                this.timer.Enabled = false;

                messenger = messengerService.Messenger;
                if (messenger == null)
                {
                    return;
                }

                if (logger.IsInfoEnabled)
                {
                    logger.Info("Checking unprocessed message");
                }

                // Get unprocessed messages
                List <IncomingMessage> unProcessedMsgs = database.IncomingMesages.Where(msg => msg.Status == IncomingMessage.ProcessingStatus.NotProcessed).ToList <IncomingMessage>();
                if (unProcessedMsgs.Count > 0)
                {
                    logger.Info("Processing " + unProcessedMsgs.Count + " messages");
                    foreach (IncomingMessage msg in unProcessedMsgs)
                    {
                        MessageInformation msgInfo = EntityHelper.FromCommonRepresentation <MessageInformation>(msg.MsgContent);
                        logger.Info("Processing message from " + msgInfo.PhoneNumber);

                        // Check for matching employee

                        string   employeeID = msgInfo.Content;
                        Employee employee   = database.Employees.Find(employeeID);
                        Gateway  gateway    = database.Gateways.Find(GlobalConstants.DefaultGatewayID);
                        if (employee != null && gateway != null)
                        {
                            if (messenger.InitializeDataConnection())
                            {
                                isDataConnectionAvailable = true;

                                // Send MMS
                                Mms mms = Mms.NewInstance(employee.EmployeeName, gateway.GatewayPhoneNumber);

                                // Multipart mixed
                                mms.MultipartRelatedType = MultimediaMessageConstants.ContentTypeApplicationMultipartMixed;
                                mms.PresentationId       = "<0000>";
                                mms.TransactionId        = EntityHelper.GenerateGuid();
                                mms.AddToAddress(msgInfo.PhoneNumber, MmsAddressType.PhoneNumber);

                                MultimediaMessageContent multimediaMessageContent = new MultimediaMessageContent();
                                multimediaMessageContent.SetContent(employee.EmployeePhoto, 0, employee.EmployeePhoto.Length);
                                multimediaMessageContent.ContentId = EntityHelper.GenerateGuid();
                                multimediaMessageContent.Type      = employee.PhotoImageType;
                                mms.AddContent(multimediaMessageContent);
                                if (messenger.Send(mms))
                                {
                                    msg.Status = IncomingMessage.ProcessingStatus.Processed;
                                }
                                else
                                {
                                    msg.Status   = IncomingMessage.ProcessingStatus.Error;
                                    msg.ErrorMsg = messenger.LastError.Message;
                                }
                                database.SaveChanges();
                            }
                            else
                            {
                                logger.Error("Unable to establish a data connection through the modem. Check if you modem support MMS");
                                if (messenger.LastError != null)
                                {
                                    logger.Error(messenger.LastError.ToString());
                                }
                            }
                        }
                        else
                        {
                            // Employee not found
                            msg.Status   = IncomingMessage.ProcessingStatus.Error;
                            msg.ErrorMsg = "Employee not found";
                            database.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error polling messages", ex);
            }
            finally
            {
                if (isDataConnectionAvailable)
                {
                    messengerService.StartMessenger();
                }
                this.timer.Enabled = true;
            }
        }