public virtual void Remove(ProfileHobbie profileHobbie)
 {
     using (var _ctx = new DatingContext())
     {
         _ctx.Entry(profileHobbie).State = EntityState.Deleted;
     }
 }
        public static List <Avatar> GetAvatars(int[] id)
        {
            List <Avatar> siteAvatars = new List <Avatar>();

            using (DatingContext db = new DatingContext())
            {
                for (int i = 0; i < id.Length; i++)
                {
                    int currentId = id[i];

                    siteAvatars.AddRange(db.Avatars.Where(x => x.siteUserId == currentId).ToList());
                }
            }
            List <Avatar> clientAvatars = new List <Avatar>();

            foreach (Avatar avatar in siteAvatars)
            {
                if (avatar != null)
                {
                    string   AvatarBase64 = (avatar.base64).Substring((avatar.base64).IndexOf(',') + 1);//конвертим js base64 строку в c# строку (убираем заголовок)
                    FileInfo fileInfo     = new FileInfo(AvatarBase64);
                    byte[]   bytes        = new byte[fileInfo.Length];
                    using (FileStream fs = fileInfo.OpenRead())
                    {
                        fs.Read(bytes, 0, bytes.Length);
                    }
                    string NewBase64 = "data:image / png; base64," + Convert.ToBase64String(bytes);//Добавляем к base64 header, который в C# почему-то не генерируется, но необъодимый js для отображения изображению
                    avatar.base64 = NewBase64;
                }
                clientAvatars.Add(avatar);
            }
            return(clientAvatars);
        }
 public bool AreFriends(string userId, string friendUserId)
 {
     using (var _ctx = new DatingContext())
     {
         var friends = _ctx.Set <FriendRequest>().Where(x => (x.UserId == userId && x.FriendRequestUserId == friendUserId) || (x.UserId == friendUserId && x.FriendRequestUserId == userId));
         return(friends.FirstOrDefault() != null && friends.FirstOrDefault().IsFriend);
     }
 }
Beispiel #4
0
 public List <Hobbie> GetAll()
 {
     using (var _ctx = new DatingContext())
     {
         var hobbies = _ctx.Set <Hobbie>();
         return(hobbies.ToList());
     }
 }
 public FriendProfile GetById(long friendProfileId)
 {
     using (var _ctx = new DatingContext())
     {
         var profile = _ctx.Set <FriendProfile>().Where(x => x.Id == friendProfileId);
         return(profile.FirstOrDefault());
     }
 }
 public List <FriendRequest> GetFriendRequests(string userId)
 {
     using (var _ctx = new DatingContext())
     {
         var friends = _ctx.Set <FriendRequest>().Where(x => x.FriendRequestUserId == userId && !x.IsFriend).Include(x => x.Profile);
         return(friends.ToList());
     }
 }
Beispiel #7
0
 public List <Profile> GetFirstFiveProfiles()
 {
     using (var _ctx = new DatingContext())
     {
         var profile = _ctx.Set <Profile>().OrderBy(x => x.CreatedDate).Take(5);
         return(profile.ToList());
     }
 }
Beispiel #8
0
 public Profile GetById(long profileId)
 {
     using (var _ctx = new DatingContext())
     {
         var profile = _ctx.Set <Profile>().Where(x => x.Id == profileId).Include(x => x.Hobbies);
         return(profile.FirstOrDefault());
     }
 }
Beispiel #9
0
 public List <ProfilePost> GetAll(long profileId)
 {
     using (var _ctx = new DatingContext())
     {
         var friends = _ctx.Set <ProfilePost>().Where(x => x.ProfileId == profileId).OrderByDescending(x => x.Date).Include(x => x.FriendUserProfile).Include(x => x.Profile);
         return(friends.ToList());
     }
 }
Beispiel #10
0
 public List <Profile> GetAll()
 {
     using (var _ctx = new DatingContext())
     {
         var profiles = _ctx.Set <Profile>().Where(x => x.Active).Include(x => x.Hobbies.Select(y => y.Hobbie));
         return(profiles.ToList());
     }
 }
Beispiel #11
0
 public Profile GetByUserName(string userName)
 {
     using (var _ctx = new DatingContext())
     {
         var profile = _ctx.Set <Profile>().Where(x => x.UserName == userName);
         return(profile.FirstOrDefault());
     }
 }
 public List <FriendProfile> GetAllFavourites(long profileId)
 {
     using (var _ctx = new DatingContext())
     {
         var friends = _ctx.Set <FriendProfile>().Where(x => x.ProfileId == profileId && x.FriendUserProfile.Active && x.IsFavourite).Include(x => x.FriendUserProfile).Include(x => x.Profile);
         return(friends.ToList());
     }
 }
Beispiel #13
0
 public Profile Add(Profile profile)
 {
     using (var _ctx = new DatingContext())
     {
         _ctx.Entry <Profile>(profile).State = System.Data.Entity.EntityState.Added;
         _ctx.SaveChanges();
         return(profile);
     }
 }
 public FriendProfile Update(FriendProfile friend)
 {
     using (var _ctx = new DatingContext())
     {
         _ctx.Entry <FriendProfile>(friend).State = System.Data.Entity.EntityState.Modified;
         _ctx.SaveChanges();
         return(friend);
     }
 }
 public VisitorProfile Add(VisitorProfile visitorProfile)
 {
     using (var _ctx = new DatingContext())
     {
         _ctx.Entry <VisitorProfile>(visitorProfile).State = System.Data.Entity.EntityState.Added;
         _ctx.SaveChanges();
         return(visitorProfile);
     }
 }
 public List <Profile> GetLastFiveVisitors(long profileId)
 {
     using (var _ctx = new DatingContext())
     {
         var friends = _ctx.Set <VisitorProfile>().Where(x => x.ProfileId == profileId && x.FriendUserProfile.Active)
                       .OrderByDescending(x => x.Date).Take(5).Select(x => x.FriendUserProfile).GroupBy(p => p.Id).Select(g => g.FirstOrDefault());
         return(friends.ToList());
     }
 }
Beispiel #17
0
 public void Remove(long?profilePostId)
 {
     using (var _ctx = new DatingContext())
     {
         var profilePost = _ctx.Set <ProfilePost>().Where(x => x.Id == profilePostId).FirstOrDefault();
         _ctx.Entry <ProfilePost>(profilePost).State = System.Data.Entity.EntityState.Deleted;
         _ctx.SaveChanges();
     }
 }
        public FriendRequest GetById(long friendRequestId)
        {
            using (var _ctx = new DatingContext())
            {
                var friends = _ctx.Set <FriendRequest>().Where(x => x.Id == friendRequestId);

                return(friends.FirstOrDefault());
            }
        }
Beispiel #19
0
 public ProfilePost Update(ProfilePost profilePost)
 {
     using (var _ctx = new DatingContext())
     {
         _ctx.Entry <ProfilePost>(profilePost).State = System.Data.Entity.EntityState.Modified;
         _ctx.SaveChanges();
         return(profilePost);
     }
 }
Beispiel #20
0
 public List <Profile> GetByFilters(string searchString, long?genderTarget)
 {
     using (var _ctx = new DatingContext())
     {
         var profile = _ctx.Set <Profile>().Where(x => x.Active && ((string.IsNullOrEmpty(searchString) || x.UserName.Contains(searchString)) ||
                                                                    (x.FirstName.Contains(searchString) || x.LastName.Contains(searchString))) &&
                                                  (genderTarget == null || x.GenderId == genderTarget)).Include(x => x.Hobbies);
         return(profile.ToList());
     }
 }
Beispiel #21
0
        private List <SiteUser> SortWithFilter(Filter filter, string gender)
        {
            bool isAllGender = false;

            if (gender == "Male")
            {
                filter.gender = true;
            }
            else if (gender == "Female")
            {
                filter.gender = false;
            }
            else
            {
                isAllGender = true;
            }

            if (filter.nameForSearch == null)
            {
                filter.nameForSearch = "";
            }
            int    from         = 0;
            int    to           = 0;
            int    ageFilterid  = filter.ageForSearch;
            string ageForSearch = db.AgeForSearch.FirstOrDefault(x => x.id == ageFilterid).rangeOfAge;

            if (ageForSearch != "All")
            {
                from = Convert.ToInt32(ageForSearch.Split(' ')[0]);
                if (from == 53)
                {
                    to = 200;
                }
                else
                {
                    to = Convert.ToInt32(ageForSearch.Split(' ')[2]);
                }
            }
            if (filter.nameForSearch == null)
            {
                filter.nameForSearch = "";
            }
            using (DatingContext db = new DatingContext())
            {
                List <SiteUser> SUsers = db.SiteUsers.Where(x =>
                                                            ((DateTime.Now.Year - x.birthDay.Year >= from && DateTime.Now.Year - x.birthDay.Year <= to) || filter.ageForSearch == -1) &&
                                                            (x.cityid == filter.cityForSearch || filter.cityForSearch == -1) &&
                                                            (x.typeForSearchid == filter.typeForSearch || filter.typeForSearch == -1) &&
                                                            (x.gender == filter.gender || isAllGender) &&
                                                            x.id != filter.id
                                                            ).ToList();

                return(SUsers);
            }
        }
 public void DeclineFriendRequest(long friendRequestId)
 {
     using (var _ctx = new DatingContext())
     {
         var friendRequest = GetById(friendRequestId);
         if (friendRequest != null)
         {
             _ctx.Entry <FriendRequest>(friendRequest).State = System.Data.Entity.EntityState.Deleted;
             _ctx.SaveChanges();
         }
     }
 }
 public FriendProfile Add(FriendProfile friend)
 {
     using (var _ctx = new DatingContext())
     {
         var foundFriend = _ctx.Set <FriendProfile>().Any(x => x.FriendProfileId == friend.FriendProfileId && x.ProfileId == friend.ProfileId);
         if (!foundFriend)
         {
             _ctx.Entry <FriendProfile>(friend).State = System.Data.Entity.EntityState.Added;
             _ctx.SaveChanges();
         }
         return(friend);
     }
 }
Beispiel #24
0
        public async Task GetDialogs(AspNetWebSocketContext context, int id)
        {
            using (DatingContext db = new DatingContext())
            {
                dialogs = db.DialogLists.Where(x => x.firstUserId == id ||
                                               x.secondUserId == id).ToList();
            }

            string json = JsonConvert.SerializeObject(dialogs);

            byte[] cleanBuffer = Encoding.UTF8.GetBytes(json);

            await context.WebSocket.SendAsync(new ArraySegment <byte>(cleanBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
        }
Beispiel #25
0
        private async Task WebSocketRequest(AspNetWebSocketContext context)
        {
            var socket = context.WebSocket;
            int id     = 0;

            while (true)
            {
                var buffer = new ArraySegment <byte>(new byte[64]);
                var result = await socket.ReceiveAsync(buffer, CancellationToken.None);//При подключенном сокете сообщения не приходит, при разрыве приходит массив нулей

                byte[] cleanBuffer = buffer.Array.Where(b => b != 0).ToArray();
                if (cleanBuffer.Length > 0)
                {
                    id = Convert.ToInt32(Encoding.UTF8.GetString(buffer.Array));
                    if (!Clients.ContainsKey(id))//Исключаем дублирование сокета клиента
                    {
                        Clients.Add(id, socket);
                        using (DatingContext db = new DatingContext())
                        {
                            SiteUser user = db.SiteUsers.FirstOrDefault(x => x.id == id);
                            user.online = true;
                            await db.SaveChangesAsync();
                        }
                    }
                }
                try
                {
                    if (socket.State == WebSocketState.CloseReceived)
                    {
                        using (DatingContext db = new DatingContext())
                        {
                            SiteUser user = db.SiteUsers.FirstOrDefault(x => x.id == id);
                            user.online = false;
                            await db.SaveChangesAsync();
                        }
                        Clients.Remove(id);
                    }
                }
                catch (ObjectDisposedException)
                {
                    using (DatingContext db = new DatingContext())
                    {
                        SiteUser user = db.SiteUsers.FirstOrDefault(x => x.id == id);
                        user.online = false;
                        await db.SaveChangesAsync();
                    }
                    Clients.Remove(id);
                }
            }
        }
        public static object SelectionWithId(int[] id)
        {
            List <ClientUser> userList = new List <ClientUser>();

            using (DatingContext db = new DatingContext())
            {
                for (int i = 0; i < id.Length; i++)
                {
                    int currentId = id[i];
                    userList.Add(new ClientUser(db.SiteUsers.FirstOrDefault(x => x.id == currentId)));
                }
            }
            List <Avatar> avatars = AvatarsController.GetAvatars(id);

            return(new { userList, avatars, id });
        }
Beispiel #27
0
        //private async Task  SortByFilter(Filter clientData, WebSocket WSocket, bool isNewAva)// List<ClientUser>
        //{
        //    string json;
        //    if (clientData.getUsersWithId != null)
        //    {
        //        List<ClientUser> userList = new List<ClientUser>();
        //        using (DatingContext db = new DatingContext())
        //        {
        //            for (int i = 0; i < clientData.getUsersWithId.Length; i++)
        //            {
        //                int currentId = clientData.getUsersWithId[i];
        //                userList.Add(new ClientUser(db.SiteUsers.FirstOrDefault(x => x.id == currentId)));
        //            }
        //        }
        //        List<Avatar> avatars = GetAvatars(clientData.getUsersWithId);
        //        object sendData = new { userList, avatars };
        //        json = JsonConvert.SerializeObject(sendData);
        //    }
        //    else
        //    {
        //        int from = 0;
        //        int to = 0;
        //        if (clientData.ageForSearch != "All")
        //        {
        //            from = Convert.ToInt32(clientData.ageForSearch.Split(' ')[0]);
        //            to = Convert.ToInt32(clientData.ageForSearch.Split(' ')[2]);

        //            if (from == 53)
        //                to = 200;
        //        }

        //        if (clientData.nameForSearch == null)
        //            clientData.nameForSearch = "";
        //        using (DatingContext db = new DatingContext())
        //        {
        //            List<SiteUser> SUsers = db.SiteUsers.Where(x =>
        //              ((DateTime.Now.Year - x.birthDay.Year >= from && DateTime.Now.Year - x.birthDay.Year <= to) || clientData.ageForSearch == "All")
        //              && x.name.Contains(clientData.nameForSearch)
        //              && (x.city == clientData.cityForSearch || clientData.cityForSearch == "All")
        //              && (x.genderForSearch == clientData.genderForSearch || clientData.genderForSearch == "All")
        //              && x.id != clientData.id
        //            ).OrderBy(x => x.name).Skip(0).Take(12).ToList();

        //            SUsers.Add(db.SiteUsers.FirstOrDefault(x => x.id == clientData.id));

        //            List<ClientUser> userList = new List<ClientUser>();
        //            foreach (SiteUser user in SUsers)
        //            {
        //                userList.Add(new ClientUser(user));
        //            }

        //            if (isNewAva)
        //            {
        //                List<int> id = new List<int>();
        //                for (int i = 0; i < userList.Count; i++)
        //                {
        //                    id.Add(userList[i].id);
        //                }
        //                List<Avatar> avatars = GetAvatars(id.ToArray());
        //                object sendData = new { userList, avatars };
        //                json = JsonConvert.SerializeObject(sendData);
        //            }
        //            else
        //                json = JsonConvert.SerializeObject(userList);
        //        }
        //    }
        //    byte[] cleanBuffer = Encoding.UTF8.GetBytes(json);
        //        await WSocket.SendAsync(new ArraySegment<byte>(cleanBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
        //}
        //private async Task  SortByFilter(Filter clientData, WebSocket WSocket, bool isNewAva)// List<ClientUser>
        //{
        //    string json;
        //    if (clientData.getUsersWithId != null)
        //    {
        //        List<ClientUser> userList = new List<ClientUser>();
        //        using (DatingContext db = new DatingContext())
        //        {
        //            for (int i = 0; i < clientData.getUsersWithId.Length; i++)
        //            {
        //                int currentId = clientData.getUsersWithId[i];
        //                userList.Add(new ClientUser(db.SiteUsers.FirstOrDefault(x => x.id == currentId)));
        //            }
        //        }
        //        List<Avatar> avatars = GetAvatars(clientData.getUsersWithId);
        //        object sendData = new { userList, avatars };
        //        json = JsonConvert.SerializeObject(sendData);
        //    }
        //    else
        //    {
        //        int from = 0;
        //        int to = 0;
        //        if (clientData.ageForSearch != "All")
        //        {
        //            from = Convert.ToInt32(clientData.ageForSearch.Split(' ')[0]);
        //            to = Convert.ToInt32(clientData.ageForSearch.Split(' ')[2]);

        //            if (from == 53)
        //                to = 200;
        //        }

        //        if (clientData.nameForSearch == null)
        //            clientData.nameForSearch = "";
        //        using (DatingContext db = new DatingContext())
        //        {
        //            List<SiteUser> SUsers = db.SiteUsers.Where(x =>
        //              ((DateTime.Now.Year - x.birthDay.Year >= from && DateTime.Now.Year - x.birthDay.Year <= to) || clientData.ageForSearch == "All")
        //              && x.name.Contains(clientData.nameForSearch)
        //              && (x.city == clientData.cityForSearch || clientData.cityForSearch == "All")
        //              && (x.genderForSearch == clientData.genderForSearch || clientData.genderForSearch == "All")
        //              && x.id != clientData.id
        //            ).OrderBy(x => x.name).Skip(0).Take(12).ToList();

        //            SUsers.Add(db.SiteUsers.FirstOrDefault(x => x.id == clientData.id));

        //            List<ClientUser> userList = new List<ClientUser>();
        //            foreach (SiteUser user in SUsers)
        //            {
        //                userList.Add(new ClientUser(user));
        //            }

        //            if (isNewAva)
        //            {
        //                List<int> id = new List<int>();
        //                for (int i = 0; i < userList.Count; i++)
        //                {
        //                    id.Add(userList[i].id);
        //                }
        //                List<Avatar> avatars = GetAvatars(id.ToArray());
        //                object sendData = new { userList, avatars };
        //                json = JsonConvert.SerializeObject(sendData);
        //            }
        //            else
        //                json = JsonConvert.SerializeObject(userList);
        //        }
        //    }
        //    byte[] cleanBuffer = Encoding.UTF8.GetBytes(json);
        //        await WSocket.SendAsync(new ArraySegment<byte>(cleanBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
        //}
        private async Task GetCurrentUsers(int[] idOfUsers, WebSocket WSocket)// List<ClientUser>
        {
            List <ClientUser> userList = new List <ClientUser>();

            using (DatingContext db = new DatingContext())
            {
                for (int i = 0; i < idOfUsers.Length; i++)
                {
                    int currentId = idOfUsers[i];
                    userList.Add(new ClientUser(db.SiteUsers.FirstOrDefault(x => x.id == currentId)));
                }
            }
            string json = JsonConvert.SerializeObject(userList);

            byte[] cleanBuffer = Encoding.UTF8.GetBytes(json);
            await WSocket.SendAsync(new ArraySegment <byte>(cleanBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
        }
        public FriendRequest AcceptFriendRequest(long friendRequestId)
        {
            using (var _ctx = new DatingContext())
            {
                var friends = _ctx.Set <FriendRequest>().Where(x => x.Id == friendRequestId);

                var friendRequest = friends.FirstOrDefault();

                friendRequest.IsFriend = true;

                _ctx.Entry(friendRequest).State = EntityState.Modified;

                _ctx.SaveChanges();

                return(friendRequest);
            }
        }
Beispiel #29
0
        public static bool IsAccess(CookieHeaderValue cookie, int id, string allowedRole)
        {
            //По факту существует 2 allowedRole- юзер, которая означает, что данные доступны всем(кроме забаненного) и Админ, означающая,что доступ только у админа, нет того, что может юзер, но не может модер и того, что может модер, но не может админ
            DatingContext db       = new DatingContext();
            SiteUser      siteUser = new SiteUser();

            if (cookie != null)
            {
                string   sessionId = cookie["UserSession"].Value;
                SiteUser authDate  = JsonConvert.DeserializeObject <SiteUser>(sessionId);
                siteUser = db.SiteUsers.FirstOrDefault((x) => x.sessionId == authDate.sessionId &&
                                                       x.id == authDate.id &&
                                                       x.roleid == authDate.roleid);
            }
            if (siteUser != null)
            {
                if (allowedRole != "Admin")//Модератор=Админ, но он не имеет доступа к редактированию админской страницы и ролей юзеров(кроме бан/разбан)это исключительно админская привилегия => разграничиваем
                {
                    if (siteUser.roleid == db.Roles.FirstOrDefault(x => x.roleName == "Admin").id ||
                        siteUser.roleid == db.Roles.FirstOrDefault(x => x.roleName == "Moder").id ||
                        siteUser.roleid == db.Roles.FirstOrDefault(x => x.roleName == allowedRole).id&& id == siteUser.id)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (siteUser.roleid == db.Roles.FirstOrDefault(x => x.roleName == "Admin").id)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Beispiel #30
0
        public InMemoryDBUtility()
        {
            DbContextOptions <DatingContext> contextOptions      = new DbContextOptions <DatingContext>();
            DbContextOptionsBuilder          optionsBuilderSkill = new DbContextOptionsBuilder(contextOptions);
            var dboption = optionsBuilderSkill.UseInMemoryDatabase().Options as DbContextOptions <DatingContext>;

            _dateContext = new DatingContext(dboption);

            DbContextOptions <UserContext> contextOptionsUser = new DbContextOptions <UserContext>();
            DbContextOptionsBuilder        optionsBuilderUser = new DbContextOptionsBuilder(contextOptionsUser);
            var userdboption = optionsBuilderUser.UseInMemoryDatabase().Options as DbContextOptions <UserContext>;

            _userContext = new UserContext(userdboption);

            //Skill Connection
            _dateConnection = new DateConnection(_dateContext);

            //User Connnection;
            _userConnection = new UserConnection(_userContext);
        }