コード例 #1
0
        public ApplicationContext()
        {
            ConsoleLogger.Write("Potranno essere assemblati ed eseguiti solo i comandi presenti nel database!",
                                "WARNING", ConsoleColor.DarkYellow);

            while (!File.Exists(docLoc))
            {
                ConsoleLogger.Write("File di database non trovato", "ERROR", ConsoleColor.Red);
                docLoc = MySupport.CWR("Inserire percorso database => ");
            }

            try {
                doc = XDocument.Load(docLoc);
            }
            catch (Exception e) {
                ConsoleLogger.Write("Non sono riuscito a leggere il database correttmente, controllane le struttura.\nDettagli: " + e.Message, "ERROR", ConsoleColor.Red);
                Environment.Exit(1);
            }

            Interpreter      = new CommandInterpreter(this);
            CommandAssembler = new Assembler(this);
            // TODO REPLACE WITH PARAMS
            CommandTemplate.ctx = this;
            CommandTemplList    = CommandTemplate.GetCommandsFromXML(doc);

            ConsoleLogger.Write("Oggetti costruiti con successo, in attesa di comandi: ", "MESSAGE", ConsoleColor.Green);
        }
コード例 #2
0
        public override string GetCommand()
        {
            string commandList    = GetCommandList();
            string commandContent = "{open_dialog_by_option, " + optionDialogInfo.TemplateId + ", [" + commandList + "]}";

            return(CommandTemplate.Replace("{0}", PreUniqueId.ToString()).Replace("{1}", PageIndex.ToString()).Replace("{2}", CommandIndex.ToString()).Replace("{3}", string.IsNullOrEmpty(PrevCommand) ? "" : "%% 执行:\"" + PrevCommand + "\"的操作").Replace("{4}", commandContent));
        }
コード例 #3
0
 private CreateCommandDocumentResponse CheckForCorrectTypes(CommandTemplate tpl, CreateCommandDocumentRequest request)
 {
     if (tpl.Parameters == null)
     {
         return(new CreateCommandDocumentResponse()
         {
             Success = true
         });
     }
     foreach (var item in tpl.Parameters)
     {
         var value = request.Body[item.Name];
         if (value != null)
         {
             if (!AreTypesEqual(value.Type, item.ParameterType))
             {
                 return(new CreateCommandDocumentResponse()
                 {
                     Success = false,
                     ErrorText = $"Invalid type for attribute '{item.Name}' in 'parameters' object. '{value.Type}' instead of '{item.ParameterType}'"
                 });
             }
         }
     }
     return(new CreateCommandDocumentResponse()
     {
         Success = true
     });
 }
コード例 #4
0
 private CreateCommandDocumentResponse CheckForMandatoryParameters(CommandTemplate tpl, CreateCommandDocumentRequest request)
 {
     if (tpl.Parameters == null)
     {
         return(new CreateCommandDocumentResponse()
         {
             Success = true
         });
     }
     if (request.CheckRequired)
     {
         foreach (var item in tpl.Parameters)
         {
             if (item.Required)
             {
                 var value = request.Body[item.Name];
                 if (value == null)
                 {
                     return new CreateCommandDocumentResponse()
                            {
                                Success = false, ErrorText = $"Required attribute '{item.Name}' in 'parameters' object missing."
                            }
                 }
                 ;
             }
         }
     }
     return(new CreateCommandDocumentResponse()
     {
         Success = true
     });
 }
コード例 #5
0
        public CommandTemplate ModifyCommandTemplate(long commandTemplateId, string name, string description, string code, string executableFile, string preparationScript)
        {
            CommandTemplate commandTemplate = _unitOfWork.CommandTemplateRepository.GetById(commandTemplateId);

            if (commandTemplate is null)
            {
                throw new RequestedObjectDoesNotExistException("The specified command template is not defined in HEAppE!");
            }

            if (!commandTemplate.IsEnabled)
            {
                throw new InputValidationException("The specified command template is deleted.");
            }

            if (commandTemplate.IsGeneric)
            {
                throw new InputValidationException("The specified command template is generic.");
            }

            if (executableFile is null)
            {
                throw new InputValidationException("The specified command template must have specified executable file!");
            }

            Cluster cluster = commandTemplate.ClusterNodeType.Cluster;
            var     commandTemplateParameters = SchedulerFactory.GetInstance(cluster.SchedulerType)
                                                .CreateScheduler(cluster)
                                                .GetParametersFromGenericUserScript(cluster, executableFile)
                                                .ToList();

            var templateParameters = new List <CommandTemplateParameter>();

            foreach (string parameter in commandTemplateParameters)
            {
                templateParameters.Add(new CommandTemplateParameter()
                {
                    Identifier  = parameter,
                    Description = parameter,
                    Query       = string.Empty
                });
            }

            commandTemplate.Name              = name;
            commandTemplate.Description       = description;
            commandTemplate.Code              = code;
            commandTemplate.PreparationScript = preparationScript;
            commandTemplate.TemplateParameters.ForEach(cmdParameters => _unitOfWork.CommandTemplateParameterRepository.Delete(cmdParameters));
            commandTemplate.TemplateParameters.AddRange(templateParameters);
            commandTemplate.ExecutableFile    = executableFile;
            commandTemplate.CommandParameters = string.Join(' ', commandTemplateParameters.Select(x => $"%%{"{"}{x}{"}"}"));

            _unitOfWork.Save();
            return(commandTemplate);
        }
コード例 #6
0
        public void RemoveCommandTemplate(long commandTemplateId)
        {
            CommandTemplate commandTemplate = _unitOfWork.CommandTemplateRepository.GetById(commandTemplateId);

            if (commandTemplate == null)
            {
                throw new RequestedObjectDoesNotExistException("The specified command template is not defined in HEAppE!");
            }

            commandTemplate.IsEnabled = false;
            _unitOfWork.Save();
        }
コード例 #7
0
        private void SetNewCommand(int commandID)
        {
            CommandTemplate template = null;

            _commandData.CommandMap.TryGetValue(commandID, out template);

            if (template != null)
            {
                Populate(new Command(template));
            }
            else
            {
                Populate(new Command(commandID, _commandData.DefaultCommandByteLength, _commandData.CommandType));
            }
        }
コード例 #8
0
        public static CommandTemplateExt ConvertIntToExt(this CommandTemplate commandTemplate)
        {
            CommandTemplateExt convert = new CommandTemplateExt()
            {
                Id                 = commandTemplate.Id,
                Name               = commandTemplate.Name,
                Description        = commandTemplate.Description,
                Code               = commandTemplate.Code,
                TemplateParameters = commandTemplate.TemplateParameters.Where(w => string.IsNullOrEmpty(w.Query) && w.IsVisible)
                                     .Select(s => s.ConvertIntToExt())
                                     .ToArray()
            };

            return(convert);
        }
コード例 #9
0
        /// <summary>
        /// Load the command set from its JSON file.
        /// </summary>
        ///
        /// The command set is the list of CommandTemplate objects available for the user to
        /// add to a route.
        ///
        /// <param name="filepath">The filename</param>
        /// <returns>Returns true if the file was loaded successfully, otherwise false is returned.</returns>
        private bool LoadCommandSet(String filepath)
        {
            bool retval = false;

            try
            {
                CommandSet = CommandTemplate.LoadCommandSet(filepath);
                retval     = true;
            }
            catch (Exception ex)
            {
                String msg = String.Format("Unable to load file {0}\n", filepath);
                MessageBox.Show(msg, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return(retval);
        }
コード例 #10
0
        /// <summary>
        /// Возвращает список команд.
        /// </summary>
        /// <returns>Список команд.</returns>
        public List <CommandTemplate> BuildCommands()
        {
            _rows = _rows.OrderBy(x => x.Type).ToList();

            List <CommandTemplate> command_templates = new List <CommandTemplate>();

            var outputs = _rows.Where(x => x.IsOutput).ToList();

            if (outputs == null || !outputs.Any())
            {
                throw new Exception("BuildCommands Не найдено возвращаемое значение.");
            }

            var output = outputs.Count > 1 ? NewCommand(BasicFunctionModel.Any, outputs) : outputs.First();

            var funcs = _rows.Where(x => x.Type == TemplateFunctionRowType.Func || x.Type == TemplateFunctionRowType.Output).OrderBy(x => x.Type).ToList();

            command_templates.Add(new CommandTemplate()
            {
                InputDataIds        = output.Input.Select(x => _rows.IndexOf(x)).ToList(),
                TriggeredCommandIds = output.Triggered.Select(x => funcs.IndexOf(x)).ToList(),
                OutputDataId        = _rows.IndexOf(output),
                FunctionHeader      = output.FunctionHeader
            });

            foreach (var func in funcs)
            {
                if (func.IsOutput)
                {
                    continue;
                }
                var command = new CommandTemplate()
                {
                    InputDataIds        = func.Input.Select(x => _rows.IndexOf(x)).ToList(),
                    TriggeredCommandIds = func.Triggered.Select(x => funcs.IndexOf(x)).ToList(),
                    OutputDataId        = _rows.IndexOf(func),
                    FunctionHeader      = func.FunctionHeader,
                    ConditionId         = func.Conditions.Select(x => _rows.IndexOf(x)).ToList()
                };
                command_templates.Add(command);
            }

            return(command_templates);
        }
コード例 #11
0
ファイル: Startup.cs プロジェクト: WikiLibs/DiscordBot
        private async Task DiscordBotTask()
        {
            _discordClient = new DiscordSocketClient();
            _reg           = new CommandRegistry();

            Configuration.Bind("Discord", _config);
            foreach (var hook in _config.AzureHooks)
            {
                _channels[hook.Name] = hook.Channel;
            }
            await _discordClient.LoginAsync(TokenType.Bot, _config.Token);

            _discordClient.MessageReceived += _socket_MessageReceived;
            bool ready = false;

            _discordClient.Ready += () =>
            {
                ready = true;
                return(Task.CompletedTask);
            };
            await _discordClient.StartAsync();

            while (!ready)
            {
                ;
            }
            _cmdChannel = _discordClient.GetChannel(_config.CmdChannel) as IMessageChannel;
            if (_cmdChannel == null)
            {
                Console.WriteLine("Could not connect with command channel");
                return;
            }
            await _cmdChannel.SendMessageAsync("WikiLibs Discord Bot Initialized");

            while (!_stop.IsCancellationRequested)
            {
                Message msg;
                while (_queue.Messages.TryDequeue(out msg))
                {
                    var ch = _discordClient.GetChannel(_channels[msg.HookName]) as IMessageChannel;
                    CommandTemplate.SendAzureCommit(_discordClient, ch, msg);
                }
            }
        }
コード例 #12
0
 private CreateCommandDocumentResponse CheckForCorrectValues(CommandTemplate tpl, CreateCommandDocumentRequest request)
 {
     if (tpl.Parameters == null)
     {
         return(new CreateCommandDocumentResponse()
         {
             Success = true
         });
     }
     foreach (var item in tpl.Parameters)
     {
         if (String.IsNullOrEmpty(item.AcceptedValues))
         {
             continue;
         }
         var accepted = item.AcceptedValues.Split(',');
         var value    = request.Body[item.Name];
         if (value != null)
         {
             if (!AreTypesEqual(value.Type, item.ParameterType))
             {
                 return(new CreateCommandDocumentResponse()
                 {
                     Success = false,
                     ErrorText = $"Invalid type for attribute '{item.Name}' in 'parameters' object. '{value.Type}' instead of '{item.ParameterType}'"
                 });
             }
             if (Array.IndexOf(accepted, value.ToString()) == -1)
             {
                 return(new CreateCommandDocumentResponse()
                 {
                     Success = false,
                     ErrorText = $"Invalid value for attribute '{item.Name}' in 'parameters' object. '{value.ToString()}' instead of '{item.AcceptedValues}'"
                 });
             }
         }
     }
     return(new CreateCommandDocumentResponse()
     {
         Success = true
     });
 }
コード例 #13
0
        /// <summary>
        /// Load the command set from its JSON file.
        /// </summary>
        ///
        /// The command set is the list of CommandTemplate objects available for the user to
        /// add to a route.
        ///
        /// <param name="filepath">The filename</param>
        /// <returns>Returns true if the file was loaded successfully, otherwise false is returned.</returns>
        private bool LoadCommandSet(String filepath)
        {
            bool retval = false;

            try
            {
                CommandSet = CommandTemplate.LoadCommandSet(filepath);
                retval     = true;
            }
            catch (Exception ex)
            {
                //don't show this error when xaml editor is trying to render or debugging
                if (!DesignerProperties.GetIsInDesignMode(this))
                {
                    String msg = String.Format("Unable to load file {0}\n", filepath);
                    MessageBox.Show(msg, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            return(retval);
        }
コード例 #14
0
 /// <summary>
 /// Add a new command to the current route.
 /// </summary>
 ///
 /// This function will create a new command from the selected command
 /// and add it to the current route after the current selection.
 ///
 /// After the command is inserted selection switches to the new command.
 ///
 /// <param name="sender"></param>
 /// <param name="e"></param>
 ///
 private void CommandTemplateLB_MouseDoubleClick(object sender, MouseButtonEventArgs e)
 {
     if (CommandTemplateLB.SelectedItem != null)
     {
         CommandTemplate item = (CommandTemplate)CommandTemplateLB.SelectedItem;
         if (item != null)
         {
             Command command = item.CreateCommandInstance();
             if (ProgramCommandsLB.SelectedItem != null)
             {
                 int index = ProgramCommandsLB.SelectedIndex + 1;
                 Commands.Insert(index, command);
                 ProgramCommandsLB.SelectedIndex = index;
             }
             else
             {
                 Commands.Add(command);
                 ProgramCommandsLB.SelectedIndex = ProgramCommandsLB.Items.Count - 1;
             }
         }
     }
 }
コード例 #15
0
        public CommandTemplateExt ModifyCommandTemplate(long commandTemplateId, string name, string description, string code, string executableFile, string preparationScript, string sessionCode)
        {
            try
            {
                using (IUnitOfWork unitOfWork = UnitOfWorkFactory.GetUnitOfWorkFactory().CreateUnitOfWork())
                {
                    AdaptorUser      loggedUser      = UserAndLimitationManagementService.GetValidatedUserForSessionCode(sessionCode, unitOfWork, UserRoleType.Administrator);
                    IManagementLogic managementLogic = LogicFactory.GetLogicFactory().CreateManagementLogic(unitOfWork);
                    CommandTemplate  commandTemplate = managementLogic.ModifyCommandTemplate(commandTemplateId, name, description, code, executableFile, preparationScript);
                    return(commandTemplate.ConvertIntToExt());
                }
            }
            catch (Exception exc)
            {
                if (exc.Message.Contains("No such file or directory"))
                {
                    ExceptionHandler.ThrowProperExternalException(new InputValidationException(exc.Message));
                }

                ExceptionHandler.ThrowProperExternalException(exc);
                return(null);
            }
        }
コード例 #16
0
        public IEnumerable <string> GetCommandTemplateParametersName(long commandTemplateId, string userScriptPath, AdaptorUser loggedUser)
        {
            CommandTemplate commandTemplate = unitOfWork.CommandTemplateRepository.GetById(commandTemplateId);

            if (commandTemplate is null)
            {
                throw new RequestedObjectDoesNotExistException("The specified command template is not defined in HEAppE!");
            }

            if (commandTemplate.IsGeneric)
            {
                string scriptPath = commandTemplate.TemplateParameters.Where(w => w.IsVisible)
                                    .FirstOrDefault()?.Identifier;
                if (string.IsNullOrEmpty(scriptPath))
                {
                    throw new RequestedObjectDoesNotExistException("The user-script command parameter for the generic command template is not defined in HEAppE!");
                }

                if (string.IsNullOrEmpty(userScriptPath))
                {
                    throw new RequestedObjectDoesNotExistException("The generic command template should contain script path!");
                }

                Cluster cluster = commandTemplate.ClusterNodeType.Cluster;
                var     commandTemplateParameters = new List <string>()
                {
                    scriptPath
                };
                commandTemplateParameters.AddRange(SchedulerFactory.GetInstance(cluster.SchedulerType).CreateScheduler(cluster).GetParametersFromGenericUserScript(cluster, userScriptPath).ToList());
                return(commandTemplateParameters);
            }
            else
            {
                return(commandTemplate.TemplateParameters.Select(s => s.Identifier)
                       .ToList());
            }
        }
コード例 #17
0
        /// <summary>
        /// Convert task specification to task
        /// </summary>
        /// <param name="jobSpecification">Job specification</param>
        /// <param name="taskSpecification">Task specification</param>
        /// <param name="schedulerAllocationCmd">Scheduler allocation cmd</param>
        /// <returns></returns>
        /// <exception cref="ApplicationException"></exception>
        public virtual object ConvertTaskSpecificationToTask(JobSpecification jobSpecification, TaskSpecification taskSpecification, object schedulerAllocationCmd)
        {
            ISchedulerTaskAdapter taskAdapter = _conversionAdapterFactory.CreateTaskAdapter(schedulerAllocationCmd);

            taskAdapter.DependsOn = taskSpecification.DependsOn;
            taskAdapter.SetEnvironmentVariablesToTask(taskSpecification.EnvironmentVariables);
            taskAdapter.IsExclusive = taskSpecification.IsExclusive;
            taskAdapter.SetRequestedResourceNumber(taskSpecification.ClusterNodeType.RequestedNodeGroups.Select(s => s.Name).ToList(),
                                                   taskSpecification.RequiredNodes.Select(s => s.NodeName).ToList(),
                                                   taskSpecification.PlacementPolicy,
                                                   taskSpecification.TaskParalizationSpecifications,
                                                   Convert.ToInt32(taskSpecification.MinCores),
                                                   Convert.ToInt32(taskSpecification.MaxCores),
                                                   taskSpecification.ClusterNodeType.CoresPerNode);

            // Do not change!!! Task name on the cluster is set as ID of the used task specification to enable pairing of cluster task info with DB task info.
            taskAdapter.Name = taskSpecification.Id.ToString(CultureInfo.InvariantCulture);

            if (Convert.ToInt32(taskSpecification.WalltimeLimit) > 0)
            {
                taskAdapter.Runtime = Convert.ToInt32(taskSpecification.WalltimeLimit);
            }

            string jobClusterDirectory = FileSystemUtils.GetJobClusterDirectoryPath(jobSpecification.FileTransferMethod.Cluster.LocalBasepath, jobSpecification);
            string workDirectory       = FileSystemUtils.GetTaskClusterDirectoryPath(jobClusterDirectory, taskSpecification);

            string stdErrFilePath = FileSystemUtils.ConcatenatePaths(workDirectory, taskSpecification.StandardErrorFile);

            taskAdapter.StdErrFilePath = workDirectory.Equals(stdErrFilePath) ? string.Empty : stdErrFilePath;

            string stdInFilePath = FileSystemUtils.ConcatenatePaths(workDirectory, taskSpecification.StandardInputFile);

            taskAdapter.StdInFilePath = workDirectory.Equals(stdInFilePath) ? string.Empty : stdInFilePath;

            string stdOutFilePath = FileSystemUtils.ConcatenatePaths(workDirectory, taskSpecification.StandardOutputFile);

            taskAdapter.StdOutFilePath = workDirectory.Equals(stdOutFilePath) ? string.Empty : stdOutFilePath;

            taskAdapter.WorkDirectory = workDirectory;
            taskAdapter.JobArrays     = taskSpecification.JobArrays;
            taskAdapter.IsRerunnable  = !string.IsNullOrEmpty(taskSpecification.JobArrays) || taskSpecification.IsRerunnable;

            taskAdapter.Queue = taskSpecification.ClusterNodeType.Queue;
            taskAdapter.ClusterAllocationName = taskSpecification.ClusterNodeType.ClusterAllocationName;
            taskAdapter.CpuHyperThreading     = taskSpecification.CpuHyperThreading ?? false;

            CommandTemplate template = taskSpecification.CommandTemplate;

            if (template is null)
            {
                throw new ApplicationException(@$ "Command Template " "{taskSpecification.CommandTemplate.Name}" " for task 
                                                  " "{taskSpecification.Name}" " does not exist in the adaptor configuration.");
            }

            Dictionary <string, string> templateParameters = CreateTemplateParameterValuesDictionary(jobSpecification, taskSpecification,
                                                                                                     template.TemplateParameters, taskSpecification.CommandParameterValues);

            taskAdapter.SetPreparationAndCommand(workDirectory, ReplaceTemplateDirectivesInCommand(template.PreparationScript, templateParameters),
                                                 ReplaceTemplateDirectivesInCommand($"{template.ExecutableFile} {template.CommandParameters}", templateParameters),
                                                 stdOutFilePath, stdErrFilePath, CreateTaskDirectorySymlinkCommand(taskSpecification));

            return(taskAdapter.AllocationCmd);
        }
コード例 #18
0
        public CommandTemplate CreateCommandTemplate(long genericCommandTemplateId, string name, string description, string code, string executableFile, string preparationScript)
        {
            CommandTemplate commandTemplate = _unitOfWork.CommandTemplateRepository.GetById(genericCommandTemplateId);

            if (commandTemplate is null)
            {
                throw new RequestedObjectDoesNotExistException("The specified command template is not defined in HEAppE!");
            }

            if (!commandTemplate.IsGeneric)
            {
                throw new InputValidationException("The specified command template is not generic.");
            }

            if (!commandTemplate.IsEnabled)
            {
                throw new InputValidationException("The specified command template is deleted.");
            }

            var commandTemplateParameter = commandTemplate.TemplateParameters.Where(w => w.IsVisible)
                                           .FirstOrDefault();

            if (string.IsNullOrEmpty(commandTemplateParameter?.Identifier))
            {
                throw new RequestedObjectDoesNotExistException("The user-script command parameter for the generic command template is not defined in HEAppE!");
            }

            if (string.IsNullOrEmpty(executableFile))
            {
                throw new InputValidationException("The generic command template should contain script path!");
            }

            Cluster cluster = commandTemplate.ClusterNodeType.Cluster;
            var     commandTemplateParameters = SchedulerFactory.GetInstance(cluster.SchedulerType)
                                                .CreateScheduler(cluster)
                                                .GetParametersFromGenericUserScript(cluster, executableFile)
                                                .ToList();

            List <CommandTemplateParameter> templateParameters = new();

            foreach (string parameter in commandTemplateParameters)
            {
                templateParameters.Add(new CommandTemplateParameter()
                {
                    Identifier  = parameter,
                    Description = parameter,
                    Query       = string.Empty
                });
            }

            CommandTemplate newCommandTemplate = new CommandTemplate()
            {
                Name               = name,
                Description        = description,
                IsGeneric          = false,
                IsEnabled          = true,
                ClusterNodeType    = commandTemplate.ClusterNodeType,
                ClusterNodeTypeId  = commandTemplate.ClusterNodeTypeId,
                Code               = code,
                ExecutableFile     = executableFile,
                PreparationScript  = preparationScript,
                TemplateParameters = templateParameters,
                CommandParameters  = string.Join(' ', commandTemplateParameters.Select(x => $"%%{"{"}{x}{"}"}"))
            };

            _unitOfWork.CommandTemplateRepository.Insert(newCommandTemplate);
            _unitOfWork.Save();

            return(newCommandTemplate);
        }
コード例 #19
0
 /// <summary>
 /// Save commands to a file.
 /// </summary>
 ///
 /// This function is primarily used to create a new command set file.
 ///
 /// <param name="filepath">The name of the file to save to</param>
 ///
 private void SaveCommandSet(String filepath)
 {
     CommandTemplate.SaveCommandSet(CommandSet, filepath);
 }
コード例 #20
0
        private async Task <CommandResult> CreateUser <TUser>(IQueryable <TUser> users, CommandTemplate command) where TUser : UserWithRole
        {
            if (command.Password.Length < 5)
            {
                return(CommandResult.Failed("Password has to have minimumt 5 letters"));
            }
            if (command.Username.Length < 5)
            {
                return(CommandResult.Failed("Username has to have minimumt 5 letters"));
            }
            if (command.Password != command.RepeatPassword)
            {
                return(CommandResult.Failed("Passwords must be matching"));
            }
            if (command.Email != command.RepeatEmail)
            {
                return(CommandResult.Failed("Emails must be matching"));
            }
            if (users.Any(u => u.AppUser.UserName == command.Username))
            {
                return(CommandResult.Failed("Username is already taken"));
            }
            if (users.Any(u => u.AppUser.Email == command.Email))
            {
                return(CommandResult.Failed("Email is already taken"));
            }

            var user = new AppUser
            {
                FirstName      = command.FirstName,
                LastName       = command.LastName,
                UserName       = command.Username,
                Email          = command.Email,
                EmailConfirmed = true,
            };

            user.PasswordHash = _userManager.PasswordHasher.HashPassword(user, command.Password);
            var result = await _userManager.CreateAsync(user);


            if (!result.Succeeded)
            {
                return(CommandResult.Failed());
            }

            switch (command)
            {
            case StudentCommand s:
                result = await _userManager.AddToRoleAsync(user, AppRoles.Student);

                break;

            case TeacherCommand t:
                result = await _userManager.AddToRoleAsync(user, AppRoles.Teacher);

                break;

            case AdminCommand a:
                result = await _userManager.AddToRoleAsync(user, AppRoles.Admin);

                break;

            default:
                break;
            }

            if (!result.Succeeded)
            {
                return(CommandResult.Failed());
            }

            switch (command)
            {
            case StudentCommand s:
                _dbContext.Add(new Student {
                    AppUser = user
                });
                break;

            case TeacherCommand t:
                _dbContext.Add(new Entities.Teacher {
                    AppUser = user
                });
                break;

            case AdminCommand a:
                _dbContext.Add(new Entities.Admin {
                    AppUser = user
                });
                break;

            default:
                break;
            }
            _dbContext.SaveChanges();

            return(CommandResult.Success());
        }
コード例 #21
0
        public override string GetCommand()
        {
            string commandContent = "{close_dialog}";

            return(CommandTemplate.Replace("{0}", PreUniqueId.ToString()).Replace("{1}", PageIndex.ToString()).Replace("{2}", CommandIndex.ToString()).Replace("{3}", string.IsNullOrEmpty(PrevCommand) ? "" : "%% 执行:\"" + PrevCommand + "\"的操作").Replace("{4}", commandContent));
        }
コード例 #22
0
        public override string GetCommand()
        {
            string commandContent = string.Format("{{open_dialog_by_message, {0}, {1}, {2}, {3}}}", messageDialogInfo.Comment, UniqueId, PageIndex + 1, CommandIndex);

            return(CommandTemplate.Replace("{0}", PreUniqueId.ToString()).Replace("{1}", PageIndex.ToString()).Replace("{2}", CommandIndex.ToString()).Replace("{3}", string.IsNullOrEmpty(PrevCommand) ? "" : "%% 执行:\"" + PrevCommand + "\"的操作").Replace("{4}", commandContent));
        }
コード例 #23
0
        private async Task <CommandResult> EditUser <TUser>(IQueryable <TUser> users, CommandTemplate command) where TUser : UserWithRole
        {
            var user = users.FirstOrDefault(x => x.ID == command.Id);

            if (user == null || user.AppUser == null)
            {
                return(CommandResult.Failed("Given user is invalid"));
            }
            if (command.Username.Length < 5)
            {
                return(CommandResult.Failed("Username has to have minimumt 5 letters"));
            }
            if (users.Any(u => u.ID != command.Id && u.AppUser.UserName == command.Username))
            {
                return(CommandResult.Failed("Username is already taken"));
            }
            if (users.Any(u => u.ID != command.Id && u.AppUser.Email == command.Email))
            {
                return(CommandResult.Failed("Email is already taken"));
            }

            var appUser = await _userManager.FindByIdAsync(user.AppUserID);

            appUser.Email     = command.Email;
            appUser.FirstName = command.FirstName;
            appUser.LastName  = command.LastName;
            appUser.UserName  = command.Username;

            var result = await _userManager.UpdateAsync(appUser);

            if (!result.Succeeded)
            {
                return(CommandResult.Failed());
            }

            return(CommandResult.Success());
        }