Пример #1
0
        protected virtual void OnCheckCommandPermissions(SteamPlayer steamPlayer, string text, ref bool shouldExecuteCommand, ref bool shouldList)
        {
            if (!text.StartsWith("/"))
            {
                return;
            }

            shouldList           = false;
            shouldExecuteCommand = false;

            var args = ArgumentsParser.ParseArguments(text.Substring(1));

            if (args.Length == 0)
            {
                return;
            }

            AsyncHelper.Schedule("Player command execution", async() =>
            {
                var player = await m_UserManager.FindUserAsync(KnownActorTypes.Player, steamPlayer.playerID.steamID.ToString(), UserSearchMode.FindById);
                if (player == null)
                {
                    return;
                }

                await m_CommandExecutor.ExecuteAsync(player, args, string.Empty);
            });
        }
Пример #2
0
        public void ParseArgumentsRecusiveToTag()
        {
            ArgumentsParser  parser           = new ArgumentsParser();
            RenamerArguments renamerArguments = parser.ParseArguments(new string[] { "*.mp3", "-recursive", "-toTag" });

            Assert.AreEqual("*.mp3", renamerArguments.Mask);
            Assert.IsTrue(renamerArguments.IsRecursive);
            Assert.AreEqual(AllowedActions.ToTag, renamerArguments.Action);
        }
Пример #3
0
        public void ParseArgumentsToFileName()
        {
            ArgumentsParser  parser           = new ArgumentsParser();
            RenamerArguments renamerArguments = parser.ParseArguments(new string[] { "*.mp3", "-toFileName" });

            Assert.AreEqual("*.mp3", renamerArguments.Mask);
            Assert.IsFalse(renamerArguments.IsRecursive);
            Assert.AreEqual(AllowedActions.ToFileName, renamerArguments.Action);
        }
Пример #4
0
        private void OnCommandExecute(string commandline)
        {
            var args = ArgumentsParser.ParseArguments(commandline);

            if (args.Length == 0)
            {
                return;
            }

            AsyncHelper.RunSync(() => m_CommandExecutor.ExecuteAsync(m_ConsoleActorAccessor.Actor, args, string.Empty));
        }
Пример #5
0
        protected virtual async Task OnExecuteCommandAsync(string command)
        {
            if (!IsAuthenticated)
            {
                await SendMessageAsync("Login required.");

                return;
            }

            var args = ArgumentsParser.ParseArguments(command);
            await m_CommandExecutor.ExecuteAsync(this, args, string.Empty);
        }
Пример #6
0
        public void ParseArguments()
        {
            ArgumentsParser parser = new ArgumentsParser();

            string[] args = new string[] { "-timer", "-permitions", "-normal" };

            Arguments arguments = parser.ParseArguments(args);

            Assert.IsTrue(arguments.IsTimeMeasure);
            Assert.IsTrue(arguments.IsCheckPermitions);
            Assert.IsTrue(arguments.IsNormalExecution);
        }
Пример #7
0
        private void OnCommandWindowInputted(string text, ref bool shouldExecuteCommand)
        {
            shouldExecuteCommand = false;

            var actor = m_ConsoleActorAccessor.Actor;
            var args  = ArgumentsParser.ParseArguments(text);

            if (args.Length == 0)
            {
                return;
            }

            AsyncHelper.Schedule("Console command execution", () => m_CommandExecutor.ExecuteAsync(actor, args, string.Empty));
        }
Пример #8
0
        public static RenamerArguments GetArguments(string[] args, ILogger logger)
        {
            ArgumentsParser  parser           = new ArgumentsParser();
            RenamerArguments renamerArguments = null;

            try
            {
                renamerArguments = parser.ParseArguments(args);
            }
            catch (ArgumentException e)
            {
                logger.WriteMessage(e.Message, Status.Error);
                Console.WriteLine("Process failed! See log.txt for full information");
            }

            return(renamerArguments);
        }
Пример #9
0
        public Options(string[] args)
        {
            Dictionary <string, string> arguments = ArgumentsParser.ParseArguments(args, arg_indicator);

            if (arguments.ContainsKey(OptionName.H) || arguments.ContainsKey(OptionName.Help))
            {
                IsHelp = true;
                arguments.Remove(OptionName.H);
                arguments.Remove(OptionName.Help);
            }

            Default = new OptionDefault();
            Wallet  = new OptionWallet();

            ApplyArgument <OptionDefault, DefaultAttribute>(arguments);
            ApplyArgument <OptionWallet, WalletAttribute>(arguments);
            error = arguments;
        }
Пример #10
0
        public void Process(string[] args, MP3File[] files, Permitions userPermitions = Permitions.Guest)
        {
            if (files == null || files.Length == 0)
            {
                throw new ArgumentException("No files to process");
            }

            ArgumentsParser parser    = new ArgumentsParser();
            Arguments       arguments = parser.ParseArguments(args);

            foreach (var file in files)
            {
                string       message     = file.Path;
                IFileRenamer fileRenamer = new FileRenamer();

                if (arguments.IsCheckPermitions)
                {
                    IFileRenamer       oldFileRenamer = fileRenamer;
                    IPermitionsChecker checker        = new PermitionsChecker();
                    fileRenamer = new FileRenamerPermitionsChecker(oldFileRenamer, checker, userPermitions);
                }

                if (arguments.IsTimeMeasure)
                {
                    IFileRenamer oldFileRenamer = fileRenamer;
                    fileRenamer = new FileRenamerTimeMeasure(oldFileRenamer);
                }

                fileRenamer.Rename(file);

                message += " successfully renamed to " + file.Path;
                if (arguments.IsTimeMeasure)
                {
                    message += " in " + ((FileRenamerTimeMeasure)fileRenamer).ElapsedTime;
                }

                Console.WriteLine(message);
            }
        }
        protected override async Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer,
                                                             IWebSocketReceiveResult result)
        {
            _logger.LogDebug($"Received {buffer.Length} bytes.");
            _logger.LogDebug(System.Text.Encoding.UTF8.GetString(buffer));
            _logger.LogDebug(string.Join(" ", buffer.Select(d => d.ToString("X"))));

            if (buffer.Length < 1)
            {
                return;
            }

            var type = buffer[0];

            switch (type)
            {
            case PacketAuthenticate:
            {
                if (context.Items.ContainsKey("user"))
                {
                    return;
                }

                var token = System.Text.Encoding.UTF8.GetString(buffer, 1, buffer.Length - 1);
                if (string.IsNullOrEmpty(token))
                {
                    _logger.LogDebug($"Closing socket.Invalid token: {token}.");
                    await CloseAsync(context);

                    return;
                }

                var user = await _authenticationService.AuthenticateAsync(token);

                if (user == null)
                {
                    _logger.LogDebug("Closing socket. User could not authenticate.");
                    await CloseAsync(context);

                    return;
                }

                if (await _permissionChecker.CheckPermissionAsync(user, PermissionAccessConsole) !=
                    PermissionGrantResult.Grant)
                {
                    _logger.LogDebug("Closing socket. User does not have permission.");

                    var msg = SerializeMessage(PacketMessage, new LogMessageDto
                        {
                            Message = $"Missing \"OpenMod.WebServer:{PermissionAccessConsole}\" permission to access console."
                        });

                    await SendAsync(context, msg);
                    await CloseAsync(context);

                    return;
                }

                var canReadLogs = false;         // await _permissionChecker.CheckPermissionAsync(user, PermissionAccessLogs) == PermissionGrantResult.Grant;
                context.Items.Add("user", canReadLogs ? user : new WebConsoleUser(user, context, this));
                context.Items.Add("canReadLogs", canReadLogs);

                _logger.LogDebug($"User accepted: {user.FullActorName} (canReadLogs: {canReadLogs})");
                break;
            }

            case PacketMessage:
            {
                if (!context.Items.ContainsKey("user"))
                {
                    _logger.LogDebug("Closing socket. User not authenticated.");
                    await CloseAsync(context);

                    return;
                }

                var user    = (IUser)context.Items["user"];
                var message = System.Text.Encoding.UTF8.GetString(buffer, 1, buffer.Length - 1);
                var args    = ArgumentsParser.ParseArguments(message);

                await _commandExecutor.ExecuteAsync(user, args, string.Empty);

                break;
            }
            }
        }
Пример #12
0
        static void Main(string[] args)
        {
            OptionSet options = default(OptionSet);

            try
            {
                options = ArgumentsParser.ParseArguments <OptionSet>(args);
            }
            catch (ConsoleArgumentsParseException cexception)
            {
                Console.WriteLine(cexception.Message);
                return;
            }
            catch (Exception)
            {
                Console.WriteLine("Something wrong");
                return;
            }

            #region header
            Console.WriteLine("*********************************************************");
            Console.WriteLine("*\t\t\t\t\t\t\t*");
            Console.WriteLine("*\t\t\tMAKEDB  \t\t\t*");
            Console.WriteLine("*\t\tGENERATE DB SCHEMA APPLICATION \t\t*");
            Console.WriteLine("*\t\t\t\t\t\t\t*");
            Console.WriteLine("*\tAUTHOR DENIS KOZLOV ([email protected]) \t*");
            Console.WriteLine("*\t\t\t 2015\t\t\t\t*");
            Console.WriteLine("*\t\t\t\t\t\t\t*");
            Console.WriteLine("*********************************************************");
            Console.WriteLine("");
            #endregion

            Console.Write("Read mkdb file....");
            string mkdbContent = "";
            try
            {
                mkdbContent = new MkdbFileReader(options.SourcePath).ReadFileContent();
                Console.Write("done\r\n");
            }
            catch (ApplicationException ae)
            {
                Console.WriteLine(ae.Message);
                return;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Something wrong");
                return;
            }

            Console.Write("Create mkdb model....");
            Db model;
            try
            {
                model = MkdbParser.Parse(mkdbContent);
                Console.Write("done\r\n");
            }
            catch (InvalidMkdbFileStructureException e)
            {
                Console.WriteLine("Invalid file structure at line {0}", e.Line);
                return;
            }

            string scheme = string.Empty;

            Console.Write("Create MS SQL Server database scheme....");
            ISchemeCreator creator = default(ISchemeCreator);
            try
            {
                creator = SchemeCreatorFactory.CreateSchemeCreator(options.ServerType);
                scheme  = creator.GenerateScript(model);
                Console.Write("done\r\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            //try save file
            XmlDictionaryWriter writer = default(XmlDictionaryWriter);
            FileStream          fs     = default(FileStream);
            try
            {
                if (options.OutputPath == string.Empty)
                {
                    options.OutputPath = Environment.CurrentDirectory;
                }

                var fullpath     = Path.Combine(options.OutputPath, Path.ChangeExtension(model.Name, ".sql"));
                var jsonFullPath = Path.Combine(options.OutputPath, Path.ChangeExtension(Path.GetFileNameWithoutExtension(options.SourcePath), ".json"));
                if (!Directory.Exists(options.OutputPath))
                {
                    Directory.CreateDirectory(options.OutputPath);
                }

                if (options.Force && File.Exists(fullpath))
                {
                    File.Delete(fullpath);
                    File.WriteAllText(fullpath, scheme);
                    Console.WriteLine("Saved sql script to '{0}'", fullpath);
                }
                else if ((!options.Force) && File.Exists(fullpath))
                {
                }
                else
                {
                    File.WriteAllText(fullpath, scheme);
                    Console.WriteLine("Saved sql script to '{0}'", fullpath);
                }


                //fs = new FileStream(jsonFullPath,
                //    FileMode.Create);
                //writer = JsonReaderWriterFactory.CreateJsonWriter(fs);
                //DataContractJsonSerializer serializator = new DataContractJsonSerializer(typeof(Db));
                //serializator.WriteObject(writer, model);

                var jsonSerializer = new JsonSerializer
                {
                    NullValueHandling     = NullValueHandling.Ignore,
                    MissingMemberHandling = MissingMemberHandling.Ignore,
                    ReferenceLoopHandling = ReferenceLoopHandling.Serialize
                };

                var sb = new StringBuilder();
                using (var sw = new StringWriter(sb))
                    using (var jtw = new JsonTextWriter(sw))
                        jsonSerializer.Serialize(jtw, model);

                var result = sb.ToString();
                File.WriteAllText(jsonFullPath, result);
                Console.WriteLine("Saved mkdb model to '{0}'", jsonFullPath);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
            if (options.GenerateDb && !string.IsNullOrEmpty(options.ConnectionString) && !string.IsNullOrEmpty(scheme) && creator != null)
            {
                Console.Write("Generating database '{0}'....", model.Name);
                try
                {
                    creator.GenerateDatabase(options.ConnectionString, scheme);
                    Console.Write("done\r\n");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }

            Console.WriteLine("Completed");
        }
Пример #13
0
        static void Main(string[] args)
        {
            OptionSet options = default(OptionSet);

            try
            {
                options = ArgumentsParser.ParseArguments <OptionSet>(args);
            }
            catch (ConsoleArgumentsParseException cexception)
            {
                Console.WriteLine(cexception.Message);
                return;
            }
            catch (Exception)
            {
                Console.WriteLine("Something wrong");
                return;
            }

            if (string.IsNullOrEmpty(options.ConnectionString) && string.IsNullOrEmpty(options.ModelPath))
            {
                Console.WriteLine("Model path or server type and connection string must be passed");
                return;
            }

            #region header
            Console.WriteLine("*********************************************************");
            Console.WriteLine("*\t\t\t\t\t\t\t*");
            Console.WriteLine("*\t\t\tMAKEDOMAIN  \t\t\t*");
            Console.WriteLine("*\t\tGENERATE DOMAIN MODEL CLASSES \t\t*");
            Console.WriteLine("*\t\t\t\t\t\t\t*");
            Console.WriteLine("*\tAUTHOR DENIS KOZLOV ([email protected]) \t*");
            Console.WriteLine("*\t\t\t 2015\t\t\t\t*");
            Console.WriteLine("*\t\t\t\t\t\t\t*");
            Console.WriteLine("*********************************************************");
            Console.WriteLine("");
            #endregion

            Db model = default(Db);

            if (!string.IsNullOrEmpty(options.ModelPath))
            {
                if (!File.Exists(options.ModelPath))
                {
                    Console.WriteLine("Model file '" + options.ModelPath + "' not exist");
                    return;
                }
                Console.Write("Read mkdb model file....");
                try
                {
                    JsonSerializer serializer = new JsonSerializer();
                    using (StreamReader sm = File.OpenText(options.ModelPath))
                    {
                        using (JsonTextReader reader = new JsonTextReader(sm))
                        {
                            model = serializer.Deserialize <Db>(reader);
                        }
                    }
                    Console.Write("done\r\n");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }
            else
            {
                //TODO: implement later...
            }

            var            basePath  = options.OutputPath;
            ICodeGenerator generator = CodeGeneratorFactory.GetCodeGenerator(options.LanguageType);
            if (generator != null)
            {
                try
                {
                    foreach (var table in model.Tables)
                    {
                        string filePath = string.Empty;

                        var tableNameStings = table.Name.Split('.');
                        if (tableNameStings.Length > 1)
                        {
                            string directory = basePath;
                            for (int i = 0; i < tableNameStings.Length - 1; i++)
                            {
                                directory = Path.Combine(directory, tableNameStings[i]);
                            }
                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }

                            var fileName = tableNameStings[tableNameStings.Length - 1];
                            if (fileName.ToLower().EndsWith("ses"))
                            {
                                fileName = fileName.Remove(fileName.Length - 2);
                            }
                            else if (fileName.ToLower().EndsWith("ies"))
                            {
                                fileName = fileName.Remove(fileName.Length - 3);
                                fileName = fileName + "y";
                            }
                            else if (fileName.ToLower().EndsWith("s"))
                            {
                                fileName = fileName.Remove(fileName.Length - 1);
                            }

                            filePath = Path.Combine(directory, Path.ChangeExtension(fileName, ("." + generator.GetExtension())));
                        }
                        else
                        {
                            var fileName = table.Name;
                            if (fileName.ToLower().EndsWith("s"))
                            {
                                fileName = fileName.Remove(fileName.Length - 1);
                            }

                            filePath = Path.Combine(basePath, Path.ChangeExtension(fileName, ("." + generator.GetExtension())));
                        }

                        string rootNamespace = Path.GetFileNameWithoutExtension(options.ModelPath) + ".domains";


                        if (File.Exists(filePath) && options.Force)
                        {
                            string safedCode  = generator.GetSafedCode(File.ReadAllText(filePath));
                            var    codeString = generator.GenerateClass(table, rootNamespace, model, safedCode);
                            File.WriteAllText(filePath, codeString);
                            Console.WriteLine("Saved domain class to '{0}'", filePath);
                        }
                        else
                        {
                            var codeString = generator.GenerateClass(table, rootNamespace, model);
                            File.WriteAllText(filePath, codeString);
                            Console.WriteLine("Saved domain class to '{0}'", filePath);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            else
            {
                throw new ApplicationException("Unknown language generator");
            }
            Console.WriteLine("Completed");
        }
Пример #14
0
        public void ParseUnknownArguments()
        {
            ArgumentsParser parser = new ArgumentsParser();

            parser.ParseArguments(new string[] { "-fake" });
        }
Пример #15
0
 private void OnCommandExecute(string commandline)
 {
     AsyncHelper.RunSync(() => m_CommandExecutor.ExecuteAsync(m_ConsoleActorAccessor.Actor, ArgumentsParser.ParseArguments(commandline), string.Empty));
 }
Пример #16
0
        public void ParseNullArguments()
        {
            ArgumentsParser parser = new ArgumentsParser();

            parser.ParseArguments(null);
        }
Пример #17
0
 public void ParseWithNoArguments()
 {
     ArgumentsParser  parser           = new ArgumentsParser();
     RenamerArguments renamerArguments = parser.ParseArguments(new string[] { });
 }
Пример #18
0
 public void ParseWithLessArguments()
 {
     ArgumentsParser  parser           = new ArgumentsParser();
     RenamerArguments renamerArguments = parser.ParseArguments(new string[] { "*.mp3" });
 }
Пример #19
0
 public void ParseWithMoreArguments()
 {
     ArgumentsParser  parser           = new ArgumentsParser();
     RenamerArguments renamerArguments = parser.ParseArguments(new string[] { "*.mp3", "-recursive", "-toFileName", "-toTag" });
 }
Пример #20
0
        private void OnCommandWindowInputted(string text, ref bool shouldExecuteCommand)
        {
            shouldExecuteCommand = false;

            text = text.Trim();
            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            var actor = m_ConsoleActorAccessor.Actor;

            AsyncHelper.Schedule("Console command execution", () => m_CommandExecutor.ExecuteAsync(actor, ArgumentsParser.ParseArguments(text), string.Empty));
        }