Exemplo n.º 1
0
 public async static Task<TopViewModel> GetTopViewModel(HttpRequestBase req, ApplicationDbContext context, bool isDebug)
 {
     TopViewModel viewModel = new TopViewModel(req);
     IQueryable<TopicModel> searchedTopics;
     if (isDebug)
     {
         searchedTopics = context.Topics.OrderBy(f => f.EvaluationOfFire).Take(TopTakeCount);
     }
     else
     {
         searchedTopics = context.Topics.Where(f => f.IsVisibleToAllUser).OrderBy(f => f.EvaluationOfFire).Take(TopTakeCount);
     }
     viewModel.TopicSections = new TopicSection[await searchedTopics.CountAsync()];
     int count = 0;
     foreach (var topicModel in searchedTopics)
     {
         viewModel.TopicSections[count] = await TopicSection.FromModelAsync(context, topicModel);
         count++;
     }
     //今もえている記事の生成
     List<ArticleModel> flamedArticles = new List<ArticleModel>();
     var flamedArticlesQuery = context.CurrentRanking.Where(f => true)
         .OrderBy(f => f.PVCoefficient).Take(3).ToList();
     foreach (var rankingModel in flamedArticlesQuery)
     {
         flamedArticles.Add(await context.Articles.FindAsync(rankingModel.ArticleId));
     }
     viewModel.FlameArticles = flamedArticles.ToArray();
     return viewModel;
 }
Exemplo n.º 2
0
        public static string GetContent(ApplicationDbContext context, string pageCode)
        {
            var contentNotFound = new PageContent
            {
                Content = "No Page Data found",
                PageCode = pageCode
            };

            var content = new PageContent();
            try
            {
                content = context.PageContents.First(pageContent => pageContent.PageCode == pageCode);
            }
            catch (Exception e)
            {
                content.Content = e.Message;
                content.PageCode = pageCode;
                return contentNotFound.Content;
            }


            if (content != null)
                return content.Content;

           
            return contentNotFound.Content;
        }
 public CourseTemplatesController(ApplicationDbContext context, ApplicationUserManager userManager,
     ApplicationRoleManager roleManager)
 {
     _context = context;
     _userManager = userManager;
     _roleManager = roleManager;
 }
        // DELETE api/memberships/5
        public void Delete(string id)
        {
            //this is a bit hacky - but the association will be coming in here
            //and it's GUID | role
            //so parse that and unassign
            var splits = id.Split('|');
            var userId = splits[0];
            var roleId = splits[1];

            //this is a new user/role assignment
            using (var db = new ApplicationDbContext())
            {
                var role = db.Roles.FirstOrDefault(x => x.Id == roleId);
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

                manager.RemoveFromRole(userId, role.Name);
                var note = new AspNetUserNote();
                note.EnteredBy = User.Identity.Name;
                note.Note = "Removed user from " + role.Name + " role";

                var user = db.Users.FirstOrDefault(x => x.Id == userId);
                user.Notes.Add(note);
                db.SaveChanges();

            }
        }
Exemplo n.º 5
0
        //public static IEnumerable<MeetingViewModel> UserMeetingsTodayAll(ApplicationDbContext context, ApplicationUser user, Double utcOffset)
        //{
        //    var meetingDtos = new List<MeetingViewModel>();
        //    UserCohortMeetingsToday(context, user, utcOffset, ref meetingDtos);
        //    MeetingsServices.UserPrivateMeetingsToday(context, user, utcOffset, ref  meetingDtos);

        //    return meetingDtos;
        //}

        private static void UserCohortMeetingsToday(ApplicationDbContext context, ApplicationUser user, Double utcOffset, ref List<MeetingViewModel> meetingDtos)
        {
            var enrollmentsWithThisUser = context.Courses.SelectMany(u => u.Enrollments.Where(e => e.ApplicationUserId == user.Id));
            var localNow = DateTime.UtcNow.AddMinutes(utcOffset);
            var localTodayDate = localNow.ToShortDateString();

            //foreach (var enrollment in enrollmentsWithThisUser)
            //{
            //    //Get all meetings with this enrollment where its cohort has a meeting that is in the future
            //    var enrollment1 = enrollment;
            //    //var cohortMeetings = context.Meetings.ToList().Where(m => m.CourseId == enrollment1.CourseId && m.Start.AddMinutes(utcOffset).ToShortDateString()==rightNow);
            //    var cohortMeetings = context.Meetings.Where(m => m.CourseId == enrollment1.CourseId).OrderBy(m => m.Start);
            //    foreach (var meeting in cohortMeetings)
            //    {
            //        if (meeting.Start.AddMinutes(utcOffset).ToShortDateString() == localTodayDate)
            //        {
            //            var meetingToAdd = new MeetingViewModel
            //            {
            //                Id = meeting.Id,
            //                Title = meeting.Title,
            //                Start = DateTime.SpecifyKind(meeting.Start, DateTimeKind.Utc).AddMinutes(utcOffset),
            //                End = meeting.End.AddMinutes(utcOffset),
            //                Description = meeting.Description,
            //                IsAllDay = meeting.IsAllDay,
            //                RecurrenceRule = meeting.RecurrenceRule,
            //                RecurrenceException = meeting.RecurrenceException,
            //                RecurrenceId = meeting.RecurrenceId,
            //                CourseId = meeting.CourseId,
            //                GtmUrl = meeting.GtmUrl
            //            };
            //            meetingDtos.Add(meetingToAdd);
            //        }
            //    }
            //}
        }
Exemplo n.º 6
0
        public static Enrollment CreateNewEnrollment(Course course, ApplicationUser user, ApplicationDbContext context)
        {
            var passedDate = DateTime.Parse("1900-1-1");

            var newEnrollment = new Enrollment
            {
                ApplicationUser = user,
                PassedDate=passedDate,
                Course= course,
                EnrollmentDate = DateTime.UtcNow
            };

            context.Enrollments.Add(newEnrollment);
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Debug.Print("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Debug.Print("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
            CreateScoRecordsForCourse(newEnrollment, context);
            return newEnrollment;
        }
Exemplo n.º 7
0
        private static void AddAllUserCohortMeetings(ApplicationDbContext context, ApplicationUser user, int utcOffset, ref List<MeetingViewModel> meetingDtos)
        {
            var enrollmentsWithThisUser = context.Courses.SelectMany(u => u.Enrollments.Where(e => e.ApplicationUserId == user.Id));

            foreach (var enrollment in enrollmentsWithThisUser)
            {
                //Get all meetings with this enrollment where its cohort has a meeting that is in the future
                Enrollment enrollment1 = enrollment;
                var cohortMeetings = context.Meetings.Where(m => m.CourseId == enrollment1.CourseId);
                foreach (var meeting in cohortMeetings)
                {
                    var meetingToAdd = new MeetingViewModel
                    {
                        Id = meeting.Id,
                        Title = meeting.Title,
                        Start = DateTime.SpecifyKind(meeting.Start, DateTimeKind.Utc).AddMinutes(utcOffset),
                        End = DateTime.SpecifyKind(meeting.End, DateTimeKind.Utc).AddMinutes(utcOffset),
                        Description = meeting.Description,
                        IsAllDay = meeting.IsAllDay,
                        RecurrenceRule = meeting.RecurrenceRule,
                        RecurrenceException = meeting.RecurrenceException,
                        RecurrenceId = meeting.RecurrenceId,
                        CourseId = meeting.CourseId,
                        GtmUrl = meeting.GtmUrl
                    };
                    meetingDtos.Add(meetingToAdd);
                }
            }
        }
Exemplo n.º 8
0
 public ManageUsersController(ApplicationDbContext context, ApplicationUserManager userManager, IEmailService emailService, ICurrentUser currentUser)
 {
     _context = context;
     _userManager = userManager;
     _emailService = emailService;
     _currentUser = currentUser;
 }
Exemplo n.º 9
0
        private async Task CreateAdminUser()
        {
          var username = "******";//ConfigurationManager.AppSettings["DefaultAdminUsername"];
          var password = "******";//ConfigurationManager.AppSettings["DefaultAdminPassword"];

          using (var context = new ApplicationDbContext())
          {
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

            var role = new IdentityRole(RoleName);

            var result = await roleManager.RoleExistsAsync(RoleName);
            if (!result)
            {
              await roleManager.CreateAsync(role);
            }

            var user = await userManager.FindByNameAsync(username);
            if (user == null)
            {
              user = new ApplicationUser { UserName = username, Email = "*****@*****.**", First = "Big", Last="Admin Person" };
              await userManager.CreateAsync(user, password);
              await userManager.AddToRoleAsync(user.Id, RoleName);
            }
          }
        }
Exemplo n.º 10
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            app.UseGoogleAuthentication();
            using (var context = new ApplicationDbContext())
            {
              context.Database.Delete();
              context.Database.Create();

            }

            CreateAdminUser().Wait();
        }
Exemplo n.º 11
0
 private void InitializeIdentityDatabase()
 {
     Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
     using (ApplicationDbContext temp = new ApplicationDbContext())
     {
         temp.Database.Initialize(true);
     }
 }
Exemplo n.º 12
0
 public MeetingsController(ApplicationDbContext context, ICurrentUser currentUser, IEmailService emailService,
     ApplicationUserManager userManager, ApplicationRoleManager roleManager)
 {
     _context = context;
     _currentUser = currentUser;
     _emailService = emailService;
     _userManager = userManager;
     _roleManager = roleManager;
 }
Exemplo n.º 13
0
 public CheckoutController(ApplicationDbContext context, 
                             ICurrentUser currentUser, 
                             IEmailService emailService,
                             ApplicationUserManager userManager, 
                             ApplicationSignInManager signInManager)
 {
     _context = context;
     _currentUser = currentUser;
     _emailService = emailService;
     _userManager = userManager;
     SignInManager = signInManager;
 }
Exemplo n.º 14
0
 public AccountController(
     UserManager<ApplicationUser> userManager,
     SignInManager<ApplicationUser> signInManager,
     IEmailSender emailSender,
     ISmsSender smsSender,
     ApplicationDbContext applicationDbContext)
 {
     _userManager = userManager;
     _signInManager = signInManager;
     _emailSender = emailSender;
     _smsSender = smsSender;
     _applicationDbContext = applicationDbContext;
 }
Exemplo n.º 15
0
 // GET api/<controller>
 public dynamic Get()
 {
     var db = new ApplicationDbContext();
     var roles = new List<dynamic>();
     foreach (var role in db.Roles)
     {
         roles.Add(new
         {
             id = role.Id,
             name=role.Name
         });
     }
     return new { roles = roles };
 }
Exemplo n.º 16
0
        // POST api/<controller>
        public dynamic Post([FromBody]dynamic model)
        {
            using (var db = new ApplicationDbContext())
            {
                string id = model.note.user;
                var user = db.Users.FirstOrDefault(x => x.Id == id);
                var note = new AspNetUserNote();
                note.CreatedAt = DateTime.Now;
                note.EnteredBy = User.Identity.Name;
                note.Note = model.note.note;
                user.Notes.Add(note);
                db.SaveChanges();
            }

            return model;
        }
Exemplo n.º 17
0
 public static ApplicationUser AddRegistrantAsUser(OrderViewModel viewModel, ApplicationDbContext context)
 {
     var user = new ApplicationUser
     {
         FirstName = viewModel.FirstName,
         LastName = viewModel.LastName,
         Address1 = viewModel.Address1,
         //Address2 = viewModel.Address2,
         City = viewModel.City,
         CountryCode = viewModel.CountryCode,
         PostalCode = viewModel.PostalCode,
         Email = viewModel.Email,
         UserName = viewModel.Email,
         Phone = viewModel.Phone,
         //Gender = viewModel.Gender
     };
     return user;
 }
Exemplo n.º 18
0
        // PUT api/users/5
        public dynamic Put(string id, dynamic model)
        {
            using (var db = new ApplicationDbContext())
            {
                var user = db.Users.FirstOrDefault(x => x.Id == id);
                //load it up!
                if (user != null)
                {
                    user.UserName = model.user.userName;
                    user.First = model.user.first;
                    user.Last = model.user.last;
                    user.Email = model.user.email;
                    user.Bio = model.user.bio;
                    user.Twitter = model.user.twitter;

                    db.SaveChanges();
                }
            }
            return model;
        }
Exemplo n.º 19
0
 public static List<SearchResultArticle> getRelatedArticles(ApplicationDbContext context, int order, int skip, ArticleModel article, int count)
 {
     ArticleThumbnailManager thumbnailManager = new ArticleThumbnailManager(new BlobStorageConnection());
     //直接の関係の記事を探す
     IQueryable<ArticleModel> query = context.Articles.Where(f => f.RelatedArticleId.Equals(article.ArticleModelId));
     query = ChangeOrder(order, query);
     query = query.Skip(skip);
     List<SearchResultArticle> articles = new List<SearchResultArticle>();
     foreach (var source in query.Take(count))
     {
         articles.Add(new SearchResultArticle()
         {
             ArticleId = source.ArticleModelId,
             LabelCount = source.LabelCount,
             PageView = source.PageView,
             Title = source.Title,
             Article_UpDate = source.UpdateTime.ToShortDateString(),
             ThumbnailTag = thumbnailManager.GenerateThumnailTag(source.ArticleModelId)
         });
     }
     int remain = count - article.LabelCount;
     if(article.LabelCount<count)
     {//取り出すカウントに満たない場合は間接的関連記事でうめる
         context.Articles.Where(f => f.ThemeId.Equals(article.ThemeId)&&!f.RelatedArticleId.Equals(article.ArticleModelId));
         query = ChangeOrder(order, query);
         query = query.Skip(skip);
         foreach (var source in query.Take(remain))
         {
             articles.Add(new SearchResultArticle()
             {
                 ArticleId = source.ArticleModelId,
                 LabelCount = source.LabelCount,
                 PageView = source.PageView,
                 Title = source.Title,
                 Article_UpDate = source.UpdateTime.ToShortDateString(),
                 ThumbnailTag = thumbnailManager.GenerateThumnailTag(source.ArticleModelId)
             });
         }
     }
     return articles;
 }
Exemplo n.º 20
0
        protected ApplicationDbContext CreateDbContext()
        {
            var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();

            optionsBuilder.UseInMemoryDatabase();

            var db = new ApplicationDbContext(optionsBuilder.Options);

            db.Libraries.Add(new Library
            {
                CreatedByUserId = "dbo",
                CreatedOn = DateTimeOffset.Now,
                ModifiedOn = DateTimeOffset.Now,
                Name = "Test Library",
                Status = StatusTypes.Active
            });

            db.SaveChanges();

            return db;
        }
        // POST api/memberships
        public void Post(dynamic model)
        {
            //this is a new user/role assignment
            using (var db = new ApplicationDbContext())
            {
                string roleId = model.membership.role;
                var role = db.Roles.FirstOrDefault(x => x.Id == roleId);
                string userId = model.membership.user;
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

                manager.AddToRole(userId, role.Name);

                var note = new AspNetUserNote();
                note.EnteredBy = User.Identity.Name;
                note.Note = "Added user to " + role.Name + " role";

                var user = db.Users.FirstOrDefault(x => x.Id == userId);
                user.Notes.Add(note);
                db.SaveChanges();
            }
        }
Exemplo n.º 22
0
 public static async Task<TopicSection> FromModelAsync(ApplicationDbContext context, TopicModel topicModel)
 {
     TopicSection section = new TopicSection();
     section.TopicTitle = topicModel.TopicTitle;
     section.TopicId = topicModel.TopicId;
     section.TopicDescription = topicModel.Description;
     ArticleModel[] newArticles =
         context.Articles.Where(f => !f.IsDraft && f.ThemeId.Equals(topicModel.TopicId))
             .OrderBy(f => f.CreationTime)
             .Take(3)
             .ToArray();
     section.NewModels = newArticles;
     List<ArticleModel> flamedArticles = new List<ArticleModel>();
     var flamedArticlesQuery = context.CurrentRanking.Where(f => f.TopicId.Equals(topicModel.TopicId))
         .OrderBy(f => f.PVCoefficient).Take(3).ToList();
     foreach (var currentRankingModel in flamedArticlesQuery)
     {
         flamedArticles.Add(await context.Articles.FindAsync(currentRankingModel.ArticleId));
     }
     section.FlamedModels = flamedArticles.ToArray();
     return section;
 }
Exemplo n.º 23
0
        public static MvcHtmlString LaunchMeetingButton(ApplicationDbContext context, ICurrentUser currentUser)
        {
            var button = new MvcHtmlString("There are no meetings scheduled for today.");

            if (currentUser.User == null)
                return button;

            var utcOffset = TimeDateServices.GetUtcOffSet();
            //person can be up to 25 minutes late for meeting and will still show on main page
            var cutOff = DateTime.UtcNow.AddMinutes(-25);

            var theseGuysMeetingsList = context.Meetings.Include("Instructor")
                .Where(m => m.Start > cutOff)
                .Where(m => m.InstructorId == currentUser.User.Id || m.StudentId == currentUser.User.Id)
                .ToList();

            var theseGuysMeetings = theseGuysMeetingsList.Select(d => new MeetingDto
            {
                StartDay = d.Start.AddMinutes(utcOffset).ToShortDateString(),
                InstructorId = d.InstructorId,
                Instructor = d.Instructor,
                Start = d.Start.AddMinutes(utcOffset),
                GtmUrl = d.GtmUrl
            });

            var localDate = DateTime.UtcNow.AddMinutes(utcOffset).ToShortDateString();
            var nextMeetingToday = theseGuysMeetings.FirstOrDefault(m => m.Start.ToShortDateString() == localDate);


            if (nextMeetingToday != null)
            {
                var buttonText = "Launch Meeting with " + nextMeetingToday.Instructor.FirstName + " at " +
                                 nextMeetingToday.Start.ToShortTimeString();

                button = BootstrapHelpers.AnchorButton(nextMeetingToday.GtmUrl, buttonText);
            }

            return button;
        }
Exemplo n.º 24
0
        public static void CreateScoRecordsForCourse(Enrollment enrollment, ApplicationDbContext context)
        {
            
            var courseTemplateId = enrollment.Course.CourseTemplateId;
            var courseScos = context.CourseScos.Include(c => c.Sco).Where(cm => cm.CourseTemplateId == courseTemplateId);

            foreach (var item in courseScos)
            {
                var scoRecord = new ScoRecord
                {
                    Title = item.Title,
                    EnrollmentId = enrollment.Id,
                    CatalogueNumber = item.CatalogueNumber,
                    ScoId = item.Sco.Id,
                    ScormName = "",
                    ScormValue = "",
                    LessonStatus = "",
                    LastClosed = DateTime.Parse("1900-1-1"),
                    Stored = DateTime.Parse("1900-1-1"),
                    TimeStamp = DateTime.Parse("1900-1-1"),
                    CourseTemplateId = enrollment.Course.CourseTemplateId,
                    CourseId = enrollment.CourseId,
                    ActorId = enrollment.ApplicationUserId,
                    //IsEnabled = item.RequiredCourseScoId == 0,
                    IsFinalExam = item.IsFinalExam
                };

                //var requiredRecord = context.CourseScos.Find(item.RequiredCourseScoId);
                //if (requiredRecord != null)
                //    scoRecord.RequiredScoId = requiredRecord.ScoId;

                context.ScoRecords.Add(scoRecord);
            }

            context.SaveChanges();
        }
Exemplo n.º 25
0
        public ActionResult Index()
        {
            bool admin, appsAdmin;

            using (var ApplicationDbContext = new ApplicationDbContext())
            {
                var id = User.Identity.GetUserId();
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext));
                admin = manager.FindById(id).Administrator;

                using(var context = new ReadContext())
                {
                    appsAdmin = context.Query<ApplicationAdministratorDto>().Any(x => x.UserId ==id);
                }

            }

            ViewBag.Admin = admin;
            ViewBag.AppsAdmin = appsAdmin;
            ViewBag.Title = "Home Page";
            ViewBag.ActiveDirectory = ConfigurationManager.AppSettings["activeDirectory"];

            return View();
        }
Exemplo n.º 26
0
 public SelectListProvider(ApplicationDbContext db, IConfigurationProvider configurationProvider)
 {
     _db = db;
     _configurationProvider = configurationProvider;
 }
 public ManageCourseScosController(ApplicationDbContext context)
 {
     _context = context;
 }
 public StudentRecordsController(ApplicationDbContext context)
 {
     _context = context;
 }
Exemplo n.º 29
0
 public CategoriesController(ApplicationDbContext context)
 {
     _context = context;
 }
Exemplo n.º 30
0
 public SuppliersController(ApplicationDbContext context)
 {
     _context = context;
 }