System.Diagnostics.Log.Error(string)

Here are the examples of the csharp api System.Diagnostics.Log.Error(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

661 Examples 7

19 Source : HealthMonitor.cs
with MIT License
from 0ffffffffh

public bool Start()
        {
            this.process = Process.GetProcessById(this.pid);

            if (this.process == null)
            {
                Log.Error("Pid: {0} could not be found.", pid);
                return false;
            }

            this.processPath = this.process.MainModule.FileName;
            this.processArgs = this.process.StartInfo.Arguments;
            
            Log.Verbose(this.processArgs);

            this.process.Exited += Process_Exited;
            this.process.EnableRaisingEvents = true;

            switch (this.procType)
            {
                case ProcessType.BackendProcess:
                    BackendHealthMon = this;
                    break;
                case ProcessType.MemcachedProcess:
                    MemcachedHealthMon = this;
                    break;
            }

            Log.Info("Monitoring started on Pid: {0} for the type of {1} process", this.pid, this.procType);
            
            return true;
        }

19 Source : Watchdog.cs
with MIT License
from 0ffffffffh

private void KillList(IEnumerable<Process> processes)
        {
            foreach (var proc in processes)
            {
                Log.Info("Attempting to kill pid {0}", proc.Id);

                try
                {
                    proc.Kill();
                }
                catch (Exception e)
                {
                    Log.Error(e.Message);
                    proc.Dispose();
                    continue;
                }

                if (!proc.WaitForExit(2000))
                {
                    Log.Error("Pid: {0} cant be killed!", proc.Id);
                }

                proc.Dispose();
            }
        }

19 Source : Watchdog.cs
with MIT License
from 0ffffffffh

private void KillList(IEnumerable<Process> processes)
        {
            foreach (var proc in processes)
            {
                Log.Info("Attempting to kill pid {0}", proc.Id);

                try
                {
                    proc.Kill();
                }
                catch (Exception e)
                {
                    Log.Error(e.Message);
                    proc.Dispose();
                    continue;
                }

                if (!proc.WaitForExit(2000))
                {
                    Log.Error("Pid: {0} cant be killed!", proc.Id);
                }

                proc.Dispose();
            }
        }

19 Source : Memcached.cs
with MIT License
from 0ffffffffh

public static Memcached AttachExist(string name, ushort port, int pid)
        {
            Memcached memcached = new Memcached();
            MemcachedIo mio;

            Log.Info("Attaching exist memcached instance.");

            if (!MemcachedInstance.WaitUntilInstanceDestroyed(name,new TimeSpan(0,0,5)))
            {
                Log.Warning("{0} could not be deregistered", name);
                return null;
            }

            try
            {
                memcached.inst = MemcachedInstance.CreateInstanceFromExist(pid, port, name);
            }
            catch (Exception e)
            {
                //probably still exist
                Log.Warning(e.Message);
                return null;
            }

            Log.Info("instance \"{0}\" created at {1} port", name, port);


            Log.Info("attaching to the memcached IO interface.");

            mio = new MemcachedIo();

            if (!mio.AttachMemcachedInstance(memcached.inst))
            {
                Log.Error("Memcached instance could not be attached to Memcached Io object");
                memcached.inst.Kill();
                memcached.inst = null;
                memcached = null;

                return null;
            }

            memcached.Instance = mio;

            Log.Info("Connection success...");

            return memcached;
        }

19 Source : Memcached.cs
with MIT License
from 0ffffffffh

public static Memcached Create(string name, ulong memSize, ushort port)
        {
            Memcached memcached = new Memcached();
            MemcachedIo mio;

            Log.Info("Creating new memcached instance.");

            memcached.inst = new MemcachedInstance(memSize, name, port);


            if (!memcached.inst.Start())
            {
                Log.Critical("Memcached instance could not be created!!");
                memcached.inst = null;
                memcached = null;

                return null;
            }

            Log.Info("instance \"{0}\" created at {1} port", name, port);


            Log.Info("attaching and connecting to the instance.");

            mio = new MemcachedIo();
            
            if (!mio.AttachMemcachedInstance(memcached.inst))
            {
                Log.Error("Memcached instance could not be attached to Memcached Io object");
                memcached.inst.Kill();
                memcached.inst = null;
                memcached = null;

                return null;
            }

            memcached.Instance = mio;

            Log.Info("Connection success...");

            return memcached;
        }

19 Source : MemcachedProcess.cs
with MIT License
from 0ffffffffh

private static void Process_Exited(object sender, EventArgs e)
        {
            MemcachedProcess mp;
            Process process = sender as Process;

            Log.Error("memcached process {0} had lost with {1} code",
                process.Id, process.ExitCode);

            if (_Processes.TryGetValue(process.Id, out mp))
            {
                if (mp.Exited != null)
                {
                    Log.Info("Calling memcached process's exit event");
                    mp.Exited(mp, null);
                }

                Log.Info("removing instance from the mc proc list");

                _Processes.Remove(process.Id);
            }

            //register new instance search
        }

19 Source : MemcachedProcess.cs
with MIT License
from 0ffffffffh

public static MemcachedProcess FireUp(ulong memSize, ushort port)
        {
            MemcachedProcess mcproc = null;

            string arg;
            ProcessStartInfo psi = null;

            arg = string.Format("-p {0} -m {1}", port,memSize);
            psi = new ProcessStartInfo(Config.Get().MemcachedPath,arg);
            psi.CreateNoWindow = true;
            psi.UseShellExecute = false;

            
            mcproc = new MemcachedProcess();

            try
            {
                mcproc.process = new Process();
                mcproc.process.EnableRaisingEvents = true;
                mcproc.process.Exited += Process_Exited;
                mcproc.process.StartInfo = psi;

                if (!mcproc.process.Start())
                {
                    mcproc.process = null;
                    mcproc = null;

                    Log.Error("Process could not be started");

                    return null;

                }

            }
            catch (Exception e)
            {
                mcproc = null;
                Log.Error("memcached process start error: %s", e.Message);
                return null;
            }

            if (!_Processes.ContainsKey(mcproc.process.Id))
                _Processes.Add(mcproc.process.Id, mcproc);

            return mcproc;
        }

19 Source : Program.cs
with MIT License
from 13xforever

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 Source : Program.cs
with MIT License
from 13xforever

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 Source : Program.cs
with MIT License
from action-bi-toolkit

static int Main(string[] args)
        {
            // When invoked w/o args, print usage and exit immediately (do not trigger ArgException)
            if ((args ?? new string[0]).Length == 0)
            {
                ArgUsage.GenerateUsageFromTemplate<CmdLineActions>().WriteLine();
                return (int)ExitCode.NoArgsProvided;
            }

            var result = default(ExitCode);
            try
            {
                var action = Args.ParseAction<CmdLineActions>(args);
                
                action.Invoke(); // throws ArgException (DuplicateArg, MissingArg, UnexpectedArg, UnknownArg, ValidationArg)

                // in Debug compilation, propagates any exceptions thrown by executing action
                // in Release compilation, a user friendly error message is displayed, and exceptions thrown are available via the HandledException property

                /* This branch only applies in Release (StandardExceptionHandling enabled) mode, and only to __parser__ exceptions */
                if (action.HandledException != null)
                {
                    // Standard output has been generated by PowerArgs framework already
                    Console.WriteLine();
                    Log.Verbose(action.HandledException, "PowerArgs exception");
                }

                // TODO Define and handle specific exceptions to report back to user directly (No PBI install, etc...)

                result = action.HandledException == null ? ExitCode.Success : ExitCode.InvalidArgs;
            }
            catch (ArgException ex)
            {
                // In RELEASE mode, the PowerArgs error has already been emitted, and the usage docs have been printed to the console at this stage
                
                if (!Environment.UserInteractive)
                {
                    Log.Fatal(ex, "Bad user input.");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Error.WriteLine(ex.Message);
                    Console.ResetColor();
#if DEBUG
                    ArgUsage.GenerateUsageFromTemplate(ex.Context.Definition).WriteLine();
#endif
                }
                result = ExitCode.InvalidArgs;
            }
            catch (PbiToolsCliException ex)
            {
                Log.Error(ex.Message);
                result = ex.ErrorCode;
            }
            catch (Exception ex) /* Any unhandled exception */
            {
                // TODO Explicitly log into crash file...
                // If CWD is not writable, put into user profile and show path...

                Log.Fatal(ex, "An unhandled exception occurred.");
                result = ExitCode.UnexpectedError;
            }

            // Prevent closing of window when debugging
            if (Debugger.IsAttached && Environment.UserInteractive)
            {
                Console.WriteLine();
                Console.Write("Press ENTER to exit...");
                Console.ReadLine();
            }

            // ExitCode:
            return (int)result;
        }

19 Source : ConverterService.cs
with GNU General Public License v3.0
from alxnbl

public string ConvertDocxToMd(Page page, string inputFilePath, string resourceFolderPath, int sectionTreeLevel)
        {
           
            var mdFilePath = Path.Combine("tmp", page.replacedleWithNoInvalidChars + ".md");

            var arguments = $"\"{Path.GetFullPath(inputFilePath)}\"  " +
                            $"--to gfm " +
                            $"-o \"{Path.GetFullPath(mdFilePath)}\" " +
                            $"--wrap=none " + // Mandatory to avoid random quote bloc to be added to markdown
                            $"--extract-media=\"tmp\"";

            var startInfo = new ProcessStartInfo
            {
                FileName = "pandoc.exe",
                Arguments = arguments,
                UseShellExecute = false,
                CreateNoWindow = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };


            Log.Debug($"{page.Id} : Start Pandoc");

            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();

                if(exeProcess.ExitCode == 0)
                {
                    Log.Debug($"{page.Id} : Pandoc success");
                }
                else
                {
                    Log.Error($"{page.Id} : Pandoc error");
                    var pandocError = exeProcess.StandardError.ReadToEnd();
                    Log.Error("Pandoc error output: {0}", pandocError);
                }


                if (_appSettings.Debug)
                {
                    Log.Debug($"Pandoc output: {exeProcess.StandardOutput.ReadToEnd()}");
                }
            }

            var mdFileContent = File.ReadAllText(mdFilePath);

            if (!_appSettings.Debug)
                File.Delete(inputFilePath);

            return mdFileContent;
        }

19 Source : GraphicsDevice.cs
with MIT License
from amerkoleci

public void RenderFrame(Action<VkCommandBuffer, VkFramebuffer, VkExtent2D> draw, [CallerMemberName] string? frameName = null)
        {
            VkResult result = AcquireNextImage(out uint swapchainIndex);

            // Handle outdated error in acquire.
            if (result == VkResult.SuboptimalKHR || result == VkResult.ErrorOutOfDateKHR)
            {
                //Resize(context.swapchain_dimensions.width, context.swapchain_dimensions.height);
                result = AcquireNextImage(out swapchainIndex);
            }

            if (result != VkResult.Success)
            {
                vkDeviceWaitIdle(VkDevice);
                return;
            }

            // Begin command recording
            VkCommandBuffer cmd = _perFrame[swapchainIndex].PrimaryCommandBuffer;

            VkCommandBufferBeginInfo beginInfo = new VkCommandBufferBeginInfo
            {
                sType = VkStructureType.CommandBufferBeginInfo,
                flags = VkCommandBufferUsageFlags.OneTimeSubmit
            };
            vkBeginCommandBuffer(cmd, &beginInfo).CheckResult();

            draw(cmd, Swapchain.Framebuffers[swapchainIndex], Swapchain.Extent);

            // Complete the command buffer.
            vkEndCommandBuffer(cmd).CheckResult();

            if (_perFrame[swapchainIndex].SwapchainReleaseSemapreplaced == VkSemapreplaced.Null)
            {
                vkCreateSemapreplaced(VkDevice, out _perFrame[swapchainIndex].SwapchainReleaseSemapreplaced).CheckResult();
            }

            VkPipelineStageFlags wait_stage = VkPipelineStageFlags.ColorAttachmentOutput;
            VkSemapreplaced waitSemapreplaced = _perFrame[swapchainIndex].SwapchainAcquireSemapreplaced;
            VkSemapreplaced signalSemapreplaced = _perFrame[swapchainIndex].SwapchainReleaseSemapreplaced;

            VkSubmitInfo submitInfo = new VkSubmitInfo
            {
                sType = VkStructureType.SubmitInfo,
                commandBufferCount = 1u,
                pCommandBuffers = &cmd,
                waitSemapreplacedCount = 1u,
                pWaitSemapreplaceds = &waitSemapreplaced,
                pWaitDstStageMask = &wait_stage,
                signalSemapreplacedCount = 1u,
                pSignalSemapreplaceds = &signalSemapreplaced
            };

            // Submit command buffer to graphics queue
            vkQueueSubmit(GraphicsQueue, submitInfo, _perFrame[swapchainIndex].QueueSubmitFence);

            result = PresentImage(swapchainIndex);

            // Handle Outdated error in present.
            if (result == VkResult.SuboptimalKHR || result == VkResult.ErrorOutOfDateKHR)
            {
                //Resize(context.swapchain_dimensions.width, context.swapchain_dimensions.height);
            }
            else if (result != VkResult.Success)
            {
                Log.Error("Failed to present swapchain image.");
            }
        }

19 Source : GraphicsDevice.cs
with MIT License
from amerkoleci

private static uint DebugMessengerCallback(VkDebugUtilsMessageSeverityFlagsEXT messageSeverity,
            VkDebugUtilsMessageTypeFlagsEXT messageTypes,
            VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
            void* userData)
        {
            string? message = Interop.GetString(pCallbackData->pMessage);
            if (messageTypes == VkDebugUtilsMessageTypeFlagsEXT.Validation)
            {
                if (messageSeverity == VkDebugUtilsMessageSeverityFlagsEXT.Error)
                {
                    Log.Error($"[Vulkan]: Validation: {messageSeverity} - {message}");
                }
                else if (messageSeverity == VkDebugUtilsMessageSeverityFlagsEXT.Warning)
                {
                    Log.Warn($"[Vulkan]: Validation: {messageSeverity} - {message}");
                }

                Debug.WriteLine($"[Vulkan]: Validation: {messageSeverity} - {message}");
            }
            else
            {
                if (messageSeverity == VkDebugUtilsMessageSeverityFlagsEXT.Error)
                {
                    Log.Error($"[Vulkan]: {messageSeverity} - {message}");
                }
                else if (messageSeverity == VkDebugUtilsMessageSeverityFlagsEXT.Warning)
                {
                    Log.Warn($"[Vulkan]: {messageSeverity} - {message}");
                }

                Debug.WriteLine($"[Vulkan]: {messageSeverity} - {message}");
            }

            return VK_FALSE;
        }

19 Source : Program.cs
with MIT License
from AnotherEnd15

private static void Main(string[] args)
		{
			// 异步方法全部会回掉到主线程
			SynchronizationContext.SetSynchronizationContext(ThreadSynchronizationContext.Instance);
			
			try
			{		
				Game.EventSystem.Add(typeof(Game).replacedembly);
				Game.EventSystem.Add(DllHelper.GetHotfixreplacedembly());
				
				ProtobufHelper.Init();
				MongoHelper.Init();
				
				// 命令行参数
				Options options = null;
				Parser.Default.ParseArguments<Options>(args)
						.WithNotParsed(error => throw new Exception($"命令行格式错误!"))
						.WithParsed(o => { options = o; });

				Game.Options = options;
				
				LogManager.Configuration.Variables["appIdFormat"] = $"{Game.Scene.Id:0000}";
				
				Log.Info($"server start........................ {Game.Scene.Id}");

				Game.EventSystem.Publish(new EventIDType.AppStart());
				
				while (true)
				{
					try
					{
						Thread.Sleep(1);
						Game.Update();
						Game.LateUpdate();
						Game.FrameFinish();
					}
					catch (Exception e)
					{
						Log.Error(e);
					}
				}
			}
			catch (Exception e)
			{
				Log.Error(e);
			}
		}

19 Source : AsyncETTaskCompletedMethodBuilder.cs
with MIT License
from AnotherEnd15

[DebuggerHidden]
        public void SetException(Exception exception)
        {
            Log.Error(exception);
        }

19 Source : TezosTokensWalletViewModel.cs
with GNU General Public License v3.0
from atomex-me

private async Task TryGetAliasAsync()
        {
            try
            {
                var response = await HttpHelper.HttpClient
                    .GetAsync($"https://api.tzkt.io/v1/accounts/{Contract.Address}")
                    .ConfigureAwait(false);

                if (!response.IsSuccessStatusCode)
                    return;

                var stringResponse = await response.Content
                    .ReadreplacedtringAsync()
                    .ConfigureAwait(false);

                var alias = JsonConvert.DeserializeObject<JObject>(stringResponse)
                    ?["alias"]
                    ?.Value<string>();

                if (alias != null)
                    _name = alias;

                await Application
                    .Current
                    .Dispatcher
                    .InvokeAsync(() =>
                    {
                        OnPropertyChanged(nameof(Name));
                        OnPropertyChanged(nameof(HasName));
                    });
            }
            catch (Exception e)
            {
                Log.Error(e, "Alias getting error.");
            }
        }

19 Source : TezosTokensWalletViewModel.cs
with GNU General Public License v3.0
from atomex-me

protected virtual async void OnBalanceUpdatedEventHandler(object sender, CurrencyEventArgs args)
        {
            try
            {
                if (Currencies.IsTezosToken(args.Currency))
                {
                    await Application.Current.Dispatcher.InvokeAsync(async () =>
                    {
                        await ReloadTokenContractsAsync();

                    }, DispatcherPriority.Background);
                }
            }
            catch (Exception e)
            {
                Log.Error(e, "Account balance updated event handler error");
            }
        }

19 Source : TezosTokensWalletViewModel.cs
with GNU General Public License v3.0
from atomex-me

protected async void OnUpdateClick()
        {
            if (_isBalanceUpdating)
                return;

            _isBalanceUpdating = true;

            _cancellation = new CancellationTokenSource();

            await _dialogViewer.ShowProgressAsync(
                replacedle: "Tokens balance updating...",
                message: "Please wait!",
                canceled: () => { _cancellation.Cancel(); });

            try
            {
                var tezosAccount = _app.Account
                    .GetCurrencyAccount<TezosAccount>(TezosConfig.Xtz);

                var tezosTokensScanner = new TezosTokensScanner(tezosAccount);

                await tezosTokensScanner.ScanAsync(
                    skipUsed: false,
                    cancellationToken: _cancellation.Token);

                // reload balances for all tezos tokens account
                foreach (var currency in _app.Account.Currencies)
                    if (Currencies.IsTezosToken(currency.Name))
                        _app.Account
                            .GetCurrencyAccount<TezosTokenAccount>(currency.Name)
                            .ReloadBalances();

            }
            catch (OperationCanceledException)
            {
                Log.Debug("Wallet update operation canceled");
            }
            catch (Exception e)
            {
                Log.Error(e, "WalletViewModel.OnUpdateClick");
                // todo: message to user!?
            }

            _dialogViewer.HideProgress();

            _isBalanceUpdating = false;
        }

19 Source : AddressesViewModel.cs
with GNU General Public License v3.0
from atomex-me

public async void RealodAddresses()
        {
            try
            {
                var account = _app.Account
                    .GetCurrencyAccount(_currency.Name);

                var addresses = (await account
                    .GetAddressesAsync())
                    .ToList();

                addresses.Sort((a1, a2) =>
                {
                    var typeResult = a1.KeyType.CompareTo(a2.KeyType);

                    if (typeResult != 0)
                        return typeResult;

                    var accountResult = a1.KeyIndex.Account.CompareTo(a2.KeyIndex.Account);

                    if (accountResult != 0)
                        return accountResult;

                    var chainResult = a1.KeyIndex.Chain.CompareTo(a2.KeyIndex.Chain);

                    return chainResult != 0
                        ? chainResult
                        : a1.KeyIndex.Index.CompareTo(a2.KeyIndex.Index);
                });

                Addresses = new ObservableCollection<AddressInfo>(
                    addresses.Select(a =>
                    {
                        var path = a.KeyType == CurrencyConfig.StandardKey && Currencies.IsTezosBased(_currency.Name)
                            ? $"m/44'/{_currency.Bip44Code}'/{a.KeyIndex.Account}'/{a.KeyIndex.Chain}'"
                            : $"m/44'/{_currency.Bip44Code}'/{a.KeyIndex.Account}'/{a.KeyIndex.Chain}/{a.KeyIndex.Index}";

                        return new AddressInfo
                        {
                            Address         = a.Address,
                            Type            = KeyTypeToString(a.KeyType),
                            Path            = path,
                            Balance         = $"{a.Balance.ToString(CultureInfo.InvariantCulture)} {_currency.Name}",
                            CopyToClipboard = CopyToClipboard,
                            OpenInExplorer  = OpenInExplorer,
                            Update          = Update,
                            ExportKey       = ExportKey
                        };
                    }));

                // token balances
                if (_currency.Name == TezosConfig.Xtz && _tokenContract != null)
                {
                    HasTokens = true;

                    var tezosAccount = account as TezosAccount;

                    var addressesWithTokens = (await tezosAccount
                        .DataRepository
                        .GetTezosTokenAddressesByContractAsync(_tokenContract))
                        .Where(w => w.Balance != 0)
                        .GroupBy(w => w.Address);
                        
                    foreach (var addressWithTokens in addressesWithTokens)
                    {
                        var addressInfo = Addresses.FirstOrDefault(a => a.Address == addressWithTokens.Key);

                        if (addressInfo == null)
                            continue;

                        if (addressWithTokens.Count() == 1)
                        {
                            var tokenAddress = addressWithTokens.First();

                            addressInfo.TokenBalance = tokenAddress.Balance.ToString("F8", CultureInfo.InvariantCulture);

                            var tokenCode = tokenAddress?.TokenBalance?.Symbol;

                            if (tokenCode != null)
                                addressInfo.TokenBalance += $" {tokenCode}";
                        }
                        else
                        {
                            addressInfo.TokenBalance = $"{addressWithTokens.Count()} TOKENS";
                        }
                    }
                }

                OnPropertyChanged(nameof(Addresses));
                OnPropertyChanged(nameof(HasTokens));
            }
            catch (Exception e)
            {
                Log.Error(e, "Error while reload addresses list.");
            }
        }

19 Source : AddressesViewModel.cs
with GNU General Public License v3.0
from atomex-me

private void CopyToClipboard(string address)
        {
            try
            {
                Clipboard.SetText(address);

                Warning = "Address successfully copied to clipboard.";
             }
            catch (Exception e)
            {
                Log.Error(e, "Copy to clipboard error");
            }
        }

19 Source : AddressesViewModel.cs
with GNU General Public License v3.0
from atomex-me

private void OpenInExplorer(string address)
        {
            try
            {
                if (Uri.TryCreate($"{_currency.AddressExplorerUri}{address}", UriKind.Absolute, out var uri))
                    Process.Start(uri.ToString());
                else
                    Log.Error("Invalid uri for address explorer");
            }
            catch (Exception e)
            {
                Log.Error(e, "Open in explorer error");
            }
        }

19 Source : AddressesViewModel.cs
with GNU General Public License v3.0
from atomex-me

private void OpenInExplorer(string address)
        {
            try
            {
                if (Uri.TryCreate($"{_currency.AddressExplorerUri}{address}", UriKind.Absolute, out var uri))
                    Process.Start(uri.ToString());
                else
                    Log.Error("Invalid uri for address explorer");
            }
            catch (Exception e)
            {
                Log.Error(e, "Open in explorer error");
            }
        }

19 Source : AddressesViewModel.cs
with GNU General Public License v3.0
from atomex-me

private async void Update(string address)
        {
            if (_isBalanceUpdating)
                return;

            _isBalanceUpdating = true;

            _cancellation = new CancellationTokenSource();

            await _dialogViewer.ShowProgressAsync(
                replacedle: "Address balance updating...",
                message: "Please wait!",
                canceled: () => { _cancellation.Cancel(); });

            try
            {
                await new HdWalletScanner(_app.Account)
                    .ScanAddressAsync(_currency.Name, address, _cancellation.Token);

                if (_currency.Name == TezosConfig.Xtz && _tokenContract != null)
                {
                    // update tezos token balance
                    var tezosAccount = _app.Account
                        .GetCurrencyAccount<TezosAccount>(TezosConfig.Xtz);

                    await new TezosTokensScanner(tezosAccount)
                        .ScanContractAsync(address, _tokenContract);

                    // reload balances for all tezos tokens account
                    foreach (var currency in _app.Account.Currencies)
                        if (Currencies.IsTezosToken(currency.Name))
                            _app.Account
                                .GetCurrencyAccount<TezosTokenAccount>(currency.Name)
                                .ReloadBalances();
                }

                RealodAddresses();

            }
            catch (OperationCanceledException)
            {
                Log.Debug("Address balance update operation canceled");
            }
            catch (Exception e)
            {
                Log.Error(e, "AddressesViewModel.OnUpdateClick");
                // todo: message to user!?
            }

            _dialogViewer.HideProgress();

            _isBalanceUpdating = false;
        }

19 Source : AddressesViewModel.cs
with GNU General Public License v3.0
from atomex-me

private async void ExportKey(string address)
        {
            try
            {
                var result = await _dialogViewer.ShowMessageAsync(
                    "Warning!",
                    "Copying the private key to the clipboard may result in the loss of all your coins in the wallet. Are you sure you want to copy the private key?",
                    MessageDialogStyle.AffirmativeAndNegative);

                if (result == MessageDialogResult.Affirmative)
                {
                    var walletAddress = await _app.Account
                        .GetAddressAsync(_currency.Name, address);

                    var hdWallet = _app.Account.Wallet as HdWallet;

                    using var privateKey = hdWallet.KeyStorage.GetPrivateKey(
                        currency: _currency,
                        keyIndex: walletAddress.KeyIndex,
                        keyType: walletAddress.KeyType);

                    using var unsecuredPrivateKey = privateKey.ToUnsecuredBytes();

                    if (Currencies.IsBitcoinBased(_currency.Name))
                    {
                        var btcBasedConfig = _currency as BitcoinBasedConfig;

                        var wif = new NBitcoin.Key(unsecuredPrivateKey)
                            .GetWif(btcBasedConfig.Network)
                            .ToWif();

                        Clipboard.SetText(wif);
                    }
                    else if (Currencies.IsTezosBased(_currency.Name))
                    {
                        var base58 = unsecuredPrivateKey.Length == 32
                            ? Base58Check.Encode(unsecuredPrivateKey, Prefix.Edsk)
                            : Base58Check.Encode(unsecuredPrivateKey, Prefix.EdskSecretKey);

                        Clipboard.SetText(base58);
                    }
                    else
                    {
                        var hex = Hex.ToHexString(unsecuredPrivateKey.Data);

                        Clipboard.SetText(hex);
                    }

                    Warning = "Private key successfully copied to clipboard.";
                }
            }
            catch (Exception e)
            {
                Log.Error(e, "Private key export error");
            }
        }

19 Source : Profiler.cs
with MIT License
from Azure

public static async Task<T> Run<T>(Func<Task<T>> func, string message, params object[] properties)
        {
            Profiler profiler = Start();
            try
            {
                T t = await func();
                profiler.Stop(message, properties);
                return t;
            }
            catch (Exception e)
            {
                Log.Error($"Encountered exception during task \"{message}\": {e.Message}", properties);
                throw;
            }
        }

19 Source : MessageEmitter.cs
with MIT License
from Azure-Samples

private Measurement CreateMeasurementFromCsvLine(string line)
        {
            try
            {
                var data = line.Split(',');
                var sampleMeasurement = new Measurement()
                {
                    MachineId = data[1],
                    MachineTemperature = data[2],
                    AmbientTemperature = data[3],
                    ConveyorBeltSpeed = data[4],
                    GearTension = data[5],
                    WorkerDetected = data[6]
                };
                return sampleMeasurement;
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Error converting csv line {line} to object");
            }
            return null;
        }

19 Source : ProviderBase.cs
with Apache License 2.0
from Capnode

internal void RunProcess(string cmd, string[] args, IDictionary<string, string> configs)
        {
            bool ok = true;
            _process = new ConfigProcess(
                cmd,
                string.Join(" ", args),
                Directory.GetCurrentDirectory(),
                true,
                (line) => Log.Trace(line),
                (line) =>
                {
                    ok = false;
                    Log.Error(line, true);
                });

            // Set Environment
            StringDictionary environment = _process.Environment;

            // Set config file
            IDictionary<string, string> config = _process.Config;
            string exeFolder = MainService.GetProgramFolder();
            config["debug-mode"] = "true";
            config["composer-dll-directory"] = exeFolder;
            config["results-destination-folder"] = ".";
            config["plugin-directory"] = ".";
            config["log-handler"] = "ConsoleLogHandler";
            config["map-file-provider"] = "LocalDiskMapFileProvider";
            config["#command"] = cmd;
            config["#parameters"] = string.Join(" ", args);
            config["#work-directory"] = Directory.GetCurrentDirectory();
            foreach (KeyValuePair<string, string> item in configs)
            {
                config.Add(item);
            }

            // Start process
            try
            {
                _process.Start();
                _process.WaitForExit();
                if (!ok) throw new ApplicationException("See logs for details");
            }
            finally
            {
                _process.Dispose();
                _process = null;
            }
        }

19 Source : ListViewModel.cs
with Apache License 2.0
from Capnode

private void DoExportList()
        {
            try
            {
                IsBusy = true;
                DataToModel();
                SaveFileDialog saveFileDialog = new()
                {
                    InitialDirectory = Directory.GetCurrentDirectory(),
                    Filter = "symbol file (*.csv)|*.csv|All files (*.*)|*.*"
                };
                if (saveFileDialog.ShowDialog() == false)
                    return;

                try
                {
                    string fileName = saveFileDialog.FileName;
                    using StreamWriter file = File.CreateText(fileName);
                    foreach (SymbolViewModel symbol in Symbols)
                    {
                        file.WriteLine(symbol.Model.Id);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, $"Failed reading {saveFileDialog.FileName}\n", true);
                }
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : MainViewModel.cs
with Apache License 2.0
from Capnode

private async Task Initialize()
        {
            try
            {
                IsBusy = true;
                Messenger.Default.Send(new NotificationMessage(Resources.LoadingConfiguration));

                // Set config
                Config.Set("data-directory", SettingsViewModel.Model.DataFolder);
                Config.Set("data-folder", SettingsViewModel.Model.DataFolder);
                Config.Set("cache-location", SettingsViewModel.Model.DataFolder);
                Config.Set("map-file-provider", "QuantConnect.Data.Auxiliary.LocalDiskMapFileProvider");

                // Initialize data folders
                string program = MainService.GetProgramFolder();
                string appDataFolder = MainService.GetAppDataFolder();
                string programDataFolder = MainService.GetProgramDataFolder();
                string userDataFolder = MainService.GetUserDataFolder();
                Log.Trace($"Program folder: {program}");
                Log.Trace($"AppData folder: {appDataFolder}");
                Log.Trace($"ProgramData folder: {programDataFolder}");
                Log.Trace($"UserData folder: {userDataFolder}");
                MainService.Delete(Path.Combine(programDataFolder, "market-hours"));
                MainService.Delete(Path.Combine(programDataFolder, "symbol-properties"));
                MainService.DeleteFolders(appDataFolder, "temp*");
                MainService.CopyDirectory(Path.Combine(program, "Content/AppData"), appDataFolder, false);
                MainService.CopyDirectory(Path.Combine(program, "Content/ProgramData"), programDataFolder, false);
                MainService.CopyDirectory(Path.Combine(program, "Content/UserData"), userDataFolder, false);

                // Read settings
                string appData = MainService.GetAppDataFolder();
                await SettingsViewModel.ReadAsync(Path.Combine(appData, "Settings.json")).ConfigureAwait(true);

                // Register providers
                ProviderFactory.RegisterProviders(SettingsViewModel.Model);

                // Read configuration
                MarketsViewModel.Read(Path.Combine(appData, "Markets.json"));
                await StrategiesViewModel.ReadAsync(Path.Combine(appData, "Strategies.json")).ConfigureAwait(true);

                // Initialize Research page
                ResearchViewModel.Initialize();
                Messenger.Default.Send(new NotificationMessage(Resources.LoadingConfigurationCompleted));
            }
            catch (Exception ex)
            {
                string message = $"{ex.Message} ({ex.GetType()})";
                Messenger.Default.Send(new NotificationMessage(message));
                Log.Error(ex, message);
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : MainViewModel.cs
with Apache License 2.0
from Capnode

private async Task DoUpdate()
        {
            await _initializer.ConfigureAwait(false);
            try
            {
                IsBusy = true;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : MarketViewModel.cs
with Apache License 2.0
from Capnode

private async Task StartMarketAsync()
        {
            try
            {
                DataToModel();
                _provider = ProviderFactory.CreateProvider(Model.Provider, _settings);
                if (_provider == null) throw new ApplicationException($"Can not create provider {Model.Provider}");
                Messenger.Default.Send(new NotificationMessage(string.Format(Resources.MarketStarted, Model.Name)));
                await Task.Run(() => MarketLoop(Model)).ConfigureAwait(false);
                IList<string> symbols = Model.Symbols.Where(x => x.Active).Select(m => m.Id).ToList();
                if (symbols.Any())
                {
                    Messenger.Default.Send(new NotificationMessage(string.Format(Resources.MarketCompleted, Model.Name)));
                }
                else
                {
                    Messenger.Default.Send(new NotificationMessage(string.Format(Resources.MarketNoSymbol, Model.Name)));
                }
            }
            catch (ApplicationException ex)
            {
                Messenger.Default.Send(new NotificationMessage(string.Format(Resources.MarketException, Model.Name, ex.Message)));
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Messenger.Default.Send(new NotificationMessage($"{ex.GetType()}: {ex.Message}"));
            }
            finally
            {
                _provider?.Dispose();
                _provider = null;
                UiThread(() =>
                {
                    ProviderModel model = Model;
                    Model = null;
                    Model = model;
                    DataFromModel();
                });
            }
        }

19 Source : MarketViewModel.cs
with Apache License 2.0
from Capnode

private void DoImportSymbols()
        {
            OpenFileDialog openFileDialog = new()
            {
                InitialDirectory = Directory.GetCurrentDirectory(),
                Multiselect = false,
                Filter = "symbol file (*.csv)|*.csv|All files (*.*)|*.*"
            };
            if (openFileDialog.ShowDialog() == false)
                return;

            try
            {
                IsBusy = true;
                foreach (string fileName in openFileDialog.FileNames)
                {
                    using var r = new StreamReader(fileName);
                    while (!r.EndOfStream)
                    {
                        string line = r.ReadLine();
                        foreach (string name in line.Split(',').Where(m => !string.IsNullOrWhiteSpace(m)))
                        {
                            SymbolModel symbol = Model.Symbols.FirstOrDefault(m => m.Id.Equals(name, StringComparison.OrdinalIgnoreCase));
                            if (symbol != null)
                            {
                                symbol.Active = true;
                            }
                            else
                            {
                                symbol = new SymbolModel(name, string.Empty, SecurityType.Base);
                                Model.Symbols.Add(symbol);
                            }
                        }
                    }
                }

                Lists.ToList().ForEach(m => m.Refresh());
                DataFromModel();
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Failed reading {openFileDialog.FileName}\n", true);
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : MarketViewModel.cs
with Apache License 2.0
from Capnode

private void DoExportSymbols(IList symbols)
        {
            Debug.replacedert(symbols != null);
            if (symbols.Count == 0)
                return;

            var saveFileDialog = new SaveFileDialog
            {
                InitialDirectory = Directory.GetCurrentDirectory(),
                Filter = "symbol file (*.csv)|*.csv|All files (*.*)|*.*"
            };
            if (saveFileDialog.ShowDialog() == false)
                return;

            try
            {
                IsBusy = true;
                string fileName = saveFileDialog.FileName;
                using StreamWriter file = File.CreateText(fileName);
                foreach (SymbolViewModel symbol in symbols)
                {
                    file.WriteLine(symbol.Model.Id);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Failed writing {saveFileDialog.FileName}\n", true);
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : MarketViewModel.cs
with Apache License 2.0
from Capnode

private void DoImportList()
        {
            var openFileDialog = new OpenFileDialog
            {
                InitialDirectory = Directory.GetCurrentDirectory(),
                Multiselect = true,
                Filter = "symbol file (*.csv)|*.csv|All files (*.*)|*.*"
            };

            if (openFileDialog.ShowDialog() == false)
            {
                return;
            }

            try
            {
                IsBusy = true;
                foreach (string fileName in openFileDialog.FileNames)
                {
                    var model = new ListModel { Name = Path.GetFileNameWithoutExtension(fileName) };
                    Model.Lists.Add(model);
                    using var r = new StreamReader(fileName);
                    while (!r.EndOfStream)
                    {
                        string line = r.ReadLine();
                        foreach (string name in line.Split(',').Where(m => !string.IsNullOrWhiteSpace(m)))
                        {
                            var symbol = Model.Symbols.FirstOrDefault(m =>
                                m.Id.Equals(name, StringComparison.OrdinalIgnoreCase) &&
                                m.Active);
                            if (symbol != null)
                            {
                                model.Symbols.Add(symbol);
                            }
                        }
                    }
                }

                DataFromModel();
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Failed reading {openFileDialog.FileName}\n", true);
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : MarketViewModel.cs
with Apache License 2.0
from Capnode

private void DbUpgrade(SymbolModel symbol)
        {
            var basedir = new DirectoryInfo(DataFolder);
            foreach (DirectoryInfo securityDir in basedir.GetDirectories())
            {
                foreach (DirectoryInfo marketDir in securityDir.GetDirectories())
                {
                    foreach (DirectoryInfo resolutionDir in marketDir.GetDirectories())
                    {
                        if (resolutionDir.GetDirectories(symbol.Id).Any()
                            || resolutionDir.GetFiles(symbol.Id + ".zip").Any())
                        {
                            if (Enum.TryParse<SecurityType>(securityDir.Name, true, out SecurityType security))
                            {
                                symbol.Security = security;
                                symbol.Market = marketDir.Name;
                                Log.Trace($"DB upgrade symbol {symbol}");
                                return;
                            }
                        }
                    }
                }
            }

            Log.Error($"DB upgrade symbol {symbol} failed!", true);
        }

19 Source : ResearchViewModel.cs
with Apache License 2.0
from Capnode

public void Initialize()
        {
            try
            {
                StopJupyter();
                SetNotebookFolder();
                _process = new ConfigProcess(
                    "jupyter.exe",
                    $"lab --no-browser",
                    _settings.Notebook,
                    false,
                    (line) => Log.Trace(line),
                    (line) =>
                    {
                        if (string.IsNullOrEmpty(line)) return;

                        int pos = line.IndexOf("http", StringComparison.OrdinalIgnoreCase);
                        if (string.IsNullOrEmpty(Source) && pos > 0)
                        {
                            Source = line[pos..];
                        }

                        Log.Trace(line);
                    });

                // Setup Python and Jupyter environment
                string exeFolder = MainService.GetProgramFolder();
                PythonSupport.SetupJupyter(_process.Environment, exeFolder);
                PythonSupport.SetupPython(_process.Environment);

                // Set config file
                IDictionary<string, string> config = _process.Config;
                config["algorithm-language"] = Language.Python.ToString();
                config["composer-dll-directory"] = exeFolder.Replace("\\", "/");
                config["data-folder"] = _settings.DataFolder.Replace("\\", "/");
                config["api-handler"] = "QuantConnect.Api.Api";
                config["job-queue-handler"] = "QuantConnect.Queues.JobQueue";
                config["messaging-handler"] = "QuantConnect.Messaging.Messaging";

                // Start process
                _process.Start();
                Initialized = true;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Python must also be installed to use Research page.\nSee: https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#quantconnect-python-algorithm-project \n");
                _process = null;
            }
        }

19 Source : SettingsViewModel.cs
with Apache License 2.0
from Capnode

public async Task<bool> ReadAsync(string fileName)
        {
            Log.Trace($"Reading {fileName}");
            if (File.Exists(fileName))
            {
                try
                {
                    using StreamReader r = new(fileName);
                    string json = r.ReadToEnd();
                    SettingModel settings = JsonConvert.DeserializeObject<SettingModel>(json);
                    Model.Copy(settings);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, $"Failed reading {fileName}\n", true);
                    return false;
                }
            }

            DataFromModel();
            return await Task.FromResult(true).ConfigureAwait(false);
        }

19 Source : SettingsViewModel.cs
with Apache License 2.0
from Capnode

internal bool Save(string fileName)
        {
            try
            {
                DataToModel();

                using StreamWriter file = File.CreateText(fileName);
                JsonSerializer serializer = new() { Formatting = Formatting.Indented };
                serializer.Serialize(file, Model);
                return true;
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Failed writing {fileName}\n", true);
                return false;
            }
        }

19 Source : StrategiesViewModel.cs
with Apache License 2.0
from Capnode

private void DoImportStrategies()
        {
            var openFileDialog = new OpenFileDialog
            {
                InitialDirectory = Directory.GetCurrentDirectory(),
                Multiselect = true,
                Filter = "json file (*.json)|*.json|All files (*.*)|*.*"
            };
            if (openFileDialog.ShowDialog() != true)
                return;

            try
            {
                IsBusy = true;
                foreach (string fileName in openFileDialog.FileNames)
                {
                    using var r = new StreamReader(fileName);
                    string json = r.ReadToEnd();
                    StrategiesModel strategies = JsonConvert.DeserializeObject<StrategiesModel>(json);
                    foreach (StrategyModel strategy in strategies.Strategies)
                    {
                        foreach (TrackModel track in strategy.Tracks)
                        {
                            track.Active = false;
                        }

                        Model.Strategies.Add(strategy);
                    }
                }

                DataFromModel();
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Failed reading {openFileDialog.FileName}\n", true);
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : ConfigProcess.cs
with Apache License 2.0
from Capnode

public bool Abort()
        {
            if (!_started) return true;

            // Send Ctrl-C
            if (AttachConsole((uint)_process.Id))
            {
                _abort = true;
                SetConsoleCtrlHandler(null, true);
                try
                {
                    if (!GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)) return false;
                    if (_process.WaitForExit(_timeout)) return true;
                    Debug.replacedert(!_process.HasExited);
                    _process.Kill();
                    if (_process.WaitForExit(_timeout)) return true;
                    return false;
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    return false;
                }
                finally
                {
                    FreeConsole();
                    SetConsoleCtrlHandler(null, false);
                    _started = false;
                }
            }

            return _process.HasExited;
        }

19 Source : LeanLauncher.cs
with Apache License 2.0
from Capnode

public void Run(TrackModel model, AccountModel account, SettingModel settings)
        {
            if (model == null) throw new ArgumentNullException(nameof(model));
            Debug.replacedert(model.Status == CompletionStatus.None);
            if (!model.Active) return;

            bool error = false;
            _process = new ConfigProcess(
                "QuantConnect.Lean.Launcher.exe",
                null,
                Directory.GetCurrentDirectory(),
                true,
                (line) => Log.Trace(line),
                (line) =>
                {
                    error = true;
                    Log.Error(line, true);
                });

            // Set Environment
            StringDictionary environment = _process.Environment;

            // Set config
            IDictionary<string, string> config = _process.Config;
            if (!SetConfig(config, model, account, settings)) return;

            // Start process
            try
            {
                if (model.AlgorithmLanguage.Equals(Language.Python))
                {
                    PythonSupport.SetupPython(_process.Environment);
                }
                _process.Start();
                _process.WaitForExit(int.MaxValue, (folder) => PostProcess(folder, model));
                model.Status = error ? CompletionStatus.Error : CompletionStatus.Success;
            }
            catch (Exception ex)
            {
                model.Status = CompletionStatus.Error;
                Log.Error($"{ex.GetType()}: {ex.Message}", true);

            }
            finally
            {
                _process.Dispose();
                _process = null;
                model.Active = false;
            }
        }

19 Source : LeanLauncher.cs
with Apache License 2.0
from Capnode

private static bool SetConfig(
            IDictionary<string, string> config,
            TrackModel model,
            AccountModel account,
            SettingModel settings)
        {
            var parameters = new Dictionary<string, string>();
            SetModel(config, model, settings);
            if (model.Account.Equals(AccountModel.AccountType.Backtest.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                SetBacktest(config);
            }
            else if (model.Account.Equals(AccountModel.AccountType.Paper.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                SetPaper(config);
            }
            else if (account == default)
            {
                Log.Error("No broker selected", true);
                return false;
            }

            SetParameters(config, model, parameters);
            return true;
        }

19 Source : StrategyViewModel.cs
with Apache License 2.0
from Capnode

private void DoImportSymbols()
        {
            var openFileDialog = new OpenFileDialog
            {
                InitialDirectory = Directory.GetCurrentDirectory(),
                Multiselect = false,
                Filter = "symbol file (*.csv)|*.csv|All files (*.*)|*.*"
            };
            if (openFileDialog.ShowDialog() == false)
                return;

            try
            {
                IsBusy = true;
                foreach (string fileName in openFileDialog.FileNames)
                {
                    using var r = new StreamReader(fileName);
                    while (!r.EndOfStream)
                    {
                        string line = r.ReadLine();
                        foreach (string name in line.Split(',').Where(m => !string.IsNullOrWhiteSpace(m)))
                        {
                            if (Model.Symbols.FirstOrDefault(m => m.Id.Equals(name, StringComparison.OrdinalIgnoreCase)) == null)
                            {
                                var symbol = new SymbolModel(name, Model.Market, Model.Security);
                                Model.Symbols.Add(symbol);
                            }
                        }
                    }
                }

                DataFromModel();
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Failed reading {openFileDialog.FileName}\n");
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : StrategyViewModel.cs
with Apache License 2.0
from Capnode

private void DoExportStrategy()
        {
            DataToModel();
            var saveFileDialog = new SaveFileDialog
            {
                InitialDirectory = Directory.GetCurrentDirectory(),
                FileName = Model.Name,
                Filter = "json file (*.json)|*.json|All files (*.*)|*.*"
            };
            if (saveFileDialog.ShowDialog() == false)
                return;

            try
            {
                IsBusy = true;
                string fileName = saveFileDialog.FileName;
                using StreamWriter file = File.CreateText(fileName);
                var serializer = new JsonSerializer();
                var strategies = new StrategiesModel();
                strategies.Strategies.Add(Model);
                serializer.Serialize(file, strategies);
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Failed writing {saveFileDialog.FileName}\n");
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : StrategyViewModel.cs
with Apache License 2.0
from Capnode

private void DoExportSymbols(IList symbols)
        {
            Debug.replacedert(symbols != null);
            if (Symbols.Count == 0 || symbols.Count == 0)
                return;

            DataToModel();
            var saveFileDialog = new SaveFileDialog
            {
                InitialDirectory = Directory.GetCurrentDirectory(),
                Filter = "symbol file (*.csv)|*.csv|All files (*.*)|*.*"
            };
            if (saveFileDialog.ShowDialog() == false)
                return;

            try
            {
                IsBusy = true;
                string fileName = saveFileDialog.FileName;
                using StreamWriter file = File.CreateText(fileName);
                foreach (SymbolViewModel symbol in symbols)
                {
                    file.WriteLine(symbol.Model.Id);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Failed writing {saveFileDialog.FileName}\n");
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : TrackViewModel.cs
with Apache License 2.0
from Capnode

internal async Task StartTrackAsync()
        {
            Debug.replacedert(Active);
            ClearRunData();

            // Account must not be null
            if (Model.Account == null)
            {
                UiThread(() =>
                {
                    Active = false;
                });
                Log.Error($"Strategy {Model.Name}: Account is not defined!", true);
                return;
            }

            // Find account
            AccountModel account = _markets.FindAccount(Model.Account);

            // Set search path if not base directory
            string folder = Path.GetDirectoryName(MainService.FullExePath(Model.AlgorithmLocation));
            string exeFolder = MainService.GetProgramFolder();
            if (!string.IsNullOrEmpty(folder) && !exeFolder.Equals(folder, StringComparison.OrdinalIgnoreCase))
            {
                StrategyViewModel.AddPath(folder);
            }

            TrackModel model = Model;
            await Task.Run(() => _leanLauncher.Run(model, account, _settings))
                .ConfigureAwait(false);

            // Split result and logs to separate files
            if (model.Status.Equals(CompletionStatus.Success) || model.Status.Equals(CompletionStatus.Error))
            {
                SplitModelToFiles(model);
            }

            // Update view
            Model = null;
            Model = model;

            UiThread(() =>
            {
                Active = false;
                DataFromModel();
            });
        }

19 Source : TrackViewModel.cs
with Apache License 2.0
from Capnode

private void DoExportSymbols(IList symbols)
        {
            Debug.replacedert(symbols != null);
            if (symbols.Count == 0)
                return;

            var saveFileDialog = new SaveFileDialog
            {
                InitialDirectory = Directory.GetCurrentDirectory(),
                Filter = "symbol file (*.csv)|*.csv|All files (*.*)|*.*"
            };
            if (saveFileDialog.ShowDialog() == false)
                return;

            try
            {
                IsBusy = true;
                string fileName = saveFileDialog.FileName;
                using StreamWriter file = File.CreateText(fileName);
                foreach (TrackSymbolViewModel symbol in symbols)
                {
                    file.WriteLine(symbol.Symbol);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Failed writing {saveFileDialog.FileName}\n", true);
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : Compression.cs
with Apache License 2.0
from Capnode

public static bool ZipData(string zipPath, Dictionary<string, string> filenamesAndData)
        {
            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var filename in filenamesAndData.Keys)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(filename);
                        var data = filenamesAndData[filename];
                        var bytes = Encoding.Default.GetBytes(data);
                        stream.PutNextEntry(entry);
                        stream.Write(bytes, 0, bytes.Length);
                        stream.CloseEntry();
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error(err);
                return false;
            }
            return true;
        }

19 Source : Compression.cs
with Apache License 2.0
from Capnode

public static bool ZipData(string zipPath, IEnumerable<KeyValuePair<string, byte[]>> filenamesAndData)
        {
            var success = true;
            var buffer = new byte[4096];

            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var file in filenamesAndData)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(file.Key);
                        //Get a Byte[] of the file data:
                        stream.PutNextEntry(entry);

                        using (var ms = new MemoryStream(file.Value))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = ms.Read(buffer, 0, buffer.Length);
                                stream.Write(buffer, 0, sourceBytes);
                            }
                            while (sourceBytes > 0);
                        }
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error(err);
                success = false;
            }
            return success;
        }

19 Source : Compression.cs
with Apache License 2.0
from Capnode

public static bool ZipData(string zipPath, string zipEntry, IEnumerable<string> lines)
        {
            try
            {
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                using (var writer = new StreamWriter(stream))
                {
                    var entry = new ZipEntry(zipEntry);
                    stream.PutNextEntry(entry);
                    foreach (var line in lines)
                    {
                        writer.WriteLine(line);
                    }
                }
                return true;
            }
            catch (Exception err)
            {
                Log.Error(err);
                return false;
            }
        }

See More Examples