예제 #1
0
        public void CD_GetValueFromEnum_valueOK()
        {
            var cd      = new CommandDictionary();
            var command = cd.AsNcString(MachineCommandType.JET_ON);

            StringAssert.Contains("JETON_Mcode", command);
        }
예제 #2
0
        private void tooltipTimer_Tick(object sender, EventArgs e)
        {
            tooltipTimer.Stop();

            int yIndex = lastMouseCoords.Y.RoundDown(CharHeight) / CharHeight;

            if (yIndex >= Lines.Count | yIndex >= _list.Count)
            {
                return;
            }
            if (iCharFromPoint(lastMouseCoords) >= Lines[yIndex].Length)
            {
                return;
            }

            string str = TokenFromPoint(lastMouseCoords).Text.TrimStart();

            if (!String.IsNullOrEmpty(str))
            {
                ACMD_CMD_INFO cmi;
                if ((cmi = CommandDictionary.FirstOrDefault(x => x.Name.StartsWith(str))) != null)
                {
                    if (cmi.EventDescription == "NONE")
                    {
                        return;
                    }

                    toolTip.ToolTipTitle       = cmi.Name;
                    toolTip.ToolTipDescription = cmi.EventDescription;
                    toolTip.Show(cmi.Name, this, lastMouseCoords, 5000);
                }
            }
        }
        /// <summary>
        /// Prompt for the data necessary to create the console commander,
        /// create it and run it
        /// </summary>
        public void Run()
        {
            Console.WriteLine($"Tello Commander {DroneCommander.Version}");

            string version = PromptForDictionaryVersion();

            if (!string.IsNullOrEmpty(version))
            {
                ConnectionType connectionType = PromptForConnectionType();
                if (connectionType != ConnectionType.None)
                {
                    CommandDictionary dictionary = CommandDictionary.ReadStandardDictionary(version);
                    switch (connectionType)
                    {
                    case ConnectionType.Mock:
                        ITelloConnection mockConnection = new MockTelloConnection(dictionary);
                        new ConsoleCommander(mockConnection, dictionary).Run(false);
                        break;

                    case ConnectionType.Simulator:
                        ITelloConnection connection = new TelloConnection(IPAddress.Loopback.ToString(), TelloConnection.DefaultTelloPort, connectionType);
                        new ConsoleCommander(connection, dictionary).Run(true);
                        break;

                    case ConnectionType.Drone:
                        new ConsoleCommander(new TelloConnection(), dictionary).Run(true);
                        break;

                    default:
                        break;
                    }
                }
            }
        }
예제 #4
0
        private void Command(ref HookContext ctx, ref TDSMHookArgs.ServerCommand args)
        {
            if (args.Prefix == "!")
            {
                return;
            }

            //Perhaps here we can use the player's PluginData, and simply store a string for the console
            if (ctx.Sender is Player)
            {
                if (CommandDictionary.ContainsKey(ctx.Player.name))
                {
                    CommandDictionary[ctx.Player.name] = "/" + args.Prefix + " " + args.ArgumentString;
                }
                else
                {
                    CommandDictionary.Add(ctx.Player.name, "/" + args.Prefix + " " + args.ArgumentString);
                }
            }
            else if (ctx.Sender is ConsoleSender)
            {
                if (CommandDictionary.ContainsKey("CONSOLE"))
                {
                    CommandDictionary["CONSOLE"] = args.Prefix + " " + args.ArgumentString;
                }
                else
                {
                    CommandDictionary.Add("CONSOLE", args.Prefix + " " + args.ArgumentString);
                }
            }
        }
예제 #5
0
        void OnPlayerDisconnected(ref HookContext ctx, ref HookArgs.PlayerLeftGame args)
        {
            if (Terraria.Main.ServerSideCharacter)
            {
#if ENTITY_FRAMEWORK_7
                using (var dbCtx = new TContext())
#elif DAPPER
                using (var dbCtx = DatabaseFactory.CreateConnection())
#endif
                {
                    using (var txn = dbCtx.BeginTransaction())
                    {
                        CharacterManager.SavePlayerData(dbCtx, txn, true, ctx.Player);
                        txn.Commit();
                    }
                }
            }
            if (ctx.Player != null)
            {
                if (CommandDictionary.ContainsKey(ctx.Player.name))
                {
                    CommandDictionary.Remove(ctx.Player.name);
                }
                //ProgramLog.Log("{0}", ctx.Player.name); //, args.Prefix + " " + args.ArgumentString);
            }
#if TDSMServer
            if (RestartWhenNoPlayers && ClientConnection.All.Count - 1 == 0)
            {
                PerformRestart();
            }
#endif
        }
예제 #6
0
        public void Update()
        {
            currentPressedKeys = Keyboard.GetState().GetPressedKeys();
            newPressedKeys     = currentPressedKeys.Except(prevPressedKeys).ToArray();

            Keys toExecute = prev;

            if (currentPressedKeys.Length == 0)
            {
                toExecute = Keys.None;
            }
            else if (newPressedKeys.Length > 0)
            {
                toExecute = newPressedKeys[0];
            }

            if (toExecute != prev && CommandDictionary.ContainsKey(toExecute))
            {
                CommandDictionary[toExecute].Execute();
            }

            NewPressedKey = Keys.None;
            if (toExecute != prev)
            {
                NewPressedKey = toExecute;
            }

            prev            = toExecute;
            prevPressedKeys = currentPressedKeys;
        }
예제 #7
0
 public void UpdateCommand(Keys key, ICommand commandClass)
 {
     if (CommandDictionary.ContainsKey(key))
     {
         CommandDictionary[key] = commandClass;
     }
 }
예제 #8
0
        public void RegisterCommand()
        {
            CommandDictionary.Add(Keys.Q, new ExitCommand());
            CommandDictionary.Add(Keys.R, new ResetCommand());

            CommandDictionary.Add(Keys.None, new SetIdleCommand());

            CommandDictionary.Add(Keys.Up, new MoveUpCommand());
            CommandDictionary.Add(Keys.Down, new MoveDownCommand());
            CommandDictionary.Add(Keys.Left, new MoveLeftCommand());
            CommandDictionary.Add(Keys.Right, new MoveRightCommand());

            CommandDictionary.Add(Keys.W, new MoveUpCommand());
            CommandDictionary.Add(Keys.S, new MoveDownCommand());
            CommandDictionary.Add(Keys.A, new MoveLeftCommand());
            CommandDictionary.Add(Keys.D, new MoveRightCommand());

            CommandDictionary.Add(Keys.Z, new UseSecondaryItemCommand());

            CommandDictionary.Add(Keys.X, new AttackCommand());
            CommandDictionary.Add(Keys.N, new AttackCommand());

            CommandDictionary.Add(Keys.Enter, new PauseCommand());
            CommandDictionary.Add(Keys.C, new SelectItemForwardCommand());

            CommandDictionary.Add(Keys.M, new MusicVolumeCommand());
            CommandDictionary.Add(Keys.PageUp, new MusicVolumeCommand());
            CommandDictionary.Add(Keys.PageDown, new MusicVolumeCommand());

            CommandDictionary.Add(Keys.P, new OpenSettingsFromPausedCommand());
            CommandDictionary.Add(Keys.Space, new SettingsSelectCommand());
            CommandDictionary.Add(Keys.Tab, new SettingsCycleOptionCommand());
            CommandDictionary.Add(Keys.B, new GoBackCommand());
            CommandDictionary.Add(Keys.F, new OpenScoreboardCommand());
        }
예제 #9
0
        /// <summary>
        /// Adds a nested command (or verb, if you will) to this command manager.
        /// </summary>
        /// <param name="verb"></param>
        /// <returns>The <see cref="CompiledCommandManager" /> created for the verb</returns>
        public override CompiledCommandManager AddVerb(string verb)
        {
            if (string.IsNullOrWhiteSpace(verb))
            {
                throw new ArgumentException("Verb cannot be null, empty or contain any whitespaces.", nameof(verb));
            }
            if (verb.Any(char.IsWhiteSpace))
            {
                throw new ArgumentException("Verb cannot have whitespaces.", nameof(verb));
            }
            if (CommandDictionary.ContainsKey(verb))
            {
                throw new InvalidOperationException("A command with this name already exists.");
            }

            // Verb creation
            var verbCommandManager = new ConsoleCommandManager();
            var verbInst           = new Verb(verbCommandManager);

            // Command registering
            var command = new VerbCompiledCommand(
                verbCommandManager,
                typeof(Verb).GetMethod(nameof(Verb.RunCommand), BindingFlags.Instance | BindingFlags.Public),
                verbInst,
                new[] { verb },
                isRaw: true
                );

            CommandList.Add(command);
            CommandLookupTable[verb] = command;

            return(verbInst.Manager);
        }
예제 #10
0
        void ProcessGlobal(string statement, int lineNumber, ref string chunkName)
        {
            if (cmdRegexp.IsMatch(statement))
            {
                // コマンド
                var m     = cmdRegexp.Match(statement);
                var key   = m.Groups[1].Value.ToLower();
                var value = m.Groups[2].Value;

                if (commands.ContainsKey(key))
                {
                    commands[key](value, lineNumber);
                }
                else
                {
                    throw new ChartErrorException($"ヘッダー {key} は存在しません.", lineNumber);
                }
            }
            else if (statement.TrimEnd().All(c => char.IsLetterOrDigit(c) || c == '_' || c == '-'))
            {
                chunkName = statement.TrimEnd().ToLower();
            }
            else
            {
                throw new ChartErrorException("構文エラーです", lineNumber);
            }
        }
예제 #11
0
        public void CD_GetValueFromStr_ValueOK()
        {
            var cd      = new CommandDictionary();
            var command = cd.AsNcString("JET_ON");

            StringAssert.Contains("JETON_Mcode", command);
        }
예제 #12
0
 public Server()
 {
     this.commandDictionary        = new CommandDictionary();
     this.remoteClients            = new List <RemoteClients>();
     this.numberOfconnectedClients = 0;
     this.mainThreadMessageQueue   = new Queue <string>();
     this.isInProgress             = true;
 }
예제 #13
0
        public void CD_Getbadstring_UnknownCommand()
        {
            var    cd      = new CommandDictionary();
            string p       = "probe";
            var    command = cd.AsNcString(p);

            StringAssert.Contains(command, p + "_UnknownCommand");
        }
예제 #14
0
    public Client(ClientSceneManager sceneManager)
    {
        this.commandDictionary      = new CommandDictionary();
        this.remoteClients          = new List <RemoteClients>();
        this.mainThreadMessageQueue = new Queue <string>();

        this.sceneManager = sceneManager;
        networkInst       = sceneManager.GetComponent <NetworkInstantiate>();
    }
예제 #15
0
 public CreateTagsCommand(List <string> resourceIds, Dictionary <string, string> tags, string resourceType)
 {
     // Currently support one tag at a time for one resource
     CommandDictionary.Add(CommandKey, "createTags");
     CommandDictionary.Add(ResourceIdsKey, resourceIds.FirstOrDefault());
     CommandDictionary.Add(ResourceTypeKey, resourceType);
     CommandDictionary.Add(TagsKey, tags.Keys.FirstOrDefault());
     CommandDictionary.Add(TagsValue, tags.Values.FirstOrDefault());
     CommandDictionary.Add(ApiKey, ConfigurationHelper.GetApiKey());
 }
예제 #16
0
 public Controller()/// sort the constructors.
 {
     commandsDictionary = new Dictionary <string, ICommand>();
     commandsDictionary.Add("generate", new GenerateSinglePlayerMazeCommand(imodel));
     commandsDictionary.Add("solve", new SolveMazeCommand(imodel));
     commandsDictionary.Add("start", new StartCommand(imodel));
     commandsDictionary.Add("join", new JoinMazeCommand(imodel));
     commandsDictionary.Add("list", new ListJoinableMazesNamesCommand(imodel));
     CommandDictionary.Add("play", new PlayCommand(imodel));
     CommandDictionary.Add("close", new CloseCommand(imodel));
 }
예제 #17
0
        public bool TrySwitchKey(Keys oldKey, Keys newKey)
        {
            bool canChange = oldKey != prev && CommandDictionary.ContainsKey(oldKey) && !CommandDictionary.ContainsKey(newKey);

            if (canChange)
            {
                ICommand command = CommandDictionary[oldKey];
                CommandDictionary.Remove(oldKey);
                CommandDictionary.Add(newKey, command);
            }
            return(canChange);
        }
예제 #18
0
        public TwitchBot(string username, string oAuth)
        {
            irc = new IRCUtil("irc.twitch.tv", 6667, username, oAuth);
            this.botUsername               = username;
            channels                       = new Dictionary <string, CommandDictionary>();
            Live                           = true;
            globalCommands                 = new CommandDictionary("#GLOBAL#", irc);
            globalCommands["shutdown"]     = new ShutdownCommand(this);
            globalCommands["leaveChannel"] = new LeaveChannelCommand(this, Level.LEVEL_MODERATOR);
            botUsername                    = username;

            this._logger = LogManager.GetCurrentClassLogger();
        }
예제 #19
0
 private void Autocomplete_OnKeyUp(object sender, KeyEventArgs e)
 {
     if (e.KeyCode == Keys.Enter | e.KeyCode == Keys.Space)
     {
         string      commandName = ((ListBox)sender).SelectedItem.ToString();
         CommandInfo info        = CommandDictionary.Find(x => x.Name.Equals(commandName, StringComparison.InvariantCultureIgnoreCase));
         int         curIndex    = GetFirstCharIndexFromLine(CurrentLineIndex) + curIndent;
         string      TempStr     = Text.Remove(curIndex, Lines[CurrentLineIndex].Length);
         Text           = TempStr.Insert(curIndex, commandName + String.Format("({0})", FomatParams(commandName)));
         SelectionStart = curIndex + CurrentLineText.Length;
         AutocompleteBox.Hide();
     }
 }
 public static void AddOptions <TValue>(this CommandDictionary <TValue> dictionary, string command, params TValue[] options)
 {
     if (dictionary.ContainsKey(command) && dictionary[command] != null)
     {
         foreach (var option in options)
         {
             dictionary[command].Add(option);
         }
     }
     else
     {
         dictionary[command] = new List <TValue>(options);
     }
 }
예제 #21
0
        /// <summary>
        /// Initializes a new instance of the WorldConfig class with the world configuration file path specified.
        /// </summary>
        /// <param name="filePath">The path to the world configuration file.</param>
        public WorldConfig(string filePath)
        {
            this.Skills   = new SkillDictionary();
            this.Commands = new CommandDictionary();

            if (!String.IsNullOrEmpty(filePath))
            {
                if (File.Exists(filePath))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(filePath);

                    if (doc.HasChildNodes)
                    {
                        this.EnableMagic       = Convert.ToBoolean(doc.DocumentElement.Attributes["enableMagic"].Value);
                        this.EnablePsionics    = Convert.ToBoolean(doc.DocumentElement.Attributes["enablePsionics"].Value);
                        this.RealismMultiplier = Convert.ToInt32(doc.DocumentElement.Attributes["realismMultiplier"].Value);
                        this.PowerMultiplier   = Convert.ToInt32(doc.DocumentElement.Attributes["powerMultiplier"].Value);
                        this.Name = doc.DocumentElement.Attributes["name"].Value;
                        this.Type = doc.DocumentElement.Attributes["type"].Value;

                        // Skills
                        XmlNodeList skills = doc.DocumentElement.SelectNodes("skills/add");
                        for (int i = 0; i < skills.Count; i++)
                        {
                            this.Skills.Add(skills[i].Attributes["name"].Value, skills[i].InnerText);
                        }

                        // Commands
                        XmlNodeList commands = doc.DocumentElement.SelectNodes("commands/add");
                        for (int i = 0; i < commands.Count; i++)
                        {
                            Command cmd = Activator.CreateInstance(System.Type.GetType(commands[i].Attributes["type"].Value)) as Command;
                            if (cmd != null)
                            {
                                this.Commands.Add(commands[i].Attributes["name"].Value, cmd);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Prompt for and return the API (dictionary) version to use
        /// </summary>
        /// <returns></returns>
        private string PromptForDictionaryVersion()
        {
            string[] versions = CommandDictionary.GetAvailableDictionaryVersions();
            string   version  = null;

            if (versions.Length == 1)
            {
                version = versions[0];
                Console.WriteLine($"Using dictionary version {version}");
            }
            else
            {
                int selection = PromptForOption("Dictionary Version:", versions);
                if (selection > 0)
                {
                    version = versions[selection - 1];
                }
            }

            return(version);
        }
        public void CreateDefaultSettings()
        {
            WriteLog = false;
            SerialPort = new SerialPortSettings();
            Commands = new CommandDictionary();

            SerialPort defaultConfig = new SerialPort();

            defaultConfig.Encoding = Encoding.ASCII;

            var portNames = System.IO.Ports.SerialPort.GetPortNames();
            if (portNames.Count() == 0)
                throw new Exception("No ports found");

            SerialPort.PortName = portNames[0];
            SerialPort.BaudRate = (BaudRate)defaultConfig.BaudRate;
            SerialPort.Parity = defaultConfig.Parity;
            SerialPort.DataBits = defaultConfig.DataBits;
            SerialPort.StopBits = defaultConfig.StopBits;
            SerialPort.Handshake = defaultConfig.Handshake;
        }
        public static bool CommandRoutine(NetworkMessage message)
        {
            //a command request sent to server
            System.Diagnostics.Debug.Assert(Server.Instance != null, "[MessageProcessing] - CommandRoutine called on client. (Talk to Alex)");

            NetworkMessage result = new NetworkMessage();

            result.Type     = MessageType.Result;
            result.Username = message.Username;

            /*
             * Some logic to wait for DM permission
             */

            bool control = true;

            if (control == true) //command is allowed
            {
                DictionaryType type    = CommandDictionary.StringToDictionaryType(message.Context);
                Command        command = CommandDictionary.Instance.CommandExecute(message.Message, type);

                if (command != null)
                {
                    result.Context = command.result;
                    result.Message = command.ToString();
                }
                else
                {
                    result.Context = "Failed";
                    result.Message = "Command failed";
                }
            }
            else //command is denied
            {
                result.Context = "Denied";
                result.Message = "DM denied your command.";
            }

            return(false);
        }
예제 #25
0
 public ListVolumesCommand(string virtualMachineId)
 {
     CommandDictionary.Add(CommandKey, "listVolumes");
     CommandDictionary.Add(VirtualMachineIdKey, virtualMachineId);
     CommandDictionary.Add(ApiKey, ConfigurationHelper.GetApiKey());
 }
예제 #26
0
        public static void WritePropertyIfSpecified(this IConsole console, string propertyName, CommandDictionary propertyValue, int indentCount = 2)
        {
            if (propertyValue?.Count > 0)
            {
                StringBuilder builder = new StringBuilder();

                builder.AppendLine("[");

                foreach (var(option, index) in propertyValue.WithIndex())
                {
                    builder.Append(Indent(indentCount + 1))
                    .Append("[")
                    .Append(option.Key)
                    .Append(", [")
                    .AppendJoin(", ", option.Value.Select(v => '"' + v + '"'))
                    .Append("]]");

                    if (index != propertyValue.Count - 1)
                    {
                        builder.AppendLine(",");
                    }
                    else
                    {
                        builder.AppendLine("");
                    }
                }

                builder.Append(Indent(indentCount))
                .Append("]");

                WritePropertyIfSpecified(console, propertyName, builder.ToString(), indentCount);
            }
        }
예제 #27
0
 public void SendVoiceCommand(CommandDictionary command)
 {
     HubProxy.Invoke("sendCommand", (int)command, _roomId);
 }
        public void Load()
        {
            SerialPort = new SerialPortSettings();
            Commands = new CommandDictionary();
            if (SettingsFileExists)
            {
                XElement spcElement = XDocument.Load(_xmlFilePath).Element("SerialPortControl");
                XElement settingsElement = spcElement.Element("Settings");
                XElement serialPortElement = settingsElement.Element("SerialPort");
                var commandElements = spcElement.Element("Commands").Elements("Command");

                WriteLog = (bool)settingsElement.Element("WriteLog");
                Listening = (bool)settingsElement.Element("Listening");

                SerialPort.PortName = serialPortElement.Element("PortName").Value;
                SerialPort.BaudRate = (BaudRate)Convert.ToInt32(serialPortElement.Element("BaudRate").Value);
                SerialPort.Parity = serialPortElement.Element("Parity").ToEnumValue<Parity>();
                SerialPort.DataBits = Convert.ToInt32(serialPortElement.Element("DataBits").Value);
                SerialPort.StopBits = serialPortElement.Element("StopBits").ToEnumValue<StopBits>();
                SerialPort.Handshake = serialPortElement.Element("Handshake").ToEnumValue<Handshake>();

                foreach (var element in commandElements)
                {
                    Command command = new Command
                    {
                        IncomingCommand = element.Element("IncomingCommand").Value,
                        Target = element.Element("Target").Value,
                        Arguments = element.Element("Arguments").Value,
                        StartInDirectory = element.Element("StartInDirectory").Value
                    };
                    Commands.Add(command.IncomingCommand, command);
                }
            }
        }
 static void Main(string[] args)
 {
     CommandDictionary supportedCommands = new CommandDictionary();
     Parser parser = new Parser(supportedCommands);
     parser.Run(args);
 }
예제 #30
0
        //static readonly ILog _log = LogManager.GetLogger(typeof(Commands));
        //if (_log.IsDebugEnabled) { _log.DebugFormat("Starting {0}", MethodBase.GetCurrentMethod().ToString()); }
        //if (_log.IsDebugEnabled) { _log.DebugFormat("Ending {0}", MethodBase.GetCurrentMethod().ToString()); }

        //Load from mission-file-docs.txt
        void LoadMissionDoc()
        {
            //First load special critical COMMANDS, then load from file.

            //LoadCreate();
            //12/30/2012
            string           txt     = Properties.Resources.mission_file_docs;
            bool             started = false;
            CommandElement   currentActiveCommand   = null;
            AttributeElement currentActiveAttribute = null;

            foreach (string ll in txt.Split('\n'))
            {
                string sline = ll.Replace("\t", string.Empty).Replace("\r", string.Empty).Trim();

                if (!started)
                {
                    if (sline.StartsWith("COMMAND", StringComparison.OrdinalIgnoreCase))
                    {
                        started = true;
                    }
                }

                if (started)
                {
                    switch (DetermineLineType(sline))
                    {
                    case LineType.Command:
                    case LineType.Condition:
                        KeyValuePair <string, string> cmd = GetCommandData(sline);
                        currentActiveCommand = new CommandElement(cmd.Key, cmd.Value);
                        if (!CommandDictionary.ContainsKey(cmd.Key))
                        {
                            CommandDictionary.Add(cmd.Key, currentActiveCommand);
                        }
                        else
                        {
                            currentActiveCommand = CommandDictionary[cmd.Key];
                        }
                        break;

                    case LineType.Attribute:
                        if (currentActiveCommand != null)
                        {
                            bool foundAttrib = false;
                            currentActiveAttribute = new AttributeElement(GetAttributeData(sline));
                            currentActiveAttribute.ParentCommand = currentActiveCommand.Text;
                            foreach (AttributeElement att in currentActiveCommand.Attributes)
                            {
                                if (att.Text == currentActiveAttribute.Text)
                                {
                                    foundAttrib            = true;
                                    currentActiveAttribute = att;
                                    break;
                                }
                            }
                            if (!foundAttrib)
                            {
                                currentActiveCommand.Attributes.Add(currentActiveAttribute);
                            }
                        }
                        break;

                    case LineType.ValueList:
                        ProcessValue(sline, currentActiveAttribute);

                        break;
                    }
                }
            }
        }
 public QueryAsyncJobResultCommand(string jobId)
 {
     CommandDictionary.Add(CommandKey, "queryAsyncJobResult");
     CommandDictionary.Add(JobIdKey, jobId);
     CommandDictionary.Add(ApiKey, ConfigurationHelper.GetApiKey());
 }
 public ListVirtualMachinesCommand()
 {
     CommandDictionary.Add(CommandKey, "listVirtualMachines");
     CommandDictionary.Add(ApiKey, ConfigurationHelper.GetApiKey());
 }
예제 #33
0
 public ListSnapshotCommand(string volumeId)
 {
     CommandDictionary.Add(CommandKey, "listSnapshots");
     CommandDictionary.Add(VolumeKey, volumeId);
     CommandDictionary.Add(ApiKey, ConfigurationHelper.GetApiKey());
 }
예제 #34
0
        static void Main(string[] args)
        {
            bool.TryParse(ConfigurationManager.AppSettings.Get("debug").Trim(), out bool debug);
            //try
            //{
            if (args.Any() || debug)
            {
                for (int a = 0; a < (args.Any() ? args.Count():1); a++)
                {
                    string   date = "", tender = "";
                    string   _SEPARATOR         = "|";
                    string   _COMMAND_SEPARATOR = ";";
                    string[] activeCommands     = ConfigurationManager.AppSettings.Get("commandList").Trim().Split(new string[] { _COMMAND_SEPARATOR }, StringSplitOptions.RemoveEmptyEntries);
                    string   timeValidator      = "(?<=:|\\s|^)(\\d{1,2}:){2}\\d{1,2}.\\d{1,3}";
                    string   ipValid            = "([0-9]{1,3}.){3}[0-9]{1,3}";

                    StreamReader sr;
                    List <Dictionary <string, string> > listDictForFile = new List <Dictionary <string, string> >();
                    string fileName = string.Format("{0}\\{1}", Environment.CurrentDirectory, "test2.txt");

#if DEBUG
                    sr       = new StreamReader(fileName);
                    fileName = fileName.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last().Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries).First();
#else
                    sr       = new StreamReader(args[a]);
                    fileName = args[a].Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last().Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries).First();
#endif

                    List <string> lineList = new List <string>();
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine().Trim();
                        if (line.Length > 1)
                        {
                            lineList.Add(line);
                        }
                    }
                    sr.Close();

                    for (int i = 0; i < lineList.Count; i++)
                    {
                        string ip          = "",
                               command     = "",
                               commandName = "";
                        //List<string> filesName = new List<string>();
                        Dictionary <DateTime, string> filesWithTime = new Dictionary <DateTime, string>();
                        DateTime time = DateTime.Now;
                        Dictionary <string, string> dictForFile = new Dictionary <string, string>();

                        bool add = false;

                        CommandDictionary <string, DateTime, DateTime, string> commandDictionary = new CommandDictionary <string, DateTime, DateTime, string>();

                        var      t    = lineList[i];
                        string[] temp = t.Split(new string[] { _SEPARATOR }, StringSplitOptions.RemoveEmptyEntries);
                        if (temp.Length == 1)
                        {
                            DateTime tDate;
                            if (DateTime.TryParse(temp[0].Trim(), out tDate))
                            {
                                date = tDate.ToLongDateString();
                            }
                        }
                        else
                        {
                            var u = Regex.Match(temp[0], timeValidator);
                            if (u.Success)
                            {
                                DateTime.TryParse(u.Value, out time);
                            }

                            if (temp[1].Trim().Equals("In"))
                            {
                                //string ipValid = "([0-9]{1,3}.){3}[0-9]{1,3}";
                                ip = Regex.Match(temp[2].Trim(), ipValid).Value;
                                if (temp.Count() >= 4)
                                {
                                    command = temp[3].Trim().Replace("CommandName:", "").Trim();
                                    if (activeCommands.Any(y => y.Equals(command)))
                                    {
                                        commandName = ConfigurationManager.AppSettings.Get(command).Trim();
                                        if (command.Equals("Upload"))
                                        {
                                            //filesName = new List<string>();
                                            filesWithTime = new Dictionary <DateTime, string>();
                                            for (int ii = 1; ii < lineList.Count; ii++)
                                            {
                                                try
                                                {
                                                    var temp2 = lineList[i + ii].Split(new string[] { _SEPARATOR }, StringSplitOptions.RemoveEmptyEntries);
                                                    if (temp2[1].Trim().Equals("Out"))
                                                    {
                                                        ii = lineList.Count;
                                                    }
                                                    else if (temp2[1].Trim().Equals("info") && temp2.Length > 2)
                                                    {
                                                        add = true;
                                                        //filesWithTime.Add(DateTime.Parse(temp2[0].Remove(temp2[0].IndexOf("->")).Trim()), temp2[2]);
                                                        filesWithTime.Add(DateTime.Parse(Regex.Match(temp2[0], timeValidator).Value), temp2[2]);
                                                    }
                                                }
                                                catch (Exception ex)
                                                { };
                                            }
                                            //string fN = string.Join(",", filesName.ToArray());
                                            commandName = ConfigurationManager.AppSettings.Get("Upload").Trim();
                                        }
                                        else if (command.Equals("LocalDownload"))
                                        {
                                            //filesName = new List<string>();
                                            filesWithTime = new Dictionary <DateTime, string>();
                                            for (int ii = 1; ii < lineList.Count; ii++)
                                            {
                                                try
                                                {
                                                    var temp2 = lineList[i + ii].Split(new string[] { _SEPARATOR }, StringSplitOptions.RemoveEmptyEntries);
                                                    if (temp2[1].Trim().Equals("Out"))
                                                    {
                                                        ii = lineList.Count;
                                                    }
                                                    else if (temp2[1].Trim().Equals("OK"))
                                                    {
                                                        add = true;
                                                        //filesName.Add(temp2[2].Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last());
                                                        filesWithTime.Add(DateTime.Parse(temp2[0].Remove(temp2[0].IndexOf("->")).Trim()), temp2[2].Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last());
                                                    }
                                                }
                                                catch { };
                                                //string fN = string.Join(",", filesName.ToArray());
                                                commandName = ConfigurationManager.AppSettings.Get("LocalDownload").Trim();
                                            }
                                        }

                                        /*else if (command.Equals("jSetBid")){
                                         * }*/
                                    }
                                    else
                                    {
                                        add         = true;
                                        commandName = ConfigurationManager.AppSettings.Get("UnknownCommand").Trim();
                                    }
                                }
                            }
                            else if (temp[1].Trim().Equals("page"))
                            {
                                //string ipValid = "([0-9]{1,3}.){3}[0-9]{1,3}";
                                ip = Regex.Match(temp[3].Trim(), ipValid).Value;
                                if (temp[2].Trim().StartsWith("/PositionForm"))
                                {
                                    tender      = temp[2].Trim().Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries)[1];
                                    commandName = string.Format(ConfigurationManager.AppSettings.Get("/PositionForm").Trim(), tender);
                                }
                                else if (temp[2].Trim().StartsWith("/BidForm"))
                                {
                                    if (temp.Count() == 4)
                                    {
                                        if (temp[2].Trim().Substring(temp[2].Length - 5, temp.Length).Equals("lot="))
                                        {
                                            add         = true;
                                            commandName = string.Format(ConfigurationManager.AppSettings.Get("/BidForm").Trim(), tender);
                                        }
                                        else if (temp[2].Trim().Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries)[2].StartsWith("web"))
                                        {
                                            add         = true;
                                            commandName = ConfigurationManager.AppSettings.Get("CreateDraft").Trim();
                                        }
                                    }
                                }
                            }
                        }
                        if (filesWithTime.Any())
                        {
                            foreach (var fn in filesWithTime)
                            {
                                dictForFile = new Dictionary <string, string>();
                                dictForFile.Add("date", date);
                                dictForFile.Add("time", fn.Key.ToString(ConfigurationManager.AppSettings.Get("timeFormat").Trim()));
                                dictForFile.Add("ip", ip);
                                dictForFile.Add("commandName", string.Format(commandName, tender, fn.Value));
                                if (!string.IsNullOrEmpty(dictForFile["commandName"]))
                                {
                                    listDictForFile.Add(dictForFile);
                                }
                            }
                        }
                        else if (add)
                        {
                            dictForFile.Add("date", date);
                            dictForFile.Add("time", time.ToString(ConfigurationManager.AppSettings.Get("timeFormat").Trim()));
                            dictForFile.Add("ip", ip);
                            dictForFile.Add("commandName", commandName);
                            if (!string.IsNullOrEmpty(dictForFile["commandName"]))
                            {
                                listDictForFile.Add(dictForFile);
                            }
                        }
                    }

                    #region xlsFileCreate
                    string outFile = string.Format("{0}\\{1}.xlsx", Environment.CurrentDirectory, fileName);                            // a.Next(0, 4578));
                    if (File.Exists(outFile))
                    {
                        File.Delete(outFile);
                    }

                    var file = new FileInfo(outFile);
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

                    using (var package = new ExcelPackage(file))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Work");
                        // --------- Data and styling goes here -------------- //
                        int col = 1, row = 1;
                        worksheet.DefaultColWidth         = 25;
                        worksheet.Cells[row, col++].Value = ConfigurationManager.AppSettings.Get("firstColumn").Trim();
                        worksheet.Cells[row, col++].Value = ConfigurationManager.AppSettings.Get("secondColumn").Trim();
                        worksheet.Cells[row, col++].Value = ConfigurationManager.AppSettings.Get("thirdColumn").Trim();
                        worksheet.Cells[row, col++].Value = ConfigurationManager.AppSettings.Get("fourthColumn").Trim();
                        int iii = 2;
                        foreach (var entity in listDictForFile)
                        {
                            col = 1;
                            try
                            {
                                worksheet.Cells[iii, col++].Value = entity["ip"];
                            }
                            catch { }
                            try
                            {
                                worksheet.Cells[iii, col++].Value = entity["date"];
                            }
                            catch { }
                            try
                            {
                                worksheet.Cells[iii, col++].Value = entity["time"];
                            }
                            catch { }
                            try
                            {
                                worksheet.Cells[iii, col++].Value = entity["commandName"];
                            }
                            catch { }
                            iii++;
                        }
                        var startRow    = 2;
                        var startColumn = 1;
                        var endRow      = 100;
                        var endColumn   = 10;
                        ///my
                        int[]  sortColumn = new int[] { 1, 2 };
                        bool[] descending = new bool[] { false, false };
                        ///my
                        using (ExcelRange excelRange = worksheet.Cells[startRow, startColumn, endRow, endColumn])
                        {
                            excelRange.Sort(sortColumn, descending, new CultureInfo("uk-UA"), CompareOptions.None);
                        }
                        package.Save();
                    }
                    #endregion xlsFileCreate
                    Console.WriteLine(string.Format("End{0}Press any key to continue", Environment.NewLine));
                    Console.ReadKey();
                }
            }
            else
            {
                Console.WriteLine(ConfigurationManager.AppSettings.Get("noFile").Trim());
                Console.ReadKey();
            }
            //}
            //catch (Exception e)
            //{
            //	Console.WriteLine(e);
            //	Console.ReadKey();
            //}
        }