Пример #1
0
        private void listen()
        {
            var input = this.ReadLine();

            try
            {
                var parameters = parseInput(input);

                var command = getCommand(parameters);

                var logger = new CommandLogger(this);

                var context = new CommandContext(logger, parameters, command);

                if (parameters.Name == "quit")
                {
                    Console.WriteLine("Goodbye");

                    return;
                }
                else if (command != null)
                {
                    runCommand(context);
                }

            }
            catch (Exception ex)
            {
                this.WriteError(ex.Message);
            }

            listen();
        }
        public void Commands_that_result_in_exceptions_are_still_intercepted()
        {
            var logger = new CommandLogger();
            Interception.AddInterceptor(logger);

            Exception exception;
            try
            {
                using (var context = new BlogContextNoInit())
                {
                    exception = Assert.Throws<SqlException>(() => context.Blogs.SqlQuery("select * from No.Chance").ToList());
                }
            }
            finally
            {
                Interception.RemoveInterceptor(logger);
            }

            Assert.Equal(2, logger.Log.Count);

            var executingLog = logger.Log[0];
            Assert.Equal(CommandMethod.ReaderExecuting, executingLog.Method);
            Assert.False(executingLog.IsAsync);
            Assert.Null(executingLog.Result);
            Assert.Null(executingLog.Exception);

            var executedLog = logger.Log[1];
            Assert.Equal(CommandMethod.ReaderExecuted, executedLog.Method);
            Assert.False(executedLog.IsAsync);
            Assert.Null(executedLog.Result);
            Assert.Same(exception, executedLog.Exception);
        }
        public void Initialization_and_simple_query_and_update_commands_can_be_logged()
        {
            var logger = new CommandLogger();
            DbInterception.Add(logger);

            try
            {
                using (var context = new BlogContextLogAll())
                {
                    BlogContext.DoStuff(context);
                }
            }
            finally
            {
                DbInterception.Remove(logger);
            }

            var commandsUsed = new bool[Enum.GetValues(typeof(CommandMethod)).Length];

            for (var i = 0; i < logger.Log.Count; i++)
            {
                var method = logger.Log[i].Method;
                commandsUsed[(int)method] = true;

                if (method.ToString().EndsWith("Executing"))
                {
                    Assert.Equal(method + 1, logger.Log[i + 1].Method);
                    Assert.Same(logger.Log[i].Command, logger.Log[i + 1].Command);
                }
            }

            // Check that every type of command used has log entries
            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuted]);
            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]);
            Assert.True(commandsUsed[(int)CommandMethod.ScalarExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.ScalarExecuted]);

            // Sanity check on command text
            var commandTexts = logger.Log.Select(l => l.CommandText.ToLowerInvariant());
            Assert.True(commandTexts.Any(c => c.StartsWith("select")));
            Assert.True(commandTexts.Any(c => c.StartsWith("create")));
            Assert.True(commandTexts.Any(c => c.StartsWith("alter")));
            Assert.True(commandTexts.Any(c => c.StartsWith("insert")));
        }
Пример #4
0
        public override void Execute(object parameter = null)
        {
            if (parameter is Fluent.ToggleButton)
            {
                ToggleButton = (ToggleButton)parameter;
            }

            OpenFileDialog ofd = new OpenFileDialog
            {
                DefaultExt = ".eXoL",
                Filter     = "eXolutio log files (*.eXoL)|*.eXoL|XML files (*.xml)|*.xml|All files (*.*)|*.*||"
            };

            if (ofd.ShowDialog() == true)
            {
                CommandLogger.LoadLogFile(ofd.FileName);
            }
        }
Пример #5
0
 public override void Action()
 {
     Console.Write(Description);
     if (_parameters != null)
     {
         Console.WriteLine(" - creating pairs:");
         for (int i = 0; i < _parameters.Length; i++)
         {
             Console.Write(_parameters[i++] + " = ");
             Console.Write(_parameters[i] + ";\n");
         }
     }
     else
     {
         Console.WriteLine(" without _parameters.");
     }
     CommandLogger.SaveToFile(this);
 }
Пример #6
0
        private static void Main(string[] args)
        {
            var config = new AppConfiguration
            {
                RootDirectoryToScan = @"C:\source",
                CellWidth           = 400,
                CellHeight          = 50,
                ShowOrphans         = true,
                OutputPath          = Path.Combine(Directory.GetCurrentDirectory() + @"\..\..\..\Graph.dgml"),
                GraphSorting        = GraphSorting.ClusterToRoots,
                ExcludedItems       = ExcludedItems
            };

            ICommandLogger       logger    = new CommandLogger();
            IDependencyExtractor extractor = new DependencyExtractor();
            var scanner = new DirectoryScanner(logger, config, extractor);

            scanner.ScanFolders();
            var logs = logger.GetLogs();


            IGraphBuilder builder        = new GraphBuilder(config);
            var           connectedNodes = builder.BuildGraph(logs);

            IInjector injector = new Injector();

            connectedNodes = injector.Inject(connectedNodes, ProjectsToAddContractLayer);

            IGraphSorter sorter = new GraphSorter(config);
            var          nodes  = sorter.GetSortedNodes(connectedNodes);

            Console.WriteLine("total: " + nodes.Count);
            Console.WriteLine("orphans: " + nodes.Count(p => p.Orphaned));
            Console.WriteLine("ymax: " + nodes.Where(p => !p.Orphaned).GroupBy(l => l.DepthLevel).Max(g => g.Count()));
            Console.WriteLine("xmax: " + nodes.Max(x => x.DepthLevel));

            var dgmlGenerator = new DgmlGenerator();

            dgmlGenerator.GenerateDgml(nodes, config);

            Console.WriteLine("done.");
            Console.ReadLine();
        }
Пример #7
0
        static Settings()
        {
            ApplicationDataPath = new Lazy <string>(() =>
            {
                if (IsPortable())
                {
                    return(GetGitExtensionsDirectory());
                }
                else
                {
                    //Make applicationdatapath version independent
                    return(Application.UserAppDataPath.Replace(Application.ProductVersion, string.Empty));
                }
            }
                                                    );

            Version version = Assembly.GetCallingAssembly().GetName().Version;

            GitExtensionsVersionString = version.Major.ToString() + '.' + version.Minor.ToString();
            GitExtensionsVersionInt    = version.Major * 100 + version.Minor;
            if (version.Build > 0)
            {
                GitExtensionsVersionString += '.' + version.Build.ToString();
                GitExtensionsVersionInt     = GitExtensionsVersionInt * 100 + version.Build;
            }
            if (!EnvUtils.RunningOnWindows())
            {
                PathSeparator      = '/';
                PathSeparatorWrong = '\\';
            }

            GitLog = new CommandLogger();

            if (!File.Exists(SettingsFilePath))
            {
                ImportFromRegistry();
                SaveXMLDictionarySettings(EncodedNameMap, SettingsFilePath);
            }
            SaveTimer.Enabled   = false;
            SaveTimer.AutoReset = false;
            SaveTimer.Elapsed  += new System.Timers.ElapsedEventHandler(OnSaveTimer);
        }
Пример #8
0
        public async Task ClearCommandLog()
        {
            try
            {
                var user = Context.User;
                if (!Helper.IsOwner(user))
                {
                    await ReplyAsync("Sorry, but you're not allowed to use that super premium command!");

                    return;
                }

                long kb = CommandLogger.Clear();
                await ReplyAsync($"Log cleared! ({kb} kB)");
            } catch (Exception ex)
            {
                await ReplyAsync("Whoops, unfortunately I couldn't clear the log.. :confused:");

                ConsoleHelper.Log($"Error clearing log, {ex.Message}!", LogSeverity.Error);
            }
        }
        public void Async_commands_that_result_in_exceptions_are_still_intercepted()
        {
            var logger = new CommandLogger();

            DbInterception.Add(logger);

            try
            {
                using (var context = new BlogContextNoInit())
                {
                    var query = context.Blogs.SqlQuery("select * from No.Chance").ToListAsync();

                    Assert.Throws <AggregateException>(() => query.Wait());

                    Assert.True(query.IsFaulted);
                }
            }
            finally
            {
                DbInterception.Remove(logger);
            }

            Assert.Equal(2, logger.Log.Count);

            var executingLog = logger.Log[0];

            Assert.Equal(CommandMethod.ReaderExecuting, executingLog.Method);
            Assert.True(executingLog.IsAsync);
            Assert.Null(executingLog.Result);
            Assert.Null(executingLog.Exception);

            var executedLog = logger.Log[1];

            Assert.Equal(CommandMethod.ReaderExecuted, executedLog.Method);
            Assert.True(executedLog.IsAsync);
            Assert.Null(executedLog.Result);
            Assert.IsType <SqlException>(executedLog.Exception);
            Assert.True(executedLog.TaskStatus.HasFlag(TaskStatus.Faulted));
        }
Пример #10
0
 public override void Execute(object parameter = null)
 {
     if (parameter is Fluent.ToggleButton)
     {
         ToggleButton = (ToggleButton)parameter;
     }
     if (CommandLogger.LoggingStarted)
     {
         CommandLogger.PauseLogging();
         if (parameter is Fluent.ToggleButton)
         {
             ((Fluent.ToggleButton)parameter).IsChecked = true;
         }
     }
     else
     {
         CommandLogger.ContinueLogging();
         if (parameter is Fluent.ToggleButton)
         {
             ((Fluent.ToggleButton)parameter).IsChecked = false;
         }
     }
 }
Пример #11
0
        static AppSettings()
        {
            ApplicationDataPath = new Lazy <string>(() =>
            {
                if (IsPortable())
                {
                    return(GetGitExtensionsDirectory());
                }
                else
                {
                    //Make applicationdatapath version independent
                    return(Application.UserAppDataPath.Replace(Application.ProductVersion, string.Empty));
                }
            }
                                                    );

            SettingsContainer = new SettingsContainer <RepoDistSettings>(null, GitExtSettingsCache.FromCache(SettingsFilePath));
            Version version = AppVersion;

            GitExtensionsVersionString = version.Major.ToString() + '.' + version.Minor.ToString();
            if (version.Build > 0)
            {
                GitExtensionsVersionString += '.' + version.Build.ToString();
            }
            if (!EnvUtils.RunningOnWindows())
            {
                PathSeparator      = '/';
                PathSeparatorWrong = '\\';
            }

            GitLog = new CommandLogger();

            if (!File.Exists(SettingsFilePath))
            {
                ImportFromRegistry();
            }
        }
        public void Commands_that_result_in_exceptions_are_still_intercepted()
        {
            var logger = new CommandLogger();

            DbInterception.Add(logger);

            Exception exception;

            try
            {
                using (var context = new BlogContextNoInit())
                {
                    exception = Assert.Throws <SqlException>(() => context.Blogs.SqlQuery("select * from No.Chance").ToList());
                }
            }
            finally
            {
                DbInterception.Remove(logger);
            }

            Assert.Equal(2, logger.Log.Count);

            var executingLog = logger.Log[0];

            Assert.Equal(CommandMethod.ReaderExecuting, executingLog.Method);
            Assert.False(executingLog.IsAsync);
            Assert.Null(executingLog.Result);
            Assert.Null(executingLog.Exception);

            var executedLog = logger.Log[1];

            Assert.Equal(CommandMethod.ReaderExecuted, executedLog.Method);
            Assert.False(executedLog.IsAsync);
            Assert.Null(executedLog.Result);
            Assert.Same(exception, executedLog.Exception);
        }
Пример #13
0
        public async Task GetCommandLog()
        {
            try
            {
                var user = Context.User;
                if (!Helper.IsOwner(user))
                {
                    await ReplyAsync("Sorry, but you're not allowed to use that super premium command!");

                    return;
                }

                var dm = await user.GetOrCreateDMChannelAsync();

                await CommandLogger.Upload(dm, Context.Channel);

                ConsoleHelper.Log($"{Context.User} requested the bot log!", LogSeverity.Info);
            } catch (Exception ex)
            {
                await ReplyAsync("Whoops, unfortunately I couldn't send you the log.. :confused:");

                ConsoleHelper.Log($"Error sending log, {ex.Message}!", LogSeverity.Error);
            }
        }
Пример #14
0
        static StaticWPFClientCommands()
        {
            ResetWindowLayout     = new guiResetWindowLayout();
            CheckForUpdates       = new guiCheckForUpdates();
            CloseActiveTab        = new guiCloseActiveTab();
            LayoutPIMLeftPSMRight = new guiLayoutCommand {
                LayoutType = guiLayoutCommand.ELayoutType.PIMLeftPSMRight
            };
            LayoutByVersions = new guiLayoutCommand {
                LayoutType = guiLayoutCommand.ELayoutType.ByVersions
            };

            CommandLogger commandLogger = new CommandLogger();

            Current.ExecutedCommand += commandLogger.OnCommandExecuted;
            guiPauseLogging          = new guiPauseLogging {
                CommandLogger = commandLogger
            };
            guiStartLogging = new guiStartLogging {
                CommandLogger = commandLogger
            };
            guiStopLogging = new guiStopLogging {
                CommandLogger = commandLogger
            };

            guiEndReplay = new guiEndReplay {
                CommandLogger = commandLogger
            };
            guiExecuteNextInLog = new guiExecuteNextInLog {
                CommandLogger = commandLogger
            };
            guiLoadLog = new guiLoadLog {
                CommandLogger = commandLogger
            };
            guiSnapshotMode = new guiSnapshotMode();
        }
Пример #15
0
        public ActionResult AddBookingEvent(FormCollection eventAndBooking)
        {
            try
            {
                var bookingId   = Convert.ToInt32(eventAndBooking["BookingID"]);
                var eventTypeId = Convert.ToInt32(eventAndBooking["EventTypeID"]);

                //get the booking
                var booking  = db.Bookings.Where(x => x.BookingID.Equals(bookingId)).FirstOrDefault();
                var property = booking.Property;

                //get the customer
                var customer     = db.Customers.FirstOrDefault(x => x.CustomerID.Equals(booking.CustomerID));
                var documentType = new PRCDocument.PRCDocumentType();



                //create new event and assign the correct typeID HERE, then can make event creation generic
                var eventToAdd = CreateBookingEventViaFactory(eventTypeId, booking);

                /*var whatAmIReturning = FullyInstantiateAndRunEvent(customer, booking);*/

                //////////GET TYPE OF DOCUMENT//////
                //STORE IN EVENT - DocumentEnum and Email Enum
                if (eventToAdd.EventType.DocumentEnumID != null)
                {
                    documentType = (PRCDocument.PRCDocumentType)eventToAdd.EventType.DocumentEnumID;
                }


                ////BEGIN GENERIC CODE
                /////////////////////////////////////////
                ////////CREATE EVENT DEPENDING ON SUB TYPE
                EventCommandCreateDocument createDocCommand;
                EventCommandSendEmail      sendEmail;
                EventCommandDocumentOutDirectoryBundleAndEmail docBundle;

                switch (eventToAdd.EventType.EventSubTypeID)
                {
                case 1:
                //does nothing, just add event
                case 2:
                    //email out
                    sendEmail = new EventCommandSendEmail(eventToAdd, (int)eventToAdd.EventType.EmailTemplateId, customer, booking);
                    eventToAdd.EventCommands.Add(sendEmail);
                    break;

                case 3:
                    createDocCommand = new EventCommandCreateDocument(eventToAdd, customer, documentType, booking);
                    sendEmail        = new EventCommandSendEmail(eventToAdd, (int)eventToAdd.EventType.EmailTemplateId, customer, booking);
                    eventToAdd.EventCommands.Add(createDocCommand);
                    eventToAdd.EventCommands.Add(sendEmail);
                    //document out + email that document
                    break;

                case 4:
                    //email reminder
                    sendEmail = new EventCommandSendEmail(eventToAdd, (int)eventToAdd.EventType.EmailTemplateId, customer, booking);
                    eventToAdd.EventCommands.Add(sendEmail);
                    break;

                case 5:
                    //create only
                    sendEmail = new EventCommandSendEmail(eventToAdd, (int)eventToAdd.EventType.EmailTemplateId, customer, booking);
                    eventToAdd.EventCommands.Add(sendEmail);
                    break;

                case 6:
                    //composite bundle and email
                    //get directory for docs
                    var bundleDir = HttpRuntime.AppDomainAppPath + "FinalBookingDocuments\\" + property.LegacyReference.ToLower() + "\\";
                    docBundle = new EventCommandDocumentOutDirectoryBundleAndEmail(bundleDir, eventToAdd, customer, documentType, booking);
                    sendEmail = new EventCommandSendEmail(eventToAdd, (int)eventToAdd.EventType.EmailEnumID, customer, booking);
                    eventToAdd.EventCommands.Add(docBundle);
                    eventToAdd.EventCommands.Add(sendEmail);
                    break;
                }



                var commandsAndResultsToLog = new List <EventCommand>();

                //execute the commands //create document using executes //create emails and bodies //do all sending

                var result = new EventCommandResult();
                foreach (var command in eventToAdd.EventCommands)
                {
                    command.EventCommandResults.Add(command.ExecuteCommand());
                    commandsAndResultsToLog.Add(command);
                }


                /////END CREATE EVENT


                ////////////////////////////
                //DO LOGGING
                //if successful log the event and the commands that ran
                //save event
                EventLogger log = new EventLogger(db);

                //strip out event wiring before loggin
                eventToAdd.EventCommands = null;
                var doLogging = log.LogEvent(eventToAdd);

                var EventCommandLogger = new CommandLogger(db);
                var eventLogger        = new EventLogger(db, EventCommandLogger);



                //save eventcoomand and result
                foreach (var commandAndResult in commandsAndResultsToLog)
                {
                    EventCommandLogger.Log(eventToAdd.EventID, commandAndResult);
                }


                //save document generated
                //if there's any docs, write them to the DB
                foreach (var doc in eventToAdd.Documents)
                {
                    doc.EventID             = eventToAdd.EventID;
                    doc.DocumentDescription = documentType.ToString();
                    doc.EmailTo             = customer.EmailAddress;
                    doc.CustomerID          = customer.CustomerID;

                    db.Documents.Add(doc);
                    db.SaveChanges();
                }


                //for view
                ViewBag.Bookingid = bookingId;

                var eventsForDDL =
                    db.EventTypes.Where(x => x.EventSchemeTypeID == 1 || x.EventSchemeTypeID == 2).ToList();
                ViewBag.EventTypeDDL = eventsForDDL;
            }
            catch (Exception ex)
            {
                MaintainanceMailer mail = new MaintainanceMailer();

                mail.theAsposeMessage.Subject = "Adding Booking Event Failed";

                mail.theAsposeMessage.Body  = ex.Message.ToString();
                mail.theAsposeMessage.Body += "----------------------------------";
                mail.theAsposeMessage.Body += ex.InnerException.ToStringDescriptive();

                throw ex;
            }


            return(View());
        }
Пример #16
0
        private static int Main(string[] args)
        {
            Debugger.AttachIfDebugDirective(args);

            AppDomain.CurrentDomain.UnhandledException += (_, eventArgs)
                                                          => ((Exception)eventArgs.ExceptionObject).Print();

            try
            {
                var configs = AppConfigs.Load();

                var appSettings = new AppSettings
                {
                    Arguments = { DefaultOptionSplit = ',', DefaultPipeTargetSymbol = "$*" },
                    ArgumentTypeDescriptors =
                    {
                        new DelegatedTypeDescriptor <Regex>("regex", p =>
                        {
                            // make it easier to specify NOT matching
                            if (p.StartsWith("$!"))
                            {
                                p = $"^((?!{p.Substring(2)}).)*$";
                            }
                            return(new Regex(p, RegexOptions.Compiled));
                        })
                    }
                };
                var appRunner = new AppRunner <GitApplication>(appSettings)
                                .UseDefaultMiddleware()
                                .GiveCancellationTokenToFlurl()
                                .Configure(c => c.UseParameterResolver(_ => AnsiConsole.Console))
                                .UseNameCasing(Case.KebabCase)
                                .UseDataAnnotationValidations(showHelpOnError: true)
                                .UseTimerDirective()
                                .UseDefaultsFromAppSetting(configs.Settings, true)
                                .UseErrorHandler((ctx, ex) =>
                {
                    var errorWriter = (ctx?.Console.Error ?? Console.Error);
                    ex.Print(errorWriter.WriteLine,
                             includeProperties: true,
                             includeData: true,
                             includeStackTrace: false);

                    // use CommandLogger if it has not already logged for this CommandContext
                    if (ctx is not null && !CommandLogger.HasLoggedFor(ctx))
                    {
                        CommandLogger.Log(ctx,
                                          writer: errorWriter.WriteLine,
                                          includeSystemInfo: true,
                                          includeAppConfig: false
                                          );

                        errorWriter.WriteLine();
                    }

                    // print help for the target command or root command
                    // if the exception occurred before a command could be parsed
                    ctx?.PrintHelp();

                    return(ExitCodes.Error.Result);
                })
                                .UseCommandLogger()
                                .RegisterContainer(configs);

                return(appRunner.Run(args));
            }
            catch (OperationCanceledException)
            {
                return(1);
            }
            catch (Exception e)
            {
                e.Print();
                return(1);
            }
        }
Пример #17
0
 public override void Action()
 {
     Console.WriteLine("Command <" + Value + "> - " + "is not supported.");
     Console.WriteLine("Use </?> to see set of allowed commands, <-exit> to terminate");
     CommandLogger.SaveToFile(this);
 }
Пример #18
0
 public override void Action()
 {
     Console.WriteLine(Description);
     Commander.Exit = true;
     CommandLogger.SaveToFile(this);
 }
Пример #19
0
 public override void Action()
 {
     Console.WriteLine(Description + ", current user is - " + Program.User);
     CommandLogger.SaveToFile(this);
 }
Пример #20
0
        public void Async_commands_that_result_in_exceptions_are_still_intercepted()
        {
            var logger = new CommandLogger();
            DbInterception.Add(logger);

            try
            {
                using (var context = new BlogContextNoInit())
                {
                    var query = context.Blogs.SqlQuery("select * from No.Chance").ToListAsync();

                    Assert.Throws<AggregateException>(() => query.Wait());

                    Assert.True(query.IsFaulted);
                }
            }
            finally
            {
                DbInterception.Remove(logger);
            }

            Assert.Equal(2, logger.Log.Count);

            var executingLog = logger.Log[0];
            Assert.Equal(CommandMethod.ReaderExecuting, executingLog.Method);
            Assert.True(executingLog.IsAsync);
            Assert.Null(executingLog.Result);
            Assert.Null(executingLog.Exception);

            var executedLog = logger.Log[1];
            Assert.Equal(CommandMethod.ReaderExecuted, executedLog.Method);
            Assert.True(executedLog.IsAsync);
            Assert.Null(executedLog.Result);
            Assert.IsType<SqlException>(executedLog.Exception);
            Assert.True(executedLog.TaskStatus.HasFlag(TaskStatus.Faulted));
        }
Пример #21
0
        static void Main(string[] args)
        {
            if (!Localization.Load())
            {
                LogFatalError("Failed to load localization data");
                return;
            }
            if (!KeyValues.Load())
            {
                LogFatalError("Failed to load the key data");
                return;
            }
            if (!KeyboardState.Load())
            {
                LogFatalError("Failed to load keyboard data");
                return;
            }

            if (args.Length > 0 && args[0].ToLower() == "clog")
            {
                CommandLogger.Run();
                return;
            }

            KeyboardDeviceManager.Connected += (KeyboardDevice device) =>
            {
                Log("Connected to device '" + device.State.ModelName + "' model:" + device.State.ModelId +
                    " fw:" + device.State.FirmwareVersion);

                string file = GetUserDataFile(device);
                if (!string.IsNullOrEmpty(file))
                {
                    try
                    {
                        string dir = Path.GetDirectoryName(file);
                        if (!Directory.Exists(dir))

                        {
                            Directory.CreateDirectory(dir);
                        }
                        if (!File.Exists(file))
                        {
                            File.WriteAllText(file, string.Empty, Encoding.UTF8);
                        }
                    }
                    catch
                    {
                    }
                }
            };
            KeyboardDeviceManager.Disconnected += (KeyboardDevice device) =>
            {
                Log("Disconnected from device '" + device.State.ModelName + "'");
            };
            KeyboardDeviceManager.StartListener();

            bool running = true;

            while (running)
            {
                string   line     = Console.ReadLine();
                string[] splitted = line.Split();
                switch (splitted[0].ToLower())
                {
                case "close":
                case "exit":
                case "quit":
                    running = false;
                    break;

                case "cls":
                case "clear":
                    Console.Clear();
                    break;

                case "map":
                case "unmap":
                {
                    bool             map = splitted[0].ToLower() == "map";
                    KeyboardDevice[] devices;
                    KeyboardLayer    targetLayer;
                    bool             targetLayerIsFn;
                    TryParseLayer(splitted, 1, out targetLayer, out targetLayerIsFn);
                    bool hasTargetLayer = targetLayer != KeyboardLayer.Invalid;
                    if (TryGetDevices(out devices))
                    {
                        foreach (KeyboardDevice device in devices)
                        {
                            UserDataFile userData = UserDataFile.Load(device.State, GetUserDataFile(device));
                            if (userData == null)
                            {
                                Log("Couldn't find user data file '" + GetUserDataFile(device) + "'");
                                continue;
                            }

                            foreach (KeyValuePair <KeyboardLayer, KeyboardStateLayer> layer in device.State.Layers)
                            {
                                if (layer.Key == KeyboardLayer.Driver)
                                {
                                    continue;
                                }

                                if (hasTargetLayer && layer.Key != targetLayer)
                                {
                                    continue;
                                }

                                device.SetLighting(layer.Key, userData);
                                device.SetMacros(layer.Key, userData);

                                for (int i = 0; i < 2; i++)
                                {
                                    bool fn = i == 1;
                                    if (targetLayer != KeyboardLayer.Invalid && fn != targetLayerIsFn)
                                    {
                                        continue;
                                    }

                                    // Setting keys to 0xFFFFFFFF is preferable compared to using what is defined in
                                    // files as this will use what is defined in the firmware.
                                    uint[] driverValues = new uint[device.State.MaxLogicCode];
                                    for (int j = 0; j < driverValues.Length; j++)
                                    {
                                        driverValues[j] = KeyValues.UnusedKeyValue;
                                    }

                                    if (map)
                                    {
                                        UserDataFile.Layer userDataLayer;
                                        if (fn)
                                        {
                                            userData.FnLayers.TryGetValue(layer.Key, out userDataLayer);
                                        }
                                        else
                                        {
                                            userData.Layers.TryGetValue(layer.Key, out userDataLayer);
                                        }
                                        if (userDataLayer != null)
                                        {
                                            for (int j = 0; j < driverValues.Length; j++)
                                            {
                                                KeyboardState.Key key = device.State.GetKeyByLogicCode(j);
                                                if (key != null)
                                                {
                                                    driverValues[j] = userDataLayer.GetKey(key.DriverValue);
                                                }
                                            }
                                        }
                                    }
                                    device.SetKeys(layer.Key, driverValues, fn);
                                }
                            }

                            // This is required to "refresh" the keyboard with the updated key info
                            if (hasTargetLayer)
                            {
                                device.SetLayer(targetLayer);
                            }
                            else
                            {
                                device.SetLayer(KeyboardLayer.Base);
                            }
                            Log("Done");
                        }
                    }
                }
                break;

                case "dumpkeys":
                {
                    int targetRow = -1;
                    if (splitted.Length > 1)
                    {
                        if (!int.TryParse(splitted[1], out targetRow))
                        {
                            targetRow = -1;
                        }
                    }
                    bool showLocationCodeInfo = false;
                    if (splitted.Length > 2)
                    {
                        showLocationCodeInfo = splitted[2] == "ex";
                    }

                    KeyboardDevice[] devices;
                    if (TryGetDevices(out devices))
                    {
                        foreach (KeyboardDevice device in devices)
                        {
                            Log("====== " + device.State.ModelId + " ======");
                            bool foundKey = false;
                            int  lastLeft = int.MinValue;
                            int  row      = 1;
                            foreach (KeyboardState.Key key in device.State.KeysByLocationCode.Values.OrderBy(
                                         x => x.Position.Top).ThenBy(x => x.Position.Left))
                            {
                                if (key.Position.Left >= 0)
                                {
                                    if (lastLeft > key.Position.Left && foundKey)
                                    {
                                        if (targetRow == -1)
                                        {
                                            Log("--------");
                                        }
                                        foundKey = false;
                                        row++;
                                    }
                                    lastLeft = key.Position.Left;
                                }

                                if (string.IsNullOrEmpty(key.KeyName) || !key.KeyName.StartsWith("LED-"))
                                {
                                    if (targetRow == -1 || row == targetRow)
                                    {
                                        Log(key.KeyName + " = " + (DriverValue)key.DriverValue +
                                            (showLocationCodeInfo ? " (" + key.LocationCode + ")" : string.Empty));
                                    }
                                    foundKey = true;
                                }
                            }
                        }
                    }
                }
                break;
                }
            }

            KeyboardDeviceManager.StopListener();
        }
Пример #22
0
        public void TestFullDocumentGenerateStack()
        {
            var db = new PortugalVillasContext();

            //Test WITH PARENT

            //TEST WITH BOOKING
            Booking booking = db.Bookings.Where(x => x.BookingID.Equals(4)).FirstOrDefault();

            booking.PropertyID = 221;
            /*           Booking booking = null;*/



            //TEST WITH CUSTOMER
            Customer aCustomer = db.Customers.Where(x => x.CustomerID == 1).FirstOrDefault();
            //TEST WITH BES
            var bes = db.BookingExtraSelections.Where(x => x.BookingExtraSelectionID == 3).First();

            bes.BookingExtraID = 1;

            //set up vars


            var type = PRCDocument.PRCDocumentType.UK_WineTasting;



            //create event  - need to give it type thus name
            var anEvent = new Event();

            anEvent.Documents = new List <Document>();
            //TEST ADD ID - PLEASE REMOVE
            anEvent.EventID = 2;
            //END TEST CODE

            anEvent.WhenCreated = DateTime.Now;
            var commandsAndResultsToLog = new List <EventCommand>();


            //create correct command
            //doc
            //email out with doc

            EventCommandCreateDocument createDocCommand;
            EventCommandSendEmail      sendEmail;

            //HOW DO WE DECIDE WHAT TYPE OF EVENT WE WANT??? depends on type??

            if (booking != null)
            {
                createDocCommand = new EventCommandCreateDocument(anEvent, aCustomer, type, booking);
                /* sendEmail = new EventCommandSendEmail(anEvent, aCustomer, booking);*/
            }
            else
            {
                createDocCommand = new EventCommandCreateDocument(anEvent, aCustomer, type, null, bes);
                /*/sendEmail = new EventCommandSendEmail(anEvent, aCustomer, null, bes);*/
            }



            //create all commands
            anEvent.EventCommands.Add(createDocCommand);
            /*       anEvent.EventCommands.Add(sendEmail);*/


            //create document using executes
            var result = new EventCommandResult();

            foreach (var command in anEvent.EventCommands)
            {
                command.EventCommandResults.Add(command.ExecuteCommand());
                commandsAndResultsToLog.Add(command);
            }

            //render

            //save to DB with all correct commands etc

            var EventCommandLogger = new CommandLogger(db);
            var eventLogger        = new EventLogger(db, EventCommandLogger);

            //save event
            eventLogger.LogEvent(anEvent);
            //save eventcoomand and result


            foreach (var commandAndResult in commandsAndResultsToLog)
            {
                EventCommandLogger.Log(anEvent.EventID, commandAndResult);
            }

            //save document generated

            //NEED TO ADD CORRECT PARAMS (which are what??)

            //if there's any docs, write them to the DB
            foreach (var doc in anEvent.Documents)
            {
                doc.EventID             = anEvent.EventID;
                doc.DocumentDescription = type.ToString();
                doc.EmailTo             = aCustomer.EmailAddress;
                doc.CustomerID          = aCustomer.CustomerID;

                db.Documents.Add(doc);
                db.SaveChanges();
            }
        }
Пример #23
0
        static void Run(bool asGUI)
        {
            BasePath     = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            DataBasePath = Path.Combine(BasePath, DataBasePath);
            UserDataPath = Path.Combine(BasePath, UserDataPath);

            if (!Localization.Load())
            {
                LogFatalError("Failed to load localization data");
                return;
            }
            if (!KeyValues.Load())
            {
                LogFatalError("Failed to load the key data");
                return;
            }
            if (!KeyboardState.Load())
            {
                LogFatalError("Failed to load keyboard data");
                return;
            }

#if COMMAND_LOGGER_ENABLED
            if (args.Length > 0 && args[0].ToLower() == "clog")
            {
                CommandLogger.Run();
                return;
            }
#endif

            KeyboardDeviceManager.Connected += (KeyboardDevice device) =>
            {
                Log("Connected to device '" + device.State.ModelName + "' model:" + device.State.ModelId +
                    " fw:" + device.State.FirmwareVersion);
                WebGUI.UpdateDeviceList();

                string file = GetUserDataFile(device);
                if (!string.IsNullOrEmpty(file))
                {
                    try
                    {
                        string dir = Path.GetDirectoryName(file);
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        if (!File.Exists(file))
                        {
                            File.WriteAllText(file, string.Empty, Encoding.UTF8);
                        }
                    }
                    catch
                    {
                    }
                }
            };
            KeyboardDeviceManager.Disconnected += (KeyboardDevice device) =>
            {
                Log("Disconnected from device '" + device.State.ModelName + "'");
                WebGUI.UpdateDeviceList();
            };
            KeyboardDeviceManager.StartListener();

            if (asGUI)
            {
                Process   currentProc = Process.GetCurrentProcess();
                Process[] procs       = Process.GetProcessesByName(currentProc.ProcessName);
                try
                {
                    foreach (Process proc in procs)
                    {
                        try
                        {
                            if (proc != currentProc && proc.Id != currentProc.Id)
                            {
                                proc.Kill();
                            }
                        }
                        catch
                        {
                        }
                    }
                }
                finally
                {
                    foreach (Process proc in procs)
                    {
                        proc.Close();
                    }
                }
                currentProc.Close();

                WebGUI.Run();
                while (WebGUI.LastPing > DateTime.Now - WebGUI.PingTimeout)
                {
                    Thread.Sleep(1000);
                }
                return;
            }

            bool running      = true;
            bool hasNullInput = false;
            while (running)
            {
                string line = Console.ReadLine();
                if (line == null)
                {
                    // Handler for potential issue where ReadLine() returns null - see https://github.com/pixeltris/GK6X/issues/8
                    if (hasNullInput)
                    {
                        Console.WriteLine("Cannot read from command line. Exiting.");
                        break;
                    }
                    hasNullInput = true;
                    continue;
                }
                hasNullInput = false;
                string[] splitted = line.Split();
                switch (splitted[0].ToLower())
                {
                case "close":
                case "exit":
                case "quit":
                    running = false;
                    break;

                case "cls":
                case "clear":
                    Console.Clear();
                    break;

                case "update_data":
                    if (splitted.Length > 1)
                    {
                        string path      = line.TrimStart();
                        int    spaceChar = path.IndexOf(' ');
                        if (spaceChar > 0)
                        {
                            path = path.Substring(spaceChar).Trim();
                        }
                        bool isValidPath = false;
                        try
                        {
                            if (Directory.Exists(path))
                            {
                                isValidPath = true;
                            }
                        }
                        catch
                        {
                        }
                        if (isValidPath)
                        {
                            UpdateDataFiles(path);
                            Log("done");
                        }
                        else
                        {
                            Log("Couldn't find path '" + path + "'");
                        }
                    }
                    else
                    {
                        Log("Bad input. Expected folder name.");
                    }
                    break;

                case "gui":
                    WebGUI.Run();
                    break;

                case "gui_to_txt":
                {
                    if (string.IsNullOrEmpty(WebGUI.UserDataPath))
                    {
                        Log("Load GUI first");
                    }
                    else
                    {
                        string userDataPath = WebGUI.UserDataPath;
                        int    accountId    = 0;
                        string accountDir   = Path.Combine(userDataPath, "Account", accountId.ToString());
                        if (Directory.Exists(accountDir))
                        {
                            foreach (KeyboardDevice device in KeyboardDeviceManager.GetConnectedDevices())
                            {
                                string deviceDir = Path.Combine(userDataPath, "Account", accountId.ToString(), "Devices", device.State.ModelId.ToString());
                                if (Directory.Exists(deviceDir))
                                {
                                    Dictionary <int, UserDataFile.Macro> macrosById = new Dictionary <int, UserDataFile.Macro>();
                                    UserDataFile userDataFile = new UserDataFile();
                                    foreach (string file in Directory.GetFiles(deviceDir, "*.cmf"))
                                    {
                                        string config = Encoding.UTF8.GetString(CMFile.Load(file));
                                        Dictionary <string, object> data = MiniJSON.Json.Deserialize(config) as Dictionary <string, object>;
                                        int           modelIndex         = (int)Convert.ChangeType(data["ModeIndex"], typeof(int));
                                        KeyboardLayer layer = (KeyboardLayer)modelIndex;

                                        //////////////////////////////////////////
                                        // Keys / macros (NOTE: Macros on different layers might wipe each other. look into.)
                                        //////////////////////////////////////////
                                        for (int i = 0; i < 2; i++)
                                        {
                                            string setStr = i == 0 ? "KeySet" : "FnKeySet";
                                            if (data.ContainsKey(setStr))
                                            {
                                                List <object> keys = data[setStr] as List <object>;
                                                foreach (object keyObj in keys)
                                                {
                                                    Dictionary <string, object> key = keyObj as Dictionary <string, object>;
                                                    int    keyIndex       = (int)Convert.ChangeType(key["Index"], typeof(int));
                                                    uint   driverValue    = KeyValues.UnusedKeyValue;
                                                    string driverValueStr = (string)key["DriverValue"];
                                                    if (driverValueStr.StartsWith("0x"))
                                                    {
                                                        if (uint.TryParse(driverValueStr.Substring(2), System.Globalization.NumberStyles.HexNumber, null, out driverValue))
                                                        {
                                                            if (KeyValues.GetKeyType(driverValue) == DriverValueType.Macro && key.ContainsKey("Task"))
                                                            {
                                                                Dictionary <string, object> task = key["Task"] as Dictionary <string, object>;
                                                                if (task != null && (string)task["Type"] == "Macro")
                                                                {
                                                                    Dictionary <string, object> taskData = task["Data"] as Dictionary <string, object>;
                                                                    string macroGuid = (string)taskData["GUID"];
                                                                    string macroFile = Path.Combine(userDataPath, "Account", accountId.ToString(), "Macro", macroGuid + ".cms");
                                                                    if (File.Exists(macroFile))
                                                                    {
                                                                        UserDataFile.Macro macro = new UserDataFile.Macro(null);
                                                                        macro.LoadFile(macroFile);
                                                                        macro.RepeatCount              = (byte)Convert.ChangeType(taskData["Repeats"], typeof(byte));
                                                                        macro.RepeatType               = (MacroRepeatType)(byte)Convert.ChangeType(taskData["StopMode"], typeof(byte));
                                                                        macro.Id                       = KeyValues.GetKeyData2(driverValue);
                                                                        macrosById[macro.Id]           = macro;
                                                                        userDataFile.Macros[macroGuid] = macro;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            driverValue = KeyValues.UnusedKeyValue;
                                                        }
                                                    }
                                                    if (keyIndex >= 0 && keyIndex < device.State.MaxLogicCode && driverValue != KeyValues.UnusedKeyValue)
                                                    {
                                                        KeyboardState.Key keyInfo = device.State.GetKeyByLogicCode(keyIndex);
                                                        if (keyInfo != null)
                                                        {
                                                            Dictionary <string, uint> vals = userDataFile.FindOrAddLayer(layer, i > 0).Keys;
                                                            if (Enum.IsDefined(typeof(DriverValue), driverValue))
                                                            {
                                                                vals[keyInfo.DriverValueName.ToLower()] = driverValue;
                                                            }
                                                            else
                                                            {
                                                                Log("Failed to map index " + keyIndex + " to " + driverValue + " on layer " + layer +
                                                                    (i > 0 ? " fn" : string.Empty));
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        //////////////////////////////////////////
                                        // Lighting
                                        //////////////////////////////////////////
                                        Dictionary <string, UserDataFile.LightingEffect> effects = new Dictionary <string, UserDataFile.LightingEffect>();
                                        string[] leHeaders = { "ModeLE", "DriverLE" };
                                        foreach (string leHeader in leHeaders)
                                        {
                                            if (data.ContainsKey(leHeader))
                                            {
                                                List <object> leEntries = data[leHeader] as List <object>;
                                                if (leEntries == null)
                                                {
                                                    // There's only one ModeLE
                                                    leEntries = new List <object>();
                                                    leEntries.Add(data[leHeader]);
                                                }
                                                foreach (object entry in leEntries)
                                                {
                                                    Dictionary <string, object> modeLE = entry as Dictionary <string, object>;
                                                    string leGuid = (string)modeLE["GUID"];
                                                    if (!string.IsNullOrEmpty(leGuid))
                                                    {
                                                        string filePath = Path.Combine(userDataPath, "Account", accountId.ToString(), "LE", leGuid + ".le");
                                                        if (!effects.ContainsKey(leGuid) && File.Exists(filePath))
                                                        {
                                                            UserDataFile.LightingEffect le = new UserDataFile.LightingEffect(userDataFile, null);
                                                            le.Load(device.State, Encoding.UTF8.GetString(CMFile.Load(filePath)));
                                                            le.Layers.Add(layer);
                                                            userDataFile.LightingEffects[leGuid] = le;
                                                            effects[leGuid] = le;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        object leDataObj;
                                                        if (modeLE.TryGetValue("LEData", out leDataObj))
                                                        {
                                                            Dictionary <string, object> leData = leDataObj as Dictionary <string, object>;
                                                            if (leData != null)
                                                            {
                                                                // This should be static lighting data only
                                                                UserDataFile.LightingEffect le = new UserDataFile.LightingEffect(userDataFile, null);
                                                                le.LoadStatic(device.State, leData);
                                                                le.Layers.Add(layer);
                                                                userDataFile.LightingEffects[Guid.NewGuid().ToString()] = le;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    userDataFile.SaveFromGUI(device.State, Path.Combine(UserDataPath, device.State.ModelId + "_exported.txt"));
                                    Log("Done");
                                    break;
                                }
                            }
                        }
                        else
                        {
                            Log("Account settings not found for account id " + accountId);
                        }
                    }
                }
                break;

                case "gui_le":
                {
                    string userDataPath = WebGUI.UserDataPath;
                    string leName       = line.Trim();
                    int    spaceIndex   = leName.IndexOf(' ');
                    if (spaceIndex > 0)
                    {
                        leName = leName.Substring(spaceIndex).Trim();
                    }
                    else
                    {
                        leName = null;
                    }
                    if (!string.IsNullOrEmpty(leName))
                    {
                        if (!string.IsNullOrEmpty(userDataPath) && Directory.Exists(userDataPath))
                        {
                            string leDir      = Path.Combine(userDataPath, "Account", "0", "LE");
                            string leListFile = Path.Combine(leDir, "lelist.json");
                            if (File.Exists(leListFile))
                            {
                                bool          foundFile = false;
                                List <object> leList    = MiniJSON.Json.Deserialize(File.ReadAllText(leListFile)) as List <object>;
                                if (leList != null)
                                {
                                    foreach (object item in leList)
                                    {
                                        Dictionary <string, object> guidName = item as Dictionary <string, object>;
                                        if (guidName["Name"].ToString() == leName)
                                        {
                                            string leFileName = Path.Combine(leDir, guidName["GUID"].ToString() + ".le");
                                            if (File.Exists(leFileName))
                                            {
                                                foreach (char c in System.IO.Path.GetInvalidFileNameChars())
                                                {
                                                    leName = leName.Replace(c, '_');
                                                }
                                                string effectString = Encoding.UTF8.GetString(CMFile.Load(leFileName));
                                                effectString = CMFile.FormatJson(effectString);
                                                File.WriteAllText(Path.Combine(DataBasePath, "lighting", leName + ".le"), effectString);
                                                Program.Log("Copied '" + leName + "'");
                                                foundFile = true;
                                            }
                                        }
                                    }
                                }
                                if (!foundFile)
                                {
                                    Program.Log("Failed to find lighting effect '" + leName + "' (it's case sensitive)");
                                }
                            }
                            else
                            {
                                Program.Log("Failed to find file '" + leListFile + "'");
                            }
                        }
                    }
                    else
                    {
                        Program.Log("Invalid input. Expected lighting effect name.");
                    }
                }
                break;

                case "findkeys":
                {
                    Log(string.Empty);
                    Log("This is used to identify keys. Press keys to see their values. Missing keys will generally show up as '(null)' and they need to be mapped in the data files Data/devuces/YOUR_MODEL_ID/");
                    Log("The 'S' values are what you want to use to map keys in your UserData file.");
                    Log(string.Empty);
                    Log("Entering 'driver' mode and mapping all keys to callbacks.");
                    Log(string.Empty);
                    KeyboardDevice[] devices;
                    if (TryGetDevices(out devices))
                    {
                        foreach (KeyboardDevice device in devices)
                        {
                            device.SetLayer(KeyboardLayer.Driver);
                            device.SetIdentifyDriverMacros();
                        }
                    }
                }
                break;

                case "map":
                case "unmap":
                {
                    bool             map = splitted[0].ToLower() == "map";
                    KeyboardDevice[] devices;
                    KeyboardLayer    targetLayer;
                    bool             targetLayerIsFn;
                    TryParseLayer(splitted, 1, out targetLayer, out targetLayerIsFn);
                    bool hasTargetLayer = targetLayer != KeyboardLayer.Invalid;
                    if (TryGetDevices(out devices))
                    {
                        foreach (KeyboardDevice device in devices)
                        {
                            UserDataFile userData = UserDataFile.Load(device.State, GetUserDataFile(device));
                            if (userData == null)
                            {
                                Log("Couldn't find user data file '" + GetUserDataFile(device) + "'");
                                continue;
                            }

                            foreach (KeyValuePair <KeyboardLayer, KeyboardStateLayer> layer in device.State.Layers)
                            {
                                if (layer.Key == KeyboardLayer.Driver)
                                {
                                    continue;
                                }

                                if (hasTargetLayer && layer.Key != targetLayer)
                                {
                                    continue;
                                }

                                device.SetLighting(layer.Key, userData);
                                device.SetMacros(layer.Key, userData);

                                for (int i = 0; i < 2; i++)
                                {
                                    bool fn = i == 1;
                                    if (targetLayer != KeyboardLayer.Invalid && fn != targetLayerIsFn)
                                    {
                                        continue;
                                    }

                                    // Setting keys to 0xFFFFFFFF is preferable compared to using what is defined in
                                    // files as this will use what is defined in the firmware.
                                    uint[] driverValues = new uint[device.State.MaxLogicCode];
                                    for (int j = 0; j < driverValues.Length; j++)
                                    {
                                        driverValues[j] = KeyValues.UnusedKeyValue;
                                    }

                                    if (map)
                                    {
                                        UserDataFile.Layer userDataLayer;
                                        if (fn)
                                        {
                                            userData.FnLayers.TryGetValue(layer.Key, out userDataLayer);
                                        }
                                        else
                                        {
                                            userData.Layers.TryGetValue(layer.Key, out userDataLayer);
                                        }
                                        if (userDataLayer != null)
                                        {
                                            for (int j = 0; j < driverValues.Length; j++)
                                            {
                                                KeyboardState.Key key = device.State.GetKeyByLogicCode(j);
                                                if (key != null)
                                                {
                                                    driverValues[j] = userDataLayer.GetKey(key);
                                                }
                                            }
                                        }
                                    }
                                    device.SetKeys(layer.Key, driverValues, fn);
                                }
                            }

                            // This is required to "refresh" the keyboard with the updated key info
                            if (hasTargetLayer)
                            {
                                device.SetLayer(targetLayer);
                            }
                            else
                            {
                                device.SetLayer(KeyboardLayer.Base);
                            }
                            Log("Done");
                        }
                    }
                }
                break;

                case "dumpkeys":
                {
                    int targetRow = -1;
                    if (splitted.Length > 1)
                    {
                        if (!int.TryParse(splitted[1], out targetRow))
                        {
                            targetRow = -1;
                        }
                    }
                    bool showLocationCodeInfo = false;
                    if (splitted.Length > 2)
                    {
                        showLocationCodeInfo = splitted[2] == "ex";
                    }

                    KeyboardDevice[] devices;
                    if (TryGetDevices(out devices))
                    {
                        foreach (KeyboardDevice device in devices)
                        {
                            Log("====== " + device.State.ModelId + " ======");
                            bool foundKey = false;
                            int  lastLeft = int.MinValue;
                            int  row      = 1;
                            foreach (KeyboardState.Key key in device.State.KeysByLocationCode.Values.OrderBy(
                                         x => x.Position.Top).ThenBy(x => x.Position.Left))
                            {
                                if (key.Position.Left >= 0)
                                {
                                    if (lastLeft > key.Position.Left && foundKey)
                                    {
                                        if (targetRow == -1)
                                        {
                                            Log("--------");
                                        }
                                        foundKey = false;
                                        row++;
                                    }
                                    lastLeft = key.Position.Left;
                                }

                                if (string.IsNullOrEmpty(key.KeyName) || !key.KeyName.StartsWith("LED-"))
                                {
                                    if (targetRow == -1 || row == targetRow)
                                    {
                                        Log(key.KeyName + " = " + key.DriverValueName +
                                            (showLocationCodeInfo ? " (" + key.LocationCode + ")" : string.Empty));
                                    }
                                    foundKey = true;
                                }
                            }
                        }
                    }
                }
                break;
                }
            }
        }
        public void Initialization_and_simple_query_and_update_commands_can_be_logged()
        {
            var logger = new CommandLogger();
            Interception.AddInterceptor(logger);

            try
            {
                using (var context = new BlogContextLogAll())
                {
                    BlogContext.DoStuff(context);
                }
            }
            finally
            {
                Interception.RemoveInterceptor(logger);
            }

            var commandsUsed = new bool[Enum.GetValues(typeof(CommandMethod)).Length];

            // Check that every "executed" call is preceded by an "executing" call.
            // (The reverse is not true since "executed" is not called for operations that throw.)
            for (var i = 0; i < logger.Log.Count; i++)
            {
                var method = logger.Log[i].Method;
                commandsUsed[(int)method] = true;

                if (method.ToString().EndsWith("Executed"))
                {
                    Assert.Equal(method - 1, logger.Log[i - 1].Method);
                }
            }

            // Check that every type of command used has log entries
            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuted]);
            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]);
            Assert.True(commandsUsed[(int)CommandMethod.ScalarExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.ScalarExecuted]);

#if NET40
            Assert.False(commandsUsed[(int)CommandMethod.AsyncNonQueryExecuting]);
            Assert.False(commandsUsed[(int)CommandMethod.AsyncNonQueryExecuted]);
            Assert.False(commandsUsed[(int)CommandMethod.AsyncReaderExecuting]);
            Assert.False(commandsUsed[(int)CommandMethod.AsyncReaderExecuted]);
#else
            Assert.True(commandsUsed[(int)CommandMethod.AsyncNonQueryExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.AsyncNonQueryExecuted]);
            Assert.True(commandsUsed[(int)CommandMethod.AsyncReaderExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.AsyncReaderExecuted]);
#endif

            // EF and SQL provider never send ExecuteScalarAsync
            Assert.False(commandsUsed[(int)CommandMethod.AsyncScalarExecuting]);
            Assert.False(commandsUsed[(int)CommandMethod.AsyncScalarExecuted]);

            // Sanity check on command text
            var commandTexts = logger.Log.Select(l => l.CommandText.ToLowerInvariant());
            Assert.True(commandTexts.Any(c => c.StartsWith("select")));
            Assert.True(commandTexts.Any(c => c.StartsWith("create")));
            Assert.True(commandTexts.Any(c => c.StartsWith("alter")));
            Assert.True(commandTexts.Any(c => c.StartsWith("insert")));
#if !NET40
            Assert.True(commandTexts.Any(c => c.StartsWith("update")));
#endif

            // Sanity check on results
            Assert.True(logger.Log.Where(l => l.Method == CommandMethod.NonQueryExecuted).All(l => l.Result != null));
            Assert.True(logger.Log.Where(l => l.Method == CommandMethod.ReaderExecuted).All(l => l.Result != null));

#if !NET40
            Assert.True(
                logger.Log.Where(
                    l => l.Method.ToString().StartsWith("Async")
                         && l.Method.ToString().EndsWith("Executed")).All(l => l.Result != null));
#endif
        }
        public void Initialization_and_simple_query_and_update_commands_can_be_logged()
        {
            var logger = new CommandLogger();

            Interception.AddInterceptor(logger);

            try
            {
                using (var context = new BlogContextLogAll())
                {
                    BlogContext.DoStuff(context);
                }
            }
            finally
            {
                Interception.RemoveInterceptor(logger);
            }

            var commandsUsed = new bool[Enum.GetValues(typeof(CommandMethod)).Length];

            // Check that every "executed" call is preceded by an "executing" call.
            // (The reverse is not true since "executed" is not called for operations that throw.)
            for (var i = 0; i < logger.Log.Count; i++)
            {
                var method = logger.Log[i].Method;
                commandsUsed[(int)method] = true;

                if (method.ToString().EndsWith("Executed"))
                {
                    Assert.Equal(method - 1, logger.Log[i - 1].Method);
                }
            }

            // Check that every type of command used has log entries
            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuted]);
            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]);
            Assert.True(commandsUsed[(int)CommandMethod.ScalarExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.ScalarExecuted]);

#if NET40
            Assert.False(commandsUsed[(int)CommandMethod.AsyncNonQueryExecuting]);
            Assert.False(commandsUsed[(int)CommandMethod.AsyncNonQueryExecuted]);
            Assert.False(commandsUsed[(int)CommandMethod.AsyncReaderExecuting]);
            Assert.False(commandsUsed[(int)CommandMethod.AsyncReaderExecuted]);
#else
            Assert.True(commandsUsed[(int)CommandMethod.AsyncNonQueryExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.AsyncNonQueryExecuted]);
            Assert.True(commandsUsed[(int)CommandMethod.AsyncReaderExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.AsyncReaderExecuted]);
#endif

            // EF and SQL provider never send ExecuteScalarAsync
            Assert.False(commandsUsed[(int)CommandMethod.AsyncScalarExecuting]);
            Assert.False(commandsUsed[(int)CommandMethod.AsyncScalarExecuted]);

            // Sanity check on command text
            var commandTexts = logger.Log.Select(l => l.CommandText.ToLowerInvariant());
            Assert.True(commandTexts.Any(c => c.StartsWith("select")));
            Assert.True(commandTexts.Any(c => c.StartsWith("create")));
            Assert.True(commandTexts.Any(c => c.StartsWith("alter")));
            Assert.True(commandTexts.Any(c => c.StartsWith("insert")));
#if !NET40
            Assert.True(commandTexts.Any(c => c.StartsWith("update")));
#endif

            // Sanity check on results
            Assert.True(logger.Log.Where(l => l.Method == CommandMethod.NonQueryExecuted).All(l => l.Result != null));
            Assert.True(logger.Log.Where(l => l.Method == CommandMethod.ReaderExecuted).All(l => l.Result != null));

#if !NET40
            Assert.True(
                logger.Log.Where(
                    l => l.Method.ToString().StartsWith("Async") &&
                    l.Method.ToString().EndsWith("Executed")).All(l => l.Result != null));
#endif
        }
        public void Async_commands_that_are_canceled_are_still_intercepted()
        {
            var logger = new CommandLogger();
            Interception.AddInterceptor(logger);

            var cancellation = new CancellationTokenSource();
            var cancellationToken = cancellation.Token;

            try
            {
                using (var context = new BlogContextNoInit())
                {
                    context.Database.Connection.Open();

                    cancellation.Cancel();

                    var command = context.Database.ExecuteSqlCommandAsync("update Blogs set Title = 'No' where Id = -1", cancellationToken);

                    try
                    {
                        command.Wait();
                    }
                    catch (AggregateException)
                    {
                        // Ignore
                    }

                    Assert.True(command.IsCanceled);

                    context.Database.Connection.Close();
                }
            }
            finally
            {
                Interception.RemoveInterceptor(logger);
            }

            Assert.Equal(2, logger.Log.Count);

            var executingLog = logger.Log[0];
            Assert.Equal(CommandMethod.NonQueryExecuting, executingLog.Method);
            Assert.True(executingLog.IsAsync);
            Assert.Null(executingLog.Result);
            Assert.Null(executingLog.Exception);

            var executedLog = logger.Log[1];
            Assert.Equal(CommandMethod.NonQueryExecuted, executedLog.Method);
            Assert.True(executedLog.IsAsync);
            Assert.Equal(0, executedLog.Result);
            Assert.Null(executedLog.Exception);
            Assert.True(executedLog.TaskStatus.HasFlag(TaskStatus.Canceled));
        }
        public void Multiple_contexts_running_concurrently_can_use_interception()
        {
            var loggers = new ConcurrentBag <CommandLogger>();

            const int executionCount = 5;

            ExecuteInParallel(
                () =>
            {
                using (var context = new BlogContextNoInit())
                {
                    var logger = new CommandLogger(context);
                    DbInterception.Add(logger);
                    loggers.Add(logger);

                    try
                    {
                        BlogContext.DoStuff(context);
                    }
                    finally
                    {
                        DbInterception.Remove(logger);
                    }

                    var commandsUsed = new bool[Enum.GetValues(typeof(CommandMethod)).Length];

                    for (var i = 0; i < logger.Log.Count; i++)
                    {
                        var method = logger.Log[i].Method;
                        commandsUsed[(int)method] = true;

                        if (method.ToString().EndsWith("Executing"))
                        {
                            Assert.Equal(method + 1, logger.Log[i + 1].Method);
                            Assert.Same(logger.Log[i].Command, logger.Log[i + 1].Command);
                        }
                    }

                    // Check that expected command have log entries
                    Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]);
                    Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]);
                    Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]);
                    Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]);
#if !NET40
                    Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuting]);
                    Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuted]);
#endif

                    // Sanity check on command text
                    var commandTexts = logger.Log.Select(l => l.CommandText.ToLowerInvariant());
                    Assert.True(commandTexts.Any(c => c.StartsWith("select")));
                    Assert.True(commandTexts.Any(c => c.StartsWith("insert")));
#if !NET40
                    Assert.True(commandTexts.Any(c => c.StartsWith("update")));
#endif

                    // Sanity check on results
                    Assert.True(logger.Log.Where(l => l.Method == CommandMethod.NonQueryExecuted).All(l => l.Result != null));
                    Assert.True(logger.Log.Where(l => l.Method == CommandMethod.ReaderExecuted).All(l => l.Result != null));
                }
            }, executionCount);

            // Check that each execution logged exactly the same commands.

            Assert.Equal(executionCount, loggers.Count);

            var firstLog = loggers.First().Log;
            foreach (var log in loggers.Select(l => l.Log).Skip(1))
            {
                Assert.Equal(firstLog.Count, log.Count);

                for (var i = 0; i < log.Count; i++)
                {
                    Assert.Equal(firstLog[i].Method, log[i].Method);
                    Assert.Equal(firstLog[i].CommandText, log[i].CommandText);

                    if (firstLog[i].Result == null)
                    {
                        Assert.Null(log[i].Result);
                    }
                    else
                    {
                        Assert.Same(firstLog[i].Result.GetType(), log[i].Result.GetType());
                    }
                }
            }
        }
Пример #28
0
        static void Main(string[] args)
        {
            BasePath     = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            DataBasePath = Path.Combine(BasePath, DataBasePath);
            UserDataPath = Path.Combine(BasePath, UserDataPath);

            if (!Localization.Load())
            {
                LogFatalError("Failed to load localization data");
                return;
            }
            if (!KeyValues.Load())
            {
                LogFatalError("Failed to load the key data");
                return;
            }
            if (!KeyboardState.Load())
            {
                LogFatalError("Failed to load keyboard data");
                return;
            }

#if COMMAND_LOGGER_ENABLED
            if (args.Length > 0 && args[0].ToLower() == "clog")
            {
                CommandLogger.Run();
                return;
            }
#endif

            KeyboardDeviceManager.Connected += (KeyboardDevice device) =>
            {
                Log("Connected to device '" + device.State.ModelName + "' model:" + device.State.ModelId +
                    " fw:" + device.State.FirmwareVersion);
                WebGUI.UpdateDeviceList();

                string file = GetUserDataFile(device);
                if (!string.IsNullOrEmpty(file))
                {
                    try
                    {
                        string dir = Path.GetDirectoryName(file);
                        if (!Directory.Exists(dir))

                        {
                            Directory.CreateDirectory(dir);
                        }
                        if (!File.Exists(file))
                        {
                            File.WriteAllText(file, string.Empty, Encoding.UTF8);
                        }
                    }
                    catch
                    {
                    }
                }
            };
            KeyboardDeviceManager.Disconnected += (KeyboardDevice device) =>
            {
                Log("Disconnected from device '" + device.State.ModelName + "'");
                WebGUI.UpdateDeviceList();
            };
            KeyboardDeviceManager.StartListener();

            bool running      = true;
            bool hasNullInput = false;
            while (running)
            {
                string line = Console.ReadLine();
                if (line == null)
                {
                    // Handler for potential issue where ReadLine() returns null - see https://github.com/pixeltris/GK6X/issues/8
                    if (hasNullInput)
                    {
                        Console.WriteLine("Cannot read from command line. Exiting.");
                        break;
                    }
                    hasNullInput = true;
                    continue;
                }
                hasNullInput = false;
                string[] splitted = line.Split();
                switch (splitted[0].ToLower())
                {
                case "close":
                case "exit":
                case "quit":
                    running = false;
                    break;

                case "cls":
                case "clear":
                    Console.Clear();
                    break;

                case "update_data":
                    if (splitted.Length > 1)
                    {
                        string path      = line.TrimStart();
                        int    spaceChar = path.IndexOf(' ');
                        if (spaceChar > 0)
                        {
                            path = path.Substring(spaceChar).Trim();
                        }
                        bool isValidPath = false;
                        try
                        {
                            if (Directory.Exists(path))
                            {
                                isValidPath = true;
                            }
                        }
                        catch
                        {
                        }
                        if (isValidPath)
                        {
                            UpdateDataFiles(path);
                            Log("done");
                        }
                        else
                        {
                            Log("Couldn't find path '" + path + "'");
                        }
                    }
                    else
                    {
                        Log("Bad input. Expected folder name.");
                    }
                    break;

                case "gui":
                    WebGUI.Run();
                    break;

                case "gui_le":
                {
                    string userDataPath = WebGUI.UserDataPath;
                    string leName       = line.Trim();
                    int    spaceIndex   = leName.IndexOf(' ');
                    if (spaceIndex > 0)
                    {
                        leName = leName.Substring(spaceIndex).Trim();
                    }
                    else
                    {
                        leName = null;
                    }
                    if (!string.IsNullOrEmpty(leName))
                    {
                        if (!string.IsNullOrEmpty(userDataPath) && Directory.Exists(userDataPath))
                        {
                            string leDir      = Path.Combine(userDataPath, "Account", "0", "LE");
                            string leListFile = Path.Combine(leDir, "lelist.json");
                            if (File.Exists(leListFile))
                            {
                                bool          foundFile = false;
                                List <object> leList    = MiniJSON.Json.Deserialize(File.ReadAllText(leListFile)) as List <object>;
                                if (leList != null)
                                {
                                    foreach (object item in leList)
                                    {
                                        Dictionary <string, object> guidName = item as Dictionary <string, object>;
                                        if (guidName["Name"].ToString() == leName)
                                        {
                                            string leFileName = Path.Combine(leDir, guidName["GUID"].ToString() + ".le");
                                            if (File.Exists(leFileName))
                                            {
                                                foreach (char c in System.IO.Path.GetInvalidFileNameChars())
                                                {
                                                    leName = leName.Replace(c, '_');
                                                }
                                                string effectString = Encoding.UTF8.GetString(CMFile.Load(leFileName));
                                                effectString = CMFile.FormatJson(effectString);
                                                File.WriteAllText(Path.Combine(DataBasePath, "lighting", leName + ".le"), effectString);
                                                Program.Log("Copied '" + leName + "'");
                                                foundFile = true;
                                            }
                                        }
                                    }
                                }
                                if (!foundFile)
                                {
                                    Program.Log("Failed to find lighting effect '" + leName + "' (it's case sensitive)");
                                }
                            }
                            else
                            {
                                Program.Log("Failed to find file '" + leListFile + "'");
                            }
                        }
                    }
                    else
                    {
                        Program.Log("Invalid input. Expected lighting effect name.");
                    }
                }
                break;

                case "findkeys":
                {
                    Log(string.Empty);
                    Log("This is used to identify keys. Press keys to see their values. Missing keys will generally show up as '(null)' and they need to be mapped in the data files Data/devuces/YOUR_MODEL_ID/");
                    Log("The 'S' values are what you want to use to map keys in your UserData file.");
                    Log(string.Empty);
                    Log("Entering 'driver' mode and mapping all keys to callbacks.");
                    Log(string.Empty);
                    KeyboardDevice[] devices;
                    if (TryGetDevices(out devices))
                    {
                        foreach (KeyboardDevice device in devices)
                        {
                            device.SetLayer(KeyboardLayer.Driver);
                            device.SetIdentifyDriverMacros();
                        }
                    }
                }
                break;

                case "map":
                case "unmap":
                {
                    bool             map = splitted[0].ToLower() == "map";
                    KeyboardDevice[] devices;
                    KeyboardLayer    targetLayer;
                    bool             targetLayerIsFn;
                    TryParseLayer(splitted, 1, out targetLayer, out targetLayerIsFn);
                    bool hasTargetLayer = targetLayer != KeyboardLayer.Invalid;
                    if (TryGetDevices(out devices))
                    {
                        foreach (KeyboardDevice device in devices)
                        {
                            UserDataFile userData = UserDataFile.Load(device.State, GetUserDataFile(device));
                            if (userData == null)
                            {
                                Log("Couldn't find user data file '" + GetUserDataFile(device) + "'");
                                continue;
                            }

                            foreach (KeyValuePair <KeyboardLayer, KeyboardStateLayer> layer in device.State.Layers)
                            {
                                if (layer.Key == KeyboardLayer.Driver)
                                {
                                    continue;
                                }

                                if (hasTargetLayer && layer.Key != targetLayer)
                                {
                                    continue;
                                }

                                device.SetLighting(layer.Key, userData);
                                device.SetMacros(layer.Key, userData);

                                for (int i = 0; i < 2; i++)
                                {
                                    bool fn = i == 1;
                                    if (targetLayer != KeyboardLayer.Invalid && fn != targetLayerIsFn)
                                    {
                                        continue;
                                    }

                                    // Setting keys to 0xFFFFFFFF is preferable compared to using what is defined in
                                    // files as this will use what is defined in the firmware.
                                    uint[] driverValues = new uint[device.State.MaxLogicCode];
                                    for (int j = 0; j < driverValues.Length; j++)
                                    {
                                        driverValues[j] = KeyValues.UnusedKeyValue;
                                    }

                                    if (map)
                                    {
                                        UserDataFile.Layer userDataLayer;
                                        if (fn)
                                        {
                                            userData.FnLayers.TryGetValue(layer.Key, out userDataLayer);
                                        }
                                        else
                                        {
                                            userData.Layers.TryGetValue(layer.Key, out userDataLayer);
                                        }
                                        if (userDataLayer != null)
                                        {
                                            for (int j = 0; j < driverValues.Length; j++)
                                            {
                                                KeyboardState.Key key = device.State.GetKeyByLogicCode(j);
                                                if (key != null)
                                                {
                                                    driverValues[j] = userDataLayer.GetKey(key);
                                                }
                                            }
                                        }
                                    }
                                    device.SetKeys(layer.Key, driverValues, fn);
                                }
                            }

                            // This is required to "refresh" the keyboard with the updated key info
                            if (hasTargetLayer)
                            {
                                device.SetLayer(targetLayer);
                            }
                            else
                            {
                                device.SetLayer(KeyboardLayer.Base);
                            }
                            Log("Done");
                        }
                    }
                }
                break;

                case "dumpkeys":
                {
                    int targetRow = -1;
                    if (splitted.Length > 1)
                    {
                        if (!int.TryParse(splitted[1], out targetRow))
                        {
                            targetRow = -1;
                        }
                    }
                    bool showLocationCodeInfo = false;
                    if (splitted.Length > 2)
                    {
                        showLocationCodeInfo = splitted[2] == "ex";
                    }

                    KeyboardDevice[] devices;
                    if (TryGetDevices(out devices))
                    {
                        foreach (KeyboardDevice device in devices)
                        {
                            Log("====== " + device.State.ModelId + " ======");
                            bool foundKey = false;
                            int  lastLeft = int.MinValue;
                            int  row      = 1;
                            foreach (KeyboardState.Key key in device.State.KeysByLocationCode.Values.OrderBy(
                                         x => x.Position.Top).ThenBy(x => x.Position.Left))
                            {
                                if (key.Position.Left >= 0)
                                {
                                    if (lastLeft > key.Position.Left && foundKey)
                                    {
                                        if (targetRow == -1)
                                        {
                                            Log("--------");
                                        }
                                        foundKey = false;
                                        row++;
                                    }
                                    lastLeft = key.Position.Left;
                                }

                                if (string.IsNullOrEmpty(key.KeyName) || !key.KeyName.StartsWith("LED-"))
                                {
                                    if (targetRow == -1 || row == targetRow)
                                    {
                                        Log(key.KeyName + " = " + key.DriverValueName +
                                            (showLocationCodeInfo ? " (" + key.LocationCode + ")" : string.Empty));
                                    }
                                    foundKey = true;
                                }
                            }
                        }
                    }
                }
                break;
                }
            }

            KeyboardDeviceManager.StopListener();
        }
Пример #29
0
        public void SetUp()
        {
            _mockLog = new Mock <ILog>();

            _logger = new CommandLogger(_mockLog.Object);
        }
Пример #30
0
        public void Multiple_contexts_running_concurrently_can_use_interception()
        {
            var loggers = new ConcurrentBag<CommandLogger>();

            const int executionCount = 5;
            ExecuteInParallel(
                () =>
                    {
                        using (var context = new BlogContextNoInit())
                        {
                            var logger = new CommandLogger(context);
                            DbInterception.Add(logger);
                            loggers.Add(logger);

                            try
                            {
                                BlogContext.DoStuff(context);
                            }
                            finally
                            {
                                DbInterception.Remove(logger);
                            }

                            var commandsUsed = new bool[Enum.GetValues(typeof(CommandMethod)).Length];

                            for (var i = 0; i < logger.Log.Count; i++)
                            {
                                var method = logger.Log[i].Method;
                                commandsUsed[(int)method] = true;

                                if (method.ToString().EndsWith("Executing"))
                                {
                                    Assert.Equal(method + 1, logger.Log[i + 1].Method);
                                    Assert.Same(logger.Log[i].Command, logger.Log[i + 1].Command);
                                }
                            }

                            // Check that expected command have log entries
                            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]);
                            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]);
                            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]);
                            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]);
#if !NET40
                            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuting]);
                            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuted]);
#endif

                            // Sanity check on command text
                            var commandTexts = logger.Log.Select(l => l.CommandText.ToLowerInvariant());
                            Assert.True(commandTexts.Any(c => c.StartsWith("select")));
                            Assert.True(commandTexts.Any(c => c.StartsWith("insert")));
#if !NET40
                            Assert.True(commandTexts.Any(c => c.StartsWith("update")));
#endif

                            // Sanity check on results
                            Assert.True(logger.Log.Where(l => l.Method == CommandMethod.NonQueryExecuted).All(l => l.Result != null));
                            Assert.True(logger.Log.Where(l => l.Method == CommandMethod.ReaderExecuted).All(l => l.Result != null));
                        }
                    }, executionCount);

            // Check that each execution logged exactly the same commands.

            Assert.Equal(executionCount, loggers.Count);

            var firstLog = loggers.First().Log;
            foreach (var log in loggers.Select(l => l.Log).Skip(1))
            {
                Assert.Equal(firstLog.Count, log.Count);

                for (var i = 0; i < log.Count; i++)
                {
                    Assert.Equal(firstLog[i].Method, log[i].Method);
                    Assert.Equal(firstLog[i].CommandText, log[i].CommandText);

                    if (firstLog[i].Result == null)
                    {
                        Assert.Null(log[i].Result);
                    }
                    else
                    {
                        Assert.Same(firstLog[i].Result.GetType(), log[i].Result.GetType());
                    }
                }
            }
        }
Пример #31
0
        private static void SicretRun()
        {
            IPEndPoint ipPoint      = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
            Socket     listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listenSocket.Bind(ipPoint);
                listenSocket.Listen(10);

                while (true)
                {
                    Socket handler = listenSocket.Accept();

                    StringBuilder builder = new StringBuilder();
                    int           bytes   = 0;
                    byte[]        data    = new byte[256];
                    Command       command = null;
                    do
                    {
                        bytes = handler.Receive(data);
                        MyMessage msg = new MyMessage();
                        msg.Data = data;

                        //command = (Command)CommadConverter.Deserialize(msg);
                        command = (Command)CommadConverter.DeSerializeToFile();

                        SaveManager saveManager = new SaveManager();
                        saveManager.SetCommand(command);
                        saveManager.Execute();

                        Mediator      mediator      = new Mediator();
                        SaveLogger    saveLogger    = new SaveLogger(mediator);
                        LoadLogger    loadLogger    = new LoadLogger(mediator);
                        CommandLogger commandLogger = new CommandLogger(mediator);
                        mediator.SetLogers(saveLogger, loadLogger, commandLogger);
                        if (command is SaveCommand)
                        {
                            saveLogger.Send(String.Format("[{0}] Game Saved.\n", DateTime.Now));
                        }
                        else
                        if (command is LoadCommand)
                        {
                            saveLogger.Send(String.Format("[{0}] Game Loaded.\n", DateTime.Now));
                        }
                        else
                        {
                            saveLogger.Send(String.Format("[{0}] {1}.\n", DateTime.Now, command.GetType().Name.ToString()));
                        }
                    }while (handler.Available > 0);


                    //string message = "200 OK";
                    //data = Encoding.Unicode.GetBytes(message);
                    //handler.Send(data);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #32
0
 private void Awake()
 {
     commandLogger = CommandLogger.singleton;
 }
Пример #33
0
 public override void Action()
 {
     Console.WriteLine(Description + " - pinging...");
     (new Thread(() => Console.Beep(500, 1000))).Start();
     CommandLogger.SaveToFile(this);
 }
Пример #34
0
 private void Start()
 {
     mainCamera    = Camera.main;
     commandLogger = CommandLogger.singleton;
 }