Пример #1
0
        private static void RegisterProfiler(ContainerBuilder builder)
        {
            if (ConfigurationHelpers.ShouldBeProfiling())
            {
                builder.Register((c, p) => new TextReporter(p.TypedAs <Func <Stream> >()))
                .As <TextReporter>()
                .As <ITransformReports>();

                builder.Register(c => new TimingStorage())
                .OnRelease(
                    storage =>
                {
                    // Write all the profiling results out to disk. Do this the ugly way
                    // because we don't know if any of the other items in the container have
                    // been removed yet.
                    Func <Stream> factory =
                        () => new FileStream(
                            Path.Combine(FileConstants.LogPath(), DefaultProfilerFileName),
                            FileMode.Append,
                            FileAccess.Write,
                            FileShare.Read);
                    var reporter = new TextReporter(factory);
                    reporter.Transform(storage.FromStartTillEnd());
                })
                .As <IStoreIntervals>()
                .As <IGenerateTimingReports>()
                .SingleInstance();

                builder.Register(c => new Profiler(
                                     c.Resolve <IStoreIntervals>()))
                .SingleInstance();
            }
        }
Пример #2
0
        private static AppDomainResolutionPaths AppDomainResolutionPathsFor(AppDomainPaths paths)
        {
            List <string> filePaths      = new List <string>();
            List <string> directoryPaths = new List <string>();

            if ((paths & AppDomainPaths.Core) == AppDomainPaths.Core)
            {
                directoryPaths.Add(Assembly.GetExecutingAssembly().LocalDirectoryPath());
            }

            if ((paths & AppDomainPaths.Plugins) == AppDomainPaths.Plugins)
            {
                // Plugins can be found in:
                // - The plugins directory in the main app directory (i.e. <INSTALL_DIRECTORY>\plugins)
                // - In the machine location for plugins (i.e. <COMMON_APPLICATION_DATA>\<COMPANY>\plugins)
                // - In the user location for plugins (i.e. <LOCAL_APPLICATION_DATA>\<COMPANY>\plugins)
                directoryPaths.Add(Path.Combine(Assembly.GetExecutingAssembly().LocalDirectoryPath(), PluginsDirectoryName));
                directoryPaths.Add(Path.Combine(FileConstants.CompanyCommonPath(), PluginsDirectoryName));
                directoryPaths.Add(Path.Combine(FileConstants.CompanyUserPath(), PluginsDirectoryName));
            }

            return(AppDomainResolutionPaths.WithFilesAndDirectories(
                       Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath),
                       filePaths,
                       directoryPaths));
        }
        /// <summary>
        /// Read object from file and deserialize JSON and map to object
        /// </summary>
        /// <returns></returns>
        public ObservableCollection <AccountMinerTypeExtraParams> ReadJsonFromFile()
        {
            string filePath = Path.Combine(FileConstants.ConfigFilePath(), FileNameConstants.MinerTypeExtraParamsFileName);

            // Create new empty list of miner type extra params
            ObservableCollection <AccountMinerTypeExtraParams> accountMinerTypeExtraParamsList = new ObservableCollection <AccountMinerTypeExtraParams>();

            try
            {
                if (File.Exists(filePath))
                {
                    // deserialize JSON directly from a file
                    using (StreamReader file = File.OpenText(filePath))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        accountMinerTypeExtraParamsList = (ObservableCollection <AccountMinerTypeExtraParams>)serializer.Deserialize(file, typeof(ObservableCollection <AccountMinerTypeExtraParams>));
                    }
                }
                else
                {
                    accountMinerTypeExtraParamsList = InitEmptyMinerTypeExtraParams();
                }
                return(accountMinerTypeExtraParamsList);
            }
            catch (Exception e)
            {
                accountMinerTypeExtraParamsList = InitEmptyMinerTypeExtraParams();

                NLogProcessing.LogError(e, "Miner type extra parameters could not be loaded. Using default values.");

                // Return defaults
                return(accountMinerTypeExtraParamsList);
            }
        }
Пример #4
0
        public static int Main()
        {
            int functionReturnResult = -1;

            using (var app = new App())
            {
                Action applicationAction =
                    () =>
                {
                    app.InitializeComponent();
                    app.Run();

                    functionReturnResult = NormalApplicationExitCode;
                };

                using (var processor = new LogBasedExceptionProcessor(
                           LoggerBuilder.ForFile(
                               Path.Combine(FileConstants.LogPath(), DefaultErrorFileName),
                               new DebugLogTemplate(new NullConfiguration(), () => DateTimeOffset.Now))))
                {
                    var result = TopLevelExceptionGuard.RunGuarded(
                        applicationAction,
                        new ExceptionProcessor[]
                    {
                        processor.Process,
                    });

                    return((result == GuardResult.Failure) ? UnhandledExceptionApplicationExitCode : functionReturnResult);
                }
            }
        }
        /// <summary>
        /// Serialize object to JSON and write/overwrite file
        /// </summary>
        /// <param name="accountMinerTypeExtraParamsList"></param>
        public void WriteJsonToFile(ObservableCollection <AccountMinerTypeExtraParams> accountMinerTypeExtraParamsList)
        {
            // Iterate through MinerBaseTypes and insert any missing miners to the list of
            // extra params
            foreach (MinerBaseType minerBaseType in Enum.GetValues(typeof(MinerBaseType)))
            {
                if (accountMinerTypeExtraParamsList.Any(x => x.MinerBaseTypeString == minerBaseType.ToString()) == false && minerBaseType != MinerBaseType.UNDEFINED)
                {
                    AccountMinerTypeExtraParams accountMinerTypeExtraParams = new AccountMinerTypeExtraParams();
                    accountMinerTypeExtraParams.ExtraParams         = "";
                    accountMinerTypeExtraParams.MinerBaseTypeString = minerBaseType.ToString();
                    accountMinerTypeExtraParamsList.Add(accountMinerTypeExtraParams);
                }
            }

            string filePath = Path.Combine(FileConstants.ConfigFilePath(), FileNameConstants.MinerTypeExtraParamsFileName);

            try
            {
                // serialize JSON directly to a file
                using (StreamWriter file = File.CreateText(filePath))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Serialize(file, accountMinerTypeExtraParamsList);
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException(string.Format("Error writing file {0}", filePath), e);
            }
        }
        /// <summary>
        /// Read object from file and deserialize JSON and map to object
        /// </summary>
        /// <returns></returns>
        public WorkerSettings ReadJsonFromFile()
        {
            string         filePath       = Path.Combine(FileConstants.ConfigFilePath(), FileNameConstants.WorkerSettingsFileName);
            WorkerSettings workerSettings = new WorkerSettings();

            try
            {
                if (File.Exists(filePath))
                {
                    // deserialize JSON directly from a file
                    using (StreamReader file = File.OpenText(filePath))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        workerSettings = (WorkerSettings)serializer.Deserialize(file, typeof(WorkerSettings));
                    }
                }
                else
                {
                    workerSettings = InitEmptyWorkerSettings(workerSettings);
                }
                return(workerSettings);
            }
            catch (Exception e)
            {
                workerSettings = InitEmptyWorkerSettings(workerSettings);

                NLogProcessing.LogError(e, "Worker settings could not be loaded. Using default values.");

                // Return defaults
                return(workerSettings);
            }
        }
Пример #7
0
        //#region "NLog"
        //NLog.Config.LoggingConfiguration config;
        //NLog.Targets.FileTarget logfile;
        //#endregion

        public static void SetupLogging()
        {
            try
            {
                var logFilePath = FileConstants.LogFilePath();
                var logFile     = Path.Combine(logFilePath, FileConstants.LogFileName);

                NLog.Config.LoggingConfiguration config  = new NLog.Config.LoggingConfiguration();
                NLog.Targets.FileTarget          logfile = new NLog.Targets.FileTarget()
                {
                    FileName         = logFile,
                    Layout           = "${longdate} ${level} ${callsite}: ${message}  ${exception}",
                    ArchiveNumbering = NLog.Targets.ArchiveNumberingMode.DateAndSequence,
                    MaxArchiveFiles  = 3,
                    ArchiveAboveSize = 1048576  // 1 MB
                };

                config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
                NLog.LogManager.Configuration = config;
            }
            catch
            {
                // Could not create log folder for some reason.
                // Let this continue for now.
            }
        }
Пример #8
0
 private static void RegisterLoggers(ContainerBuilder builder)
 {
     builder.Register(c => LoggerBuilder.ForFile(
                          Path.Combine(FileConstants.LogPath(), DefaultInfoFileName),
                          new DebugLogTemplate(
                              c.Resolve <IConfiguration>(),
                              () => DateTimeOffset.Now)))
     .As <ILogger>()
     .SingleInstance();
 }
Пример #9
0
 private static void RegisterLoggers(ContainerBuilder builder)
 {
     builder.Register(c => LoggerBuilder.ForFile(
                          Path.Combine(
                              FileConstants.LogPath(),
                              string.Format(
                                  CultureInfo.InvariantCulture,
                                  DefaultInfoFileName,
                                  Process.GetCurrentProcess().Id)),
                          new DebugLogTemplate(
                              c.Resolve <IConfiguration>(),
                              () => DateTimeOffset.Now)))
     .As <ILogger>()
     .SingleInstance();
 }
        /// <summary>
        /// Serialize object to JSON and write/overwrite file
        /// </summary>
        /// <param name="workerSettings"></param>
        public void WriteJsonToFile(WorkerSettings workerSettings)
        {
            string filePath = Path.Combine(FileConstants.ConfigFilePath(), FileNameConstants.WorkerSettingsFileName);

            try
            {
                // serialize JSON directly to a file
                using (StreamWriter file = File.CreateText(filePath))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Serialize(file, workerSettings);
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException(string.Format("Error writing file {0}", filePath), e);
            }
        }
Пример #11
0
        /// <summary>
        /// Serialize object to JSON and write/overwrite file
        /// </summary>
        /// <param name="accountIdentity"></param>
        public void WriteJsonToFile(AccountIdentity accountIdentity)
        {
            string filePath = Path.Combine(FileConstants.ConfigFilePath(), FileNameConstants.AccountIdentityFileName);

            try
            {
                // serialize JSON directly to a file
                using (StreamWriter file = File.CreateText(filePath))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Serialize(file, accountIdentity);
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException(string.Format("Error reading reading file {0}", filePath), e);
            }
        }
Пример #12
0
        private static void RegisterProfiler(ContainerBuilder builder)
        {
            try
            {
                var value = ConfigurationManager.AppSettings[LoadProfilerAppSetting];

                bool result;
                if (bool.TryParse(value, out result) && result)
                {
                    // Only register the storage and the profiler because we won't be writing out
                    // intermediate results here anyway. No point in registering report converters
                    builder.Register(c => new TimingStorage())
                    .OnRelease(
                        storage =>
                    {
                        // Write all the profiling results out to disk. Do this the ugly way
                        // because we don't know if any of the other items in the container have
                        // been removed yet.
                        Func <Stream> factory =
                            () => new FileStream(
                                Path.Combine(FileConstants.LogPath(), DefaultProfilerFileName),
                                FileMode.OpenOrCreate,
                                FileAccess.Write,
                                FileShare.Read);
                        var reporter = new TextReporter(factory);
                        reporter.Transform(storage.FromStartTillEnd());
                    })
                    .As <IStoreIntervals>();

                    builder.Register(c => new Profiler(
                                         c.Resolve <IStoreIntervals>()));
                }
            }
            catch (ConfigurationErrorsException)
            {
                // could not retrieve the AppSetting from the config file
                // meh ...
            }
        }
Пример #13
0
 private IEnumerable <string> FeedbackReportsFilePaths()
 {
     try
     {
         var path = FileConstants.CompanyUserPath();
         return(m_FileSystem.Directory.GetFiles(
                    path,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "*.{0}",
                        FileConstants.FeedbackReportExtension),
                    SearchOption.AllDirectories));
     }
     catch (UnauthorizedAccessException)
     {
         return(new List <string>());
     }
     catch (IOException)
     {
         return(new List <string>());
     }
 }
Пример #14
0
        static int Main(string[] args)
        {
            {
                Debug.Assert(args != null, "The arguments array should not be null.");
            }

            int functionReturnResult = -1;

            using (var processor = new LogBasedExceptionProcessor(
                       LoggerBuilder.ForFile(
                           Path.Combine(FileConstants.LogPath(), DefaultErrorFileName),
                           new DebugLogTemplate(new NullConfiguration(), () => DateTimeOffset.Now))))
            {
                var result = TopLevelExceptionGuard.RunGuarded(
                    () => functionReturnResult = RunApplication(args),
                    new ExceptionProcessor[]
                {
                    processor.Process,
                });

                return((result == GuardResult.Failure) ? UnhandledExceptionApplicationExitCode : functionReturnResult);
            }
        }
Пример #15
0
        /// <summary>
        /// Read object from file and deserialize JSON and map to object
        /// </summary>
        /// <returns></returns>
        public AccountIdentity ReadJsonFromFile()
        {
            string          filePath        = Path.Combine(FileConstants.ConfigFilePath(), FileNameConstants.AccountIdentityFileName);
            AccountIdentity accountIdentity = new AccountIdentity();

            try
            {
                if (File.Exists(filePath))
                {
                    // deserialize JSON directly from a file
                    using (StreamReader file = File.OpenText(filePath))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        accountIdentity = (AccountIdentity)serializer.Deserialize(file, typeof(AccountIdentity));
                    }
                }
                return(accountIdentity);
            }
            catch (Exception e)
            {
                NLogProcessing.LogError(e, "Could not load Account Identity file.");
                return(accountIdentity);
            }
        }
 public void Init()
 {
     _target = new FileConstants();
 }