public static int UpdateCodeForUserByPhone(string iPhoneNum, SignalRChatContext iDB)
        {
            try {
                if (iDB == null)
                {
                    iDB = new SignalRChatContext();
                }

                var objToUpdate = iDB.Users.Where(x => x.Phone == iPhoneNum).Select(x => x.SignInCodes).FirstOrDefault();

                if (objToUpdate == null)
                {
                    return(-1);
                }

                objToUpdate.Code       = CreateCode();
                objToUpdate.UpdateDate = DateTime.Now;

                iDB.SaveChanges();

                return(objToUpdate.Code);
            }
            catch (Exception ex) {
                throw new Exception();
            }
        }
Beispiel #2
0
        public async Task <object> saveUserChat(vmMessage _model)
        {
            string message = string.Empty;

            try
            {
                using (_ctx = new SignalRChatContext())
                {
                    UserChat model = new UserChat()
                    {
                        Chatid        = _ctx.UserChat.DefaultIfEmpty().Max(x => x == null ? 0 : x.Chatid) + 1,
                        Connectionid  = _model.Connectionid,
                        Senderid      = _model.Senderid,
                        Receiverid    = _model.Receiverid,
                        Message       = _model.Message,
                        Messagestatus = _model.Messagestatus,
                        Messagedate   = _model.Messagedate,
                        IsGroup       = _model.IsGroup,
                        IsPrivate     = _model.IsPrivate,
                        IsMultiple    = _model.IsMultiple
                    };
                    _ctx.UserChat.Add(model);
                    await _ctx.SaveChangesAsync();

                    message = "Saved";
                }
            }
            catch (Exception ex)
            {
                message = "Error:" + ex.ToString();
            }
            return(message);
        }
Beispiel #3
0
        public static UserCls CreateNewUser(UserPartial iUser, SignalRChatContext iDB)
        {
            var userToAdd = new Users
            {
                Age          = iUser.age,
                CreationDate = DateTime.Now,
                FirstName    = iUser.firstName,
                LastName     = iUser.lastName,
                Phone        = iUser.phone,
                UserName     = iUser.userName,
                Icon         = iUser.icon
            };

            iDB.Users.Add(userToAdd);
            iDB.SaveChanges();

            UserCls ret = new UserCls
            {
                id        = userToAdd.UserId,
                age       = userToAdd.Age,
                firstName = iUser.firstName,
                lastName  = iUser.lastName,
                phone     = iUser.phone,
                userName  = iUser.userName,
                icon      = iUser.icon
            };

            return(ret);
        }
Beispiel #4
0
        public async Task <bool> DeleteChatFor(long chatId, long deleteFor)
        {
            bool success = false;

            try
            {
                using (dbContext = new SignalRChatContext())
                {
                    UserChat userChat = await(from x in dbContext.UserChat
                                              where x.Chatid == chatId
                                              select x).FirstOrDefaultAsync();

                    if (userChat != null && (userChat.Deletedfor > 0 || deleteFor < 0))
                    {
                        dbContext.Remove(userChat);
                    }
                    else
                    {
                        userChat.Deletedfor = deleteFor;
                        dbContext.Update(userChat);
                    }

                    await dbContext.SaveChangesAsync();

                    success = true;
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            return(success);
        }
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                MembershipUser         user =
                    Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);

                    SignalRChatContext context = new SignalRChatContext();
                    context.Users.Add(new User
                    {
                        UserId   = new Guid(user.ProviderUserKey.ToString()),
                        Nickname = model.UserName,
                        //Email = model.Email,
                        //Phone = model.Phone
                    });
                    context.SaveChanges();

                    return(View("Start"));
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #6
0
        public static int IsUserExist(string iPhoneNum, SignalRChatContext iDB)
        {
            if (iDB == null)
            {
                iDB = new SignalRChatContext();
            }

            return(iDB.Users.Where(x => x.Phone == iPhoneNum).Select(x => x.UserId).FirstOrDefault());
        }
        public static ValidateCodeOutput ValidateCode(string iPhoneNum, int iCode)
        {
            SignalRChatContext DB = new SignalRChatContext();

            var ret = DB.SignInCodes.Where(x => x.User.Phone == iPhoneNum && x.Code == iCode).Select(x => new ValidateCodeOutput {
                userId = x.User.UserId, userName = x.User.UserName
            }).FirstOrDefault();

            return(ret);
        }
Beispiel #8
0
        //       private JwtIssuerOptions jwtIssuerOptions;

        public AccountRepository(
            IMapper mapper,
            IConfiguration configuration,
            UserManager <AppUser> user_manager,
            SignInManager <AppUser> signin_manager,
            SignalRChatContext context)
        {
            _mapper             = mapper;
            this.user_manager   = user_manager;
            this.signin_manager = signin_manager;
            this._context       = context;
            this._config        = configuration;
        }
Beispiel #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SignalRChatContext signalRChatContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(appBuilder =>
                {
                    appBuilder.Run(async context =>
                    {
                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync("An unexpected fault happend. sorry");
                    });
                });
            }
            app.UseStaticFiles();

            app.UseSignalR(options =>
            {
                // options.MapHub<MessageHub>("/MessageHub");
            });
            app.UseAuthentication();
            app.UseMiddleware <WebSocketsMiddleware>();
            app.UseMvc(cfg =>
            {
                cfg.MapRoute(name: "Default",
                             template: "{controller=App}/{action=Index}/{id?}");
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(name: "Default",
                                             pattern: "{controller=App}/{action=Index}/{id?}");
                endpoints.MapFallbackToController("Index", "App");

                endpoints.MapHub <RoomsHub>("/RoomHub");
            });

            if (true)
            {
                //Seed the database
                using (var scope = app.ApplicationServices.CreateScope())
                {
                    var seeder = scope.ServiceProvider.GetService <Seeder>();
                    seeder.Seed().Wait();
                }
            }
        }
Beispiel #10
0
        public static List <UserCls> GetFullUserList(SignalRChatContext iDB, int iUserId)
        {
            var retList = iDB.Users.Where(x => x.UserId != iUserId).OrderBy(x => x.FirstName).Take(1000).Select(x => new UserCls
            {
                id        = x.UserId,
                age       = x.Age,
                firstName = x.FirstName,
                lastName  = x.LastName,
                phone     = x.Phone,
                userName  = x.UserName,
                icon      = x.Icon
            }).ToList();

            return(retList);
        }
        public static int GenerateCodeForUser(int iUserId, SignalRChatContext iDB)
        {
            SignInCodes addObj = new SignInCodes();
            var         code   = CreateCode();

            addObj.Code       = code;
            addObj.UpdateDate = DateTime.Now;
            addObj.UserId     = iUserId;

            var ret = iDB.SignInCodes.Add(addObj);

            iDB.SaveChanges();

            return(addObj.Code);
        }
Beispiel #12
0
        public static List <MsgObject> GetChatHistory(int iFromUserId, int iToUserId, SignalRChatContext iDb)
        {
            if (iDb == null)
            {
                iDb = new SignalRChatContext();
            }

            List <MsgObject> res = iDb.Messages.Where(x => (x.MsgFromUserId == iFromUserId && x.MsgToUserId == iToUserId) || (x.MsgFromUserId == iToUserId && x.MsgToUserId == iFromUserId)).Select(x => new MsgObject {
                msg        = x.Msg,
                sentDate   = x.SendDate,
                fromUserId = x.MsgFromUserId, //user id should not be returned.
                toUserId   = x.MsgToUserId
            }).OrderBy(x => x.sentDate).ToList();

            return(res);
        }
Beispiel #13
0
        public static UserCls UserByPhoneAndCode(string iPhoneNum, int iCode)
        {
            SignalRChatContext DB = new SignalRChatContext();

            var userDetails = DB.Users.Where(x => x.Phone == iPhoneNum && x.SignInCodes.Code == iCode).Select(x => new UserCls {
                age       = x.Age,
                firstName = x.FirstName,
                icon      = x.Icon,
                id        = x.UserId,
                lastName  = x.LastName,
                phone     = x.Phone,
                userName  = x.UserName
            }).FirstOrDefault();

            return(userDetails);
        }
Beispiel #14
0
        public async Task <UserChat> SaveItemAsync(UserChat item)
        {
            try
            {
                using (dbContext = new SignalRChatContext())
                {
                    EntityEntry <UserChat> newItem = dbContext.UserChat.Add(item);
                    await dbContext.SaveChangesAsync();

                    return(newItem.Entity);
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Beispiel #15
0
        public async Task <ActionResult> CreateUser(UserPartial iUser)
        {
            try
            {
                SignalRChatContext DB = new SignalRChatContext();

                using (var transaction = DB.Database.BeginTransaction())
                {
                    try
                    {
                        bool isExist = UserFunctions.CheckIfUserExist(iUser, DB);

                        if (isExist == true)
                        {
                            return(BadRequest());
                        }

                        UserCls newUser = UserFunctions.CreateNewUser(iUser, DB);
                        newUser.code = SignInCodesFucntions.GenerateCodeForUser(newUser.id, DB);

                        transaction.Commit();

                        newUser.token = JwtHandler.CreateJwt(newUser.id, newUser.userName, DateTime.Now);

                        await hubContext.Clients.All.AddUserEvent(newUser.id);

                        return(new JsonResult(newUser));
                    }
                    catch (Exception exc)
                    {
                        //write exc to log...
                        transaction.Rollback();
                        return(BadRequest());
                    }
                }
            }
            catch (Exception ex)
            {
                //write ex to log...
                return(BadRequest());
            }
        }
Beispiel #16
0
        public static MsgObject SendMsg(int iFromUser, int iToUser, string iMsg, SignalRChatContext iDb)
        {
            var msgToAdd = new Messages();

            msgToAdd.Msg           = iMsg;
            msgToAdd.MsgFromUserId = iFromUser;
            msgToAdd.MsgToUserId   = iToUser;
            msgToAdd.SendDate      = DateTime.Now;

            iDb.Messages.Add(msgToAdd);
            iDb.SaveChanges();

            MsgObject ret = new MsgObject();

            ret.msg        = msgToAdd.Msg;
            ret.fromUserId = msgToAdd.MsgFromUserId;
            ret.toUserId   = msgToAdd.MsgToUserId;
            ret.sentDate   = msgToAdd.SendDate;

            return(ret);
        }
Beispiel #17
0
        public List <UserChat> GetChatHistoryOfUser(long userId, long contactId)
        {
            List <UserChat> userChat = null;

            try
            {
                using (dbContext = new SignalRChatContext())
                {
                    userChat = (from x in dbContext.UserChat
                                where (((x.Senderid == userId && x.Receiverid == contactId) || (x.Receiverid == userId && x.Senderid == contactId)) && x.Deletedfor != userId)
                                select x).ToList();
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
                userChat = null;
            }

            return(userChat);
        }
Beispiel #18
0
        public async Task <User> GetUserByEmailAsync(string email)
        {
            User user = null;

            try
            {
                using (dbContext = new SignalRChatContext())
                {
                    user = await(from x in dbContext.User
                                 where x.Email == email
                                 select x).FirstOrDefaultAsync();
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
                user = null;
            }

            return(user);
        }
Beispiel #19
0
        public ActionResult GetFullUserList()
        {
            int userId = ExractIdFromToken();

            if (userId == 0)
            {
                return(BadRequest());
            }

            //var token = Request.Headers.FirstOrDefault(x => x.Key == "Authorization").Value.FirstOrDefault();
            //int userId = 0;
            //if (JwtHandler.IsTokenValid(token , out userId) == false) {
            //    return BadRequest();
            //}

            SignalRChatContext Db = new SignalRChatContext();

            List <UserCls> userListRes = UserFunctions.GetFullUserList(Db, userId);

            return(new JsonResult(userListRes));
        }
Beispiel #20
0
        public async Task <object> getUserlogin(UserLogin model)
        {
            var loggeduser = (dynamic)null;

            try
            {
                using (_ctx = new SignalRChatContext())
                {
                    loggeduser = await(from x in _ctx.UserLogin
                                       where x.UserName == model.UserName && x.UserPass == model.UserPass
                                       select x).FirstOrDefaultAsync();
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
                loggeduser = null;
            }

            return(loggeduser);
        }
Beispiel #21
0
        public async Task <User> GetItemAsync(int id)
        {
            User user = null;

            try
            {
                using (dbContext = new SignalRChatContext())
                {
                    user = await(from x in dbContext.User
                                 where x.Id == id
                                 select x).FirstOrDefaultAsync();
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
                user = null;
            }

            return(user);
        }
        public async Task <ActionResult> SendMsg(chatMsgInput iMsgIobj)
        {
            try
            {
                int userId = ExractIdFromToken();
                if (userId == 0)
                {
                    return(BadRequest());
                }

                SignalRChatContext DB = new SignalRChatContext();

                using (var transaction = DB.Database.BeginTransaction())
                {
                    try
                    {
                        MsgObject res = MsgFunctions.SendMsg(userId, iMsgIobj.toUserId, iMsgIobj.msg, DB);

                        transaction.Commit();

                        await hubContext.Clients.All.SentMsgEvent(userId, iMsgIobj.toUserId, iMsgIobj.msg);

                        return(new JsonResult(res));
                    }
                    catch (Exception exc)
                    {
                        //write exc to log...
                        transaction.Rollback();
                        return(BadRequest());
                    }
                }
            }
            catch (Exception ex)
            {
                //write ex to log...
                return(BadRequest());
            }
        }
Beispiel #23
0
        public Task <List <UserChat> > getUserChat(UserChat model)
        {
            return(Task.Run(() =>
            {
                List <UserChat> userChat = null;
                try
                {
                    using (_ctx = new SignalRChatContext())
                    {
                        userChat = (from x in _ctx.UserChat
                                    where (x.Senderid == model.Senderid && x.Receiverid == model.Receiverid) || (x.Receiverid == model.Senderid && x.Senderid == model.Receiverid)
                                    select x).ToList();
                    }
                }
                catch (Exception ex)
                {
                    ex.ToString();
                    userChat = null;
                }

                return userChat;
            }));
        }
 public MessageRepository(SignalRChatContext context)
 {
     _context = context;
 }
Beispiel #25
0
        public static bool CheckIfUserExist(UserPartial iUser, SignalRChatContext iDB)
        {
            bool res = iDB.Users.Any(x => x.UserName == iUser.userName || x.Phone == iUser.phone);

            return(res);
        }
 public RoomsRepository(SignalRChatContext context)
 {
     _ctx = context;
 }
Beispiel #27
0
        public static List <MsgObject> GetChatMsgByUser(int iUserId, int iPage, int iBulk, SignalRChatContext iDb)
        {
            List <MsgObject> res = iDb.Messages.Where(x => x.MsgFromUserId == iUserId).Select(x => new MsgObject
            {
                fromUserId = x.MsgFromUserId,
                msg        = x.Msg,
                sentDate   = x.SendDate,
                toUserId   = x.MsgToUserId,
            }).OrderByDescending(x => x.sentDate).Skip(iPage * iBulk).Take(iBulk).ToList();

            return(res);
        }