Ejemplo n.º 1
0
        public IActionResult Euler(ParametersViewModel pvm)
        {
            var   viewModel = new ParametersViewModel();
            var   list      = new List <Point>();
            var   xt        = pvm.xt;
            var   t         = pvm.a;
            float predictor;

            Console.WriteLine($"Cuando t es: {t} / x es: {xt}");
            list.Add(new Point {
                x = t, y = xt
            });
            while (t < pvm.b)
            {
                predictor = xt + pvm.h * func(xt, t, pvm.function);
                xt        = xt + (0.5f) * (func(xt, t, pvm.function) + func(predictor, t + pvm.h, pvm.function)) * pvm.h;
                t         = t + pvm.h;
                Console.WriteLine($"Cuando t es: {t} / x es: {xt}");
                list.Add(new Point {
                    x = (float)Math.Round(t, 2), y = xt
                });
            }
            viewModel.EulerMejoradoPoints = list;
            var listEuler = EulerOrden1(pvm);

            viewModel.EulerPoints = listEuler;
            return(View(viewModel));
        }
Ejemplo n.º 2
0
 public DataTypeViewModel(DocumentIdViewModel id,
                          DocumentUriViewModel uri,
                          TitlesViewModel titlesViewModel,
                          SyntaxViewModel syntaxViewModel,
                          DocumentReferenceViewModel @base,
                          LocationViewModel location,
                          InheritanceViewModel inheritance,
                          ParametersViewModel parameters,
                          ReturnsViewModel returns,
                          UxClassPropertiesViewModel uxProperties,
                          ValuesViewModel values,
                          CommentViewModel comment,
                          DocumentReferenceViewModel declaredIn,
                          ImplementedInterfacesViewModel implementedInterfaces,
                          AttributesViewModel attributes,
                          IEntity underlyingEntity)
     : base(id, uri, titlesViewModel, syntaxViewModel, comment, declaredIn, underlyingEntity)
 {
     Base                  = @base;
     Location              = location;
     Inheritance           = inheritance;
     Parameters            = parameters;
     Returns               = returns;
     UxProperties          = uxProperties;
     Values                = values;
     ImplementedInterfaces = implementedInterfaces;
     Attributes            = attributes;
 }
Ejemplo n.º 3
0
 public MainWindowViewModel()
 {
     ParametersVM   = new ParametersViewModel(this);
     Dome2DVM       = new Dome2DViewModel(this);
     Dome3DVM       = new Dome3DViewModel(this);
     ColorChooserVM = new ColorChooserViewModel(this);
 }
Ejemplo n.º 4
0
 /// <summary>
 ///		Graba la dimensión
 /// </summary>
 public void SaveDetails(bool newName)
 {
     if (ValidateData())
     {
         // Añade el origen de datos si es nuevo
         if (DataSource.DataWarehouse.DataSources[DataSource.Id] == null)
         {
             DataSource.DataWarehouse.DataSources.Add(DataSource);
         }
         // Asigna las propiedades
         DataSource.Id  = Key;
         DataSource.Sql = Sql;
         // Asigna las columnas
         DataSource.Columns.Clear();
         DataSource.Columns.AddRange(ColumnsViewModel.GetColumns());
         // Asigna los parámetros
         DataSource.Parameters.Clear();
         DataSource.Parameters.AddRange(ParametersViewModel.GetParameters());
         // Graba la solución
         ReportingSolutionViewModel.SaveDataWarehouse(DataSource.DataWarehouse);
         // Cambia la cabecera
         Header = DataSource.Id;
         // Indica que no ha habido modificaciones
         IsUpdated = false;
     }
 }
Ejemplo n.º 5
0
        public MainViewModel()
        {
            Login      = new LoginViewModel();
            Models     = new ModelsViewModel();
            Parameters = new ParametersViewModel();
            Reports    = new ReportsViewModel();
            Entry      = new EntryViewModel();
            Years      = new ObservableCollection <int>();

            AddYearCommand    = new RoutedUICommand("AddYear", "AddYear", typeof(MainViewModel));
            BackupCommand     = new RoutedUICommand("Backup", "Backup", typeof(MainViewModel));
            DeleteYearCommand = new RoutedUICommand("DeleteYear", "DeleteYear", typeof(MainViewModel));
            LoginCommand      = new RoutedUICommand("Login", "Login", typeof(MainViewModel));
            RefreshCommand    = new RoutedUICommand("Refresh", "Refresh", typeof(MainViewModel));
            HelpCommand       = new RoutedUICommand("Help", "Help", typeof(MainViewModel));

            Bindings = new CommandBindingCollection()
            {
                new CommandBinding(AddYearCommand, AddYearExecuted, AddYearCanExecute),
                new CommandBinding(BackupCommand, BackupExecuted, BackupCanExecute),
                new CommandBinding(DeleteYearCommand, DeleteYearExecuted, DeleteYearCanExecute),
                new CommandBinding(LoginCommand, LoginExecuted),
                new CommandBinding(RefreshCommand, RefreshExecuted),
                new CommandBinding(HelpCommand, HelpExecuted),
            };

            LoadYears();
        }
Ejemplo n.º 6
0
 /// <summary>
 ///     Sets the scheduling parameters.
 ///     If true, parent controller method must truncate the Colors table t (optional), and notify the user that the current
 ///     schedule is redundant
 ///     If false, parent controller method must  notify the user that a better schedule may be possible, and suggest
 ///     rescheduling
 /// </summary>
 /// <param name="parameters">The parameters.</param>
 /// <returns>Whether or not any of the parameters became stricter.</returns>
 public static bool SetSchedulingParameters(ParametersViewModel parameters)
 {
     return((parameters.Days != Color.MaxDays && Color.SetMaxDays(parameters.Days)) |
            (parameters.TimeSlots != Color.MaxTimeSlots && Color.SetMaxTimeSlots(parameters.TimeSlots)) |
            (parameters.ConcurrencyLimit != Color.ConcurrencyLimit &&
             Color.SetConcurrencyLimit(parameters.ConcurrencyLimit)));
 }
Ejemplo n.º 7
0
 public KeyValuePair<ContentControl, Action> GetConfigurationView()
 {
     var view = new ParametersView();
     var viewModel = new ParametersViewModel();
     view.DataContext = viewModel;
     return new KeyValuePair<ContentControl, Action>(view, viewModel.SaveAction);
 }
        public ActionResult Set(ParametersViewModel parameters)
        {
            if (!ModelState.IsValid)
            {
                return(View(parameters));
            }
            try
            {
                if (EntityModifier.SetSchedulingParameters(parameters))
                {
                    TempData["messageState"] = 2; //0-success 1-warning 2-danger
                    TempData["message"]      =
                        @"Due to the parameters becoming stricter, the old schedule is now redundant, 
press the Reschedule button to generate a schedule that satisfies the new parameters";
                }
                else
                {
                    TempData["messageState"] = 1; //0-success 1-warning 2-danger
                    TempData["message"]      =
                        @"The parameters did not become stricter, so the current schedule (if it exists) is valid.
Also, a more optimal schedule may be possible, try by pressing Reschedule";
                }

                TempData["paramSuccess"] = true;
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
                return(View(parameters));
            }

            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 9
0
        public ActionResult RerenderIndex(int ReportId)
        {
            List <DB.ReportSPParameter> reportPara          = DB_MSBDW.ReportSPParameters.Where(sp => sp.SSRSReportId == ReportId).OrderByDescending(sp => sp.RowCreateDate).ToList();
            ParametersViewModel         parametersViewModel = new ParametersViewModel(reportPara);

            ViewData["selectedReportId"]   = ReportId;
            ViewData["buttonName"]         = "PA";
            ViewData["selectedReportName"] = DB_MSBDW.SSRSReport1.FirstOrDefault(re => re.id == ReportId).rpt_name;
            return(View(parametersViewModel.reportSPParameters));
        }
Ejemplo n.º 10
0
        private void SaveParameter(EditingFormModel form)
        {
            form.parameter.MetaData.Variants = form.Variants;
            var model = new ParametersViewModel()
            {
                EditingForm = form
            };

            model.SaveParentsAndChildren();
            Get <IParameterRepository>().Edit(form.parameter);
        }
Ejemplo n.º 11
0
        public IChildView GetInstrumentationView()
        {
            var model   = new ParametersViewModel();
            var command = new WeaveFileCommand(new CodeWeaverService(), model);

            model.Clear();

            var view = new AssemblyInstrumentationView {
                AssemblyServices = this.GetAssemblyServices(),
                WeaveCommand     = command,
                Parameter        = model
            };

            return(view);
        }
Ejemplo n.º 12
0
        // GET: Parameters

        public ActionResult Index(int id, string name)
        {
            int    selectedReport     = id;
            string selectedReportName = name;



            List <DB.ReportSPParameter> reportPara          = DB_MSBDW.ReportSPParameters.Where(sp => sp.SSRSReportId == selectedReport).OrderByDescending(sp => sp.RowCreateDate).ToList();
            ParametersViewModel         parametersViewModel = new ParametersViewModel(reportPara);

            ViewData["selectedReportId"]   = selectedReport;
            ViewData["buttonName"]         = "PA";
            ViewData["selectedReportName"] = selectedReportName;
            return(View(parametersViewModel.reportSPParameters));
        }
Ejemplo n.º 13
0
 public AttachedMemberViewModel(DocumentIdViewModel id,
                                DocumentUriViewModel uri,
                                TitlesViewModel titles,
                                DocumentReferenceViewModel declaredIn,
                                ParametersViewModel parameters,
                                ReturnsViewModel returns,
                                ValuesViewModel values,
                                AttachedMemberSourceViewModel source,
                                CommentViewModel comment,
                                IEntity underlyingEntity)
     : base(id, uri, titles, null, comment, declaredIn, underlyingEntity)
 {
     Parameters = parameters;
     Returns    = returns;
     Values     = values;
     Source     = source;
 }
Ejemplo n.º 14
0
        public ActionResult AddingParameter(AddFormModel form)
        {
            ParametersViewModel viewModel = new ParametersViewModel();

            if (ModelState.IsValid)
            {
                if (form != null)
                {
                    viewModel.AddForm            = form;
                    viewModel.AddForm.Parameters = Get <IParameterRepository>().GetAllParam();
                    viewModel.SetPropertiesAndMetadata();
                    if (!form.parameter.MetaData.Is_var)
                    {
                        var flag = Get <IParameterRepository>().Add(form.parameter);
                        return(RedirectTo <ParametersController>(a => a.AddConfirm()));
                    }
                    else
                    {
                        if (form.NumValue == 0)
                        {
                            return(RedirectTo <ParametersController>(a => a.AddParameter(form)));
                        }
                        else
                        {
                            TempData["newParameter"] = form.parameter;
                            var varForm = new VarFormModel()
                            {
                                NumVariant = form.NumValue,
                                Variants   = new Variant[form.NumValue],
                                Parameter  = form.parameter
                            };
                            return(RedirectTo <ParametersController>(a => a.Var(varForm)));
                        }
                    }
                }
                else
                {
                    throw new Exception("Отсутствует форма с данными,необходимы для создания параметра здоровья.");
                }
            }
            else
            {
                throw new Exception("Форма с входными данными не прошла валидацию.");
            }
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> DailyParameters(ParametersViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var    user   = HttpContext.User;
                string userId = userManager.GetUserId(user);

                var userParam = appContext.Params.Where(x => x.UserId.Equals(userId) & x.Date.Date.Equals(viewModel.Date.ToUniversalTime().Date)).FirstOrDefault();

                if (userParam == null)
                {
                    await appContext.Params.AddAsync(
                        new Param
                    {
                        UserId  = userId,
                        Date    = viewModel.Date.ToUniversalTime(),
                        Weight  = viewModel.Weight,
                        Breast  = viewModel.Breast,
                        Waist   = viewModel.Waist,
                        Buttock = viewModel.Pelvis,
                        Thigh   = viewModel.Thigh
                    });
                }
                else
                {
                    userParam.Date    = viewModel.Date.ToUniversalTime();
                    userParam.Weight  = viewModel.Weight;
                    userParam.Breast  = viewModel.Breast;
                    userParam.Waist   = viewModel.Waist;
                    userParam.Buttock = viewModel.Pelvis;
                    userParam.Thigh   = viewModel.Thigh;
                    appContext.Params.Update(userParam);
                }
                await appContext.SaveChangesAsync();

                return(RedirectToAction("BodyStat", "Statistic"));
            }
            else
            {
                return(View(viewModel));
            }
        }
Ejemplo n.º 16
0
        private void SourceButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                DefaultExt = Const.DafaultExtention,
                Filter     = Const.DefaultFilter
            };

            if (openFileDialog.ShowDialog() == true)
            {
                SourceLbl.Content    = openFileDialog.FileName;
                SourceParametersList = OpenFile(openFileDialog.FileName);
            }
            if (SourceParametersList != null && TargetParametersList != null)
            {
                TableGrid.Visibility = Visibility.Visible;
                DataGrid.ItemsSource = GetList(SourceParametersList, TargetParametersList);
                ResultLbl.Content    = ParametersViewModel.TotalStatusResult(SourceParametersList, TargetParametersList);
            }
        }
Ejemplo n.º 17
0
        private List <Point> EulerOrden1(ParametersViewModel pvm)
        {
            var list = new List <Point>();
            var xt   = pvm.xt;
            var t    = pvm.a;

            list.Add(new Point {
                x = t, y = xt
            });
            while (t < pvm.b)
            {
                xt = xt + pvm.h * func(xt, t, pvm.function);
                t  = t + pvm.h;
                Console.WriteLine($"Cuando t es: {t} / x es: {xt}");
                list.Add(new Point {
                    x = (float)Math.Round(t, 2), y = xt
                });
            }
            return(list);
        }
        public async Task <IActionResult> RunNow([FromBody] RunNowViewModel request)
        {
            try
            {
                ParametersViewModel.VerifyParameterNameAvailability(request.JobParameters);

                Guid AutomationId = request.AutomationId;
                Guid AgentId      = request.AgentId;
                Guid AgentGroupId = request.AgentGroupId;

                Schedule schedule = new Schedule();
                schedule.AgentId        = AgentId;
                schedule.AgentGroupId   = AgentGroupId;
                schedule.CRONExpression = "";
                schedule.LastExecution  = DateTime.UtcNow;
                schedule.NextExecution  = DateTime.UtcNow;
                schedule.IsDisabled     = false;
                schedule.ProjectId      = null;
                schedule.StartingType   = "RunNow";
                schedule.Status         = "New";
                schedule.ExpiryDate     = DateTime.UtcNow.AddDays(1);
                schedule.StartDate      = DateTime.UtcNow;
                schedule.AutomationId   = AutomationId;
                schedule.CreatedOn      = DateTime.UtcNow;
                schedule.CreatedBy      = applicationUser?.UserName;

                var jsonScheduleObj = JsonSerializer.Serialize <Schedule>(schedule);
                _hubManager.ExecuteJob(jsonScheduleObj, request.JobParameters);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(ex.GetActionResult());
            }
        }
Ejemplo n.º 19
0
        public IActionResult DailyParameters()
        {
            var user = HttpContext.User;
            ParametersViewModel viewModel = new ParametersViewModel {
                Date = DateTime.Now
            };
            string userId           = userManager.GetUserId(user);
            var    currentUserParam = appContext.Params.Where(x => x.UserId.Equals(userId) & x.Date.Date.Equals(DateTime.UtcNow.Date)).FirstOrDefault();

            if (currentUserParam != null) // на эту дату есть уже внесенные данные в базе данных
            {
                viewModel = new ParametersViewModel
                {
                    Date   = currentUserParam.Date.ToLocalTime(),
                    Breast = currentUserParam.Breast,
                    Pelvis = currentUserParam.Buttock,
                    Thigh  = currentUserParam.Thigh,
                    Waist  = currentUserParam.Waist,
                    Weight = currentUserParam.Weight
                };
            }

            return(View(viewModel));
        }
Ejemplo n.º 20
0
 public MemberViewModel(DocumentIdViewModel id,
                        DocumentUriViewModel uri,
                        TitlesViewModel titles,
                        SyntaxViewModel syntax,
                        LocationViewModel location,
                        DocumentReferenceViewModel declaredIn,
                        ParametersViewModel parameters,
                        ReturnsViewModel returns,
                        UxMemberPropertiesViewModel uxProperties,
                        ValuesViewModel values,
                        MemberFlagsViewModel flags,
                        CommentViewModel comment,
                        AttributesViewModel attributes,
                        IEntity underlyingEntity)
     : base(id, uri, titles, syntax, comment, declaredIn, underlyingEntity)
 {
     Location     = location;
     Parameters   = parameters;
     Returns      = returns;
     UxProperties = uxProperties;
     Flags        = flags;
     Values       = values;
     Attributes   = attributes;
 }
Ejemplo n.º 21
0
        /// <summary>
        ///		Comprueba los datos introducidos
        /// </summary>
        private bool ValidateData()
        {
            bool validated = false;

            // Comprueba los datos
            if (string.IsNullOrWhiteSpace(Key))
            {
                ReportingSolutionViewModel.SolutionViewModel.MainController.SystemController.ShowMessage("Introduzca la clave del origen de datos");
            }
            else if (string.IsNullOrWhiteSpace(Sql))
            {
                ReportingSolutionViewModel.SolutionViewModel.MainController.SystemController.ShowMessage("Introduzca el comando SQL del origen de datos");
            }
            else if (ColumnsViewModel.Items.Count == 0)
            {
                ReportingSolutionViewModel.SolutionViewModel.MainController.SystemController.ShowMessage("No se ha definido ninguna columna");
            }
            else if (ColumnsViewModel.ValidateData() && ParametersViewModel.ValidateData())
            {
                validated = true;
            }
            // Devuelve el valor que indica si se ha podido grabar
            return(validated);
        }
Ejemplo n.º 22
0
        public string CreateJob(string scheduleSerializeObject, IEnumerable <ParametersViewModel>?parameters)
        {
            var schedule = JsonSerializer.Deserialize <Schedule>(scheduleSerializeObject);

            if (organizationSettingManager.HasDisallowedExecution())
            {
                return("DisallowedExecution");
            }

            var automationVersion = automationVersionRepository.Find(null, a => a.AutomationId == schedule.AutomationId).Items?.FirstOrDefault();

            //if this is a scheduled job get the schedule parameters
            if (schedule.StartingType.Equals("RunNow") == false)
            {
                List <ParametersViewModel> parametersList = new List <ParametersViewModel>();

                var scheduleParameters = scheduleParameterRepository.Find(null, p => p.ScheduleId == schedule.Id).Items;
                foreach (var scheduleParameter in scheduleParameters)
                {
                    ParametersViewModel parametersViewModel = new ParametersViewModel
                    {
                        Name      = scheduleParameter.Name,
                        DataType  = scheduleParameter.DataType,
                        Value     = scheduleParameter.Value,
                        CreatedBy = scheduleParameter.CreatedBy,
                        CreatedOn = DateTime.UtcNow
                    };
                    parametersList.Add(parametersViewModel);
                }
                parameters = parametersList.AsEnumerable();
            }

            Job job = new Job();

            job.AgentId             = schedule.AgentId == null ? Guid.Empty : schedule.AgentId.Value;
            job.CreatedBy           = schedule.CreatedBy;
            job.CreatedOn           = DateTime.UtcNow;
            job.EnqueueTime         = DateTime.UtcNow;
            job.JobStatus           = JobStatusType.New;
            job.AutomationId        = schedule.AutomationId == null ? Guid.Empty : schedule.AutomationId.Value;
            job.AutomationVersion   = automationVersion != null ? automationVersion.VersionNumber : 0;
            job.AutomationVersionId = automationVersion != null ? automationVersion.Id : Guid.Empty;
            job.Message             = "Job is created through internal system logic.";

            foreach (var parameter in parameters ?? Enumerable.Empty <ParametersViewModel>())
            {
                JobParameter jobParameter = new JobParameter
                {
                    Name      = parameter.Name,
                    DataType  = parameter.DataType,
                    Value     = parameter.Value,
                    JobId     = job.Id ?? Guid.Empty,
                    CreatedBy = schedule.CreatedBy,
                    CreatedOn = DateTime.UtcNow,
                    Id        = Guid.NewGuid()
                };
                jobParameterRepository.Add(jobParameter);
            }

            jobRepository.Add(job);
            _hub.Clients.All.SendAsync("botnewjobnotification", job.AgentId.ToString());
            webhookPublisher.PublishAsync("Jobs.NewJobCreated", job.Id.ToString()).ConfigureAwait(false);

            return("Success");
        }
Ejemplo n.º 23
0
 public ParametersPage(ParametersViewModel model)
 {
     InitializeComponent();
     _model         = model;
     BindingContext = _model;
 }
        public async Task <IActionResult> Put(string id, [FromBody] CreateScheduleViewModel request)
        {
            try
            {
                ParametersViewModel.VerifyParameterNameAvailability(request.Parameters);
                //validate the cron expression
                if (!string.IsNullOrWhiteSpace(request.CRONExpression))
                {
                    try
                    {
                        CronExpression expression = CronExpression.Parse(request.CRONExpression, CronFormat.Standard);
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("Save", string.Concat("Invalid cron expression, ", ex.Message));
                        return(BadRequest(ModelState));
                    }
                }

                Guid entityId = new Guid(id);

                var existingSchedule = repository.GetOne(entityId);
                if (existingSchedule == null)
                {
                    return(NotFound());
                }

                existingSchedule.Name           = request.Name;
                existingSchedule.AgentId        = request.AgentId;
                existingSchedule.AgentGroupId   = request.AgentGroupId;
                existingSchedule.CRONExpression = request.CRONExpression;
                existingSchedule.LastExecution  = request.LastExecution;
                existingSchedule.NextExecution  = request.NextExecution;
                existingSchedule.IsDisabled     = request.IsDisabled;
                existingSchedule.ProjectId      = request.ProjectId;
                existingSchedule.StartingType   = request.StartingType;
                existingSchedule.Status         = request.Status;
                existingSchedule.ExpiryDate     = request.ExpiryDate;
                existingSchedule.StartDate      = request.StartDate;
                existingSchedule.AutomationId   = request.AutomationId;

                var response = await base.PutEntity(id, existingSchedule);

                _manager.DeleteExistingParameters(entityId);

                var set = new HashSet <string>();
                foreach (var parameter in request.Parameters ?? Enumerable.Empty <ParametersViewModel>())
                {
                    if (!set.Add(parameter.Name))
                    {
                        ModelState.AddModelError("ScheduleParameter", "ScheduleParameter Name Already Exists");
                        return(BadRequest(ModelState));
                    }

                    ScheduleParameter scheduleParameter = new ScheduleParameter
                    {
                        Name       = parameter.Name,
                        DataType   = parameter.DataType,
                        Value      = parameter.Value,
                        ScheduleId = entityId,
                        CreatedBy  = applicationUser?.UserName,
                        CreatedOn  = DateTime.UtcNow,
                        Id         = Guid.NewGuid()
                    };
                    _scheduleParameterRepository.Add(scheduleParameter);
                }

                _recurringJobManager.RemoveIfExists(existingSchedule.Id?.ToString());

                if (request.IsDisabled == false && !request.StartingType.ToLower().Equals("manual"))
                {
                    var jsonScheduleObj = JsonSerializer.Serialize <Schedule>(existingSchedule);

                    _backgroundJobClient.Schedule(() => _hubManager.ScheduleNewJob(jsonScheduleObj),
                                                  new DateTimeOffset(existingSchedule.StartDate.Value));
                }

                return(response);
            }
            catch (Exception ex)
            {
                return(ex.GetActionResult());
            }
        }
 public ParametersWindow(ObservableCollection <Parameter> parameterList)
 {
     InitializeComponent();
     DataContext = new ParametersViewModel(parameterList);
 }
 public ParametersWindow()
 {
     InitializeComponent();
     DataContext = new ParametersViewModel();
 }
Ejemplo n.º 27
0
 public ParametersView(ParametersViewModel parametersViewModel)
 {
     InitializeComponent();
     DataContext = parametersViewModel;
 }
Ejemplo n.º 28
0
 public ViewModelLocator()
 {
     _main = new MainViewModel();
     _parameters = new ParametersViewModel();
     _parameterValues = new ParameterValuesViewModel();
 }
        public async Task <IActionResult> Post([FromBody] CreateScheduleViewModel request)
        {
            ParametersViewModel.VerifyParameterNameAvailability(request.Parameters);
            if (request == null)
            {
                ModelState.AddModelError("Save", "No data passed");
                return(BadRequest(ModelState));
            }

            //validate the cron expression
            if (!string.IsNullOrWhiteSpace(request.CRONExpression))
            {
                try
                {
                    CronExpression expression = CronExpression.Parse(request.CRONExpression, CronFormat.Standard);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("Save", string.Concat("Invalid cron expression, ", ex.Message));
                    return(BadRequest(ModelState));
                }
            }

            Guid entityId = Guid.NewGuid();

            if (request.Id == null || !request.Id.HasValue || request.Id.Equals(Guid.Empty))
            {
                request.Id = entityId;
            }

            try
            {
                Schedule requestObj = request.Map(request); //assign request to schedule entity

                foreach (var parameter in request.Parameters ?? Enumerable.Empty <ParametersViewModel>())
                {
                    ScheduleParameter scheduleParameter = new ScheduleParameter
                    {
                        Name       = parameter.Name,
                        DataType   = parameter.DataType,
                        Value      = parameter.Value,
                        ScheduleId = entityId,
                        CreatedBy  = applicationUser?.UserName,
                        CreatedOn  = DateTime.UtcNow,
                        Id         = Guid.NewGuid()
                    };
                    _scheduleParameterRepository.Add(scheduleParameter);
                }

                var response = await base.PostEntity(requestObj);

                _recurringJobManager.RemoveIfExists(requestObj.Id?.ToString());

                if (request.IsDisabled == false && !request.StartingType.ToLower().Equals("manual"))
                {
                    var jsonScheduleObj = JsonSerializer.Serialize <Schedule>(requestObj);

                    _backgroundJobClient.Schedule(() => _hubManager.ScheduleNewJob(jsonScheduleObj),
                                                  new DateTimeOffset(requestObj.StartDate.Value));
                }

                return(response);
            }
            catch (Exception ex)
            {
                return(ex.GetActionResult());
            }
        }
Ejemplo n.º 30
0
        public string CreateJob(string scheduleSerializeObject, IEnumerable<ParametersViewModel>? parameters)
        {
            var schedule = JsonSerializer.Deserialize<Schedule>(scheduleSerializeObject);
            //if schedule has expired
            if (DateTime.UtcNow > schedule.ExpiryDate)
            {
                _recurringJobManager.RemoveIfExists(schedule.Id.Value.ToString());//removes an existing recurring job
                return "ScheduleExpired";
            }

            if (_organizationSettingManager.HasDisallowedExecution())
            {
                return "DisallowedExecution";
            }

            //if this is not a "RunNow" job, then use the schedule parameters
            if (schedule.StartingType.Equals("RunNow") == false)
            {
                if (schedule.MaxRunningJobs != null)
                {
                    if (ActiveJobLimitReached(schedule.Id, schedule.MaxRunningJobs))
                    {
                        return "ActiveJobLimitReached";
                    }
                }

                List<ParametersViewModel> parametersList = new List<ParametersViewModel>();

                var scheduleParameters = _scheduleParameterRepository.Find(null, p => p.ScheduleId == schedule.Id).Items;
                foreach (var scheduleParameter in scheduleParameters)
                {
                    ParametersViewModel parametersViewModel = new ParametersViewModel
                    {
                        Name = scheduleParameter.Name,
                        DataType = scheduleParameter.DataType,
                        Value = scheduleParameter.Value,
                        CreatedBy = scheduleParameter.CreatedBy,
                        CreatedOn = DateTime.UtcNow
                    };
                    parametersList.Add(parametersViewModel);
                }
                parameters = parametersList.AsEnumerable();
            }

            var automationVersion = _automationVersionRepository.Find(null, a => a.AutomationId == schedule.AutomationId).Items?.FirstOrDefault();

            Job job = new Job();
            job.AgentId = schedule.AgentId == null ? Guid.Empty : schedule.AgentId.Value;
            job.AgentGroupId = schedule.AgentGroupId == null ? Guid.Empty : schedule.AgentGroupId.Value;
            job.CreatedBy = schedule.CreatedBy;
            job.CreatedOn = DateTime.UtcNow;
            job.EnqueueTime = DateTime.UtcNow;
            job.JobStatus = JobStatusType.New;
            job.AutomationId = schedule.AutomationId == null ? Guid.Empty : schedule.AutomationId.Value;
            job.AutomationVersion = automationVersion != null ? automationVersion.VersionNumber : 0;
            job.AutomationVersionId = automationVersion != null ? automationVersion.Id : Guid.Empty;
            job.Message = "Job is created through internal system logic.";
            job.ScheduleId = schedule.Id;

            foreach (var parameter in parameters ?? Enumerable.Empty<ParametersViewModel>())
            {
                JobParameter jobParameter = new JobParameter
                {
                    Name = parameter.Name,
                    DataType = parameter.DataType,
                    Value = parameter.Value,
                    JobId = job.Id ?? Guid.Empty,
                    CreatedBy = schedule.CreatedBy,
                    CreatedOn = DateTime.UtcNow,
                    Id = Guid.NewGuid()
                };
                _jobParameterRepository.Add(jobParameter);
            }
            _jobRepository.Add(job);

            if (job.AgentGroupId == null || job.AgentGroupId == Guid.Empty)
            {
                _hub.Clients.All.SendAsync("botnewjobnotification", job.AgentId.ToString());
            }
            else //notify all group members
            {
                var agentsInGroup = _agentGroupManager.GetAllMembersInGroup(job.AgentGroupId.ToString());
                foreach (var groupMember in agentsInGroup ?? Enumerable.Empty<AgentGroupMember>())
                {
                    _hub.Clients.All.SendAsync("botnewjobnotification", groupMember.AgentId.ToString());
                }
            }

            _webhookPublisher.PublishAsync("Jobs.NewJobCreated", job.Id.ToString()).ConfigureAwait(false);

            return "Success";
        }