Example #1
0
        protected virtual bool Login(bool goToConfigLink = true)
        {
            defaultWait.Until(driver => driver.Navigate()).GoToUrl(EduLink);
            firstLoad.Until(driver => driver.Url.Contains(EDU_URI));

            bool loadedCookies = LoadCookies(CookiesPath);

            logger?.Debug("Loaded {0}: {1}", CookiesPath, loadedCookies);

            driver.Navigate().GoToUrl(LoginLink);

            //TODO Replace with factory method
            bool firefox = config.Driver.Browser == "firefox";

            // if(firefox) checks:
            //   firefox can't insert google classroom cookies into edu.google.com
            try
            {
                bool loggedIn = false;
                if (!loadedCookies)
                {
                    loggedIn = userWait.Until(driver =>
                    {
                        logger.Trace($"Matching {driver.Url} against {ClassroomLink}");
                        return(driver.Url.Contains(ClassroomLink));
                    });
                    if (loggedIn)
                    {
                        driver.Navigate().GoToUrl(EduLink);

                        // Save edu.google.com cookies insted of classroom's
                        /*if (firefox)*/
                        firstLoad.Until(driver => driver.Url.Contains(EDU_URI));

                        SaveCookies(driver.Manage().Cookies.AllCookies, CookiesPath);
                    }
                }
                else
                {
                    loggedIn = firstLoad.Until(driver =>
                    {
                        return(driver.Url.Contains(ClassroomLink));
                    });
                }
                if (loggedIn && goToConfigLink)
                {
                    GoHome();
                }
                return(loggedIn);
            }
            catch (WebDriverTimeoutException ex)
            {
                logger.Error("Timed out", ex);
            }
            return(false);
        }
Example #2
0
        static void Main(string[] args)
        {
            SetupLogger();
            FullConfig?config = GetConfig();

            if (config == null)
            {
                return;
            }

            CancellationTokenSource source = new();

            Classroom classroom = new Classroom(config, source.Token);
            Meet?     meet      = null;

            try
            {
                meet = classroom.InitMeetInstance(source.Token);
                logger?.Debug("Starting classroom");
                Task crTask = classroom.Start();
                logger?.Debug("Starting meet");
                Task meetTask = meet.Start();
                logger?.Debug("Started all");
                Console.ReadLine();
                source.Cancel();
                Task.WaitAll(crTask, meetTask);
            }
            catch (AggregateException ex)
            {
                if (ex.InnerException is TaskCanceledException)
                {
                    logger?.Info("Successfully canceled");
                }
                else
                {
                    logger?.Error(ex);
                }
            }
            catch (Exception ex)
            {
                logger?.Error(ex);
            }
            finally
            {
                source.Dispose();
                meet?.Dispose();
                classroom.Dispose();
            }
        }
Example #3
0
 public WebHost(IRootPathProvider rootPathProvider, Func<NancyContext> getContext)
 {
   this.rootPathProvider = rootPathProvider;
   this.getContext = getContext;
   this.logger = NLog.LogManager.GetCurrentClassLogger();
   logger.Debug("WebHost.ctor: constructed!");
 }
Example #4
0
        private async Task MeetLoop()
        {
            try
            {
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        logger?.Debug("Succesfully canceled");
                        break;
                    }
                    string?teacher = activeMessage?.Teacher;
                    string?link    = GetLink(activeMessage);
                    logger?.Debug("Got teacher {0}", teacher);
                    // No entry until right message
                    while (link == null && activeMessage != null)
                    {
                        // Wait for lastMessage update
                        while (teacher == activeMessage.Teacher)
                        {
                            await Task.Delay(new TimeSpan(0, 0, 1), token);
                        }

                        link = GetLink(activeMessage);

                        teacher = activeMessage.Teacher;
                    }
                    logger?.Debug("Got link {0}", link);

                    if (link == null)
                    {
                        logger?.Debug("Link is null");
                    }

                    await TryEnterMeet(link);

                    await Task.Delay(new TimeSpan(0, 0, seconds : 30), token);
                }
            }
            catch (TaskCanceledException)
            {
                logger.Debug("Successfully canceled");
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
Example #5
0
        public static Environment Load(string path)
        {
            try {
                logger.Trace($"Loading Environment '{path}'.");

                if (!IsEnvironment(path))
                {
                    throw new Exception($"Environment '{path}' does not exist.");
                }

                var ef  = Path.Combine(path, ENVROOTFILE);
                var env = IEntityExtensions.Deserialize <Environment>(ef);

                var uf = Path.Combine(path, AUTHDBFILE);
                if (File.Exists(uf))
                {
                    var other = AuthDB.Load(uf);
                    env.AuthDB.Merge(other);
                }

                for (var i = env.Auths.Length - 1; i >= 0; --i)
                {
                    var impPath = env.Auths[i].GetRootedPath(path);
                    var other   = AuthDB.Load(impPath);
                    env.AuthDB.Merge(other);
                }

                var inext = env.Imports.Length;
                for (var i = 0; i < env.Imports.Length; ++i)
                {
                    var imp = env.Imports[i];

                    if (!String.IsNullOrEmpty(imp.After))
                    {
                        inext = i;
                        break;
                    }

                    var impPath = imp.GetRootedPath(path);
                    env.Import(impPath, imp.After, imp.WithAuth);
                }

                foreach (var f in Directory.EnumerateFiles(path, "*.xml"))
                {
                    var fn = Path.GetFileName(f);
                    if (Strings.IsReserved(fn[0]))
                    {
                        continue;
                    }

                    var fw = Framework.Load(f);
                    env.Merge(fw, fw.After);
                }

                for (var i = inext; i < env.Imports.Length; ++i)
                {
                    var imp     = env.Imports[i];
                    var impPath = imp.GetRootedPath(path);
                    env.Import(impPath, imp.After.IfNull(LAST), imp.WithAuth);
                }

                try {
                    var hse = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                    var hsa = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                    foreach (var f in env.frameworks)
                    {
                        foreach (var ev in f.EVars)
                        {
                            if (!hse.Add(ev.Name))
                            {
                                throw new ValidationException($"Environment variable '{ev.Name}' is duplicated.");
                            }
                        }
                        foreach (var ai in f.Addins)
                        {
                            if (!hsa.Add(ai.QFileName))
                            {
                                throw new ValidationException($"Addin '{ai.QFileName}' is duplicated.");
                            }
                        }
                        foreach (var b in f.Boxes)
                        {
                            foreach (var c in b.Controls)
                            {
                                c.SetParent(f);
                            }
                        }
                    }
                }
                catch (ValidationException vex) {
                    vex.Parents.Add($"Environment => {env.Name}");
                    throw;
                }

                return(env);
            }
            catch (Exception ex) {
                if (!(ex is ValidationException vex))
                {
                    logger.Debug(ex, $"Error loading Environment '{path}'");
                    vex = new ValidationException($"{ex.Message}", ex);
                }
                vex.Parents.Add(path);
                throw vex;
            }
        }
Example #6
0
        private static void Main(string[] args)
        {
            // Need to reset the Working directory, since when we called via the Explorer Context menu, it'll be different
            Directory.SetCurrentDirectory(Application.StartupPath);

            // Add our Bin and Bin\Bass Directory to the Path
            SetPath(Path.Combine(Application.StartupPath, "Bin"));
            SetPath(Path.Combine(Application.StartupPath, @"Bin\Bass"));

            _portable      = 0;
            _startupFolder = "";
            // Process Command line Arguments
            foreach (string arg in args)
            {
                if (arg.ToLower().StartsWith("/folder="))
                {
                    _startupFolder = arg.Substring(8);
                }
                else if (arg.ToLower() == "/portable")
                {
                    _portable = 1;
                }
            }

            try
            {
                // Let's see, if we already have an instance of MPTagThat open
                using (var mmf = MemoryMappedFile.OpenExisting("MPTagThat"))
                {
                    if (_startupFolder == string.Empty)
                    {
                        // Don't allow a second instance of MPTagThat running
                        return;
                    }

                    byte[] buffer            = Encoding.Default.GetBytes(_startupFolder);
                    var    messageWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "MPTagThat_IPC");

                    // Create accessor to MMF
                    using (var accessor = mmf.CreateViewAccessor(0, buffer.Length))
                    {
                        // Write to MMF
                        accessor.WriteArray <byte>(0, buffer, 0, buffer.Length);
                        messageWaitHandle.Set();

                        // End exit this instance
                        return;
                    }
                }
            }
            catch (FileNotFoundException)
            {
                // The Memorymap does not exist, so MPTagThat is not yet running
            }

            // Read the Config file
            ReadConfig();

            // Register Bass
            BassRegistration.BassRegistration.Register();

            using (new ServiceScope(true))
            {
                ILogger logger = new FileLogger("MPTagThat.log", NLog.LogLevel.Debug, _portable);
                ServiceScope.Add(logger);

                NLog.Logger log = ServiceScope.Get <ILogger>().GetLogger;

                log.Info("MPTagThat is starting...");

                log.Info("Registering Services");
                log.Debug("Registering Settings Manager");
                ServiceScope.Add <ISettingsManager>(new SettingsManager());
                // Set the portable Indicator
                ServiceScope.Get <ISettingsManager>().SetPortable(_portable);
                // Set the Max Songs number
                ServiceScope.Get <ISettingsManager>().SetMaxSongs(_maxSongs);

                try
                {
                    logger.Level = NLog.LogLevel.FromString(Options.MainSettings.DebugLevel);
                }
                catch (ArgumentException)
                {
                    Options.MainSettings.DebugLevel = "Info";
                    logger.Level = NLog.LogLevel.FromString(Options.MainSettings.DebugLevel);
                }

                log.Debug("Registering Localisation Services");
                ServiceScope.Add <ILocalisation>(new StringManager());

                log.Debug("Registering Message Broker");
                ServiceScope.Add <IMessageBroker>(new MessageBroker());

                log.Debug("Registering Theme Manager");
                ServiceScope.Add <IThemeManager>(new ThemeManager());

                log.Debug("Registering Action Handler");
                ServiceScope.Add <IActionHandler>(new ActionHandler());

                // Move Init of Services, which we don't need immediately to a separate thread to increase startup performance
                Thread initService = new Thread(DoInitService);
                initService.IsBackground = true;
                initService.Name         = "InitService";
                initService.Start();

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                try
                {
                    _main = new Main();

                    // Set the Startup Folder we might have received via an argument, before invoking the form
                    _main.CurrentDirectory = _startupFolder;
                    Application.Run(_main);
                }
                catch (OutOfMemoryException)
                {
                    GC.Collect();
                    MessageBox.Show(ServiceScope.Get <ILocalisation>().ToString("message", "OutOfMemory"),
                                    ServiceScope.Get <ILocalisation>().ToString("message", "Error_Title"), MessageBoxButtons.OK);
                    log.Error("Running out of memory. Scanning aborted.");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ServiceScope.Get <ILocalisation>().ToString("message", "FatalError"),
                                    ServiceScope.Get <ILocalisation>().ToString("message", "Error_Title"), MessageBoxButtons.OK);
                    log.Error("Fatal Exception: {0}\r\n{1}", ex.Message, ex.StackTrace);
                }
            }
        }
Example #7
0
        public Recorder(RecorderView view)
        {
            this.view = view;
            view.recorder = this;

            /////////// Setup logger ///////////
            logger = NLog.LogManager.GetCurrentClassLogger();
            loggerWCF = NLog.LogManager.GetLogger("Capture.Recorder.WCF");

            /////////// Setup WCF notification to a BriefMaker ///////////
            briefMakerClient = new BriefMakerServiceReference.BriefMakerClient();

            /////////// Download Symbols ///////////
            try
            {
                logger.Debug("Downloading symbols");
                var dbSymbols = from s in dc.Symbols select s;

                foreach (var s in dbSymbols)
                {
                    if (String.IsNullOrWhiteSpace(s.Name))
                    {
                        logger.Error("SymbolID:" + s.SymbolID + " does not have a name(symbol). Item will be skipped.");
                        continue;
                    }
                    if (s.SymbolID > 255 || s.SymbolID < 0)
                    {
                        logger.Error("SymbolID:" + s.SymbolID + " range is not valid. Supported(0-255). Item will be skipped.");
                        continue;
                    }

                    SecurityType secType = s.Type.Trim() == "STK" ? SecurityType.Stock : SecurityType.Index;
                    string market = s.Market.Trim();

                    var new_symb = new MarketSymbol()
                    {
                        SymbolID = s.SymbolID,
                        Symbol = s.Name.Trim(),
                        securityType = s.Type.Trim() == "STK" ? SecurityType.Stock : SecurityType.Index,
                        Market = s.Market
                    };
                    symbols.Add(new_symb);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Database Exception: " + ex.Message);
                logger.Error("Make sure that the connection string is set correctly in app.config.");
                Thread.Sleep(5000);
                ShutdownRecorder();
            }


            // Setup BinaryWriters
            logger.Debug("Downloading symbols");
            capturingWriter = new BinaryWriter(new MemoryStream(MemoryStreamReserveSpace));
            capturingWriter.Write((long)0);  // leave some space at the beginning for time later
            manufacturedWriterForFuture = new BinaryWriter(new MemoryStream(MemoryStreamReserveSpace));
            manufacturedWriterForFuture.Write((long)0);  // leave some space at the beginning for time later

            // Run this thread will a little higher priority since it is dealing with real-time information.
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            // Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;

            view.timer.Tick += new EventHandler(timer1Sec_Tick);


            while (true)
            {
                TimeSpan timespan = new TimeSpan(DateTime.Now.Ticks - lastRecievedUpdate.Ticks);
                if (timespan.Seconds > 30)
                {
                    logger.Info("No Data received in over 30 seconds. Requesting Reconnect...");
                    lastRecievedUpdate = DateTime.Now;
                    ConnectToIB();
                }

                if (terminateRequested || (DateTime.Now.TimeOfDay > settings.ShutDownTime))
                {
                    logger.Info("Close requested or automatic end of day shutdown.");
                    ShutdownRecorder();
                    break;
                }

                view.BeginInvoke((MethodInvoker)delegate
                {
                    view.toolStripStatusLabelEventCt.Text = totalCaptureEventsForDisplay.ToString() + " (" + (totalCaptureEventsForDisplay - lastTotalCaptureEventsForDisplay).ToString() + "/sec)";  // runs on UI thread 
                    lastTotalCaptureEventsForDisplay = totalCaptureEventsForDisplay;
                    view.toolStripStatusLabelLastBrfID.Text = lastUpdateTime.ToString();
                });  // runs on UI thread 

                Thread.Sleep(1000);
            }
        }
Example #8
0
        /// <summary>
        /// Looks for newer versions of the software than the currently known version.
        /// </summary>
        /// <returns>Returns an AvailableSoftware instance with the information
        /// that was retrieved from the net.</returns>
        public override AvailableSoftware searchForNewer()
        {
            logger.Debug("Searching for newer version of CMake...");
            // Just getting the latest release does not work here, because that may also be a release candidate, and we do not want that.
            string html;

            using (var client = new WebClient())
            {
                try
                {
                    html = client.DownloadString("https://github.com/Kitware/CMake/releases");
                }
                catch (Exception ex)
                {
                    logger.Warn("Exception occurred while checking for newer version of CMake: " + ex.Message);
                    return(null);
                }
            }

            // HTML text will contain links to releases like "https://github.com/Kitware/CMake/releases/tag/v3.19.4".
            Regex reVersion      = new Regex("CMake/releases/tag/v([0-9]+\\.[0-9]+\\.[0-9])\"");
            var   matchesVersion = reVersion.Matches(html);

            if (matchesVersion.Count == 0)
            {
                return(null);
            }
            var versions = new List <Triple>(matchesVersion.Count);

            foreach (Match item in matchesVersion)
            {
                versions.Add(new Triple(item.Groups[1].Value));
            }
            versions.Sort();
            string currentVersion = versions[versions.Count - 1].full();

            // download checksum file, e.g. "https://github.com/Kitware/CMake/releases/download/v3.19.4/cmake-3.19.4-SHA-256.txt"
            string htmlCode = null;

            using (var client = new WebClient())
            {
                try
                {
                    htmlCode = client.DownloadString("https://github.com/Kitware/CMake/releases/download/v" + currentVersion + "/cmake-" + currentVersion + "-SHA-256.txt");
                }
                catch (Exception ex)
                {
                    logger.Warn("Exception occurred while checking for newer version of CMake: " + ex.Message);
                    return(null);
                }
                client.Dispose();
            } // using

            // find SHA256 hash for 32 bit installer
            Regex reHash    = new Regex("[a-f0-9]{64}  cmake.+windows\\-i386\\.msi");
            Match matchHash = reHash.Match(htmlCode);

            if (!matchHash.Success)
            {
                return(null);
            }
            string newHash32Bit = matchHash.Value.Substring(0, 64);

            // find SHA256 hash for 64 bit installer
            reHash    = new Regex("[a-f0-9]{64}  cmake.+windows\\-x86_64\\.msi");
            matchHash = reHash.Match(htmlCode);
            if (!matchHash.Success)
            {
                return(null);
            }
            string newHash64Bit = matchHash.Value.Substring(0, 64);
            // construct new information
            var newInfo = knownInfo();

            newInfo.newestVersion = currentVersion;
            // e. g. https://github.com/Kitware/CMake/releases/download/v3.19.4/cmake-3.19.4-win32-x86.msi (until 3.19.8)
            //    or https://github.com/Kitware/CMake/releases/download/v3.20.2/cmake-3.20.2-windows-i386.msi (since 3.20.0)
            newInfo.install32Bit.downloadUrl = "https://github.com/Kitware/CMake/releases/download/v" + currentVersion + "/cmake-" + currentVersion + "-windows-i386.msi";
            newInfo.install32Bit.checksum    = newHash32Bit;
            // e. g. https://github.com/Kitware/CMake/releases/download/v3.19.4/cmake-3.19.4-win64-x64.msi (until 3.19.8)
            //    or https://github.com/Kitware/CMake/releases/download/v3.20.1/cmake-3.20.1-windows-x86_64.msi (since 3.20.0)
            newInfo.install64Bit.downloadUrl = "https://github.com/Kitware/CMake/releases/download/v" + currentVersion + "/cmake-" + currentVersion + "-windows-x86_64.msi";
            newInfo.install64Bit.checksum    = newHash64Bit;
            return(newInfo);
        }
Example #9
0
 public UserClaimsController(BaseIUOW uow)
 {
     _logger.Debug("InstanceId: " + _instanceId);
     _uow = uow;
 }
Example #10
0
 /// <summary>
 /// 调试信息
 /// </summary>
 /// <param name="message"></param>
 /// <param name="exception"></param>
 public static void Debug(string message, Exception exception = null)
 {
     logger.Debug(message);
 }
Example #11
0
 public static void Debug(string msg, params object[] args)
 {
     logger.Debug(msg, args);
 }
        public void RequestSubDirs(TreeViewFolderBrowserHelper helper, TreeNodePath parent, TreeViewCancelEventArgs e)
        {
            if (parent.Path == null)
            {
                return;
            }

            if (parent.Path == "")
            {
                rootFolder = RootFolder.None;
            }

            string sql             = string.Empty;
            bool   createDummyNode = true;
            string nodeTag;

            // We have a Special folder, when we are at the root level
            if (parent.IsSpecialFolder)
            {
                rootFolder = RootFolder.None;
            }

            if (rootFolder == RootFolder.None)
            {
                switch ((string)parent.Tag)
                {
                case "artist":
                    rootFolder = RootFolder.Artist;
                    sql        = SQL_STMT_ARTIST;
                    break;

                case "albumartist":
                    rootFolder = RootFolder.AlbumArtist;
                    sql        = SQL_STMT_ALBUMARTIST;
                    break;

                case "album":
                    rootFolder      = RootFolder.Album;
                    sql             = SQL_STMT_ALBUM;
                    createDummyNode = false;
                    break;

                case "genre":
                    rootFolder = RootFolder.Genre;
                    sql        = SQL_STMT_GENRE;
                    break;
                }
            }
            else if (rootFolder == RootFolder.Artist)
            {
                sql             = string.Format(SQL_STMT_ARTISTSEARCH, Util.RemoveInvalidChars(parent.Path));
                isRootFolder    = false;
                createDummyNode = false;
            }
            else if (rootFolder == RootFolder.AlbumArtist)
            {
                sql             = string.Format(SQL_STMT_ALBUMARTISTSEARCH, Util.RemoveInvalidChars(parent.Path));
                isRootFolder    = false;
                createDummyNode = false;
            }
            else if (rootFolder == RootFolder.Genre)
            {
                isRootFolder = false;
                string[] searchString = (parent.Tag as string).Split('\\');
                if (searchString.GetLength(0) == 2)
                {
                    sql             = string.Format(SQL_STMT_GENREARTISTSEARCH, Util.RemoveInvalidChars(parent.Path));
                    createDummyNode = true;
                }
                else
                {
                    sql = string.Format(SQL_STMT_GENREARTISTALBUMSEARCH, Util.RemoveInvalidChars(searchString[1]),
                                        Util.RemoveInvalidChars(parent.Path));
                    createDummyNode = false;
                }
            }

            string connection = string.Format(@"Data Source={0}", Options.MainSettings.MediaPortalDatabase);

            try
            {
                SQLiteConnection conn = new SQLiteConnection(connection);
                conn.Open();
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    cmd.Connection  = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = sql;
                    log.Debug("TreeViewBrowser: Executing sql: {0}", sql);
                    using (SQLiteDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            string       dbValue = reader.GetString(0);
                            TreeNodePath newNode = CreateTreeNode(helper, dbValue, dbValue, createDummyNode, false, false);
                            if (isRootFolder)
                            {
                                nodeTag = (string)parent.Tag;
                            }
                            else
                            {
                                nodeTag = string.Format(@"{0}\{1}", parent.Tag, dbValue);
                            }
                            newNode.Tag = nodeTag;
                            parent.Nodes.Add(newNode);
                        }
                    }
                }
                conn.Close();
            }
            catch (Exception ex)
            {
                log.Error("TreeViewBrowser: Error executing sql: {0}", ex.Message);
            }
        }
Example #13
0
        public static void Run(Options opts)
        {
            logger.Info("Starting...");

            var DetectedGame = opts.Game;
            var GameFolder   = opts.GamePath;
            var UseLocators  = true;

            if (GameFolder == null)
            {
                GameFolder = Environment.CurrentDirectory;
            }

            foreach (var gameDef in GameDefinition.All)
            {
                if (gameDef.Probe(GameFolder))
                {
                    DetectedGame = gameDef.Game;
                    UseLocators  = false;
                }
            }

            var definition = GameDefinition.FromGame(DetectedGame);
            GameInstallation installation;

            if (UseLocators)
            {
                installation = GameInstallation
                               .FindAll(new[] { definition })
                               .FirstOrDefault();
            }
            else
            {
                installation = new GameInstallation(definition, GameFolder);
            }

            if (installation == null)
            {
                Console.WriteLine($"OpenSAGE was unable to find any installations of {definition.DisplayName}.\n");

                Console.WriteLine("You can manually specify the installation path by setting the following environment variable:");
                Console.WriteLine($"\t{definition.Identifier.ToUpper()}_PATH=<installation path>\n");

                Console.WriteLine("OpenSAGE doesn't yet detect every released version of every game. Please report undetected versions to our GitHub page:");
                Console.WriteLine("\thttps://github.com/OpenSAGE/OpenSAGE/issues");

                Console.WriteLine("\n\n Press any key to exit.");

                Console.ReadLine();

                Environment.Exit(1);
            }

            logger.Debug($"Have installation of {definition.DisplayName}");

            Platform.Start();

            var traceEnabled = !string.IsNullOrEmpty(opts.TraceFile);

            if (traceEnabled)
            {
                GameTrace.Start(opts.TraceFile);
            }

            // TODO: Read game version from assembly metadata or .git folder
            // TODO: Set window icon.
            var config = new Configuration()
            {
                UseFullscreen  = opts.Fullscreen,
                UseRenderDoc   = opts.RenderDoc,
                LoadShellMap   = !opts.NoShellmap,
                UseUniquePorts = opts.UseUniquePorts
            };

            UPnP.InitializeAsync(TimeSpan.FromSeconds(10)).ContinueWith(_ => logger.Info($"UPnP status: {UPnP.Status}"));

            logger.Debug($"Have configuration");

            using (var game = new Game(installation, opts.Renderer, config))
            {
                game.GraphicsDevice.SyncToVerticalBlank = !opts.DisableVsync;

                game.DeveloperModeEnabled = opts.DeveloperMode;

                if (opts.DeveloperMode)
                {
                    game.Window.Maximized = true;
                }

                if (opts.ReplayFile != null)
                {
                    var replayFile = game.ContentManager.UserDataFileSystem?.GetFile(Path.Combine("Replays", opts.ReplayFile));
                    if (replayFile == null)
                    {
                        logger.Debug("Could not find entry for Replay " + opts.ReplayFile);
                        game.ShowMainMenu();
                    }

                    game.LoadReplayFile(replayFile);
                }
                else if (opts.Map != null)
                {
                    game.Restart = StartMap;
                    StartMap();

                    void StartMap()
                    {
                        var mapCache = game.AssetStore.MapCaches.GetByName(opts.Map);

                        if (mapCache == null)
                        {
                            logger.Debug("Could not find MapCache entry for map " + opts.Map);
                            game.ShowMainMenu();
                        }
                        else if (mapCache.IsMultiplayer)
                        {
                            var pSettings = new PlayerSetting?[]
                            {
                                new PlayerSetting(null, game.AssetStore.PlayerTemplates.GetByName("FactionAmerica"), new ColorRgb(255, 0, 0), 0, PlayerOwner.Player),
                                new PlayerSetting(null, game.AssetStore.PlayerTemplates.GetByName("FactionGLA"), new ColorRgb(0, 255, 0), 0, PlayerOwner.EasyAi),
                            };

                            logger.Debug("Starting multiplayer game");

                            game.StartMultiPlayerGame(opts.Map,
                                                      new EchoConnection(),
                                                      pSettings,
                                                      0,
                                                      Environment.TickCount);
                        }
                        else
                        {
                            logger.Debug("Starting singleplayer game");

                            game.StartSinglePlayerGame(opts.Map);
                        }
                    }
                }
                else
                {
                    logger.Debug("Showing main menu");
                    game.ShowMainMenu();
                }

                logger.Debug("Starting game");

                game.Run();
            }

            if (traceEnabled)
            {
                GameTrace.Stop();
            }

            Platform.Stop();
        }
 protected override void OnError(Guid id, string error)
 {
     logger.Debug($"UserGuid={id} Error={error}");
 }
Example #15
0
        public Form1()
        {
            InitializeComponent();

            m_logger.Debug("Initializing iR SDK Wrapper");

            m_wrapper = new SdkWrapper();
            m_wrapper.SessionInfoUpdated += OnSessionInfoUpdated;
            m_wrapper.TelemetryUpdated   += OnTelemetryUpdated;

            m_logger.Debug("Starting iR SDK Wrapper");
            m_wrapper.Start();
            m_logger.Debug("Wrapper Started");

            m_tooltip.SetToolTip(nudFuelMult, "Sets the multiplier to the fuel rate used during the calculation for fuel needed.");
            m_tooltip.SetToolTip(nudLapOffset, "Adds this number of laps to the race length during fuel calculation.");
            m_tooltip.SetToolTip(cbOnlyGreen, "When enabled, only laps done in a race under green flag conditions are logged. Useful if you expect a lot of cautions.");
            m_tooltip.SetToolTip(btnEnableAutoFuel, "If enabled, will automatically set the pitstop fuel amount when you cross the yellow cones.\nIf disabled, will only monitor.");
            m_tooltip.SetToolTip(cbUnits, "Selects which units to use when displaying and calculating fuel. Automatic will try to use what the game does.");

            OpenConfig();

            if (cbUnits.SelectedIndex == -1)
            {
                cbUnits.SelectedIndex = 0;
            }

            UpdateLabels();
        }
Example #16
0
        /// <summary>
        /// Gets a security token from the federation server.
        /// </summary>
        /// <returns>
        /// The security token, which is basically a JWT token string.
        /// </returns>
        private SecurityTokenAdapter GetSecurityTokenFromServer()
        {
            logger.Info("Getting security token from the auth server");

            var keyPair = sessionKeySupplier.GetKeyPair();

            if (keyPair == null)
            {
                throw new InvalidOperationException("Keypair is not generated, it is null");
            }

            var publicKey = (RsaKeyParameters)keyPair.Public;

            if (publicKey == null)
            {
                throw new InvalidOperationException("Public key is missing in the key pair");
            }

            string publicKeyDerBase64 = null;

            try
            {
                byte[] publicKeyDer = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey).GetDerEncoded();
                publicKeyDerBase64 = Convert.ToBase64String(publicKeyDer);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Failed to convert public key from RsaKeyParameters type to string type", e);
            }

            var certificateAndKeyPair = leafCertificateSupplier.GetCertificateAndKeyPair();

            if (certificateAndKeyPair == null)
            {
                throw new InvalidOperationException("Certificate and key pair are not present");
            }

            var leafCertificate = certificateAndKeyPair.Certificate;

            if (leafCertificate == null)
            {
                throw new InvalidOperationException("Leaf certificate is not present");
            }

            if (certificateAndKeyPair.PrivateKey == null)
            {
                throw new InvalidOperationException("Leaf certificate's private key is missing");
            }

            HashSet <string> intermediateStrings = null;

            if (intermediateCertificateSuppliers != null &&
                intermediateCertificateSuppliers.Count > 0)
            {
                logger.Debug("Intermediate certificate(s) were supplied");

                intermediateStrings = new HashSet <string>();
                foreach (var supplier in intermediateCertificateSuppliers)
                {
                    var supplierCertificateAndKeyPair = supplier.GetCertificateAndKeyPair();
                    if (supplierCertificateAndKeyPair != null &&
                        supplierCertificateAndKeyPair.Certificate != null)
                    {
                        intermediateStrings.Add(Convert.ToBase64String(supplierCertificateAndKeyPair.Certificate.RawData));
                    }
                }
            }

            // create request body to be sent to the auth service
            var url            = this.federationEndpoint + Constants.AUTH_SERVICE_PATH;
            var requestBody    = new X509FederationRequest(publicKeyDerBase64, Convert.ToBase64String(leafCertificate.RawData), intermediateStrings, purpose);
            var httpRequestMsg = new HttpRequestMessage(HttpMethod.Post, new Uri(url));

            httpRequestMsg.Content = ContentHelper.CreateHttpContent(requestBody);

            var keyId = this.tenancyId + Constants.FED_KEY_PATH + AuthUtils.GetFingerPrint(leafCertificate.Thumbprint);

            if (FederationSigner == null)
            {
                FederationSigner = new FederationRequestSigner((RsaKeyParameters)certificateAndKeyPair.PrivateKey, keyId);
            }
            FederationSigner.SignRequest(httpRequestMsg);
            var requestContent = httpRequestMsg.Content.ReadAsStringAsync().Result;

            logger.Debug($"request content to Auth service is {requestContent}");

            HttpResponseMessage response = null;

            try
            {
                if (Client == null)
                {
                    Client = new HttpClient();
                }
                for (int retry = 0; retry < Constants.RETRIES; retry++)
                {
                    response = Client.SendAsync(httpRequestMsg).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        break;
                    }
                    Thread.Sleep(Constants.RETRY_MILLIS);
                }
                if (response == null || !response.IsSuccessStatusCode)
                {
                    logger.Debug("Received non successful response while trying to get the AUTH token");
                    ResponseHelper.HandleNonSuccessfulResponse(response);
                }
            }
            finally
            {
                Client.Dispose();
                Client = null;
            }

            var securityTokenContent = response.Content.ReadAsStringAsync().Result;
            var securityToken        = JsonConvert.DeserializeObject <SecurityToken>(securityTokenContent);

            logger.Info($"Security Token received from the Auth Service");
            return(new SecurityTokenAdapter(securityToken.Token));
        }
Example #17
0
        void Log(LogItem item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (item.LogException != null)
            {
                switch (item.Level)
                {
                case LogLevel.Fatal:
                    _logger.FatalException(item.Text, item.LogException);
                    break;

                case LogLevel.Error:
                    _logger.ErrorException(item.Text, item.LogException);
                    break;

                case LogLevel.Warn:
                    _logger.WarnException(item.Text, item.LogException);
                    break;

                case LogLevel.Info:
                    _logger.InfoException(item.Text, item.LogException);
                    break;

                case LogLevel.Debug:
                    _logger.DebugException(item.Text, item.LogException);
                    break;

                default:
                    _logger.InfoException(item.Text, item.LogException);
                    break;
                }
            }
            else
            {
                switch (item.Level)
                {
                case LogLevel.Fatal:
                    _logger.Fatal(item.Text);
                    break;

                case LogLevel.Error:
                    _logger.Error(item.Text);
                    break;

                case LogLevel.Warn:
                    _logger.Warn(item.Text);
                    break;

                case LogLevel.Info:
                    _logger.Info(item.Text);
                    break;

                case LogLevel.Debug:
                    _logger.Debug(item.Text);
                    break;

                default:
                    _logger.Info(item.Text);
                    break;
                }
            }
        }
Example #18
0
        public void Notify(string destination, List <EventItem> events)
        {
            try
            {
                LogNotify(destination, events);
                string[] specificChannelKeywords = new[] { "camera", "cam", "c", "picture", "pic", "p", "channel", "ch", "กล้อง" };

                string[]   interestEventTypes = new string[] { "follow", "message" };
                LineClient client             = new LineClient(_accessToken);
                foreach (var ev in events)
                {
                    if (!interestEventTypes.Contains(ev.type))
                    {
                        continue;
                    }
                    if (ev.source != null && ev.source.type == "user")
                    {
                        if (ev.message != null)
                        {
                            if (ev.message.type == "text")
                            {
                                var validCommand = false;
                                var comandBlocks = ev.message.text.Split(new char[] { ' ' });
                                if (comandBlocks.Length == 2)
                                {
                                    var key       = comandBlocks[0].Trim().ToLower();
                                    var channel   = comandBlocks[1].Trim();
                                    int channelId = 0;
                                    if (specificChannelKeywords.Contains(key) && int.TryParse(channel, out channelId))
                                    {
                                        _logger.Debug(string.Format("process-capture-command>> channel: {0}, mId:{1}", channelId, ev.message.id));
                                        var camera = GetCameraInfo(channelId);
                                        if (camera != null)
                                        {
                                            var imageUrl = GetCameraImage(camera.StillImageUrl, camera.UserName, camera.Password);
                                            if (!string.IsNullOrEmpty(imageUrl))
                                            {
                                                client.AddMessageQueue(new SendMessageItem
                                                {
                                                    type = "image",
                                                    originalContentUrl = imageUrl,
                                                    previewImageUrl    = imageUrl,
                                                });
                                                var replyRes = client.ReplyToUser(ev.replyToken);
                                                validCommand = true;
                                                _logger.Debug("reply-image>>" + imageUrl + ", res:" + replyRes.Success.ToString() + ", msg:" + replyRes.Message);
                                            }
                                        }
                                    }
                                }

                                if (!validCommand)
                                {
                                    client.AddMessageQueue(new SendMessageItem
                                    {
                                        type = "text",
                                        text = "คำสังไม่ถูกต้อง หรือไม่พบช่องที่ระบุ กรุณาลองใหม่อีกครั้ง"
                                    });

                                    var replyRes = client.ReplyToUser(ev.replyToken);
                                    _logger.Debug("reply-invalid message>> " + ev.message.text + ", res:" + replyRes.Success.ToString() + ", msg:" + replyRes.Message);
                                }
                            }
                        }
                        else if (ev.type == "follow")
                        {
                            client.AddMessageQueue(new SendMessageItem
                            {
                                type = "text",
                                text = "ยินดีต้อนรับเข้าสู่ระบบดูภาพนิ่งจากกล้องผ่าน LINE\r\nคุณสามารถพิมพ์คำสั่งเพื่อดูกล้องได้ดังนี้\r\n\r\ncam [เลขที่]\r\ncamera [เลขที่]\r\npic [เลขที่]\r\npicture [เลขที่]"
                            });

                            var replyRes = client.ReplyToUser(ev.replyToken);
                            _logger.Debug("reply-greeting message>> res:" + replyRes.Success.ToString() + ", msg:" + replyRes.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Notify-incoming:" + "des:" + destination + ", error:" + ex.Message);
            }
        }
        private void btnApply_Click(object sender, EventArgs e)
        {
            saveSettings();
            gcode.setup(false);                                         // load defaults from setup-tab
            gcode.gcodeXYFeed       = (float)nUDToolFeedXY.Value;       // override devault values
            gcode.gcodeZFeed        = (float)nUDToolFeedZ.Value;        // override devault values
            gcode.gcodeSpindleSpeed = (float)nUDToolSpindleSpeed.Value; // override devault values
            gcode.gcodeZDown        = (float)nUDImportGCZDown.Value;
            gcodeTangEnable         = Properties.Settings.Default.importGCTangentialEnable;

            Logger.Debug("Create GCode {0}", gcode.getSettings());

            gcodeString.Clear();

            gcode.Tool(gcodeString, tprop.toolnr, tprop.name);
            //       if (!Properties.Settings.Default.importGCSpindleToggle) gcode.SpindleOn(gcodeString, "Start");

            float x, y, rShape, d, dTool, overlap, rTool, zStep;
            float zStart = 0;

            x       = (float)nUDShapeX.Value;
            y       = (float)nUDShapeY.Value;
            rShape  = (float)nUDShapeR.Value;
            d       = 2 * rShape;
            dTool   = (float)nUDToolDiameter.Value;              // tool diameter;
            overlap = dTool * (float)nUDToolOverlap.Value / 100; // tool overlap
            if (rBToolpath1.Checked)
            {
                dTool = 0;
            }                                                   // engrave
            if (rBToolpath3.Checked)
            {
                dTool = -dTool;
            }                                                   // outside
            rTool = dTool / 2;                                  // tool radius

            int   counter = 0, safety = 100;
            int   zStepCount = 0;
            float dx = 0, dy = 0, rDelta = 0;
            int   passCount   = 0;
            int   figureCount = 1;

            gcode.jobStart(gcodeString, "StartJob");
            //    gcode.PenUp(gcodeString);

            bool inOneStep = (nUDToolZStep.Value >= -nUDImportGCZDown.Value);

            gcode.Comment(gcodeString, xmlMarker.figureStart + " Id=\"" + figureCount.ToString() + "\" >");
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            if (rBShape1.Checked)                               // rectangle
            {
                getOffset(x, y);
                offsetX -= rTool; offsetY -= rTool;
                x       += dTool; y += dTool;                   // width +/- tool diameter (outline / inline)
                zStep    = zStart;
                while (zStep > (float)nUDImportGCZDown.Value)   // nUDImportGCZDown.Value e.g. -2
                {
                    zStep -= (float)nUDToolZStep.Value;         // nUDToolZStep.Value e.g.  0.5
                    if (zStep < (float)nUDImportGCZDown.Value)
                    {
                        zStep = (float)nUDImportGCZDown.Value;
                    }

                    if ((overlap > x / 2) || (overlap > y / 2))
                    {
                        overlap = (float)(Math.Min(x, y) / 2.1);
                    }

                    //if ((zStepCount++ == 0) || !cBNoZUp.Checked)    // move up the 1st time
                    if (!(zStepCount++ == 0) && !cBNoZUp.Checked)     // move up the 1st time
                    {
                        gcode.PenUp(gcodeString);
                        if (!inOneStep)
                        {
                            gcode.Comment(gcodeString, xmlMarker.passEnd + ">");             //+ "  " + passCount.ToString() + ">");
                        }
                    }
                    passCount++;

                    if (gcodeTangEnable)
                    {
                        gcode.setTangential(gcodeString, 90, true);
                    }

                    if (!inOneStep)
                    {
                        gcode.Comment(gcodeString, string.Format("{0} Nr=\"{1}\" step=\"{2:0.000}\" final=\"{3:0.000}\">", xmlMarker.passStart, passCount, zStep, nUDImportGCZDown.Value));
                    }

                    if (cBToolpathPocket.Checked)
                    {
                        gcode.MoveToRapid(gcodeString, offsetX + overlap, offsetY + overlap, "");
                    }
                    else
                    {
                        gcode.MoveToRapid(gcodeString, offsetX, offsetY, "");
                    }
                    gcode.gcodeZDown = zStep;                               // adapt Z-deepth
                    gcode.PenDown(gcodeString);
                    if (cBToolpathPocket.Checked)                           // 1st pocket
                    {
                        if ((x > Math.Abs(dTool)) && (y > Math.Abs(dTool))) // wide enough for pocket
                        {
                            dx = overlap; dy = overlap;
                            while (((dx < x / 2) && (dy < y / 2)) && (counter++ < safety))
                            {
                                makeRect(offsetX + dx, offsetY + dy, offsetX + x - dx, offsetY + y - dy, 0, false);  // rectangle clockwise
                                dx += overlap; dy += overlap;
                                if ((dx < x / 2) && (dy < y / 2))
                                {
                                    gcode.MoveTo(gcodeString, offsetX + dx, offsetY + dy, "Pocket");
                                }
                            }
                            if (cBNoZUp.Checked)
                            {
                                gcode.MoveTo(gcodeString, offsetX, offsetY, "Pocket finish");
                            }
                            else
                            {
                                gcode.PenUp(gcodeString, "Pocket finish");
                                gcode.MoveToRapid(gcodeString, offsetX, offsetY, "Pocket finish");
                                gcode.PenDown(gcodeString);
                            }
                        }
                    }

                    makeRect(offsetX, offsetY, offsetX + x, offsetY + y, 0, true);  // final rectangle clockwise
                }
                gcode.PenUp(gcodeString);
                if (!inOneStep)
                {
                    gcode.Comment(gcodeString, xmlMarker.passEnd + ">");             //+ " " + passCount.ToString() + ">");
                }
            }
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            else if (rBShape2.Checked)           // rectangle with round edge
            {
                getOffset(x, y);
                offsetX -= rTool; offsetY -= rTool;
                x       += dTool; y += dTool;

                if ((overlap > x / 2) || (overlap > y / 2))
                {
                    overlap = (float)(Math.Min(x, y) / 2.1);
                }
                //                   gcode.Move(gcodeString, 0, offsetX, offsetY + r, false, "");
                zStep = zStart;
                while (zStep > (float)nUDImportGCZDown.Value)
                {
                    zStep -= (float)nUDToolZStep.Value;
                    if (zStep < (float)nUDImportGCZDown.Value)
                    {
                        zStep = (float)nUDImportGCZDown.Value;
                    }

                    //                    if ((zStepCount++ == 0) || !cBNoZUp.Checked)    // move up the 1st time
                    if (!(zStepCount++ == 0) && !cBNoZUp.Checked)     // move up the 1st time
                    {
                        gcode.PenUp(gcodeString);
                        if (!inOneStep)
                        {
                            gcode.Comment(gcodeString, xmlMarker.passEnd + ">");             //+ " " + passCount.ToString() + ">");
                        }
                    }
                    passCount++;

                    if (gcodeTangEnable)
                    {
                        gcode.setTangential(gcodeString, 90, true);
                    }

                    if (!inOneStep)
                    {
                        gcode.Comment(gcodeString, string.Format("{0} Nr=\"{1}\" step=\"{2:0.000}\" final=\"{3:0.000}\">", xmlMarker.passStart, passCount, zStep, nUDImportGCZDown.Value));
                    }

                    if (cBToolpathPocket.Checked)
                    {
                        gcode.MoveToRapid(gcodeString, offsetX + overlap, offsetY + rShape, "");
                    }
                    else
                    {
                        gcode.MoveToRapid(gcodeString, offsetX, offsetY + rShape, "");
                    }
                    gcode.gcodeZDown = zStep;               // adapt Z-deepth
                    gcode.PenDown(gcodeString);
                    if (cBToolpathPocket.Checked)
                    {
                        dx = overlap; dy = overlap; rDelta = rShape - overlap;
                        while (((dx < x / 2) && (dy < y / 2)) && (counter++ < safety))
                        {
                            makeRect(offsetX + dx, offsetY + dy, offsetX + x - dx, offsetY + y - dy, rDelta, false);  // rectangle clockwise
                            dx += overlap; dy += overlap; rDelta -= overlap;
                            if (dx > x / 2)
                            {
                                dx = x / 2;
                            }
                            if (dy > x / 2)
                            {
                                dy = y / 2;
                            }
                            if (rDelta < 0)
                            {
                                rDelta = 0;
                            }
                            if ((dx < x / 2) && (dy < y / 2))
                            {
                                gcode.MoveTo(gcodeString, offsetX + dx, offsetY + dy + rDelta, "");
                            }
                        }
                        if (cBNoZUp.Checked)
                        {
                            gcode.MoveTo(gcodeString, offsetX, offsetY + rShape, "");
                        }
                        else
                        {
                            gcode.PenUp(gcodeString);
                            gcode.MoveToRapid(gcodeString, offsetX, offsetY + rShape, "");
                            gcode.PenDown(gcodeString);
                        }
                    }
                    makeRect(offsetX, offsetY, offsetX + x, offsetY + y, rShape, true);  // rectangle clockwise
                }
                gcode.PenUp(gcodeString);
                if (!inOneStep)
                {
                    gcode.Comment(gcodeString, xmlMarker.passEnd + ">");             //+ " " + passCount.ToString() + ">");
                }
            }
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            else if (rBShape3.Checked)           // circle
            {
                getOffset(d, d);
                offsetX -= rTool; offsetY -= rTool;
                rShape  += rTool;                   // take care of tool diameter if set

                if (overlap > rShape)
                {
                    overlap = (float)(rShape / 2.1);
                }

                zStep = zStart;
                while (zStep > (float)nUDImportGCZDown.Value)
                {
                    //if ((zStepCount++ == 0) || !cBNoZUp.Checked)    // move up the 1st time
                    if (!(zStepCount++ == 0) && !cBNoZUp.Checked)     // move up the 1st time
                    {
                        gcode.PenUp(gcodeString);
                        if (!inOneStep)
                        {
                            gcode.Comment(gcodeString, xmlMarker.passEnd + ">");             //+ " " + passCount.ToString() + ">");
                        }
                    }
                    passCount++;

                    if (gcodeTangEnable)
                    {
                        gcode.setTangential(gcodeString, 90, true);
                    }


                    if (!inOneStep)
                    {
                        gcode.Comment(gcodeString, string.Format("{0} Nr=\"{1}\" step=\"{2:0.000}\" final=\"{3:0.000}\">", xmlMarker.passStart, passCount, zStep, nUDImportGCZDown.Value));
                    }

                    if (cBToolpathPocket.Checked)
                    {
                        gcode.MoveToRapid(gcodeString, offsetX + rShape - overlap, offsetY + rShape, "");
                    }
                    else
                    {
                        gcode.MoveToRapid(gcodeString, offsetX, offsetY + rShape, "");
                    }
                    zStep -= (float)nUDToolZStep.Value;
                    if (zStep < (float)nUDImportGCZDown.Value)
                    {
                        zStep = (float)nUDImportGCZDown.Value;
                    }
                    gcode.gcodeZDown = zStep;               // adapt Z-deepth
                    gcode.PenDown(gcodeString);
                    rDelta  = overlap;
                    counter = 0;
                    if ((cBToolpathPocket.Checked) && (rShape > 2 * rTool))
                    {
                        while ((rDelta < rShape) && (counter++ < safety))
                        {
                            gcode.setTangential(gcodeString, -270, false);  //
                            gcode.Arc(gcodeString, 2, offsetX + rShape - rDelta, offsetY + rShape, rDelta, 0, "");
                            rDelta += overlap;
                            if (rDelta < rShape)
                            {
                                gcode.MoveTo(gcodeString, offsetX + rShape - rDelta, offsetY + rShape, "");
                            }
                        }
                        gcode.MoveTo(gcodeString, offsetX, offsetY + rShape, "");
                    }
                    gcode.setTangential(gcodeString, -270, false);  //
                    gcode.Arc(gcodeString, 2, offsetX, offsetY + rShape, rShape, 0, "");
                }
                gcode.PenUp(gcodeString);
                if (!inOneStep)
                {
                    gcode.Comment(gcodeString, xmlMarker.passEnd + ">");             //+ " " + passCount.ToString() + ">");
                }
            }
            gcode.Comment(gcodeString, Graphic2GCode.SetFigureEnd(figureCount));

            gcode.jobEnd(gcodeString, "EndJob");      // Spindle / laser off
            //    if (Properties.Settings.Default.importGCZEnable)
            //         gcode.SpindleOff(gcodeString, "Finish - Spindle off");

            string header = gcode.GetHeader("Simple Shape");
            string footer = gcode.GetFooter();

            gcodeString.Replace(',', '.');
            shapegcode = header + gcodeString.ToString() + footer;
        }
Example #20
0
 public void Debug(object message)
 {
     logger.Debug(message);
 }
Example #21
0
        private async Task <HttpResponseMessage> HandleExistingAuthenticationAsync(HttpRequestMessage request, CancellationToken cancellationToken, string currentAccessToken)
        {
            request.Headers.Add("Authorization", "Bearer " + currentAccessToken);
            var response = await base.SendAsync(request, cancellationToken);

            var expired = response.Headers.Contains("X-Token-Expired");

            //test for 403 and actual bearer token in initial request
            if (response.StatusCode == HttpStatusCode.Unauthorized &&
                request.Headers.Any(d => d.Key == "Authorization" && d.Value.Any(d => d.StartsWith("Bearer"))))
            {
                Log.Trace("Found Bearer authentication and current request was unauthorized - Authenticating ...");
                try
                {
                    await Semaphore.WaitAsync(cancellationToken);

                    var authRequest = await GetAuthenticationRequestMessage(response);

                    Log.Debug("Requesting authentication response using {Url}", authRequest.RequestUri);
                    using (var authResponse = await base.SendAsync(authRequest, cancellationToken))
                    {
                        if (!authResponse.IsSuccessStatusCode)
                        {
                            Log.Error("Invalid status code {StatusCode}, Reason: {Reason}", authResponse.StatusCode, authResponse.ReasonPhrase);
                            throw new Exception(string.Format("Invalid status code {0}, Reason: {1}", authResponse.StatusCode, authResponse.ReasonPhrase));
                        }

                        var authResponseString = await authResponse.Content.ReadAsStringAsync();

                        var authResponseResult = JsonConvert.DeserializeObject <JwtAuthenticationResult>(authResponseString);

                        if (authResponseResult == null || authResponseResult.AuthenticationRequired)
                        {
                            Log.Debug("RemoteEnd forced reauthentication");
                            return(await HandleNoAuthenticationAsync(request, cancellationToken, true));
                        }

                        Log.Debug("Updating token store");
                        await AuthenticationSurface.UpdateTokenStoreAsync(authResponseResult);

                        Log.Trace("Assigning accessToken to request");
                        request.Headers.Remove("Authorization");
                        request.Headers.Add("Authorization", "Bearer " + authResponseResult.AccessToken);

                        response.Dispose();
                        // Retry with updated token
                        Log.Trace("Executing original request");
                        response = await base.SendAsync(request, cancellationToken);
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e, "Failed to handle original request");
                    throw;
                }
                finally
                {
                    Semaphore.Release();
                }
            }

            return(response);
        }
Example #22
0
        // 为所有输入文件生成vs脚本,并添加任务至TaskManager。
        private void WizardFinish(object sender, RoutedEventArgs e)
        {
            // 处理PROJECTDIR标签
            if (Constants.projectDirRegex.IsMatch(vsScript))
            {
                string[] dirTag     = Constants.projectDirRegex.Split(vsScript);
                string   projectDir = new DirectoryInfo(wizardInfo.ProjectFile).Parent.FullName;
                vsScript = dirTag[0] + dirTag[1] + "r\"" + projectDir + "\"" + dirTag[3];
            }

            string updatedVsScript = vsScript;

            // 处理MEMORY标签
            if (Constants.memoryRegex.IsMatch(updatedVsScript))
            {
                string[] memoryTag = Constants.memoryRegex.Split(updatedVsScript);
                updatedVsScript = memoryTag[0] + memoryTag[1] + eachFreeMemory.ToString() + memoryTag[3];
            }

            // 处理DEBUG标签
            if (Constants.debugRegex.IsMatch(updatedVsScript))
            {
                string[] debugTag = Constants.debugRegex.Split(updatedVsScript);
                if (debugTag.Length < 4)
                {
                    // error
                    System.Windows.MessageBox.Show("Debug标签语法错误!", "新建任务向导", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                updatedVsScript = debugTag[0] + debugTag[1] + "None" + debugTag[3];
            }

            string[] inputTemplate = Constants.inputRegex.Split(updatedVsScript);

            // 新建任务
            // 1、清理残留文件
            // 2、新建脚本文件
            // 3、新建任务参数
            Cleaner cleaner = new Cleaner();

            foreach (string inputFile in wizardInfo.InputFile)
            {
                List <TaskDetail> existing = workerManager.tm.GetTasksByInputFile(inputFile);
                bool skip = existing.Any(i => i.Progress == TaskStatus.TaskProgress.RUNNING || i.Progress == TaskStatus.TaskProgress.WAITING);

                if (skip)
                {
                    System.Windows.MessageBox.Show($"{inputFile}已经在任务列表里,将跳过处理。", $"{inputFile}已经在任务列表里", MessageBoxButton.OK, MessageBoxImage.Error);
                    continue;
                }

                // 清理文件
                cleaner.Clean(inputFile, new List <string> {
                    json.InputScript, inputFile + ".lwi"
                });

                EpisodeConfig config  = null;
                string        cfgPath = inputFile + ".json";
                FileInfo      cfgFile = new FileInfo(cfgPath);
                if (cfgFile.Exists)
                {
                    try
                    {
                        string configStr = File.ReadAllText(cfgPath);
                        config = JsonConvert.DeserializeObject <EpisodeConfig>(configStr);
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show(ex.ToString(), cfgFile.Name + "文件写错了诶", MessageBoxButton.OK, MessageBoxImage.Error);
                        continue;
                    }
                }

                // 新建vpy文件(inputname.m2ts-mmddHHMM.vpy)
                string vpy = inputTemplate[0] + inputTemplate[1] + "r\"" +
                             inputFile + "\"" + inputTemplate[3];

                string       inputSuffixPath           = inputFile.Replace(':', '_');
                const string stripCommonPathComponents = "BDBOX/BDROM/BD/BDMV/STREAM/BD_VIDEO"; // FIXME: do not hardcode this.
                string[]     strippedComponents        = stripCommonPathComponents.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var comp in strippedComponents)
                {
                    inputSuffixPath = Regex.Replace(inputSuffixPath, @"[/\\]" + Regex.Escape(comp) + @"[/\\]", "\\");
                }
                Logger.Debug("Transformed input path: " + inputSuffixPath);
                string newPath = new DirectoryInfo(wizardInfo.ProjectFile).Parent.FullName + "/" + inputSuffixPath;
                Directory.CreateDirectory(new DirectoryInfo(newPath).Parent.FullName);
                string outPath = Regex.Replace(newPath, @"[/\\]._[/\\]", "\\output\\");
                Directory.CreateDirectory(new DirectoryInfo(outPath).Parent.FullName);

                DateTime time     = DateTime.Now;
                string   fileName = newPath + "-" + time.ToString("MMddHHmm") + ".vpy";
                File.WriteAllText(fileName, vpy);

                FileInfo   finfo = new FileInfo(inputFile);
                TaskDetail td    = new TaskDetail
                {
                    TaskName  = string.IsNullOrEmpty(json.ProjectName) ? finfo.Name : json.ProjectName + "-" + finfo.Name,
                    Taskfile  = json.Clone() as TaskProfile,
                    InputFile = inputFile,
                };
                td.Taskfile.WorkingPathPrefix = newPath;
                td.Taskfile.OutputPathPrefix  = outPath;

                // 更新输入脚本和输出文件拓展名
                td.Taskfile.InputScript = fileName;
                if (config != null)
                {
                    td.Taskfile.Config = config.Clone() as EpisodeConfig;
                }
                td.UpdateOutputFileName();

                // 寻找章节
                td.ChapterStatus = ChapterService.UpdateChapterStatus(td);
                workerManager.AddTask(td);
            }
        }
Example #23
0
 public void SendKeySignature()
 {
     Log.Debug("kfd: key signature");
     Protocol.SendKeySignature();
 }
        protected AbstractServerPageStatePersister(Page page)
            : base(page)
        {
            CompressThreshold = 40960; // bytes
            Expiration        = TimeSpan.FromDays(1);

            if (IsDebugEnabled)
            {
                log.Debug("Page 상태정보를 관리하기 위해 [{0}] 인스턴스를 생성했습니다. CompressThreshold=[{1}], Expiration=[{2}] (minutes)",
                          GetType().FullName, CompressThreshold, Expiration);
            }
        }
Example #25
0
        /// <summary>
        /// Метод создаем маршруты на день основываясь на данных всесенных в поля <c>Routes</c>, <c>Orders</c>,
        /// <c>Drivers</c> и <c>Forwarders</c>.
        /// </summary>
        public void CreateRoutes()
        {
            WarningMessages.Clear();
            ProposedRoutes.Clear();             //Очищаем сразу, так как можем выйти из метода ранее.

            logger.Info("Подготавливаем заказы...");
            PerformanceHelper.StartMeasurement($"Строим оптимальные маршруты");
            MainClass.progressBarWin.ProgressStart(4);

            /// Создаем список поездок всех водителей. Тут перебираем всех водителей с машинами
            /// и создаем поездки для них, в зависимости от выбранного режима работы.
            var trips = Drivers.Where(x => x.Car != null)
                        .OrderBy(x => x.PriorityAtDay)
                        .SelectMany(x => x.DaySchedule != null
                                                                                                ? x.DaySchedule.Shifts.Select(s => new PossibleTrip(x, s))
                                                                                                : new[] { new PossibleTrip(x, null) }
                                    )
                        .ToList();

            /// Стыкуем уже созданные маршрутные листы с возможными поездками, на основании водителя и смены.
            /// Если уже созданный маршрут не найдет в поездках создаем поездку для него.
            foreach (var existRoute in Routes)
            {
                var trip = trips.FirstOrDefault(x => x.Driver == existRoute.Driver && x.Shift == existRoute.Shift);
                if (trip != null)
                {
                    trip.OldRoute = existRoute;
                }
                else
                {
                    trips.Add(new PossibleTrip(existRoute));
                }
                //Проверяем все ли заказы из МЛ присутствуют в списке заказов. Если их нет. Добавляем.
                foreach (var address in existRoute.Addresses)
                {
                    if (!Orders.Any(x => x.Id == address.Order.Id))
                    {
                        Orders.Add(address.Order);
                    }
                }
            }

            var possibleRoutes = trips.ToArray();

            if (possibleRoutes.Length == 0)
            {
                AddWarning("Для построения маршрутов, нет водителей.");
                return;
            }

            TestCars(possibleRoutes);

            var areas = UoW.GetAll <LogisticsArea>().ToList();
            List <LogisticsArea>   unusedDistricts  = new List <LogisticsArea>();
            List <CalculatedOrder> calculatedOrders = new List <CalculatedOrder>();

            /// Перебираем все заказы, исключаем те которые без координат, определяем для каждого заказа район
            /// на основании координат. И создавая экземпляр <c>CalculatedOrder</c>, происходит подсчет сумарной
            /// информации о заказа. Всего бутылей, вес и прочее.
            foreach (var order in Orders)
            {
                if (order.DeliveryPoint.Longitude == null || order.DeliveryPoint.Latitude == null)
                {
                    continue;
                }
                var point = new Point((double)order.DeliveryPoint.Latitude.Value, (double)order.DeliveryPoint.Longitude.Value);
                var aria  = areas.Find(x => x.Geometry.Contains(point));
                if (aria != null)
                {
                    var oldRoute = Routes.FirstOrDefault(r => r.Addresses.Any(a => a.Order.Id == order.Id));
                    if (oldRoute != null)
                    {
                        calculatedOrders.Add(new CalculatedOrder(order, aria, false, oldRoute));
                    }
                    else if (possibleRoutes.SelectMany(x => x.Districts).Any(x => x.District.Id == aria.Id))
                    {
                        calculatedOrders.Add(new CalculatedOrder(order, aria));
                    }
                    else if (!unusedDistricts.Contains(aria))
                    {
                        unusedDistricts.Add(aria);
                    }
                }
            }
            Nodes = calculatedOrders.ToArray();
            if (unusedDistricts.Count > 0)
            {
                AddWarning("Районы без водителей: {0}", String.Join(", ", unusedDistricts.Select(x => x.Name)));
            }

            /// Создаем калькулятор расчета расстояний. Он сразу запрашивает уже имеющиеся расстояния из кеша
            /// и в фоновом режиме начинает считать недостающую матрицу.
            distanceCalculator = new ExtDistanceCalculator(DistanceProvider.Osrm, Nodes.Select(x => x.Order.DeliveryPoint).ToArray(), DebugBuffer);

            MainClass.progressBarWin.ProgressAdd();
            logger.Info("Развозка по {0} районам.", calculatedOrders.Select(x => x.District).Distinct().Count());
            PerformanceHelper.AddTimePoint(logger, $"Подготовка заказов");

            /// Пред запуском оптимизации мы должны создать модель и внести в нее все необходимые данные.
            logger.Info("Создаем модель...");
            RoutingModel routing = new RoutingModel(Nodes.Length + 1, possibleRoutes.Length, 0);

            /// Создаем измерение со временем на маршруте.
            /// <c>horizon</c> - ограничивает максимально допустимое значение диапазона, чтобы не уйти за границы суток;
            /// <c>maxWaitTime</c> - Максимальное время ожидания водителя. То есть водитель закончил разгрузку следующий
            /// адрес в маршруте у него не должен быть позже чем на 3 часа ожидания.
            int horizon        = 24 * 3600;
            int maxWaitTime    = 3 * 3600;
            var timeEvaluators = possibleRoutes.Select(x => new CallbackTime(Nodes, x, distanceCalculator)).ToArray();

            routing.AddDimensionWithVehicleTransits(timeEvaluators, maxWaitTime, horizon, false, "Time");
            var time_dimension = routing.GetDimensionOrDie("Time");

            /// Ниже заполняем все измерения для учета бутылей, веса, адресов, объема.
            var bottlesCapacity = possibleRoutes.Select(x => (long)x.Car.MaxBottles).ToArray();

            routing.AddDimensionWithVehicleCapacity(new CallbackBottles(Nodes), 0, bottlesCapacity, true, "Bottles");

            var weightCapacity = possibleRoutes.Select(x => (long)x.Car.MaxWeight).ToArray();

            routing.AddDimensionWithVehicleCapacity(new CallbackWeight(Nodes), 0, weightCapacity, true, "Weight");

            var volumeCapacity = possibleRoutes.Select(x => (long)(x.Car.MaxVolume * 1000)).ToArray();

            routing.AddDimensionWithVehicleCapacity(new CallbackVolume(Nodes), 0, volumeCapacity, true, "Volume");

            var addressCapacity = possibleRoutes.Select(x => (long)(x.Car.MaxRouteAddresses)).ToArray();

            routing.AddDimensionWithVehicleCapacity(new CallbackAddressCount(Nodes.Length), 0, addressCapacity, true, "AddressCount");

            var bottlesDimension = routing.GetDimensionOrDie("Bottles");
            var addressDimension = routing.GetDimensionOrDie("AddressCount");

            for (int ix = 0; ix < possibleRoutes.Length; ix++)
            {
                /// Устанавливаем функцию получения стоимости маршрута.
                routing.SetArcCostEvaluatorOfVehicle(new CallbackDistanceDistrict(Nodes, possibleRoutes[ix], distanceCalculator), ix);
                /// Добавляем фиксированный штраф за приоритет водителя.
                routing.SetFixedCostOfVehicle((possibleRoutes[ix].DriverPriority - 1) * DriverPriorityPenalty, ix);

                var cumulTimeOnEnd   = routing.CumulVar(routing.End(ix), "Time");
                var cumulTimeOnBegin = routing.CumulVar(routing.Start(ix), "Time");

                /// Устанавливаем минимальные(мягкие) границы для измерений. При значениях меньше менемальных, маршрут все таки принимается,
                /// но вносятся некоторые штрафные очки на последнюю точку маршрута.
                bottlesDimension.SetEndCumulVarSoftLowerBound(ix, possibleRoutes[ix].Car.MinBottles, MinBottlesInRoutePenalty);
                addressDimension.SetEndCumulVarSoftLowerBound(ix, possibleRoutes[ix].Car.MinRouteAddresses, MinAddressesInRoutePenalty);

                /// Устанавливаем диапазон времени для движения по маршруту в зависимости от выбраной смены,
                /// день, вечер и с учетом досрочного завершения водителем работы.
                if (possibleRoutes[ix].Shift != null)
                {
                    var shift   = possibleRoutes[ix].Shift;
                    var endTime = possibleRoutes[ix].EarlyEnd.HasValue
                                                                                                        ? Math.Min(shift.EndTime.TotalSeconds, possibleRoutes[ix].EarlyEnd.Value.TotalSeconds)
                                                                                                        : shift.EndTime.TotalSeconds;
                    cumulTimeOnEnd.SetMax((long)endTime);
                    cumulTimeOnBegin.SetMin((long)shift.StartTime.TotalSeconds);
                }
                else if (possibleRoutes[ix].EarlyEnd.HasValue)                  //Устанавливаем время окончания рабочего дня у водителя.
                {
                    cumulTimeOnEnd.SetMax((long)possibleRoutes[ix].EarlyEnd.Value.TotalSeconds);
                }
            }

            for (int ix = 0; ix < Nodes.Length; ix++)
            {
                /// Проставляем на каждый адрес окно времени приезда.
                var startWindow = Nodes[ix].Order.DeliverySchedule.From.TotalSeconds;
                var endWindow   = Nodes[ix].Order.DeliverySchedule.To.TotalSeconds - Nodes[ix].Order.CalculateTimeOnPoint(false);               //FIXME Внимание здесь задаем время без экспедитора и без учета скорости водителя. Это не правильно, но другого варианта я придумать не смог.
                if (endWindow < startWindow)
                {
                    AddWarning("Время разгрузки на {2}, не помещается в диапазон времени доставки. {0}-{1}", Nodes[ix].Order.DeliverySchedule.From, Nodes[ix].Order.DeliverySchedule.To, Nodes[ix].Order.DeliveryPoint.ShortAddress);
                    endWindow = startWindow;
                }
                time_dimension.CumulVar(ix + 1).SetRange((long)startWindow, (long)endWindow);
                /// Добавляем абсолютно все заказы в дизюкцию. Если бы заказы небыли вдобавлены в отдельные дизьюкции
                /// то при не возможность доставить хоть один заказ. Все решение бы считаль не верным. Добавление каждого заказа
                /// в отдельную дизьюкцию, позволяет механизму не вести какой то и заказов, и все таки формировать решение с недовезенными
                /// заказами. Дизьюкция работает так. Он говорит, если хотя бы один заказ в этой группе(дизьюкции) доставлен,
                /// то все хорошо, иначе штраф. Так как у нас в кадой дизьюкции по одному заказу. Мы получаем опциональную доставку каждого заказа.
                routing.AddDisjunction(new int[] { ix + 1 }, MaxDistanceAddressPenalty);
            }

            logger.Debug("Nodes.Length = {0}", Nodes.Length);
            logger.Debug("routing.Nodes() = {0}", routing.Nodes());
            logger.Debug("GetNumberOfDisjunctions = {0}", routing.GetNumberOfDisjunctions());

            RoutingSearchParameters search_parameters =
                RoutingModel.DefaultSearchParameters();

            // Setting first solution heuristic (cheapest addition).
            /// Указывается стратегия первоначального заполнения. Опытным путем было вычислено, что именно при
            /// стратегиях вставки маршруты получаются с набором точек более близких к друг другу. То есть в большей
            /// степени облачком. Что воспринималось человеком как более отпимальное. В отличии от большенства других
            /// стратегий в которых маршруты, формируюся скорее по лентами ведущими через все обезжаемые раоны. То есть водители
            /// чаще имели пересечения маршутов.
            search_parameters.FirstSolutionStrategy =
                FirstSolutionStrategy.Types.Value.ParallelCheapestInsertion;

            search_parameters.TimeLimitMs = MaxTimeSeconds * 1000;
            /// Отключаем внутреннего кеширования расчитанных значений. Опытным путем было проверено, что включение этого значения.
            /// Значительно(на несколько секунд) увеличивает время закрытия модели и сокращает иногда не значительно время расчета оптимизаций.
            /// И в принцепе становится целесообразно только на количествах заказов 300-400. При количестве заказов менее 200
            /// влючение отпечатков значений. Не уменьшало, а увеличивало общее время расчета. А при большом количестве заказов
            /// время расчета уменьшалось не значительно.
            search_parameters.FingerprintArcCostEvaluators = false;
            //search_parameters.OptimizationStep = 100;

            var solver = routing.solver();

            PerformanceHelper.AddTimePoint(logger, $"Настроили оптимизацию");
            MainClass.progressBarWin.ProgressAdd();
            logger.Info("Закрываем модель...");

            if (WarningMessages.Count > 0 &&
                !MessageDialogWorks.RunQuestionDialog("При построении транспортной модели обнаружены следующие проблемы:\n{0}\nПродолжить?",
                                                      String.Join("\n", WarningMessages.Select(x => "⚠ " + x))))
            {
                return;
            }

            logger.Info("Рассчет расстояний между точками...");
            routing.CloseModelWithParameters(search_parameters);

#if DEBUG
            PrintMatrixCount(distanceCalculator.matrixcount);
#endif
            //Записывем возможно не схраненый кеш в базу.
            distanceCalculator.FlushCache();
            //Попытка хоть как то ослеживать что происходит в момент построения. Возможно не очень правильная.
            //Пришлось создавать 2 монитора.
            var lastSolution = solver.MakeLastSolutionCollector();
            lastSolution.AddObjective(routing.CostVar());
            routing.AddSearchMonitor(lastSolution);
            routing.AddSearchMonitor(new CallbackMonitor(solver, OrdersProgress, DebugBuffer, lastSolution));

            PerformanceHelper.AddTimePoint(logger, $"Закрыли модель");
            logger.Info("Поиск решения...");
            MainClass.progressBarWin.ProgressAdd();

            Assignment solution = routing.SolveWithParameters(search_parameters);
            PerformanceHelper.AddTimePoint(logger, $"Получили решение.");
            logger.Info("Готово. Заполняем.");
            MainClass.progressBarWin.ProgressAdd();
#if DEBUG
            PrintMatrixCount(distanceCalculator.matrixcount);
#endif
            Console.WriteLine("Status = {0}", routing.Status());
            if (solution != null)
            {
                // Solution cost.
                Console.WriteLine("Cost = {0}", solution.ObjectiveValue());
                time_dimension = routing.GetDimensionOrDie("Time");

                //Читаем полученные маршруты.
                for (int route_number = 0; route_number < routing.Vehicles(); route_number++)
                {
                    var  route       = new ProposedRoute(possibleRoutes[route_number]);
                    long first_node  = routing.Start(route_number);
                    long second_node = solution.Value(routing.NextVar(first_node));                     // Пропускаем первый узел, так как это наша база.
                    route.RouteCost = routing.GetCost(first_node, second_node, route_number);

                    while (!routing.IsEnd(second_node))
                    {
                        var time_var = time_dimension.CumulVar(second_node);
                        var rPoint   = new ProposedRoutePoint(
                            TimeSpan.FromSeconds(solution.Min(time_var)),
                            TimeSpan.FromSeconds(solution.Max(time_var)),
                            Nodes[second_node - 1].Order
                            );
                        rPoint.DebugMaxMin = String.Format("\n({0},{1})[{3}-{4}]-{2} Cost:{5}",
                                                           new DateTime().AddSeconds(solution.Min(time_var)).ToShortTimeString(),
                                                           new DateTime().AddSeconds(solution.Max(time_var)).ToShortTimeString(),
                                                           second_node,
                                                           rPoint.Order.DeliverySchedule.From.ToString("hh\\:mm"),
                                                           rPoint.Order.DeliverySchedule.To.ToString("hh\\:mm"),
                                                           routing.GetCost(first_node, second_node, route_number)
                                                           );
                        route.Orders.Add(rPoint);

                        first_node       = second_node;
                        second_node      = solution.Value(routing.NextVar(first_node));
                        route.RouteCost += routing.GetCost(first_node, second_node, route_number);
                    }

                    if (route.Orders.Count > 0)
                    {
                        ProposedRoutes.Add(route);
                        logger.Debug("Маршрут {0}: {1}",
                                     route.Trip.Driver.ShortName,
                                     String.Join(" -> ", route.Orders.Select(x => x.DebugMaxMin))
                                     );
                    }
                    else
                    {
                        logger.Debug("Маршрут {0}: пустой", route.Trip.Driver.ShortName);
                    }
                }
            }

#if DEBUG
            logger.Debug("SGoToBase:{0}", String.Join(", ", CallbackDistanceDistrict.SGoToBase.Select(x => $"{x.Key.Driver.ShortName}={x.Value}")));
            logger.Debug("SFromExistPenality:{0}", String.Join(", ", CallbackDistanceDistrict.SFromExistPenality.Select(x => $"{x.Key.Driver.ShortName}={x.Value}")));
            logger.Debug("SUnlikeDistrictPenality:{0}", String.Join(", ", CallbackDistanceDistrict.SUnlikeDistrictPenality.Select(x => $"{x.Key.Driver.ShortName}={x.Value}")));
            logger.Debug("SLargusPenality:{0}", String.Join(", ", CallbackDistanceDistrict.SLargusPenality.Select(x => $"{x.Key.Driver.ShortName}={x.Value}")));
#endif

            MainClass.progressBarWin.ProgressAdd();

            if (ProposedRoutes.Count > 0)
            {
                logger.Info($"Предложено {ProposedRoutes.Count} маршрутов.");
            }
            PerformanceHelper.Main.PrintAllPoints(logger);

            if (distanceCalculator.ErrorWays.Count > 0)
            {
                logger.Debug("Ошибок получения расстояний {0}", distanceCalculator.ErrorWays.Count);
                var uniqueFrom = distanceCalculator.ErrorWays.Select(x => x.FromHash).Distinct().ToList();
                var uniqueTo   = distanceCalculator.ErrorWays.Select(x => x.ToHash).Distinct().ToList();
                logger.Debug("Уникальных точек: отправки = {0}, прибытия = {1}", uniqueFrom.Count, uniqueTo.Count);
                logger.Debug("Проблемные точки отправки:\n{0}",
                             String.Join("; ", distanceCalculator.ErrorWays
                                         .GroupBy(x => x.FromHash)
                                         .Where(x => x.Count() > (uniqueTo.Count / 2))
                                         .Select(x => CachedDistance.GetText(x.Key)))
                             );
                logger.Debug("Проблемные точки прибытия:\n{0}",
                             String.Join("; ", distanceCalculator.ErrorWays
                                         .GroupBy(x => x.ToHash)
                                         .Where(x => x.Count() > (uniqueFrom.Count / 2))
                                         .Select(x => CachedDistance.GetText(x.Key)))
                             );
            }
        }
Example #26
0
        /// <summary>
        /// Process a G-code that should be interpreted by the control server
        /// </summary>
        /// <param name="code">Code to process</param>
        /// <returns>Result of the code if the code completed, else null</returns>
        public static async Task <CodeResult> Process(Commands.Code code)
        {
            if (code.Channel == CodeChannel.File && FileExecution.Job.IsSimulating)
            {
                // Ignore M-codes from files in simulation mode...
                return(null);
            }

            switch (code.MajorNumber)
            {
            // Save or load heightmap
            case 29:
                CodeParameter cp = code.Parameter('S', 0);
                if (cp == 1 || cp == 3)
                {
                    if (await SPI.Interface.Flush(code))
                    {
                        string file         = code.Parameter('P', FilePath.DefaultHeightmapFile);
                        string physicalFile = await FilePath.ToPhysicalAsync(file, FileDirectory.System);

                        try
                        {
                            Heightmap map = null;
                            if (cp == 1)
                            {
                                map = new Heightmap();
                                await map.Load(physicalFile);

                                await using (await SPI.Interface.LockMovementAndWaitForStandstill(code.Channel))
                                {
                                    await SPI.Interface.SetHeightmap(map);
                                }

                                string virtualFile = await FilePath.ToVirtualAsync(physicalFile);

                                using (await Model.Provider.AccessReadWriteAsync())
                                {
                                    Model.Provider.Get.Move.Compensation.File = virtualFile;
                                }

                                CodeResult result = new();
                                using (await Model.Provider.AccessReadOnlyAsync())
                                {
                                    if (Model.Provider.Get.Move.Axes.Any(axis => axis.Letter == 'Z' && !axis.Homed))
                                    {
                                        result.Add(MessageType.Warning, "The height map was loaded when the current Z=0 datum was not determined. This may result in a height offset.");
                                    }
                                }
                                result.Add(MessageType.Success, $"Height map loaded from file {file}");
                                return(result);
                            }
                            else
                            {
                                await using (await SPI.Interface.LockMovementAndWaitForStandstill(code.Channel))
                                {
                                    map = await SPI.Interface.GetHeightmap();
                                }

                                if (map.NumX * map.NumY > 0)
                                {
                                    await map.Save(physicalFile);

                                    string virtualFile = await FilePath.ToVirtualAsync(physicalFile);

                                    using (await Model.Provider.AccessReadWriteAsync())
                                    {
                                        Model.Provider.Get.Move.Compensation.File = virtualFile;
                                    }
                                    return(new CodeResult(MessageType.Success, $"Height map saved to file {file}"));
                                }
                                return(new CodeResult());
                            }
                        }
                        catch (Exception e)
                        {
                            _logger.Debug(e, "Failed to access height map file");
                            if (e is AggregateException ae)
                            {
                                e = ae.InnerException;
                            }
                            return(new CodeResult(MessageType.Error, $"Failed to {(cp == 1 ? "load" : "save")} height map {(cp == 1 ? "from" : "to")} file {file}: {e.Message}"));
                        }
                    }
                    throw new OperationCanceledException();
                }
                break;
            }
            return(null);
        }
Example #27
0
 protected override void DebugInternal(string message, KeyValuePair <string, object>[] extData = null)
 {
     _logger?.Debug(buildString(null, message, extData));
 }
Example #28
0
        private void OpenKmpeg(object info)
        {
            logger.Trace("OpenKmpeg start");
            ConnectInfo connectInfo = (ConnectInfo)info;
            uint        time        = Convert.ToUInt32((connectInfo.StartTime - new DateTime(1970, 1, 1)).TotalSeconds);

            bool success = false;

            m_KMPEGHandle = KMPEG4.KOpenInterface();
            KMPEG4.Media_Connect_Config4 mediaConfig = new KMPEG4.Media_Connect_Config4();

            mediaConfig.ConnectTimeOut   = 2;
            mediaConfig.ContactType      = (int)KMPEG4.CONTACT_TYPE.CONTACT_TYPE_HTTP_WOC_PREVIEW;
            mediaConfig.HTTPPort         = connectInfo.Port;
            mediaConfig.Password         = connectInfo.Password;
            mediaConfig.UniCastIP        = connectInfo.HostName;
            mediaConfig.UserID           = connectInfo.UserID;
            mediaConfig.TCPVideoStreamID = 0;
            string session = "1234" + m_SelectID;

            mediaConfig.PlayFileName = time > 0 ? $"/Media/SyncPlayback?deviceid={connectInfo.SelectID}&syncsession={session}" :
                                       $"/Media/Streaming?deviceid={connectInfo.SelectID}&streamid={connectInfo.StreamId}";
            logger.Debug($"Prepare play file:{mediaConfig.PlayFileName}");

            success = KMPEG4.KSetMediaConfig4(m_KMPEGHandle, ref mediaConfig);

            SetImageCallback3();
            SetTimeCodeExRecive();

            if (KMPEG4.KConnect(m_KMPEGHandle))
            {
                if (KMPEG4.KStartStreaming(m_KMPEGHandle))
                {
                    KMPEG4.KPlay(m_KMPEGHandle);

                    m_URLCommand = new URLCommand(connectInfo.HostName, connectInfo.Port, connectInfo.UserID, connectInfo.Password, session);
                    if (time > 0)
                    {
                        m_URLCommand.SetCurrentTime(time.ToString());
                        System.Threading.SpinWait.SpinUntil(() => false, 1000);
                        m_URLCommand.SetPlayMode("1");
                        m_URLCommand.Play();
                    }
                    else
                    {
                    }

                    KMPEG4.KSetVolume(m_KMPEGHandle, 100, 100);
                    KMPEG4.KSetMute(m_KMPEGHandle, false);
                }
                else
                {
                    m_KMPEGConnectFail = true;
                }
            }
            else
            {
                m_KMPEGConnectFail = true;
            }
            logger.Trace("OpenKmpeg done");
        }
Example #29
0
        void GmapWidget_ButtonPressEvent(object o, ButtonPressEventArgs args)
        {
            if (args.Event.Button == 1)
            {
                bool markerIsSelect = false;
                if (args.Event.State.HasFlag(ModifierType.LockMask))
                {
                    foreach (var marker in addressesOverlay.Markers)
                    {
                        if (marker.IsMouseOver)
                        {
                            var markerUnderMouse = selectedMarkers
                                                   .Where(m => m.Tag is Order)
                                                   .FirstOrDefault(x => (x.Tag as Order).Id == (marker.Tag as Order)?.Id);

                            if (markerUnderMouse == null)
                            {
                                selectedMarkers.Add(marker);
                                logger.Debug("Маркер с заказом №{0} добавлен в список выделенных", (marker.Tag as Order)?.Id);
                            }
                            else
                            {
                                selectedMarkers.Remove(markerUnderMouse);
                                logger.Debug("Маркер с заказом №{0} исключен из списка выделенных", (marker.Tag as Order)?.Id);
                            }
                            markerIsSelect = true;
                        }
                    }
                    UpdateSelectedInfo(selectedMarkers);
                    UpdateAddressesOnMap();
                    return;
                }
                if (!markerIsSelect)
                {
                    selectedMarkers.Clear();
                    logger.Debug("Список выделенных маркеров очищен");
                }
                UpdateAddressesOnMap();

                if (poligonSelection)
                {
                    GRect rect = new GRect((long)args.Event.X - 5, (long)args.Event.Y - 5, 10, 10);
                    rect.OffsetNegative(gmapWidget.RenderOffset);

                    dragSelectionPointId = brokenSelection.LocalPoints.FindIndex(rect.Contains);
                    if (dragSelectionPointId != -1)
                    {
                        gmapWidget.DisableAltForSelection = false;
                        return;
                    }
                }

                if (args.Event.State.HasFlag(ModifierType.ControlMask))
                {
                    if (!poligonSelection)
                    {
                        poligonSelection = true;
                        logger.Debug("Старт выделения через полигон.");
                        var startPoint = gmapWidget.FromLocalToLatLng((int)args.Event.X, (int)args.Event.Y);
                        brokenSelection = new GMapPolygon(new List <PointLatLng> {
                            startPoint
                        }, "Выделение");
                        gmapWidget.UpdatePolygonLocalPosition(brokenSelection);
                        selectionOverlay.Polygons.Add(brokenSelection);
                    }
                    else
                    {
                        logger.Debug("Продолжили.");
                        var newPoint = gmapWidget.FromLocalToLatLng((int)args.Event.X, (int)args.Event.Y);
                        brokenSelection.Points.Add(newPoint);
                        gmapWidget.UpdatePolygonLocalPosition(brokenSelection);
                    }
                    OnPoligonSelectionUpdated();
                }
                else
                {
                    logger.Debug("Закончили.");
                    poligonSelection = false;
                    UpdateSelectedInfo(new List <GMapMarker>());
                    selectionOverlay.Clear();
                }
            }

            if (args.Event.Button == 3 && addressesOverlay.Markers.FirstOrDefault(m => m.IsMouseOver)?.Tag is Order order)
            {
                Menu popupMenu = new Menu();
                var  item      = new MenuItem(string.Format("Открыть {0}", order));
                item.Activated += (sender, e) => {
                    var dlg = new OrderDlg(order)
                    {
                        HasChanges = false
                    };
                    dlg.SetDlgToReadOnly();
                    Tab.TabParent.AddSlaveTab(Tab, dlg);
                };
                popupMenu.Add(item);
                popupMenu.ShowAll();
                popupMenu.Popup();
            }
        }
 // For some reason, this fires twice. Can't track down why, but it does.
 private void SettingsFileChange(object sender, FileSystemEventArgs e)
 {
     logger.Debug("Settings file changed, refreshing settings from disk.");
     Helper.LoadSettings(true);
     return;
 }
Example #31
0
        public List <TorrentEntry> AllFilesBeingDownloaded()
        {
            List <TorrentEntry> r = new List <TorrentEntry>();

            BEncodeLoader bel = new BEncodeLoader();

            foreach (BTDictionaryItem dictitem in ResumeDat.GetDict().Items)
            {
                if ((dictitem.Type != BTChunk.kDictionaryItem))
                {
                    continue;
                }

                if ((dictitem.Key == ".fileguard") || (dictitem.Data.Type != BTChunk.kDictionary))
                {
                    continue;
                }

                if (dictitem.Data is BTError err)
                {
                    logger.Error($"Error finding BT items: {err.Message}");
                    return(r);
                }

                BTDictionary d2 = (BTDictionary)(dictitem.Data);

                BTItem p = d2.GetItem("prio");
                if ((p is null) || (p.Type != BTChunk.kString))
                {
                    continue;
                }

                BTString prioString    = (BTString)(p);
                string   directoryName = Path.GetDirectoryName(ResumeDatPath) + System.IO.Path.DirectorySeparatorChar;

                string torrentFile = dictitem.Key;
                if (!File.Exists(torrentFile))                 // if the torrent file doesn't exist
                {
                    torrentFile = directoryName + torrentFile; // ..try prepending the resume.dat folder's path to it.
                }
                if (!File.Exists(torrentFile))
                {
                    continue; // can't find it.  give up!
                }
                BTFile tor = bel.Load(torrentFile);
                if (tor is null)
                {
                    continue;
                }

                List <string> a = tor.AllFilesInTorrent();
                if (a is null)
                {
                    continue;
                }

                int c = 0;

                p = d2.GetItem("path");
                if ((p is null) || (p.Type != BTChunk.kString))
                {
                    continue;
                }

                string defaultFolder = ((BTString)p).AsString();

                BTItem targets    = d2.GetItem("targets");
                bool   hasTargets = ((targets != null) && (targets.Type == BTChunk.kList));
                BTList targetList = (BTList)(targets);

                foreach (string s in a)
                {
                    if ((c < prioString.Data.Length) && (prioString.Data[c] != BTPrio.Skip))
                    {
                        try
                        {
                            string saveTo = FileHelper
                                            .FileInFolder(defaultFolder, TVSettings.Instance.FilenameFriendly(s)).Name;

                            if (hasTargets)
                            {
                                // see if there is a target for this (the c'th) file
                                foreach (BTItem t in targetList.Items)
                                {
                                    BTList    l    = (BTList)(t);
                                    BTInteger n    = (BTInteger)(l.Items[0]);
                                    BTString  dest = (BTString)(l.Items[1]);
                                    if (n.Value == c)
                                    {
                                        saveTo = dest.AsString();
                                        break;
                                    }
                                }
                            }

                            int          percent = (a.Count == 1) ? PercentBitsOn((BTString)(d2.GetItem("have"))) : -1;
                            TorrentEntry te      = new TorrentEntry(torrentFile, saveTo, percent);
                            r.Add(te);
                        }
                        catch (System.IO.PathTooLongException ptle)
                        {
                            //this is not the file we are looking for
                            logger.Debug(ptle);
                        }
                    }

                    c++;
                }
            }

            return(r);
        }
        public bool SendEmail(MailMessage message)
        {
            // Do not proceed further if mail relay is disabled.
            if (!_config.Enabled)
            {
                Logger.Warn("Mail Relay is disabled.");
                return(true);
            }

            // Configure the SMTP client and send the message
            var client = new SmtpClient
            {
                Host = _config.Address,
                Port = _config.Port,

                // Use whatever SSL mode is set.
                EnableSsl      = _config.EnableSsl,
                DeliveryMethod = SmtpDeliveryMethod.Network
            };

            if (_config.EnableSsl)
            {
                ServicePointManager.ServerCertificateValidationCallback = (s, certificate, chain, sslPolicyErrors) => true;
            }

            Logger.Debug($"Email configuration | Server: {_config.Address} Port: {_config.Port} SSL: {_config.EnableSsl}");

            message.From = new MailAddress(_config.MailFromAddress, "Profile Designer Portal");

            // If Mail Relay is in debug mode set all addresses to the configuration file.
            if (_config.Debug)
            {
                Logger.Debug($"Mail relay is in debug mode. Redirecting target email to: {string.Join("|", _config.DebugToAddresses)}");
                message.To.Clear();
                foreach (var address in _config.DebugToAddresses)
                {
                    message.To.Add(new MailAddress(address));
                }
            }

            // If the user has setup credentials, use them.
            if (!string.IsNullOrEmpty(_config.Username) && !string.IsNullOrEmpty(_config.Password))
            {
                client.Credentials = new NetworkCredential(_config.Username, _config.Password);
                Logger.Debug("Credentials are set in app settings, will leverage for SMTP connection.");
            }

            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                if (ex is SmtpException)
                {
                    Logger.Error("An SMTP exception occurred while attempting to relay mail.");
                }
                else
                {
                    Logger.Error("A general exception occured while attempting to relay mail.");
                }

                Logger.Error(ex.Message);
                return(false);
            }
            finally
            {
                message.Dispose();
            }

            Logger.Info("Message relay complete.");
            return(true);
        }