Example #1
0
 private static string GetGroupTo(Message mess)
 {
     using (DataModelContainer db = new DataModelContainer())
     {
         return(db.Groups.FirstOrDefault(x => x.Id == mess.GroupTo_Id).Name);
     }
 }
Example #2
0
        // GET: UserInfo
        public ActionResult Index()
        {
            DataModelContainer dbContext = new DataModelContainer();

            ViewData.Model = dbContext.UserInfo;
            return(View());
        }
Example #3
0
        public static void SendUnreadPrivateMessageToClient(object data)
        {
            int        userId   = (int)data;
            ClientInfo clientTo = listClients.FirstOrDefault(x => x.UserId == userId);

            using (DataModelContainer db = new DataModelContainer())
            {
                int[] messIds    = db.ReadMessages.Where(x => x.User_Id == userId && x.IsRead == false).Select(x => x.Message_Id).ToArray();
                var   unreadMess = db.Messages.Where(x => (x.UserTo_Id == userId && x.IsRead == false) || messIds.Contains(x.Id)).OrderBy(x => x.Date); // все непрочитанные сообщения, личные и групповые

                foreach (var mess in unreadMess)
                {
                    if (mess.UserTo_Id != null) //личное сообщение
                    {
                        bool res = clientTo.callback.ReceivePrivateMessage(GetLoginFrom(mess), GetLoginTo(mess), mess.Text, mess.Date);
                        if (res)
                        {
                            mess.IsRead = true;
                            db.Entry(mess).Property(c => c.IsRead).IsModified = true;
                        }
                    }
                    else //групповое сообщение
                    {
                        bool res = clientTo.callback.ReceivePrivateMessage(GetLoginFrom(mess), GetGroupTo(mess), mess.Text, mess.Date);
                        if (res)
                        {
                            ReadMessage rm = db.ReadMessages.FirstOrDefault(x => x.Message_Id == mess.Id && x.User_Id == userId);
                            rm.IsRead = true;
                            db.Entry(rm).Property(c => c.IsRead).IsModified = true;
                        }
                    }
                }
                db.SaveChanges();
            }
        }
Example #4
0
        public void expendFilter_1()
        {
            dataModels = new DataModelContainer();

            string[] filter1     = { "AAA", "BBB", "CCC", "DDD" };
            string[] returnTable = dataModels._A_expendFilter(filter1, 4);
            for (int count = 0; count < 4; count++)
            {
                //TODO A revoir complètement
                StringAssert.AreEqualIgnoringCase(filter1[count], returnTable[count]);
            }

            string[] filter2 = { "AAA", "*", "DDD" };
            returnTable = dataModels._A_expendFilter(filter2, 4);
            Assert.AreEqual("AAA", returnTable[0]);
            Assert.AreEqual("*", returnTable[1]);
            Assert.AreEqual("*", returnTable[2]);
            Assert.AreEqual("DDD", returnTable[3]);

            string[] filter3 = { "AAA", "*" };
            returnTable = dataModels._A_expendFilter(filter3, 4);
            Assert.AreEqual("AAA", returnTable[0]);
            Assert.AreEqual("*", returnTable[1]);
            Assert.AreEqual("*", returnTable[2]);
            Assert.AreEqual("*", returnTable[3]);

            string[] filter4 = { "*", "DDD" };
            returnTable = dataModels._A_expendFilter(filter4, 4);
            Assert.AreEqual("*", returnTable[0]);
            Assert.AreEqual("*", returnTable[1]);
            Assert.AreEqual("*", returnTable[2]);
            Assert.AreEqual("DDD", returnTable[3]);
        }
Example #5
0
        public void test_compute()
        {
            dataModels = new DataModelContainer();

            string modelName             = "DA.FALCON.7X.7X.UV1.DRY";
            List <CommandFactor> factors = new List <CommandFactor>();

            factors.Add(new CommandFactor("SF=2"));
            factors.Add(new CommandFactor("ALT=1600"));
            factors.Add(new CommandFactor("TEMP=30"));
            factors.Add(new CommandFactor("GW=62000"));
            factors.Add(new CommandFactor("A/I=0"));

            //System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.DefaultTraceListener());


            dataModels.loadDataModels("", "DA.*");
            // TODO Tester si on peut bien injecter un nouveau directory path grace à loadDataModels()


            //System.Diagnostics.Debug.WriteLine("Data Models Directory : " + dataModels.getDataModelsDirectory()[0]);
            //System.Diagnostics.Debug.WriteLine("Press a key");

            // Assert.IsTrue(dataModels.dataModelIndex(modelName) == 0);
            // Assert.IsFalse(double.IsNaN(dataModels.compute(modelName, factors)));
        }
Example #6
0
        private void NewMethod()
        {
            DataModelContainer db = new DataModelContainer();
            var minyear           = db.T_ProductTradeDaySummary.Min(m => m.TradeYear);//获取数据表中最早的一年

            ViewBag.minyear = minyear;
        }
Example #7
0
        public int createComment(int userId, int movieId, string commentContent)
        {
            using (var db = new DataModelContainer())
            {
                db.Database.Connection.Open();

                var myComment = new Comment()
                {
                    content = commentContent,
                    UserId  = userId,
                    MovieId = movieId
                };

                db.Entry(myComment).State = System.Data.Entity.EntityState.Added;
                int res = db.SaveChanges();

                if (res > 0)
                {
                    MessageBox.Show("Comment creation successful");
                    return(res);
                }
                else
                {
                    MessageBox.Show("Error cant create comment");
                    return(res);
                }
            }
        }
Example #8
0
        public int addRate(int userId, int movieId, int rateValue)
        {
            using (var db = new DataModelContainer())
            {
                db.Database.Connection.Open();

                var myRate = new Rate()
                {
                    rate    = rateValue,
                    UserId  = userId,
                    MovieId = movieId
                };

                db.Entry(myRate).State = System.Data.Entity.EntityState.Added;
                int res = db.SaveChanges();

                if (res > 0)
                {
                    MessageBox.Show("successfuly add rate");
                    return(res);
                }
                else
                {
                    MessageBox.Show("Error can't add rate to the movie");
                    return(res);
                }
            }
        }
Example #9
0
 public void AddList(Cell[,] gameField, int TypeGame, int Iter)
 {
     using (var db = new DataModelContainer())
     {
         var game = new Game()
         {
             Type = TypeGame, SizeX = gameField.Length / gameField.GetLength(0), SizeY = gameField.GetLength(0), Iteration = Iter
         };
         db.GameSet.Add(game);
         Coords coord;
         for (int i = 0; i < gameField.Length / gameField.GetLength(0); i++)
         {
             for (int j = 0; j < gameField.GetLength(0); j++)
             {
                 if (gameField[i, j] != null)
                 {
                     coord = new Coords()
                     {
                         CoordX = gameField[i, j].CoordX, CoordY = gameField[i, j].CoordY, TypeLiving = (int)gameField[i, j].livingName, Game = game
                     };
                     db.CoordsSet.Add(coord);
                 }
             }
         }
         db.SaveChanges();
     }
 }
Example #10
0
        public void TestMethod1()
        {
            DataModelContainer db = new DataModelContainer();
            var temp = new UserInfoBLL().GetList(o => true);

            foreach (UserInfo userinfo in temp)
            {
                string a = userinfo.Name;
            }
            //for (int i = 29; i < 30; i++)
            //{
            //    UserInfo userinfo = new UserInfo()
            //    {
            //        Name = "测试" + i
            //    };
            //    new UserInfoBLL().Add(userinfo);
            //    //new UserInfoDAL().Add();
            //}
            //new UserInfoBLL().Delete(new UserInfo()
            //{
            //    ID = 2
            //});
            //var temp = new UserInfoBLL().GetList( o => o.Name.Contains("测"));
            //foreach (UserInfo userinfo in temp)
            //{

            //}
            //
            // TODO: 在此处添加测试逻辑
            //
        }
Example #11
0
        public async Task <ActionResult> add(FileViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                string url      = "/Content/FileManager/" + model.file.FileName;
                string savePath = AppDomain.CurrentDomain.BaseDirectory + url;
                System.Diagnostics.Debug.WriteLine("dir   " + AppDomain.CurrentDomain.BaseDirectory);
                model.file.SaveAs(savePath);
                using (DataModelContainer db = new DataModelContainer())
                {
                    User user = (User)Session["user"];
                    File file = new File()
                    {
                        User_id    = user.id,
                        title      = model.title,
                        url        = url,
                        createtime = new DateTime(),
                        isshared   = model.isShared == 1
                    };

                    db.File.Add(file);
                    db.SaveChanges();
                }
            }
            return(View(model));
        }
Example #12
0
 public Façade()
 {
     dataModelContainer = new DataModelContainer();
     utilisateurDao     = new UtilisateurDao(dataModelContainer);
     movieDao           = new MovieDao(dataModelContainer);
     commentsDao        = new CommentsDao(dataModelContainer);
 }
Example #13
0
        private void FillDataView(DataGridView dataGridView)
        {
            int i, count;

            try
            {
                using (db = new DataModelContainer())
                {
                    db.Database.CreateIfNotExists();
                    count = db.GameSet.Count();
                    if (count != 0)
                    {
                        dataGridView.RowCount    = count;
                        dataGridView.ColumnCount = 5;
                        i = 0;
                        foreach (var item in db.GameSet)
                        {
                            dataGridView[0, i].Value = item.Id;
                            dataGridView[1, i].Value = item.Type;
                            dataGridView[2, i].Value = item.Iteration;
                            dataGridView[3, i].Value = item.SizeX;
                            dataGridView[4, i].Value = item.SizeY;
                            i++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                recordBase.ErrorBase(ex);
            }
        }
Example #14
0
        /// <summary>
        /// 内连接查询
        /// </summary>
        /// <param name="userQueryParam">查询条件</param>
        /// <returns>查询结果</returns>
        public IQueryable <UserInfoRoleInfo> LoagUserPageData(UserQueryParam userQueryParam)
        {
            short delFlag            = (short)Glove.IOT.Model.Enum.StatusFlagEnum.Deleted;
            DataModelContainer model = new DataModelContainer();
            //内连接查询
            var query = from t1 in model.UserInfo
                        join t2 in model.R_UserInfo_RoleInfo on t1.Id equals t2.UserInfoId
                        join t3 in model.RoleInfo on t2.RoleInfoId equals t3.Id
                        where (t2.StatusFlag != delFlag && t3.StatusFlag != delFlag)
                        select new UserInfoRoleInfo
            {
                UId        = t1.Id,
                RId        = t3.Id,
                UCode      = t1.UCode,
                UName      = t1.UName,
                RoleName   = t3.RoleName,
                StatusFlag = t1.StatusFlag
            };

            userQueryParam.Total = query.Count();

            return(query.OrderBy(u => u.UId)
                   .Skip(userQueryParam.PageSize * (userQueryParam.PageIndex - 1))
                   .Take(userQueryParam.PageSize).AsQueryable());
        }
Example #15
0
 private static string GetLoginTo(Message mess)
 {
     using (DataModelContainer db = new DataModelContainer())
     {
         return(db.Users.FirstOrDefault(x => x.Id == mess.UserTo_Id).Login);
     }
 }
Example #16
0
 public static List <Clients> GetAllClients()
 {
     using (var context = new DataModelContainer())
     {
         List <Clients> clients = new List <Clients>();
         return(context.Set <Clients>().ToList());
     }
 }
Example #17
0
        public ActionResult Create(UserInfo userInfo)
        {
            DataModelContainer dbContext = new DataModelContainer();

            dbContext.UserInfo.Add(userInfo);
            dbContext.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #18
0
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         Connection = null;
         Context    = null;
     }
 }
Example #19
0
        public List <Movies> SearchMovies(string query)
        {
            DataModelContainer ctx         = new DataModelContainer();
            List <string>      query_words = query.Split(' ', ',').ToList();
            List <Movies>      results     = ctx.MoviesSet.Where(m => query_words.Any(q => m.Name.Contains(q) || m.Genre.Contains(q) || m.Description.Contains(q))).ToList();

            return(results);
        }
Example #20
0
        public User LogUser(User user)
        {
            DataModelContainer ctx = DataModelContainer.GetDb();

            return(ctx.UserSet
                   .Where(u => u.Login == user.Login && user.Password == u.Password)
                   .Select(u => u).FirstOrDefault());
        }
Example #21
0
        public bool DeleteComment(Comment comment)
        {
            DataModelContainer ctx      = DataModelContainer.GetDb();
            Comment            toDelete = ctx.CommentSet.Where(c => c.Id == comment.Id).FirstOrDefault();

            ctx.CommentSet.Remove(toDelete);
            ctx.SaveChanges();
            return(true);
        }
Example #22
0
        public bool DeleteMovie(Movie movie)
        {
            DataModelContainer ctx = new DataModelContainer();
            Movie toDelete         = ctx.MovieSet.Where(m => m.Id == movie.Id).FirstOrDefault();

            ctx.MovieSet.Remove(toDelete);
            ctx.SaveChanges();
            return(true);
        }
Example #23
0
        public Room GetRoom(int id)
        {
            using (DataModelContainer container = new DataModelContainer())
            {
                var room = container.Rooms.FirstOrDefault(r => r.Id == id);

                return(room);
            }
        }
Example #24
0
        public IEnumerable <Room> GetRooms()
        {
            using (DataModelContainer container = new DataModelContainer())
            {
                var rooms = container.Rooms;

                return(rooms.ToList());
            }
        }
Example #25
0
        public Hotel GetHotel()
        {
            using (DataModelContainer container = new DataModelContainer())
            {
                var hotel = container.Hotels.FirstOrDefault();

                return(hotel);
            }
        }
Example #26
0
        public Movie CreateMovie(Movie movie)
        {
            DataModelContainer ctx = new DataModelContainer();

            Console.WriteLine("movie in create: " + movie.Title);
            ctx.MovieSet.Add(movie);
            ctx.SaveChanges();
            return(movie);
        }
Example #27
0
        public bool DeleteUser(User user)
        {
            DataModelContainer ctx = DataModelContainer.GetDb();
            User toDelete          = ctx.UserSet.Where(u => u.Id == user.Id).FirstOrDefault();

            ctx.UserSet.Remove(toDelete);
            ctx.SaveChanges();
            return(true);
        }
Example #28
0
        public List <Movie> SearchMovies(string query)
        {
            Console.WriteLine("SearchMovies");
            DataModelContainer ctx         = new DataModelContainer();
            List <string>      query_words = query.Split(' ', ',').ToList();
            List <Movie>       results     = ctx.MovieSet.Where(m => query_words.Any(q => m.Title.Contains(q) || m.Abstract.Contains(q) || m.Type.Contains(q))).ToList();

            return(results);
        }
Example #29
0
        public User CreateUser(User user)
        {
            DataModelContainer ctx = DataModelContainer.GetDb();

            Console.WriteLine("user in create: " + user.Login);
            ctx.UserSet.Add(user);
            ctx.SaveChanges();
            return(user);
        }
Example #30
0
        public Comment CreateComment(Comment comment)
        {
            DataModelContainer ctx = new DataModelContainer();

            Console.WriteLine("comment in create: " + comment.Message);
            ctx.CommentSet.Add(comment);
            ctx.SaveChanges();
            return(comment);
        }
 public ActionResult BasicStats()
 {
     DataModelContainer db = new DataModelContainer();
     if (User.IsInRole(Constants.UPAYA_ADMIN))
     {
         StringBuilder sb = new StringBuilder();
         foreach (PartnerCompany comp in db.PartnerCompanies)
         {
             sb.Append("<b>"+comp.Name+"</b><br />");
             sb.Append(GetBasicStats(db, comp.Id) + "<br /><br />");
         }
         ViewBag.Message = sb.ToString();
     }
     else if (User.IsInRole(Constants.PARTNER_ADMIN))
     {
         Guid compId = AccountHelper.GetCurCompanyId(db);
         string msg = GetBasicStats(db, compId);
         ViewBag.Message = msg;
     }
     return View();
 }
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    // Successful login here; do something...
                    try
                    {
                        // Update the last login time
                        DataModelContainer db = new DataModelContainer();
                        Guid userId = Guid.Parse(user.Id);
                        Logins l = db.Logins.Find(userId);
                        if (l == null)
                        {
                            l = new Logins();
                            l.Id = userId;
                            l.LastLoginTime = DateTime.UtcNow;
                            db.Logins.Add(l);
                        }
                        else
                        {
                            l.LastLoginTime = DateTime.UtcNow;
                        }
                        db.SaveChanges();

                        // Set the company name
                        //if (User.IsInRole(Constants.PARTNER_ADMIN))
                        {
                            PartnerStaffMember psmu = db.PartnerStaffMembers.Where(x => x.Id == userId).FirstOrDefault();
                            if (psmu != null)
                            {
                                Session["CompanyName"] = psmu.PartnerCompany.Name;
                            }
                            else
                            {
                                PartnerAdmin pau = db.PartnerAdmins.Where(x => x.Id == userId).FirstOrDefault();
                                if (pau != null)
                                {
                                    Session["CompanyName"] = pau.PartnerCompany.Name;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    
                    //return RedirectToLocal(returnUrl);
                    // Always go to Home
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        string GetBasicStats(DataModelContainer db, Guid companyId)
        {
            int benefCount = db.Beneficiaries.Where(x => x.PCompanyId == companyId).Count();
            string msg = "Beneficiaries: " + benefCount;

            int totalAdults = 0, totalChildren = 0;
            int withAdult = 0, withChild = 0, withHomeInfo = 0, withHealthInfo = 0, withMealsInfo = 0;
            foreach (Beneficiary b in db.Beneficiaries.Where(x => x.PCompanyId == companyId))
            {
                if (b.Adults.Count() > 0)
                {
                    withAdult++;
                    totalAdults += b.Adults.Count();
                }
                if (b.Children.Count() > 0)
                {
                    withChild++;
                    totalChildren += b.Children.Count();
                }
                if (b.HousingInfo != null)
                    withHomeInfo++;
                if (b.HealthCareInfo != null)
                    withHealthInfo++;
                if (b.Meals != null)
                    withMealsInfo++;
            }
            msg += "<br />Beneficiaries with adult records: " + withAdult;
            msg += "<br />Beneficiaries with child records: " + withChild;
            msg += "<br />Total adults: " + totalAdults;
            msg += "<br />Total children: " + totalChildren;
            msg += "<br />Beneficiaries with housing info: " + withHomeInfo;
            msg += "<br />Beneficiaries with healthcare info: " + withHealthInfo;
            msg += "<br />Beneficiaries with meals info: " + withMealsInfo;
            return msg;
        }
        public ActionResult InitDB()
        {
            DataModelContainer db = new DataModelContainer();
            bool needSaving = false;

            //-----------------------------------------------------------------
            if (!db.Genders.Any(g => g.Title == "Male"))
            {
                db.Genders.Add(new Gender() { Title = "Male" });
                needSaving = true;
            }
            if (!db.Genders.Any(g => g.Title == "Female"))
            {
                db.Genders.Add(new Gender() { Title = "Female" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            if (!db.Countries.Any(c => c.Name == "India"))
            {
                db.Countries.Add(new Country() { Id = "in", Name = "India" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            string[] items = new string[] {
                               "ap", "Andhra Pradesh", "in",      "up", "Uttar Pradesh", "in",
                               "ar", "Arunachal Pradesh", "in",   "cg", "Chhattisgarh", "in",
                               "as", "Assam", "in",               "tr", "Tripura", "in",
                               "br", "Bihar", "in",               "tn", "Tamil Nadu", "in",
                               "mh", "Maharashtra", "in",         "py", "Puducherry", "in",
                               "pb", "Punjab", "in",              "nl", "Nagaland", "in",
                               "sk", "Sikkim", "in",              "or", "Odisha", "in",
                               "ga", "Goa", "in",                 "ka", "Karnataka", "in",
                               "gj", "Gujarat", "in",             "hr", "Haryana", "in",
                               "hp", "Himachal Pradesh", "in",    "jk", "Jammu & Kashmir", "in",
                               "jh", "Jharkhand", "in",           "ka", "Karnataka", "in",
                               "rj", "Rajasthan", "in",           "ml", "Meghalaya", "in",
                               "kl", "Kerala", "in",              "mp", "Madhya Pradesh", "in",
                               "mn", "Manipur", "in",             "wb", "West Bengal", "in"
                             };
            for(int i=0; i<items.Length; i+=3)
            {
                string abbr = items[i], name = items[i+1], cid = items[i + 2];
                if (!db.States.Any(sx => sx.CountryId == cid && (sx.Abbr == abbr || sx.Name == name)))
                {
                    db.States.Add(new State() { Abbr = abbr, Name = name, CountryId = cid });
                    needSaving = true;
                }
            }
            if (needSaving)
            {
                db.SaveChanges();
                needSaving = false;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Not religious", "Hindu", "Muslim", "Christian", "Other" };
            foreach(string itm in items)
                if (!db.Religions.Any(r => r.Title == itm))
                {
                    db.Religions.Add(new Religion() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------------
            items = new string[] { /*"Not disabled",*/ "Deaf", "Dumb", "Blind", "Dysfunctional hand", "Dysfunctional leg", "Other"};
            foreach(string itm in items)
                if (!db.Disabilities.Any(d => d.Title == itm))
                {
                    db.Disabilities.Add(new Disability() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            if (!db.StaffTypes.Any(st => st.Title == "Field"))
            {
                db.StaffTypes.Add(new StaffType() { Title = "Field" });
                needSaving = true;
            }
            if (!db.StaffTypes.Any(st => st.Title == "Office"))
            {
                db.StaffTypes.Add(new StaffType() { Title = "Office" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            if (!db.Languages.Any(e => e.Title == "English"))
            {
                db.Languages.Add(new Language() { Title = "English" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Government school", "Private school", "Madrasa", "Anganwadi" };
            foreach (string itm in items)
                if (!db.SchoolTypes.Any(st => st.Title == itm))
                {
                    db.SchoolTypes.Add(new SchoolType() { Title = itm });
                    needSaving = true;
                }
            if (!db.SchoolTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.SchoolTypes.Add(new SchoolType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Schedule Caste (SC)", "Schedule Tribe (ST)", "Other Backward Caste (OBC)", "General" };
            foreach (string itm in items)
                if (!db.Castes.Any(c => c.Title == itm))
                {
                    db.Castes.Add(new Caste() { Title = itm });
                    needSaving = true;
                }

            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "1", "2", "3", "4", "5", "8", "10", "12", "Graduate", "Illiterate" };
            foreach (string itm in items)
                if (!db.EducationLevels.Any(e => e.Title == itm))
                {
                    db.EducationLevels.Add(new EducationLevel() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "1", "2", "3", "4", "5", "8", "10", "12", "Graduate", "Illiterate" };
            foreach (string itm in items)
                if (!db.ClassLevels.Any(e => e.Title == itm))
                {
                    db.ClassLevels.Add(new ClassLevel() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Son", "Daughter", "Brother", "Sister", "Grandchild", "In-law", "Niece", "Nephew", "Adopted" };
            foreach (string itm in items)
                if (!db.ChildRelationships.Any(r => r.Title == itm))
                {
                    db.ChildRelationships.Add(new ChildRelationship() { Title = itm });
                    needSaving = true;
                }
            if (!db.ChildRelationships.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.ChildRelationships.Add(new ChildRelationship() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Husband", "Wife", "Brother", "Sister", "Son", "Daughter", "Mother-in-Law", "Father-in-Law",
                                   "Daughter-in-Law", "Son-in-Law", "Sister-in-Law", "Brother-in-Law", "Niece", "Nephew", "Grandmother", "Grandfather" };
            foreach (string itm in items)
                if (!db.AdultRelationships.Any(r => r.Title == itm))
                {
                    db.AdultRelationships.Add(new AdultRelationship() { Title = itm });
                    needSaving = true;
                }
            if (!db.AdultRelationships.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.AdultRelationships.Add(new AdultRelationship() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Raised bed", /*"Bed net",*/ "Chair", /*"Mirror",*/ "Mobile phone", /*"Telephone (land line)",*/ "Refrigerator",
                "Storage drum", "Cook stove", "Door with lock", /*"Window with lock",*/ "Television", "VCR/DVD/VCD", "Bicycle", "Car",
                "MC/scooter", "Generator", /*"Inverter",*/ "Almira", "Pressure cooker/pan", "Casserole/thermos/thermoware", /*"Pushcard/rickshaw",*/
                "Sawing machine", /*"Electric fan",*/ "Chicken", "Goats/pig", "Cow (female, dairy)", "Cow (male)", "Buffalo", "Room", "Radio",
                // Partner specific?
                "Plow", "Diesel pump", "Loom (hand)", "Loom (powered)", "Warping machine", "Spindle", "Bobbin", "Shuttle"
            };
            foreach (string itm in items)
                if (!db.AssetTypes.Any(e => e.Title == itm))
                {
                    db.AssetTypes.Add(new AssetType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Rice", "Roti", "Leafy Vegetables", "Potato", "Cauliflower", "Tomato" };
            foreach (string itm in items)
                if (!db.MealTypes.Any(mt => mt.Title == itm))
                {
                    db.MealTypes.Add(new MealType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Kirana Shop", "Fair Price Shop (Ration Shop)", "Weekly Village Market", "Local Mandi" };
            foreach (string itm in items)
                if (!db.FoodSourceTypes.Any(fs => fs.Title == itm))
                {
                    db.FoodSourceTypes.Add(new FoodSourceType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Under 0.5km", "0.5 - 2km", "2 - 7km", "7 - 10km", "More than 10km" };
            foreach (string itm in items)
                if (!db.SchoolDistances.Any(sd => sd.Title == itm))
                {
                    db.SchoolDistances.Add(new SchoolDistance() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Non-Working", "Cultivator", "Self Employed in Agriculture", "Beedi Maker",
                                   "NREGA Worker", "Other Casual Labor (Coolie)", "Cattle/Animal Rearing", "Weaver", "Handicraftsman", "Small business owner",
                                   "Student", "Riskshaw Puller", "Housewife", "Factory Worker", "Helper-Weaving activity" };

            foreach (string itm in items)
                if (!db.Occupations.Any(ao => ao.Title == itm))
                {
                    db.Occupations.Add(new Occupation() { Title = itm });
                    needSaving = true;
                }
            if (!db.Occupations.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.Occupations.Add(new Occupation() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            for (byte i = 1; i < 6; i++)
                if (!db.SchoolDaysPerWeek.Any(ao => ao.Id == i))
                {
                    db.SchoolDaysPerWeek.Add(new SchoolDayPerWeek() { Id = i, Title = ""+i });
                    needSaving = true;
                }
            if(needSaving)
            {
                db.SaveChanges();
                needSaving = false;
            }
            //-----------------------------------------------------------------
            items = GetIndianDistricts();
            for (int i = 0; i < items.Length; i += 4)
            {
                string abbr = items[i].ToLower(), name = items[i + 1], stabbr = items[i + 2].ToLower(), cid = items[i + 3].ToLower();
                State st = db.States.Where(x => x.CountryId == cid && x.Abbr == stabbr).FirstOrDefault();
                if (st != null)
                {
                    if (!db.Districts.Any(d => d.StateId == st.Id && (d.Abbr == abbr || d.Name == name)))
                    {
                        db.Districts.Add(new District() { Abbr = abbr, Name = name, StateId = st.Id });
                        needSaving = true;
                        //db.SaveChanges();
                    }
                }
            }
            //-----------------------------------------------------------------
            items = new string[] { "Spiritual Healer / Tantrik", "Homoepathic / Ayurvedic Doctor", "RMP", "Primary Health Centre (PHC) / Govt Doctor",
                                   "Pvt Clinic / MBBS", "Hospital" };
            foreach (string itm in items)
                if (!db.HcProviderTypes.Any(hp => hp.Title == itm))
                {
                    db.HcProviderTypes.Add(new HcProviderType() { Title = itm });
                    needSaving = true;
                }
            if (!db.HcProviderTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.HcProviderTypes.Add(new HcProviderType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Fever", "Cough", "Diarrehea", "Joint pain", "Fatigue", "Wound", "Skin rash or lesion", "Malaria", "Tuberculosis",
                                   "Animal bite", "Dehydration", "Headache", "Infection", "Gynecological problems", "Tumor/growth" };
            foreach (string itm in items)
                if (!db.HealthIssueTypes.Any(hi => hi.Title == itm))
                {
                    db.HealthIssueTypes.Add(new HealthIssueType() { Title = itm });
                    needSaving = true;
                }
            if (!db.HealthIssueTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.HealthIssueTypes.Add(new HealthIssueType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Spiritual Healer / Tantrik", "Homoepathic / Ayurvedic Doctor", "RMP", "Primary Health Centre (PHC) / Govt Doctor",
                                   "Pvt Clinic / MBBS", "Hospital" };
            foreach (string itm in items)
                if (!db.MedSourceTypes.Any(ms => ms.Title == itm))
                {
                    db.MedSourceTypes.Add(new MedSourceType() { Title = itm });
                    needSaving = true;
                }
            if (!db.MedSourceTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.MedSourceTypes.Add(new MedSourceType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Yellow Ration Card", "Red Ration Card", "Blue Ration Card", "Health Card", "Voter ID Card", "Weaver's Card" };
            foreach (string itm in items)
                if (!db.GovCardTypes.Any(gc => gc.Title == itm))
                {
                    db.GovCardTypes.Add(new GovCardType() { Title = itm });
                    needSaving = true;
                }
            if (!db.GovCardTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.GovCardTypes.Add(new GovCardType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Housing (Indira Awaas Yojana)", "Finance/SHG", "Employment/training", "Childcare/ICDS (Anaganwadi)/Mid-day Meal",
                                   "100 days Work Guarantee (NREGA)", "Ration Shop (PDS)", "Aadhar/Voter ID Card", "Subsidized Yarn or Loom (Weaver's Card)",
                                   "Health Insurance (RSBY)" };

            foreach (string itm in items)
                if (!db.GovServiceTypes.Any(gs => gs.Title == itm))
                {
                    db.GovServiceTypes.Add(new GovServiceType() { Title = itm });
                    needSaving = true;
                }
            if (!db.GovServiceTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.GovServiceTypes.Add(new GovServiceType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "1", "2 - 3", "4 - 5", "> 5" };
            foreach (string itm in items)
                if (!db.NumberOfRoomsTypes.Any(nx => nx.Title == itm))
                {
                    db.NumberOfRoomsTypes.Add(new NumberOfRoomsType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Thatch/Mud", "Tiles", "Stones", "Cement" };
            foreach (string itm in items)
                if (!db.WallMaterialTypes.Any(wx => wx.Title == itm))
                {
                    db.WallMaterialTypes.Add(new WallMaterialType() { Title = itm });
                    needSaving = true;
                }
            if (!db.WallMaterialTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.WallMaterialTypes.Add(new WallMaterialType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Thatch/Mud", "Tiles", "Stones", "Cement" };
            foreach (string itm in items)
                if (!db.RoofMaterialTypes.Any(wx => wx.Title == itm))
                {
                    db.RoofMaterialTypes.Add(new RoofMaterialType() { Title = itm });
                    needSaving = true;
                }
            if (!db.RoofMaterialTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.RoofMaterialTypes.Add(new RoofMaterialType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Public Well/Tap", "Private Tap", "Private Pump", "Borewell" };
            foreach (string itm in items)
                if (!db.WaterSourceTypes.Any(wx => wx.Title == itm))
                {
                    db.WaterSourceTypes.Add(new WaterSourceType() { Title = itm });
                    needSaving = true;
                }
            if (!db.WaterSourceTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.WaterSourceTypes.Add(new WaterSourceType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Open", "Pit", "Bricks", "Flush" };
            foreach (string itm in items)
                if (!db.ToiletTypes.Any(wx => wx.Title == itm))
                {
                    db.ToiletTypes.Add(new ToiletType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Firewood", "Coal", "LPG", "Electricity", "Kerosene" };
            foreach (string itm in items)
                if (!db.CookingEnergyTypes.Any(wx => wx.Title == itm))
                {
                    db.CookingEnergyTypes.Add(new CookingEnergyType() { Title = itm });
                    needSaving = true;
                }
            if (!db.CookingEnergyTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.CookingEnergyTypes.Add(new CookingEnergyType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            if (!db.HouseQualityTypes.Any(g => g.Title == "Unknown" || g.Id == 0))
            {
                db.HouseQualityTypes.Add(new HouseQualityType() { Id = 0, Title = "Unknown" });
                needSaving = true;
            }
            /*
            if (!db.HouseQualityTypes.Any(g => g.Title == "Pucca" || g.Id == (byte)'p'))
            {
                db.HouseQualityTypes.Add(new HouseQualityType() { Id = (byte)'p', Title = "Pucca" });
                needSaving = true;
            }
            if (!db.HouseQualityTypes.Any(g => g.Title == "Semi-pucca" || g.Id == (byte)'s'))
            {
                db.HouseQualityTypes.Add(new HouseQualityType() { Id = (byte)'s', Title = "Semi-pucca" });
                needSaving = true;
            }
            if (!db.HouseQualityTypes.Any(g => g.Title == "Kacha" || g.Id == (byte)'k'))
            {
                db.HouseQualityTypes.Add(new HouseQualityType() { Id = (byte)'k', Title = "Kacha" });
                needSaving = true;
            }
            */
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Self owned", "Rented", "Religious grant", "Government housing" };
            foreach (string itm in items)
                if (!db.HouseOwnershipTypes.Any(ot => ot.Title == itm))
                {
                    db.HouseOwnershipTypes.Add(new HouseOwnershipType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "0 - 15 minutes", "15 - 30 minutes", "30 - 60 minutes", "More than 1 hour" };
            foreach (string itm in items)
                if (!db.WaterSourceDistanceTypes.Any(wd => wd.Title == itm))
                {
                    db.WaterSourceDistanceTypes.Add(new WaterSourceDistanceType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "No loan", "Food", "Medical expense", "School fee", "Asset purchase/maintenance", "Housing",
                                    "Agricultural purpose" };
            foreach (string itm in items)
                if (!db.LoanPurposeTypes.Any(wd => wd.Title == itm))
                {
                    db.LoanPurposeTypes.Add(new LoanPurposeType() { Title = itm });
                    needSaving = true;
                }
            if (!db.LoanPurposeTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.LoanPurposeTypes.Add(new LoanPurposeType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "No savings", "Bank Account", "Post Office Account", "SHG", "Savings in the household", "Government bonds/Certificates",
                                    "Chit funds" };
            foreach (string itm in items)
                if (!db.SavingsTypes.Any(wd => wd.Title == itm))
                {
                    db.SavingsTypes.Add(new SavingsType() { Title = itm });
                    needSaving = true;
                }
            if (!db.SavingsTypes.Any(x => x.Title == "Others" || x.Id == 255))
            {
                db.SavingsTypes.Add(new SavingsType() { Id = 255, Title = "Others" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            /*
            items = new string[] { "Unknown" };
            foreach (string itm in items)
                if (!db.WorkDaysPerMonthTypes.Any(wd => wd.Title == itm))
                {
                    db.WorkDaysPerMonthTypes.Add(new WorkDaysPerMonthType() { Title = itm });
                    needSaving = true;
                }
            */
            //-----------------------------------------------------------------
            items = new string[] { "Ragi/Bajra", "Rice", "Wheat", "Coarse Millets" };
            foreach (string itm in items)
                if (!db.GrainTypes.Any(wd => wd.Title == itm))
                {
                    db.GrainTypes.Add(new GrainType() { Title = itm });
                    needSaving = true;
                }
            if (!db.GrainTypes.Any(x => x.Title == "Others" || x.Id == 255))
            {
                db.GrainTypes.Add(new GrainType() { Id = 255, Title = "Others" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Chana Dal", "Moong Dal", "Arhar Dal", "Soya Beans", "Masoor Dal", "Black Eyed Dal" };
            foreach (string itm in items)
                if (!db.PulseTypes.Any(wd => wd.Title == itm))
                {
                    db.PulseTypes.Add(new PulseType() { Title = itm });
                    needSaving = true;
                }
            if (!db.PulseTypes.Any(x => x.Title == "Others" || x.Id == 255))
            {
                db.PulseTypes.Add(new PulseType() { Id = 255, Title = "Others" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Tubers (Potato, Sweet potato, Yam, Onion)", "Green leafy vegetables (Spinach, Meethi, Saag)",
                                    "Root vegetables (Radish, Carrot, Tapioca)", "Tomato", "Jackfruit", "Beans" };
            foreach (string itm in items)
                if (!db.VegetableTypes.Any(wd => wd.Title == itm))
                {
                    db.VegetableTypes.Add(new VegetableType() { Title = itm });
                    needSaving = true;
                }
            if (!db.VegetableTypes.Any(x => x.Title == "Others" || x.Id == 255))
            {
                db.VegetableTypes.Add(new VegetableType() { Id = 255, Title = "Others" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Mostly (more than 5 times per month)", "Often (3-4 times per month)",
                                   "Sometimes (2-3 times per month)", "Rarely", "Never (Don't consume non-veg)" };
            foreach (string itm in items)
                if (!db.AvgNonVegPerMTypes.Any(x => x.Title == itm))
                {
                    db.AvgNonVegPerMTypes.Add(new AvgNonVegPerMType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Mostly", "Often", "Sometimes", "Rarely", "Never" };
            foreach (string itm in items)
                if (!db.PKGPerMTypes.Any(x => x.Title == itm))
                {
                    db.PKGPerMTypes.Add(new PKGPerMType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "School availability", "Can't afford school", "Works for you", "Works for  someone else", "Attended school before",
                                    "Not interested in school", "Not old enough to attend" };
            foreach (string itm in items)
                if (!db.WhyNotInSchoolTypes.Any(wx => wx.Title == itm))
                {
                    db.WhyNotInSchoolTypes.Add(new WhyNotInSchoolType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------

            if(needSaving)
                db.SaveChanges();

            return View();
        }
        public ActionResult ShowRecentUsers()
        {
            List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
            DataModelContainer db = new DataModelContainer();
            int count = 0;
            foreach(Logins lg in db.Logins.OrderByDescending(item => item.LastLoginTime))
            {
                if (lg.Id == AccountHelper.GetCurUserId())
                    continue;
                TimeSpan ts = DateTime.UtcNow - lg.LastLoginTime;
                if (ts.TotalDays > 2)
                    continue;
                Dictionary<string, object> item = new Dictionary<string, object>();
                item["Name"] = AccountHelper.GetUserNameForId(lg.Id);
                item["Time"] = lg.LastLoginTime;
                item["Ago"] = ts;
                data.Add(item);
                if (++count > 50)
                    break;
            }

            return View(data);
        }