Example #1
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            var services = new ServiceCollection();

            DbContextInstaller.ConfigureDbContext(services);
            SchedulerDbContext db = new SchedulerDbContext(new DbContextOptions <SchedulerDbContext>());
            Task task             = new Task();

            task.Name = "Пописать";
            User usere = new User();

            usere.Task = new List <Task>();
            usere.Task.Add(task);
            usere.Name     = "Валентин Дядька";
            usere.Email    = "*****@*****.**";
            usere.Password = "******";
            //db.Userses.Find(1).Task.Remove(db.Userses.Find(1).Task.Find(t=>t.Id==2)); // я понимаю, что при таком подходе в бд всё равно останется задача. Оно и к лучшему. Будет что фсб показать
            db.Userses.Add(usere);
            db.Taskses.Add(task);
            db.SaveChanges();
            foreach (var user in db.Userses.ToList())
            {
                Console.WriteLine($"{user.Id}.{user.Name}+{user.Password}");
                //Console.WriteLine($"{first}");
            }
        }
Example #2
0
        public ActionResult DeleteConfirmed(int id)
        {
            var job = new Job();

            try
            {
                using (var ctx = new SchedulerDbContext())
                {
                    job = ctx.Jobs.Where(j => j.JobId == id).Include("Collection").FirstOrDefault();

                    if (User.IsInRole("SystemAdministrator") || job.Collection.TenantId == CurrentTenant.TenantId)
                    {
                        ctx.Jobs.Remove(job);
                        ctx.SaveChanges();
                    }
                }
            }

            catch (Exception ex)
            {
                LogService.Info("Jobs not found", ex.Message, ex.InnerException);
            }

            return(RedirectToAction("Index"));
        }
Example #3
0
 public void Dispose()
 {
     using (var context = new SchedulerDbContext(options))
     {
         context.Database.EnsureDeleted();
     }
 }
        public ActionResult DeleteConfirmed(int id)
        {
            try
            {
                using (var ctx = new SchedulerDbContext())
                {
                    //Get collection from db
                    JobCollection collection = ctx.Collections.Find(id);

                    if (User.IsInRole("SystemAdministrator") || collection.TenantId == CurrentTenant.TenantId)
                    {
                        //Remove collection from db
                        ctx.Collections.Remove(collection);
                        ctx.SaveChanges();
                    }
                }
            }

            catch (Exception ex)
            {
                LogService.Info("Collections not found", ex.Message, ex.InnerException);
            }

            return(RedirectToAction("Index"));
        }
Example #5
0
        public JsonResult Filtered(int jobid, string val)
        {
            //Create the model
            var model = new JobViewModel();
            var job   = new Job();

            try
            {
                using (var ctx = new SchedulerDbContext())
                {
                    job = ctx.Jobs.Include("Log").Where(i => i.JobId == jobid).FirstOrDefault();
                }

                //Add job to model
                model.Job = job;

                if (String.IsNullOrEmpty(val))
                {
                    // Do nothing
                    model.Job.Log.ToList();
                }
                else
                {
                    model.Job.Log = job.Log.Where(x => x.Details == val).ToList();
                }
            }

            catch (Exception ex)
            {
                LogService.Info("Jobs not found", ex.Message, ex.InnerException);
            }

            return(Json(new { data = model.Job.Log.Select(l => l).ToList() }, JsonRequestBehavior.AllowGet));
        }
Example #6
0
        public JsonResult JobLogDetails(int jobid, int logid)
        {
            try
            {
                using (var ctx = new SchedulerDbContext())
                {
                    // Get the related entry
                    var logEntry = ctx.JobLogEntries.FirstOrDefault(jle => jle.EntryId == logid);

                    var str = logEntry.Details;

                    // Convert to json
                    JsonLogResponse json = JsonConvert.DeserializeObject <JsonLogResponse>(str);

                    if (logEntry != null)
                    {
                        //return Json(new { Test1 = logEntry.Change, Test2 = logEntry.Summary }, JsonRequestBehavior.AllowGet);

                        return(Json(json, JsonRequestBehavior.AllowGet));
                    }
                }
            }

            catch (Exception ex)
            {
                LogService.Info("Job log not found", ex.Message, ex.InnerException);
            }

            return(Json(null, JsonRequestBehavior.AllowGet));
        }
Example #7
0
        static void Main(string[] args)
        {
            var context = new SchedulerDbContext();

            Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(o =>
            {
                if (o.Verbose)
                {
                    Console.WriteLine($"Verbose output enabled. Current Arguments: -v {o.Verbose}");
                    Console.WriteLine("Quick Start Example! App is in Verbose mode!");
                }
                else
                {
                    Console.WriteLine($"Current Arguments: -v {o.Verbose}");
                    Console.WriteLine("Quick Start Example!");
                }
                if (o.DropDatabase)
                {
                    context.Database.EnsureDeleted();
                }
                if (o.CreateDatabase)
                {
                    context.Database.EnsureCreated();
                }
            });
        }
 public void SaveEvent(Event @event)
 {
     using (_db = new SchedulerDbContext())
     {
         _db.Users.Find(UserId).Events.Add(@event);
         _db.SaveChanges();
     }
 }
Example #9
0
        public ContextTestBase()
        {
            var options = ContextOptionsFactory.CreateSqliteOptions <SchedulerDbContext>();

            context = new SchedulerDbContext(options);
            context.Database.OpenConnection();
            context.Database.EnsureCreated();
        }
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            //Create the model
            var model = new JobCollectionViewModel();

            var collection = new JobCollection();

            try
            {
                using (var ctx = new SchedulerDbContext())
                {
                    // Get the collection db
                    collection = ctx.Collections.Where(i => i.CollectionId == id).Include("Tenant").Include("Application").FirstOrDefault();

                    if (User.IsInRole("SystemAdministrator") || collection.TenantId == CurrentTenant.TenantId)
                    {
                        //Add collection to model
                        model.Collection = collection;
                    }
                    else
                    {
                        return(View("Authorize"));
                    }
                }

                // Create the breadcrumb
                var breadcrumb = new List <BreadcrumbItemViewModel>();
                breadcrumb.Add(new BreadcrumbItemViewModel()
                {
                    Text = "Collections",
                    Link = "/Collections"
                });

                breadcrumb.Add(new BreadcrumbItemViewModel()
                {
                    Text = collection.Name,
                    Link = "/Collections/" + id + "/Details"
                });

                breadcrumb.Add(new BreadcrumbItemViewModel()
                {
                    Text = "Delete Confirm"
                });

                ViewBag.Breadcrumb = breadcrumb;
            }

            catch (Exception ex)
            {
                LogService.Info("Collections not found", ex.Message, ex.InnerException);
            }

            return(View(model));
        }
Example #11
0
        public static void Initialize(SchedulerDbContext context)
        {
            context.Database.EnsureCreated();

            if (context.Users.Any())
            {
                return;
            }
        }
Example #12
0
 public DisconnectedStateTestBase()
 {
     options = ContextOptionsFactory.CreateSqliteOptions <SchedulerDbContext>();
     using (var context = new SchedulerDbContext(options))
     {
         context.Database.OpenConnection();
         context.Database.EnsureCreated();
     }
 }
 public SchedulerUser GetUser()
 {
     using (_db = new SchedulerDbContext())
     {
         var user = _db.Users.Include(u => u.Events.Select(e => e.Participants))
                         .Include(u => u.Contacts)
                         .FirstOrDefault(u => u.Id == UserId);
         return user;
     }
 }
 public SchedulerUser GetUser()
 {
     using (_db = new SchedulerDbContext())
     {
         var user = _db.Users.Include(u => u.Events.Select(e => e.Participants))
                    .Include(u => u.Contacts)
                    .FirstOrDefault(u => u.Id == UserId);
         return(user);
     }
 }
Example #15
0
        public static void RegisterJobs()
        {
            // Log the state
            LogService.Debug("Registering jobs!");

            using (var db = new SchedulerDbContext())
            {
                // Get the active jobs
                var activeJobs = db.Jobs.Where(j => j.Status == EntityStatus.Active).Include("Collection").ToList();

                // Log the state
                LogService.Debug("Active job count:" + activeJobs.Count);

                foreach (var job in activeJobs)
                {
                    if (!string.IsNullOrEmpty(job.CronExpression))
                    {
                        try
                        {
                            RecurringJob.AddOrUpdate(job.AppKey + "." + job.Process, () => JobService.Process(job.JobId, job.Name), job.CronExpression, TimeZoneInfo.Local);
                        }
                        catch (Exception ex)
                        {
                            // Log the state
                            LogService.Debug("Error while registering job! JobId:" + job.JobId + "; JobName:" + job.Name + "; Exception:" + ex.ToString());
                        }
                    }
                }

                // Get the paused jobs
                var pausedJobs = db.Jobs.Where(j => j.Status == EntityStatus.Freezed).Include("Collection").ToList();

                // Log the state
                LogService.Debug("Paused job count:" + pausedJobs.Count);

                foreach (var job in pausedJobs)
                {
                    RecurringJob.RemoveIfExists(job.AppKey + "." + job.Process);
                }

                // Get the passive jobs
                var passiveJobs = db.Jobs.Where(j => j.Status == EntityStatus.Passive).Include("Collection").ToList();

                // Log the state
                LogService.Debug("Passive job count:" + pausedJobs.Count);

                foreach (var job in passiveJobs)
                {
                    RecurringJob.RemoveIfExists(job.AppKey + "." + job.Process);
                }
            }

            // Log the state
            LogService.Debug("All active jobs registered!");
        }
        public Event GetUserSpecificEvent(int?id)
        {
            using (_db = new SchedulerDbContext())
            {
                var userEvents = _db.Events.Include(ev => ev.Participants)
                                 .FirstOrDefault(e => (e.Id == id) && (e.SchedulerUserId == UserId));

                /*_db.Users.Find(UserId).Events.Find(e => e.Id == id);*/
                return(userEvents);
            }
        }
        public void Should_have_database_connection_string()
        {
            using (var context = new SchedulerDbContext())
            {
                context.Database.Should().NotBeNull();

                context.Database.Connection.Should().NotBeNull();

                context.Database.Connection.DataSource.Should().NotBeNullOrEmpty();
            }
        }
		public JobScheduler(bool isPrimary, 
            Func<Type, IJobActivity> getJob, 
            Func<IAppConfigRepository> appConfigRepository, 
            ILogger traceSource)
        {
            // get a quartzScheduler
            _quartzScheduler = SchedulerFactory.GetScheduler();
            _schedulerDbTools = new SchedulerDbContext(appConfigRepository);
		    _traceSource = traceSource;
		    _isPrimary = isPrimary;
		    _getJob = getJob;
        }
 public JobScheduler(bool isPrimary,
                     Func <Type, IJobActivity> getJob,
                     Func <IAppConfigRepository> appConfigRepository,
                     ILogger traceSource)
 {
     // get a quartzScheduler
     _quartzScheduler  = SchedulerFactory.GetScheduler();
     _schedulerDbTools = new SchedulerDbContext(appConfigRepository);
     _traceSource      = traceSource;
     _isPrimary        = isPrimary;
     _getJob           = getJob;
 }
Example #20
0
        public ActionResult Edit([Bind(Include = "JobId,CollectionId,Type,Name,AppKey,Process,Description,CronExpression,JobUrl,ProcessResult,SendSummary,Created,Updated,Status")] EditJobViewModel jobViewModel)
        {
            try
            {
                using (var ctx = new SchedulerDbContext())
                {
                    // Get existing job from db
                    var job = ctx.Jobs.Where(j => j.JobId == jobViewModel.JobId).FirstOrDefault();

                    job.Type           = jobViewModel.Type;
                    job.Name           = jobViewModel.Name;
                    job.CronExpression = jobViewModel.CronExpression;
                    job.AppKey         = jobViewModel.AppKey;
                    job.Process        = jobViewModel.Process;
                    job.Description    = jobViewModel.Description;
                    job.JobUrl         = jobViewModel.JobUrl;
                    job.Status         = jobViewModel.Status;

                    //Get tenantId
                    var tenantID = ctx.Collections.Where(t => t.CollectionId == jobViewModel.CollectionId).FirstOrDefault().TenantId;

                    if (User.IsInRole("SystemAdministrator") || tenantID == CurrentTenant.TenantId)
                    {
                        if (ModelState.IsValid)
                        {
                            ctx.Entry(job).State = EntityState.Modified;
                            ctx.SaveChanges();
                            return(RedirectToAction("Index"));
                        }
                        ViewBag.CollectionId = new SelectList(ctx.Collections.ToList(), "CollectionId", "Name", job.CollectionId);
                    }
                    else
                    {
                        return(View("Authorize"));
                    }
                }
            }

            catch (Exception ex)
            {
                LogService.Info("Jobs not found", ex.Message, ex.InnerException);
            }


            return(View(jobViewModel));
        }
Example #21
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string enteredEmails;

            if (value != null)
            {
                enteredEmails = value.ToString();
            }
            else
            {
                enteredEmails = string.Empty;
            }
            List <string> emails = enteredEmails.Split(',').ToList();

            PropertyInfo propertyInfo   = validationContext.ObjectType.GetProperty(EventId);
            object       currentEventId = propertyInfo.GetValue(validationContext.ObjectInstance);

            int id;

            if (currentEventId is int)
            {
                id = (int)currentEventId;
            }
            else
            {
                id = 0;
            }

            using (var dbContext = new SchedulerDbContext())
            {
                Event currentEvent = dbContext.Events.Find(id);
                foreach (var e in emails)
                {
                    var email = _service.RemoveBrackets(e);

                    bool isNotYetInvited = currentEvent.Participants.All(p => p.Email != email);

                    if (!isNotYetInvited)
                    {
                        var errorMsg = String.Format(@"{0} is already invited", email);
                        return(new ValidationResult(errorMsg));
                    }
                }
            }
            return(ValidationResult.Success);
        }
        protected override void Seed(SchedulerDbContext context)
        {
            //    var address = new Address()
            //    {
            //        City = "Duluth",
            //        State = "GA",
            //        Street = "12334 TEST ST",
            //        Zip = "123456-7890"
            //    };
            //    var appointments = new List<Appointment>()
            //    {

            //    };
            //    var clientPhoneNumbers = new List<CompanyPhoneNumber>()
            //    {

            //    };
            //    var clientTwilio = new CompanyTwilio()
            //    {

            //    };
            //    var clientType = new CompanyType()
            //    {

            //    };
            //    var customers = new List<Customer>(){};
            //    var employees = new List<Employee>(){};
            //    context.Companies.AddOrUpdate(
            //            new Company
            //            {
            //                Address = address,
            //                Appointments = appointments,
            //                CompanyPhoneNumbers = clientPhoneNumbers,
            //                CompanyTwilio = clientTwilio,
            //                CompanyType = clientType,
            //                CreatedDate = DateTime.Now,
            //                Customers = customers,
            //                Employees = employees,
            //                Name = new Name(),
            //                TimeZone = "Eastern Standard Time",
            //                IsActive = true
            //            }
            //        );
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string enteredEmails;
            if (value != null)
            {
                enteredEmails = value.ToString();
            }
            else
            {
                enteredEmails = string.Empty;
            }
            List<string> emails = enteredEmails.Split(',').ToList();

            PropertyInfo propertyInfo = validationContext.ObjectType.GetProperty(EventId);
            object currentEventId = propertyInfo.GetValue(validationContext.ObjectInstance);

            int id;
            if (currentEventId is int)
            {
                id = (int)currentEventId;
            }
            else
            {
                id = 0;
            }

            using (var dbContext = new SchedulerDbContext())
            {
                Event currentEvent = dbContext.Events.Find(id);
                foreach (var e in emails)
                {
                    var email = _service.RemoveBrackets(e);

                    bool isNotYetInvited = currentEvent.Participants.All(p => p.Email != email);

                    if (!isNotYetInvited)
                    {
                        var errorMsg = String.Format(@"{0} is already invited", email);
                        return new ValidationResult(errorMsg);
                    }
                }
            }
            return ValidationResult.Success;
        }
Example #24
0
        private static void SeedSchedules(
            SchedulerDbContext schedulerDb,
            bool hasSchedules,
            out IEnumerable <Schedule> schedules)
        {
            if (!hasSchedules)
            {
                // TO DO Seed schedules.
                schedules = new List <Schedule>()
                {
                };

                schedulerDb.Schedules.AddRange(schedules);
            }
            else
            {
                schedules = schedulerDb.Schedules.ToList();
            }
        }
        public ActionResult Create([Bind(Include = "CollectionId,TenantId,ApplicationId,Name,Created,Status")] JobCollection collection)
        {
            try
            {
                using (SchedulerDbContext ctx = new SchedulerDbContext())
                {
                    if (User.IsInRole("SystemAdministrator") || collection.TenantId == CurrentTenant.TenantId)
                    {
                        if (ModelState.IsValid)
                        {
                            ctx.Collections.Add(collection);
                            ctx.SaveChanges();
                            return(RedirectToAction("Index"));
                        }
                    }
                    else
                    {
                        return(View("Authorize"));
                    }
                }
            }

            catch (Exception ex)
            {
                LogService.Info("Collections not found", ex.Message, ex.InnerException);
            }

            using (var saasDb = new SaasDbContext())
            {
                if (User.IsInRole("SystemAdministrator"))
                {
                    ViewBag.TenantId      = new SelectList(saasDb.Tenants.ToList(), "TenantId", "Name");
                    ViewBag.ApplicationId = new SelectList(saasDb.Applications.ToList(), "Id", "Name");
                }
                else
                {
                    ViewBag.TenantId      = new SelectList(saasDb.Tenants.Where(i => i.TenantId == CurrentTenant.TenantId).ToList(), "TenantId", "Name");
                    ViewBag.ApplicationId = new SelectList(saasDb.Applications.Where(a => a.TenantId == CurrentTenant.TenantId).ToList(), "Id", "Name");
                }
            }

            return(View(collection));
        }
        public ActionResult Edit([Bind(Include = "CollectionId,ApplicationId,TenantId,Name,Created,Status")] EditJobCollectionViewModel collectionViewModel)
        {
            try
            {
                if (User.IsInRole("SystemAdministrator") || collectionViewModel.TenantId == CurrentTenant.TenantId)
                {
                    using (var ctx = new SchedulerDbContext())
                    {
                        // Get existing collection from db
                        var collection = ctx.Collections.Where(c => c.CollectionId == collectionViewModel.CollectionId).FirstOrDefault();

                        collection.Name   = collectionViewModel.Name;
                        collection.Status = collectionViewModel.Status;

                        if (ModelState.IsValid)
                        {
                            //Update collection
                            ctx.Entry(collection).State = EntityState.Modified;
                            ctx.SaveChanges();
                            return(RedirectToAction("Index"));
                        }
                    }
                }
                else
                {
                    return(View("Authorize"));
                }

                using (var saaSctx = new SaasDbContext())
                {
                    ViewBag.TenantId      = new SelectList(saaSctx.Tenants.ToList(), "TenantId", "Name");
                    ViewBag.ApplicationId = new SelectList(saaSctx.Applications.ToList(), "Id", "Name");
                }
            }

            catch (Exception ex)
            {
                LogService.Info("Collections not found", ex.Message, ex.InnerException);
            }

            return(View(collectionViewModel));
        }
        public void Should_open_and_close_connection_to_existing_databasee()
        {
            using (var context = new SchedulerDbContext())
            {
                if (context.Database.Exists())
                {
                    var conn = context.Database.Connection;

                    conn.State.ToString().ShouldBeEquivalentTo(ConnectionState.Closed.ToString());

                    conn.Open();

                    conn.State.ToString().ShouldBeEquivalentTo(ConnectionState.Open.ToString());

                    conn.Close();

                    conn.State.ToString().ShouldBeEquivalentTo(ConnectionState.Closed.ToString());
                }
            }
        }
 public void PrepareTaskSchedule(string systemJobId, bool allowMultipleInstances)
 {
     lock (keylock)
     {
         var job          = SystemJobs.FirstOrDefault(sj => sj.SystemJobId == systemJobId);
         var taskSchedule = TaskSchedules.SingleOrDefault(ts => ts.SystemJobId == systemJobId);
         if (taskSchedule == null)
         {
             var startedDateTime   = DateTime.UtcNow;
             var originalFrequency = SchedulerDbContext.PeriodToFrequency(job.Period);
             var newTaskSchedule   = new TaskSchedule
             {
                 Frequency = originalFrequency,
                 NextScheduledStartTime = startedDateTime.AddMinutes(originalFrequency),
                 SystemJobId            = systemJobId
             };
             TaskSchedules.Add(newTaskSchedule);
         }
     }
 }
Example #29
0
        public ActionResult Create([Bind(Include = "JobId,CollectionId,Type,Name,AppKey,Process,Description,CronExpression,JobUrl,ProcessResult,SendSummary,Created,Updated,Status")] Job job)
        {
            try
            {
                using (var ctx = new SchedulerDbContext())
                {
                    if (User.IsInRole("SystemAdministrator"))
                    {
                        if (ModelState.IsValid)
                        {
                            ctx.Jobs.Add(job);
                            ctx.SaveChanges();
                            return(RedirectToAction("Index"));
                        }
                    }
                    else
                    {
                        var tenantid = ctx.Collections.Where(i => i.CollectionId == job.CollectionId).FirstOrDefault().TenantId;

                        if (tenantid == CurrentTenant.TenantId)
                        {
                            if (ModelState.IsValid)
                            {
                                ctx.Jobs.Add(job);
                                ctx.SaveChanges();
                                return(RedirectToAction("Index"));
                            }
                        }
                    }

                    ViewBag.CollectionId = new SelectList(ctx.Collections, "CollectionId", "Name", job.CollectionId);
                }
            }

            catch (Exception ex)
            {
                LogService.Info("Jobs not found", ex.Message, ex.InnerException);
            }

            return(View(job));
        }
Example #30
0
        // GET: Jobs
        public ActionResult Index()
        {
            List <Job> jobs = new List <Job>();

            try
            {
                // Get the jobs from the database
                if (User.IsInRole("SystemAdministrator"))
                {
                    using (var ctx = new SchedulerDbContext())
                    {
                        jobs = ctx.Jobs.Include("Collection").ToList();
                    }
                }
                else
                {
                    using (var ctx = new SchedulerDbContext())
                    {
                        jobs = ctx.Jobs.Where(i => i.Collection.TenantId == CurrentTenant.TenantId).Include("Collection").ToList();
                    }
                }

                // Create the breadcrumb
                var breadcrumb = new List <BreadcrumbItemViewModel>();
                breadcrumb.Add(new BreadcrumbItemViewModel()
                {
                    Text = "Jobs"
                });

                ViewBag.Breadcrumb = breadcrumb;
            }

            catch (Exception ex)
            {
                LogService.Info("Jobs not found", ex.Message, ex.InnerException);
            }

            return(View(jobs));
        }
Example #31
0
        public ActionResult Create()
        {
            try
            {
                using (var ctx = new SchedulerDbContext())
                {
                    if (User.IsInRole("SystemAdministrator"))
                    {
                        ViewBag.CollectionId = new SelectList(ctx.Collections.ToList(), "CollectionId", "Name");
                    }
                    else
                    {
                        ViewBag.CollectionId = new SelectList(ctx.Collections.Where(i => i.TenantId == CurrentTenant.TenantId).ToList(), "CollectionId", "Name");
                    }
                }
                // Create the breadcrumb
                var breadcrumb = new List <BreadcrumbItemViewModel>();
                breadcrumb.Add(new BreadcrumbItemViewModel()
                {
                    Text = "Jobs",
                    Link = "/Jobs"
                });

                breadcrumb.Add(new BreadcrumbItemViewModel()
                {
                    Text = "New"
                });

                ViewBag.Breadcrumb = breadcrumb;
            }

            catch (Exception ex)
            {
                LogService.Info("Jobs not found", ex.Message, ex.InnerException);
            }

            return(View());
        }
        public ScheduleInfoesController(SchedulerDbContext context, ILogger <HomeController> logger, ISchedulerFactory schedulerFactory, IOptions <BASE_PATHS> settings, TestDBContext testDBContext)
        {
            _context          = context;
            JobCenter.Manager = new ScheduleManager(_context);

            _logger           = logger;
            _schedulerFactory = schedulerFactory;

            _BASE_PATHS         = settings.Value;
            TaskJob.BASE_PATH   = _BASE_PATHS.MedicalHealth;
            TaskJobS1.BASE_PATH = _BASE_PATHS.MedicalHealthS1;
            TaskJobSY.BASE_PATH = _BASE_PATHS.MedicalHealthSY;

            var users = testDBContext.Users.Where(a => a.Id < 10).ToList();

            foreach (var item in users)
            {
                Console.Write(item.Id.ToString() + ", " + item.DisplayName);
                Console.WriteLine();
            }
            User addone = new User()
            {
                DisplayName  = "Admin",
                CreationDate = DateTime.Now,
                DownVotes    = 100,
                UpVotes      = 1000
            };

            testDBContext.Users.Add(addone);
            testDBContext.SaveChanges();//自增主键在插入成功后,会自动赋值过去
            var delone = testDBContext.Users.FirstOrDefault(a => a.Id == addone.Id);

            if (delone != null)
            {
                testDBContext.Users.Remove(delone);
                testDBContext.SaveChanges();//本身就是一个事务
            }
        }
        public ActionResult Index()
        {
            List <JobCollection> collections = new List <JobCollection>();

            try
            {
                using (var ctx = new SchedulerDbContext())
                {
                    if (User.IsInRole("SystemAdministrator"))
                    {
                        //Get all collections with tenant from db
                        collections = ctx.Collections.Include(c => c.Tenant).Include(c => c.Application).ToList();
                    }
                    else
                    {
                        collections = ctx.Collections.Where(i => i.TenantId == CurrentTenant.TenantId).Include(xi => xi.Application).ToList();
                    }
                }
            }
            catch (Exception ex)
            {
                LogService.Info("Collections not found", ex.Message, ex.InnerException);
            }

            // Create the breadcrumb
            var breadcrumb = new List <BreadcrumbItemViewModel>();

            breadcrumb.Add(new BreadcrumbItemViewModel()
            {
                Text = "Collections"
            });

            ViewBag.Breadcrumb = breadcrumb;

            return(View(collections));
        }
 public EventsController(SchedulerDbContext context, Service service)
 {
     _db = context;
     _service = service;
 }
 public ResponseController(SchedulerDbContext context)
 {
     _db = context;
 }
 public void SaveEvent(Event @event)
 {
     using (_db = new SchedulerDbContext())
     {
         _db.Users.Find(UserId).Events.Add(@event);
         _db.SaveChanges();
     }
 }
        public Event GetUserSpecificEvent(int? id)
        {
            using (_db = new SchedulerDbContext())
            {
                var userEvents = _db.Events.Include(ev => ev.Participants)
                                          .FirstOrDefault(e => (e.Id == id) && (e.SchedulerUserId == UserId));

                /*_db.Users.Find(UserId).Events.Find(e => e.Id == id);*/
                return userEvents;
            }
        }
 public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager,SchedulerDbContext context)
 {
     UserManager = userManager;
     SignInManager = signInManager;
     _db = context;
 }