public void Remove(int me, int favoriteId)
 {
     var db = new OkbDbContext();
     var fav = db.Favorites.Find(me, favoriteId);
     db.Favorites.Remove(fav);
     db.SaveChanges();
 }
        public List<LocationPinyinModel> GetDistricts(int id)
        {
            var db = new OkbDbContext();

            var result = from loc in db.Locations.AsNoTracking()
                         where loc.LocationId1 == id
                         select loc;

            var list = new List<LocationPinyinModel>();

            foreach (var loc in result)
            {
                var pinyinArr = PinyinHelper.ToHanyuPinyinStringArray(loc.LocationName2[0]);

                list.Add(new LocationPinyinModel
                {
                    LocationId = loc.LocationId2,
                    LocationName = loc.LocationName2,
                    Pinyin = pinyinArr != null ? pinyinArr[0] : ""
                });
            }

            list.Sort((loc1, loc2) => loc1.Pinyin.CompareTo(loc2.Pinyin));

            return list;
        }
Beispiel #3
0
        /// <summary>
        /// Seed the Answers using SqlBulkCopy for performance.  
        /// </summary>
        public void SeedAnswers(int numOfUsers, int numOfAnswersPerUser)
        {
            //Skip if answers exist
            OkbDbContext context = new OkbDbContext();
            if (context.Answers.Count() > 0)
            {
                context.Dispose();
                return;
            }
            context.Dispose();

            UserAnswerBulkDataReader bulkReader = new UserAnswerBulkDataReader(numOfUsers, numOfAnswersPerUser, "", "Answers");

            using (SqlBulkCopy sbc = new SqlBulkCopy(connString,
                SqlBulkCopyOptions.TableLock |
                SqlBulkCopyOptions.UseInternalTransaction))
            {
                sbc.BatchSize = 2000;
                sbc.DestinationTableName = "Answers";

                foreach (var col in bulkReader.ColumnMappings)
                {
                    sbc.ColumnMappings.Add(col);
                }

                sbc.WriteToServer(bulkReader);
            }
        }
 public string GetLocationString(int locId1, int locId2)
 {
     var db = new OkbDbContext();
     var loc = db.Locations.Find(locId1, locId2);
     if(loc != null)
     {
         return loc.LocationName2 + ", " + loc.LocationName1;
     }
     return "";
 }
 public void Save(int me, int favoriteId)
 {
     var db = new OkbDbContext();
     db.Favorites.Add(new Favorite
     {
         ProfileId = me,
         FavoriteId = favoriteId,
         FavoriteDate = DateTime.Now
     });
     db.SaveChanges();
 }
        public IList<Profile> GetFavorites(int profileId)
        {
            var db = new OkbDbContext();

            var query = from favorite in db.Favorites.AsNoTracking()
                        where favorite.ProfileId == profileId
                        orderby favorite.FavoriteDate descending
                        select favorite.FavoriteProfile;

            return query.ToList();
        }
        public IList<Profile> GetActiveUsers()
        {
            var db = new OkbDbContext();
            var loginThreshold = DateTime.Now.AddHours(-OkbConstants.ACTIVE_USER_INTERVAL);
            var query = from user in db.Users
                        where user.LastLoginDate > loginThreshold
                        join profile in db.Profiles.AsNoTracking() on user.ProfileId equals profile.Id
                        orderby user.LastLoginDate descending
                        select profile;

            return query.ToList();
        }
 public void AnsweredQuestionActivity(int who, string quesText, string choiceText)
 {
     var db = new OkbDbContext();
     db.ActivityFeed.Add(new Activity
     {
         Who = who,
         CategoryId = (int)OkbConstants.ActivityCategories.AnsweredQuestion,
         Field1 = Truncate(quesText, OkbConstants.FEED_BLURB_SIZE),
         Field2 = Truncate(choiceText, OkbConstants.FEED_BLURB_SIZE),
         Timestamp = DateTime.Now
     });
     db.SaveChanges();
 }
        public void EditProfileTextActivity(int who, string what)
        {
            var db = new OkbDbContext();
            var act = new Activity
            {
                Who = who,
                CategoryId = (int)OkbConstants.ActivityCategories.EditedProfileText,
                Field1 = Truncate(what, OkbConstants.FEED_BLURB_SIZE),
                Timestamp = DateTime.Now
            };

            db.ActivityFeed.Add(act);
            db.SaveChanges();
        }
        /// <summary>
        /// Starts a new conversation with the given user by adding their message to the database.
        /// returns the Id of the newly created conversation. Increments the unread count of the 
        /// user the message was sent to.
        /// </summary>
        public async Task<int> StartConversation(int from, int to, string subject, string message)
        {
            var db = new OkbDbContext();
            Message msg;
            ConversationMap mapMe, mapOther;

            //// New conversation
            var conv = new Conversation { Subject = subject };
            db.Conversations.Add(conv);

            msg = new Message
            {
                Conversation = conv,
                From = from,
                MessageText = message,
                Timestamp = DateTime.Now
            };
            db.Messages.Add(msg);

            //My copy of the conversation
            mapMe = new ConversationMap
            {
                Conversation = conv,
                LastMessage = msg,
                Other = to,
                ProfileId = from,
                HasBeenRead = true,
                HasReplies = false
            };
            db.ConversationMap.Add(mapMe);

            //Other's copy of the conversation
            mapOther = new ConversationMap
            {
                Conversation = conv,
                LastMessage = msg,
                Other = from,
                ProfileId = to,
                HasBeenRead = false,
                HasReplies = true
            };
            db.ConversationMap.Add(mapOther);

            await db.SaveChangesAsync();

            //Everything OK - we can increment the unread count
            IncrementUnreadCount(to);

            return conv.Id; //return new conversation Id
        }
        /// <summary>
        /// Gets a list of all the answer choices for a given question
        /// </summary>
        private IList<string> GetChoices(int id)
        {
            var db = new OkbDbContext();
            var list = new List<string>();
            var result = from choice in db.QuestionChoices.AsNoTracking()
                         where choice.QuestionId == id
                         orderby choice.Index ascending
                         select choice;

            foreach (var choice in result)
            {
                list.Add(choice.Text);
            }

            return list;
        }
Beispiel #12
0
        /////////////////////////// Private Methods ///////////////////////////////////
        protected int GetProfileId()
        {
            int profileId;
           
            var db = new OkbDbContext();
            var id = Context.User.Identity.GetUserId();
            var user = db.Users.Find(id);

            if (user == null)
            {
                // No profile exists for user!??!?
                throw new Exception("No profile exists for user");
            }

            profileId = user.Profile.Id;

            return profileId;
        }
Beispiel #13
0
        /// <summary>
        /// Seed the Activity feed with a bunch of activities.
        /// Can be Joined, AnsweredQuestion, UploadedPhoto, or EditedProfile
        /// </summary>
        public void SeedActivities(int n)
        {
            var db = new OkbDbContext();
            var rand = new Random();

            for (int i = 0; i < n; i++)
            {
                db.ActivityFeed.Add(new Activity
                {
                    Who = (rand.Next() % 1000) + 1,
                    CategoryId = (rand.Next() % 4) + 1,
                    Timestamp = RandomTime(rand),
                    Field1 = "this is some test text for metadata field. lorum ipsum dolor blah blah blah"
                });
            }

            db.SaveChanges();
        }
        /// <summary>
        /// Gets the next 2 un-answered questions for the user. 
        ///  - Will return a list with either 0, 1 or 2 elements. 
        ///  - The questions are ordered by Rank so questions returned will be the next "best" questions. 
        ///  - Skipped questions are stored in the DB (but not the cache) so they won't be included in the returned questions. 
        ///  - Performance-wise loops thru the answers and questions in the DB and builds a HashSet and list respectively,
        ///    so a fairly expensive operation. Have room for optimization.
        /// </summary>
        public IList<QuestionModel> Next2Questions(int profileId)
        {
            var db = new OkbDbContext();

            //Build answer dictionary
            var result = from answer in db.Answers.AsNoTracking()
                         where answer.ProfileId == profileId
                         select answer;

            var set = new HashSet<Int16>();

            foreach (var answer in result)
            {
                set.Add(answer.QuestionId);
            }

            var list = new List<QuestionModel>();

            int count = 0;

            //Loop thru all the questions ordered by rank
            var questions = from q in db.Questions.AsNoTracking()
                            orderby q.Rank ascending
                            select q;

            foreach (var question in questions)
            {
                if (set.Contains(question.Id)) continue;
                list.Add(new QuestionModel
                {
                    Id = question.Id,
                    Text = question.Text,
                    Choices = GetChoices(question.Id)
                });

                count++;

                if (count >= 2) break; //just get the next 2 questions
            }

            return list;
        }
        /// <summary>
        /// Peforms a match search for a user given their search preferences and returns a list
        /// of sorted matches.
        /// </summary>
        public List<MatchModel> Search(int profileId, MatchCriteriaModel criteria)
        {
            var db = new OkbDbContext();
            var matches = new List<MatchModel>();

            var query = BuildSearchQuery(db, criteria);

            var myAnswers = _matchCalc.GetAnswerDict(profileId);

            foreach (var p in query)
            {
                var matchResult = _matchCalc.CalculateMatchPercent(p.Id, myAnswers);

                matches.Add(new MatchModel
                {
                    MatchPercent = matchResult.MatchPercent,
                    FriendPercent = matchResult.FriendPercent,
                    EnemyPercent = matchResult.EnemeyPercent,
                    UserId = p.UserId,
                    Nickname = p.Nickname,
                    ProfileId = p.Id,
                    Photo = p.GetFirstHeadshot(),
                    Age = p.GetAge(),
                    Gender = p.Gender,
                    Location = _locRepo.GetLocationString(p.LocationId1, p.LocationId2)
                });
            }

            //For now just sort the list by match %
            matches.Sort(delegate (MatchModel m1, MatchModel m2)
            {
                return m2.MatchPercent.CompareTo(m1.MatchPercent);
            });

            return matches;
        }
        /// <summary>
        /// 
        /// Updates/Adds a users answer in the database. Called by AnswerQuestion which already
        /// validated the answer so we don't have to here.
        /// 
        /// </summary>
        protected async Task AnswerDbAsync(Answer ans)
        {
            var db = new OkbDbContext();

            var dbAns = await db.Answers.FindAsync(ans.ProfileId, ans.QuestionId);

            //Are we updating a question or adding a new one?
            if (dbAns == null)
            {
                //new answer
                ans.LastAnswered = DateTime.Now;
                db.Answers.Add(ans);
            }
            else
            {
                //update answer
                dbAns.ChoiceIndex = ans.ChoiceIndex;
                dbAns.ChoiceWeight = ans.ChoiceWeight;
                dbAns.ChoiceAccept = ans.ChoiceAccept;
                dbAns.LastAnswered = DateTime.Now;
            }

            await db.SaveChangesAsync();
        }
 public void UploadPhotoActivity(int who, string what)
 {
     var db = new OkbDbContext();
     db.ActivityFeed.Add(new Activity
     {
         Who = who,
         CategoryId = (int)OkbConstants.ActivityCategories.UploadedPhoto,
         Field1 = what,
         Timestamp = DateTime.Now
     });
     db.SaveChanges();
 }
 public Conversation GetConversation(int id)
 {
     var db = new OkbDbContext();
     var conv =  db.Conversations.Find(id);
     return conv;
 }
Beispiel #19
0
        /// <summary>
        /// Simulations answering one question to see how fast we can insert answers into the DB.
        /// Should be called in a loop and given a Random object.
        /// </summary>
        public void SimulateAnsweringQuestion(Random rand)
        {
            var db = new OkbDbContext();
            var ans = new Answer
            {
                ProfileId = rand.Next(2, 200000),
                QuestionId = (short)rand.Next(201, 1243),
                ChoiceIndex = 1,
                ChoiceWeight = 1,
                ChoiceAccept = 1,
                LastAnswered = DateTime.Now
            };

            try
            {
                db.Answers.Add(ans);
                db.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }
        }
Beispiel #20
0
        /// <summary>
        /// Seed the users by creating a OkbUser and Profile for each user.  Takes a list of provinces
        /// and randomizes the location of each user.  Uses the UserProfileBulkReader to generate random
        /// profiles.
        /// </summary>
        public void SeedUsers(int numOfUsers, IList<LocationPinyinModel> provinces, int commitCount = 100)
        {
            var db = new OkbDbContext();
            var profileGen = new ProfileGenerator(provinces);
            var userManager = new UserManager<OkbUser, string>(new UserStore<OkbUser>(db));

            db.Configuration.AutoDetectChangesEnabled = false;

            for (int i = 1; i < numOfUsers; i++)
            {
                var email = "test" + i + "@okboba.com";
                var user = new OkbUser
                {
                    UserName = email,
                    Email = email,
                    PasswordHash = userManager.PasswordHasher.HashPassword("password"),
                    SecurityStamp = Guid.NewGuid().ToString(),
                    JoinDate = DateTime.Now
                };

                var profile = profileGen.Next();

                user.Profile = profile;
                profile.UserId = user.Id;

                db.Users.Add(user);

                if (i % commitCount == 0)
                {
                    db.SaveChanges();
                    db.Dispose();
                    db = new OkbDbContext();
                    db.Configuration.AutoDetectChangesEnabled = false;
                }
            }

            db.SaveChanges();
        }
Beispiel #21
0
        public void SeedTranslateQuestions(List<TranslateQuestion> quesList)
        {
            var db = new OkbDbContext();

            foreach (var q in quesList)
            {
                db.TranslateQuestions.Add(q);
            }
            var ret = db.SaveChanges();
        }
Beispiel #22
0
        /// <summary>
        /// Seed the Questions from the given file containg Okc Questions
        /// </summary>
        public void SeedOkcQuestions(string filename)
        {
            var db = new OkbDbContext();
            if (db.Questions.Count() > 0) return;

            //////////////// Insert Okcupid questions ////////////////////
            var stream = new StreamReader(filename);
            int count = 1;

            while (!stream.EndOfStream)
            {
                var line = stream.ReadLine();

                int index = 1;
                string answerLine;

                //Loop thru answers
                while ((answerLine = stream.ReadLine()) != "" && !stream.EndOfStream)
                {
                    db.QuestionChoices.Add(new QuestionChoice
                    {
                        QuestionId = (short)count,
                        Index = (byte)index,
                        Score = 0,
                        Text = answerLine
                    });

                    index++;
                }

                //Add Question
                db.Questions.Add(new Question
                {
                    Id = (short)count,
                    Rank = count,
                    Text = line,
                    TraitId = null
                });

                count++;

                db.SaveChanges();
            }
        }
Beispiel #23
0
        /// <summary>
        /// Update the database with okboba questions
        /// </summary>
        public void SeedOkbQuestions(string filename)
        {
            string answerLine;

            var stream = new StreamReader(filename);

            var rgx = new Regex("^\\d+\\. (.*)");

            var db = new OkbDbContext();

            int count = 1;

            while (!stream.EndOfStream)
            {
                var line = stream.ReadLine(); //question
                var match = rgx.Match(line);

                var questionText = match.Groups[1].Value;

                var ques = db.Questions.Find(count);
                ques.Text = questionText;

                int index = 1;

                //delete old choices
                db.QuestionChoices.RemoveRange(db.QuestionChoices.Where(c => c.QuestionId == count));

                //Loop thru answers
                while ((answerLine = stream.ReadLine()) != "" && !stream.EndOfStream)
                {
                    db.QuestionChoices.Add(new QuestionChoice
                    {
                        QuestionId = (short)count,
                        Index = (byte)index,
                        Score = 0,
                        Text = answerLine
                    });

                    index++;
                }

                count++;

                db.SaveChanges();
            }

            //db.SaveChanges();
        }
Beispiel #24
0
        /// <summary>
        /// Seed the Locations from the given file
        /// </summary>
        public void SeedLocations(string filename)
        {
            OkbDbContext db = new OkbDbContext();
            if (db.Locations.Count() > 0)
            {
                db.Dispose();
                return;
            }

            //Read from file
            using (StreamReader sr = new StreamReader(filename))
            {
                string line;
                Int16 provinceCount = 1;

                while ((line = sr.ReadLine()) != null)
                {
                    var cities = line.Split(' ');

                    //First entry is the province
                    string province = cities[0];

                    for (Int16 districtCount = 1; districtCount < cities.Length; districtCount++)
                    {
                        string district = cities[districtCount];

                        var loc = new Location
                        {
                            LocationId1 = provinceCount,
                            LocationId2 = districtCount,
                            LocationName1 = province,
                            LocationName2 = district
                        };
                        //Update the database
                        db.Locations.Add(loc);
                        db.SaveChanges();
                    }
                    provinceCount++;
                }
            }
        }
Beispiel #25
0
        /// <summary>
        /// Seed the detail options from the given file
        /// </summary>
        public void SeedDetailOptions(string filename)
        {
            var sr = new StreamReader(filename);
            var colName = "";
            var details = new List<ProfileDetailOption>();
            byte id = 0;
            var db = new OkbDbContext();

            while (!sr.EndOfStream)
            {
                var line = sr.ReadLine();
                if (line.IndexOf('\t') != -1)
                {
                    //detail option
                    db.ProfileDetailOptions.Add(new ProfileDetailOption
                    {
                        ColName = colName,
                        Id = id,
                        Value = line.Trim()
                    });
                    //details.Add(new ProfileDetailOption
                    //{
                    //    ColName = colName,
                    //    Id = id,
                    //    Value = line.Trim()
                    //});

                    id++;
                }
                else
                {
                    //new detail
                    colName = line.Split(',')[1].Trim();
                    id = 1;
                }
            }

            db.SaveChanges();

            //Dump it out
            //foreach (var option in details)
            //{
            //    Console.WriteLine("{0}, {1}, {2}", option.Id, option.ColName, option.Value);
            //}
        }
        public IEnumerable<ActivityModel> GetActivities(int numOfActivities, byte lookingGender, int me)
        {
            //get the top N activities
            var db = new OkbDbContext();

            var result = from activity in db.ActivityFeed.AsNoTracking()
                         join profile in db.Profiles.AsNoTracking()
                         on activity.Who equals profile.Id
                         where profile.Id != me && profile.Gender == lookingGender
                         orderby activity.Timestamp descending
                         select new ActivityModel
                         {
                             Activity = activity,
                             Profile = profile
                         };

            var feed = new List<ActivityModel>();

            foreach (var item in result.Take(numOfActivities))
            {
                feed.Add(item);
            }

            return feed;
        }
        /// <summary>
        /// Gets all the unread conversations in the database that haven't been sent to email.
        /// Used by the Mail Job to notify users of unread mail.
        /// </summary>
        public IEnumerable<UnreadConversationModel> GetUnreadConversations()
        {
            var db = new OkbDbContext();

            var result = from map in db.ConversationMap.AsNoTracking()
                         where map.HasBeenRead == false && map.HasBeenEmailed == false
                         join otherProfile in db.Profiles.AsNoTracking() on map.Other equals otherProfile.Id
                         join profile in db.Profiles.AsNoTracking() on map.ProfileId equals profile.Id
                         join user in db.Users.AsNoTracking() on profile.UserId equals user.Id
                         select new UnreadConversationModel
                         {
                             Map = map,
                             OtherProfile = otherProfile,
                             Email = user.Email,
                             UserId = user.Id,
                             Name = profile.Nickname
                         };

            return result.ToList();
        }
 /// <summary>
 /// Marks all the conversations as emailed. called by the mail job after it has finished 
 /// emailing all the users their unread conversations.
 /// </summary>
 public void MarkAllAsEmailed()
 {
     var db = new OkbDbContext();
     var sql = "update ConversationMaps set HasBeenEmailed = 1 where HasBeenEmailed = 0";
     db.Database.ExecuteSqlCommand(sql);            
 }
Beispiel #29
0
        /// <summary>
        /// 
        /// Loads the inital answer cache from the database. Returns the number of answers
        /// loaded. Should be called when the app first starts.  Could take up a lot of memory.
        /// 
        /// </summary>
        public int LoadAnswerCache()
        {
            int count = 0;
            _answerCache = new Dictionary<int, List<CacheAnswer>>();

            var db = new OkbDbContext();
            List<CacheAnswer> list;

            foreach (var ans in db.Answers.AsNoTracking())
            {
                //Don't load questions the user skipped (ChoiceBit==null)
                if (ans.ChoiceIndex == null) continue;

                if (!_answerCache.TryGetValue(ans.ProfileId, out list))
                {
                    list = new List<CacheAnswer>();
                    _answerCache.Add(ans.ProfileId, list);
                }

                list.Add(new CacheAnswer
                {
                    QuestionId = ans.QuestionId,
                    ChoiceBit = ans.ChoiceBit(),
                    ChoiceAccept = ans.ChoiceAccept,
                    ChoiceWeight = ans.ChoiceWeight,
                    LastAnswered = ans.LastAnswered
                });

                count++;
            }

            return count;
        }
 public void JoinedActivity(int who)
 {
     var db = new OkbDbContext();
     db.ActivityFeed.Add(new Activity
     {
         Who = who,
         CategoryId = (int)OkbConstants.ActivityCategories.Joined,
         Field1 = "",
         Timestamp = DateTime.Now
     });
     db.SaveChanges();
 }