Example #1
0
        static ChoEnvironmentSettings()
        {
            ChoConfigurationManager.Refresh();
            _appConfigFileWatcher = new ChoConfigurationChangeFileWatcher("AppConfigFileWatcher", ChoConfigurationManager.ApplicationConfigurationFilePath);
            _appConfigFileWatcher.DoNotUseGlobalQueue = true;

            _appConfigFileWatcher.SetConfigurationChangedEventHandler("OnEnvironmentChanged", (sender, e) =>
            {
                // ChoAppFrxSettings.RefreshSection();
                //ChoCommandLineParserSettings.RefreshSection();
                CheckNChangeEnvironment();
            });

            if (ChoApplication.OnInitialize != null)
            {
                ChoApplication.OnInitialize(ChoAppFrxSettings.Me);
            }

            Environment = ChoAppFrxSettings.Me.AppEnvironment.NTrim();
            _sharedEnvironmentConfigFilePath = ChoSharedEnvironmentManager.SharedEnvironmentConfigFilePath;
            _appFrxFilePath = ChoSharedEnvironmentManager.AppFrxFilePath;

            LoadSharedEnvironmentManager();
            _appConfigFileWatcher.StartWatching();
        }
Example #2
0
        public void OnObjectChanged(object sender, EventArgs e)
        {
            _instance = sender as ChoGlobalApplicationSettings;
            ChoApplication.Refresh();

            ChoEventManager.GetValue(GetType()).OnObjectChanged(sender, e);
        }
Example #3
0
        internal static void CheckNChangeEnvironment()
        {
            bool envChanged = false;

            string environment = ChoAppFrxSettings.Me.AppEnvironment.NTrim();
            string sharedEnvironmentConfigFilePath = ChoSharedEnvironmentManager.SharedEnvironmentConfigFilePath;
            string appFrxFilePath = ChoSharedEnvironmentManager.AppFrxFilePath;

            if (environment != Environment)
            {
                envChanged = true;
                ChoApplication.Trace(true, "Environment changed from '{0}' to '{1}'.".FormatString(Environment, environment));
                Environment = environment;
            }
            if (sharedEnvironmentConfigFilePath != _sharedEnvironmentConfigFilePath)
            {
                envChanged = true;
                ChoApplication.Trace(true, "SharedEnvironmentConfgiFilePath changed from '{0}' to '{1}'.".FormatString(_sharedEnvironmentConfigFilePath, sharedEnvironmentConfigFilePath));
                _sharedEnvironmentConfigFilePath = sharedEnvironmentConfigFilePath;
            }
            if (appFrxFilePath != _appFrxFilePath)
            {
                envChanged = true;
                ChoApplication.Trace(true, "AppFrxFilePath changed from '{0}' to '{1}'.".FormatString(_appFrxFilePath, appFrxFilePath));
                _appFrxFilePath = appFrxFilePath;
            }

            if (envChanged)
            {
                LoadSharedEnvironmentManager();
                OnEnvironmentChanged();
            }
        }
 private void RunAtStartup()
 {
     try
     {
         ChoApplication.RunAtSystemStartup(!this._runAtStartupContextMenuItem.Checked);
     }
     catch { }
 }
        protected override void OnAfterCommandLineArgObjectLoaded(string[] commandLineArgs)
        {
            ChoShellExtensionActionMode?sem = GetShellExtensionActionMode();

            if (DisplayAvailProperties || DisplayAvailTypeParsersNFormatters)
            {
                if (DisplayAvailProperties)
                {
                    ChoApplication.DisplayMsg(ChoPropertyManagerSettings.Me.GetHelpText(), null, ConsoleColor.Yellow);
                }
                if (DisplayAvailTypeParsersNFormatters)
                {
                    ChoApplication.DisplayMsg(ChoTypesManager.GetHelpText(), null, ConsoleColor.Green);
                }
                if (!ConfigObjectTypeName.IsNullOrWhiteSpace())
                {
                    ChoApplication.DisplayMsg(ChoConfigurationManager.GetHelpText(ChoType.GetType(ConfigObjectTypeName)), null, ConsoleColor.Green);
                }
                Environment.Exit(0);
            }
            else if (!ConfigObjectTypeName.IsNullOrWhiteSpace())
            {
                ChoApplication.DisplayMsg(ChoConfigurationManager.GetHelpText(ChoType.GetType(ConfigObjectTypeName)), null, ConsoleColor.Green);
                Environment.Exit(0);
            }
            else if (sem != null)
            {
                if (sem.Value == ChoShellExtensionActionMode.Register)
                {
                    ChoShellExtension.Register();
                    ChoTrace.WriteLine("Shell Extensions registered successfully.");

                    ChoShellFileAssociation.Register();
                    ChoTrace.WriteLine("File Associations registered successfully.");

                    Environment.Exit(0);
                }
                else if (sem.Value == ChoShellExtensionActionMode.Unregister)
                {
                    ChoShellExtension.Unregister();
                    ChoTrace.WriteLine("Shell Extensions unregistered successfully.");

                    ChoShellFileAssociation.Unregister();
                    ChoTrace.WriteLine("File Associations unregistered successfully.");

                    Environment.Exit(0);
                }
            }

            if (ChoShellExtension.ExecuteShellExtensionMethodIfAnySpecified(commandLineArgs))
            {
                ChoTrace.WriteLine("Shell Extension ran successfully.");
                Environment.Exit(0);
            }

            base.OnAfterCommandLineArgObjectLoaded(commandLineArgs);
        }
Example #6
0
        private static bool ReplaceToken(IChoPropertyReplacer[] propertyReplacers, StringBuilder message,
                                         string propertyName, string format, object context)
        {
            if (!String.IsNullOrEmpty(propertyName))
            {
                if (propertyName == "@this")
                {
                    if (context != null)
                    {
                        message.Append(ChoObject.Format(context, format));
                    }
                    return(true);
                }
                foreach (IChoPropertyReplacer propertyReplacer in propertyReplacers)
                {
                    if (!(propertyReplacer is IChoKeyValuePropertyReplacer))
                    {
                        continue;
                    }

                    IChoKeyValuePropertyReplacer dictionaryPropertyReplacer = propertyReplacer as IChoKeyValuePropertyReplacer;
                    if (dictionaryPropertyReplacer == null || !dictionaryPropertyReplacer.ContainsProperty(propertyName, context))
                    {
                        continue;
                    }
                    //if (propertyName.Contains("@this"))
                    //{
                    //    if (context == null)
                    //        context = message.ToString();

                    //    message.Clear();
                    //}

                    message.Append(dictionaryPropertyReplacer.ReplaceProperty(propertyName, format, context));
                    return(true);
                }
            }

            string propertyValue;
            bool   retValue = ChoApplication.OnPropertyResolve(propertyName, format, context, out propertyValue);

            if (retValue)
            {
                if (propertyValue != null)
                {
                    message.Append(propertyValue);
                }
                return(true);
            }

            //if (!format.IsNullOrWhiteSpace())
            //{
            //    message.Append(ChoObject.Format(propertyName, format));
            //    return true;
            //}
            return(false);
        }
Example #7
0
 private void RunAtStartup()
 {
     try
     {
         ChoApplication.RunAtSystemStartup("{0}_I".FormatString(ChoGlobalApplicationSettings.Me.ApplicationNameWithoutExtension),
                                           ChoAssembly.GetEntryAssembly().Location, !this._runAtStartupContextMenuItem.Checked);
     }
     catch { }
 }
Example #8
0
 protected virtual void OnShutdown()
 {
     try
     {
         OnStop();
     }
     catch (Exception ex)
     {
         ChoApplication.WriteToEventLog(ex.ToString());
     }
 }
Example #9
0
 private void FatalApplicationException(object sender, ChoFatalErrorEventArgs e)
 {
     try
     {
         ChoApplication.WriteToEventLog(e.ToString(), System.Diagnostics.EventLogEntryType.Error);
     }
     catch
     {
         //TODO: Write to system log
     }
 }
Example #10
0
        static ChoAppDomain()
        {
            //ChoApplication.Initialize();
            RegisterAppDomainEvents();
            string envPath = ChoEnvironmentSettings.GetConfigFilePath();
            ChoGlobalApplicationSettings x = ChoGlobalApplicationSettings.Me;

            ChoApplication.Refresh();
            ChoTypesManager.Initialize();
            ChoAbortableQueuedExecutionService asyncExecutionService = ChoAbortableQueuedExecutionService.Global;

            _Load();
        }
Example #11
0
        public string ReplaceProperty(string propertyName, string format, object context)
        {
            if (String.IsNullOrEmpty(propertyName))
            {
                return(propertyName);
            }

            switch (propertyName)
            {
            case "APPLICATION_NAME":
                return(ChoObject.Format(ChoGlobalApplicationSettings.Me.ApplicationName, format));

            case "PROCESS_ID":
                return(ChoObject.Format(ChoApplication.ProcessId, format));

            case "THREAD_ID":
                return(ChoObject.Format(ChoApplication.GetThreadId(), format));

            case "THREAD_NAME":
                return(ChoObject.Format(ChoApplication.GetThreadName(), format));

            case "RANDOM_NO":
                return(ChoObject.Format(ChoRandom.NextRandom(), format));

            case "TODAY":
                if (String.IsNullOrEmpty(format))
                {
                    return(System.DateTime.Today.ToShortDateString());
                }
                else
                {
                    return(ChoObject.Format(System.DateTime.Today, format));
                }

            case "NOW":
                if (String.IsNullOrEmpty(format))
                {
                    return(System.DateTime.Now.ToShortTimeString());
                }
                else
                {
                    return(ChoObject.Format(System.DateTime.Now, format));
                }

            case "SEQ_NO":
                return(ChoObject.Format(_sequenceGeneratorSettings.Value.Next(), format));

            default:
                return(ChoObject.Format(propertyName, format));
            }
        }
Example #12
0
 void _defaultContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e)
 {
     if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.ContextMenuSettings.DisplayRunAtSystemsStartupMenuItem)
     {
         if (ChoWindowsIdentity.IsAdministrator())
         {
             _runAtStartupContextMenuItem.Checked = ChoApplication.IsAppRunAtSystemStartup("{0}_I".FormatString(ChoGlobalApplicationSettings.Me.ApplicationNameWithoutExtension));
         }
         else
         {
             //_runAtStartupContextMenuItem.Text = ChoApplication.IsAppRunAtSystemStartup() ? "Remove Run at Systems &Startup" : "Run at Systems &Startup";
         }
     }
 }
Example #13
0
 /// <summary>
 /// This class should be created and passed into Application.Run( ... )
 /// </summary>
 public ChoApplicationContext(ChoApplicationHost appHost)
 {
     ChoGuard.ArgumentNotNull(appHost, "ApplicationHost");
     _appHost   = appHost;
     _mainForm  = appHost.GetMainWindowObject();
     _hasWindow = appHost.IsWindowApp;
     BuildDefaultContextMenu();
     this._components = new System.ComponentModel.Container();
     this.NotifyIcon  = new ChoNotifyIcon(this._components);
     PreInitializeContext(appHost);
     ChoApplication.RaiseAfterNotifyIconConstructed(NotifyIcon);
     InitializeContext(appHost);
     _defaultTrayTipMsg = "{0} is running...".FormatString(ChoGlobalApplicationSettings.Me.ApplicationName);
 }
        private static XmlDocument LoadBackupSharedEnvironmentConfigFile(string backupSharedEnvironmentConfigFilePath)
        {
            XmlDocument doc = new XmlDocument();

            if (!backupSharedEnvironmentConfigFilePath.IsNullOrEmpty() &&
                File.Exists(backupSharedEnvironmentConfigFilePath))
            {
                ChoApplication.Trace(true, "Loading backup shared environment config file: {0}".FormatString(backupSharedEnvironmentConfigFilePath));
                doc.Load(backupSharedEnvironmentConfigFilePath);
            }
            else
            {
                ChoApplication.Trace(true, "No backup shared environment config file found.");
            }

            return(doc);
        }
Example #15
0
        public static string ToString(object target, string formatName)
        {
            if (target == null)
            {
                return(String.Empty);
            }

            if (!HasFormatterSpecified(target))
            {
                Func <object, string> customFormatter = ChoGlobalObjectFormatters.GetObjectFormatHandler(target.GetType(), formatName);
                if (customFormatter != null)
                {
                    return(customFormatter(target));
                }
                else
                {
                    ICustomFormatter formatter = ChoFormatProvider.Instance.GetFormat(target.GetType()) as ICustomFormatter;

                    ICustomFormatter tmpFormatter = formatter;
                    if (ChoApplication.OnObjectFormatterResolve(target.GetType(), out tmpFormatter))
                    {
                        formatter = tmpFormatter;
                    }

                    if (formatter != null)
                    {
                        return(formatter.Format(formatName, target, null));
                    }
                    else if (formatName.IsNullOrWhiteSpace())
                    {
                        return(ToString(target));
                    }
                    else
                    {
                        return(ChoObject.Format(target, formatName));
                    }
                }
            }
            else
            {
                return(ToString(target));
            }
        }
Example #16
0
        public string GetHelpText()
        {
            StringBuilder msg = new StringBuilder("List of available properties" + Environment.NewLine);

            msg.AppendLine();
            msg.AppendLine("@this - Context info will be replaced.");
            msg.AppendLine();

            foreach (IChoPropertyReplacer propertyReplacer in PropertyReplacers)
            {
                if (propertyReplacer.AvailablePropeties == null)
                {
                    continue;
                }

                ChoStringMsgBuilder msg1 = new ChoStringMsgBuilder(propertyReplacer.Name);

                foreach (KeyValuePair <string, string> keyValue in propertyReplacer.AvailablePropeties)
                {
                    msg1.AppendFormatLine("{0} - {1}", keyValue.Key, keyValue.Value);
                }

                msg.AppendLine(msg1.ToString());
            }

            ChoStringMsgBuilder msg2 = new ChoStringMsgBuilder("Application Propeties");

            foreach (Dictionary <string, string> dict in ChoApplication.GetPropertyHelpTexts())
            {
                if (dict == null)
                {
                    continue;
                }

                foreach (KeyValuePair <string, string> keyValue in dict)
                {
                    msg2.AppendFormatLine("{0} - {1}", keyValue.Key, keyValue.Value);
                }
            }
            msg.AppendLine(msg2.ToString());

            return(msg.ToString());
        }
Example #17
0
        /// <summary>
        /// Unhandled exception handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //TODO: able to hook into user dll method
            string    errorMsg = "An application error occurred. Please contact the adminstrator with the following information:\n\n";
            Exception ex       = (Exception)e.ExceptionObject;

            if (ex != null)
            {
                errorMsg = ChoApplicationException.ToString(ex);
                ChoApplication.WriteToEventLog(errorMsg);
                //errorMsg += ex.Message + "\n\nStack Trace:\n" + ex.StackTrace;
                //ChoApplication.WriteToEventLog(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace, EventLogEntryType.Error);
            }
            else
            {
                ChoApplication.WriteToEventLog(errorMsg + "Unknown exception occured.", EventLogEntryType.Error);
            }

            Console.WriteLine(errorMsg);
            Environment.FailFast(errorMsg, ex);
        }
        static ChoEnvironmentSettings()
        {
            _appConfigFileWatcher.DoNotUseGlobalQueue = true;

            _appConfigFileWatcher.SetConfigurationChangedEventHandler("OnEnvironmentChanged", (sender, e) =>
            {
                //ConfigurationManager.RefreshSection("appSettings");
                ChoAppFrxSettings.RefreshSection();

                bool envChanged = false;

                string environment = ChoAppFrxSettings.Me.AppEnvironment.NTrim();
                string sharedEnvironmentConfigFilePath = SharedEnvironmentConfigFilePath;

                if (environment != Environment)
                {
                    envChanged = true;
                    ChoApplication.Trace(true, "Environment changed from '{0}' to '{1}'.".FormatString(Environment, environment));
                    Environment = environment;
                }
                if (sharedEnvironmentConfigFilePath != _sharedEnvironmentConfigFilePath)
                {
                    envChanged = true;
                    ChoApplication.Trace(true, "SharedEnvironmentConfgiFilePath changed from '{0}' to '{1}'.".FormatString(_sharedEnvironmentConfigFilePath, sharedEnvironmentConfigFilePath));
                    _sharedEnvironmentConfigFilePath = sharedEnvironmentConfigFilePath;
                }

                if (envChanged)
                {
                    LoadSharedEnvironmentManager();
                    OnEnvironmentChanged();
                }
            });

            Environment = ChoAppFrxSettings.Me.AppEnvironment.NTrim();
            _sharedEnvironmentConfigFilePath = SharedEnvironmentConfigFilePath;

            LoadSharedEnvironmentManager();
            _appConfigFileWatcher.StartWatching();
        }
        private static void LoadFrxConfigPath()
        {
            ChoEnvironmentDetails environmentDetails = null;

            lock (_padLock)
            {
                environmentDetails = _sharedEnvironmentManager.GetEnvironmentDetails();
                if (environmentDetails != null && environmentDetails.Freeze)
                {
                    Environment = environmentDetails.Name;
                    ChoApplication.Trace(true, "This host is Freezed to '{0}' environment.".FormatString(environmentDetails.Name));
                }
                else
                {
                    environmentDetails = _sharedEnvironmentManager.GetEnvironmentDetailsByEnvironment(Environment);
                    if (environmentDetails == null)
                    {
                        if (!Environment.IsNullOrWhiteSpace())
                        {
                            ChoApplication.Trace(true, "The '{0}' environment found in the configuration file.".FormatString(Environment));
                        }
                        environmentDetails = _sharedEnvironmentManager.GetEnvironmentDetailsByEnvironment();
                    }
                }
            }

            if (environmentDetails != null)
            {
                Environment = environmentDetails.Name;
                ChoApplication.Trace(true, "Using the '{0}' environment.".FormatString(Environment));
                _configFilePath = environmentDetails.AppFrxFilePath;
            }
            else
            {
                ChoApplication.Trace(true, "No Environment found for this host.");
                _configFilePath = null;
            }
        }
Example #20
0
        private static bool ReplaceToken(IChoPropertyReplacer[] propertyReplacers, StringBuilder message,
                                         string propertyName, string format)
        {
            if (!String.IsNullOrEmpty(propertyName))
            {
                foreach (IChoPropertyReplacer propertyReplacer in propertyReplacers)
                {
                    if (!(propertyReplacer is IChoKeyValuePropertyReplacer))
                    {
                        continue;
                    }

                    IChoKeyValuePropertyReplacer dictionaryPropertyReplacer = propertyReplacer as IChoKeyValuePropertyReplacer;
                    if (dictionaryPropertyReplacer == null || !dictionaryPropertyReplacer.ContainsProperty(propertyName))
                    {
                        continue;
                    }
                    message.Append(dictionaryPropertyReplacer.ReplaceProperty(propertyName, format));
                    return(true);
                }
            }

            string propertyValue;
            bool   retValue = ChoApplication.OnPropertyResolve(propertyName, format, out propertyValue);

            if (retValue)
            {
                if (propertyValue != null)
                {
                    message.Append(propertyValue);
                }
                return(true);
            }

            return(false);
        }
Example #21
0
        public void Initialize()
        {
            if (ApplicationBehaviourSettings == null)
            {
                ApplicationBehaviourSettings = new ChoApplicationBehaviourSettings();
            }

            if (TrayApplicationBehaviourSettings == null)
            {
                TrayApplicationBehaviourSettings = new ChoTrayApplicationBehaviourSettings();
            }

            if (LogSettings == null)
            {
                LogSettings = new ChoLogSettings();
            }

            if (ApplicationName.IsNullOrWhiteSpace())
            {
                try
                {
                    ApplicationName = System.IO.Path.GetFileName(ChoAssembly.GetEntryAssemblyLocation());
                }
                catch (System.Security.SecurityException ex)
                {
                    ChoApplication.Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());
                }
            }

            if (ApplicationName.IsNullOrEmpty())
            {
                ChoApplication.OnFatalApplicationException(101, "Missing ApplicationName.");
            }

            ApplicationNameWithoutExtension = Path.GetFileNameWithoutExtension(ApplicationName);

            if (EventLogSourceName.IsNullOrWhiteSpace())
            {
                EventLogSourceName = System.IO.Path.GetFileName(ChoAssembly.GetEntryAssemblyLocation());
            }
            if (LogSettings.LogTimeStampFormat.IsNullOrWhiteSpace())
            {
                LogSettings.LogTimeStampFormat = "yyyy-MM-dd hh:mm:ss.fffffff";
            }

            if (LogSettings.LogFileName.IsNullOrWhiteSpace())
            {
                LogSettings.LogFileName = ChoPath.ChangeExtension(ApplicationName, ChoReservedFileExt.Log);
            }

            LogSettings.LogFileName = ChoPath.CleanFileName(LogSettings.LogFileName);
            if (Path.IsPathRooted(LogSettings.LogFileName))
            {
                LogSettings.LogFileName = Path.GetFileName(LogSettings.LogFileName);
            }

            try
            {
                DateTime.Now.ToString(LogSettings.LogTimeStampFormat);
            }
            catch (Exception ex)
            {
                ChoApplication.Trace(ChoTrace.ChoSwitch.TraceError, "Invalid LogTimeStampFormat '{0}' configured.".FormatString(LogSettings.LogTimeStampFormat));
                ChoApplication.Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());
                LogSettings.LogTimeStampFormat = "yyyy-MM-dd hh:mm:ss.fffffff";
            }

            try
            {
                string sharedEnvConfigDir = null;

                if (!AppFrxConfigFilePath.IsNullOrEmpty())
                {
                    sharedEnvConfigDir = Path.GetDirectoryName(AppFrxConfigFilePath);
                }

                if (AppConfigFilePath.IsNullOrWhiteSpace())
                {
                    if (sharedEnvConfigDir.IsNullOrWhiteSpace())
                    {
                        ApplicationConfigFilePath = ChoPath.GetFullPath(Path.Combine(ChoReservedDirectoryName.Config, ChoPath.AddExtension(ChoPath.CleanFileName(ApplicationName), ChoReservedFileExt.Xml)));
                    }
                    else
                    {
                        ApplicationConfigFilePath = Path.Combine(sharedEnvConfigDir, ChoPath.AddExtension(ChoPath.CleanFileName(ApplicationName), ChoReservedFileExt.Xml));
                    }
                }
                else
                {
                    if (!Path.IsPathRooted(AppConfigFilePath))
                    {
                        if (sharedEnvConfigDir.IsNullOrWhiteSpace())
                        {
                            ApplicationConfigFilePath = ChoPath.GetFullPath(Path.Combine(ChoReservedDirectoryName.Config, AppConfigFilePath));
                        }
                        else
                        {
                            ApplicationConfigFilePath = Path.Combine(sharedEnvConfigDir, AppConfigFilePath);
                        }
                    }
                    else
                    {
                        ApplicationConfigFilePath = AppFrxConfigFilePath;
                    }
                }

                ApplicationConfigDirectory = Path.GetDirectoryName(ApplicationConfigFilePath);
            }
            catch (System.Security.SecurityException ex)
            {
                // This security exception will occur if the caller does not have
                // some undefined set of SecurityPermission flags.
                ChoApplication.Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());
            }

            #region Get HostName

            // Get the DNS host name of the current machine
            try
            {
                // Lookup the host name
                if (HostName.IsNullOrWhiteSpace())
                {
                    HostName = System.Net.Dns.GetHostName();
                }
            }
            catch (System.Net.Sockets.SocketException)
            {
            }
            catch (System.Security.SecurityException)
            {
                // We may get a security exception looking up the hostname
                // You must have Unrestricted DnsPermission to access resource
            }

            // Get the NETBIOS machine name of the current machine
            if (HostName.IsNullOrWhiteSpace())
            {
                try
                {
                    HostName = Environment.MachineName;
                }
                catch (InvalidOperationException)
                {
                }
                catch (System.Security.SecurityException)
                {
                    // We may get a security exception looking up the machine name
                    // You must have Unrestricted EnvironmentPermission to access resource
                }
            }

            #endregion Get HostName

            #region Get IpAddresses

            try
            {
                IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
                for (int i = 0; i < localIPs.Length; i++)
                {
                    IPAddresses.Add(localIPs[i].ToString());
                }
            }
            catch (System.Net.Sockets.SocketException)
            {
            }
            catch (System.Security.SecurityException)
            {
                // We may get a security exception looking up the hostname
                // You must have Unrestricted DnsPermission to access resource
            }

            #endregion Get IpAddresses

            if (LogSettings.TraceLevel < 0)
            {
                LogSettings.TraceLevel = 4;
            }

            if (!LogSettings.LogFolder.IsNullOrWhiteSpace())
            {
                ApplicationLogDirectory = ChoString.ExpandProperties(LogSettings.LogFolder, ChoEnvironmentVariablePropertyReplacer.Instance);
            }
            //else
            //    ApplicationLogDirectory = Path.Combine(Path.GetDirectoryName(ChoGlobalApplicationSettings.SharedEnvConfigPath), ChoReservedDirectoryName.Logs);

            if (ApplicationLogDirectory.IsNullOrWhiteSpace())
            {
                if (ChoApplication.AppEnvironment.IsNullOrWhiteSpace())
                {
                    ApplicationLogDirectory = Path.Combine(ChoPath.AssemblyBaseDirectory, ChoReservedDirectoryName.Logs);
                }
                else
                {
                    ApplicationLogDirectory = Path.Combine(ChoPath.AssemblyBaseDirectory, ChoReservedDirectoryName.Logs, ChoApplication.AppEnvironment);
                }
            }
            if (!Path.IsPathRooted(ApplicationLogDirectory))
            {
                ApplicationLogDirectory = Path.Combine(ChoPath.AssemblyBaseDirectory, ApplicationLogDirectory);
            }

            if (ChoApplication.ApplicationMode == ChoApplicationMode.Service)
            {
                TrayApplicationBehaviourSettings.TurnOn = false;
            }
        }
Example #22
0
        private static void Initialize()
        {
            if (_isInitialized)
            {
                return;
            }

            lock (_padLock)
            {
                if (_isInitialized)
                {
                    return;
                }

                _logBackupDay = DateTime.Today;

                InitializeAppInfo();

                if (!ServiceInstallation)
                {
                    if (ApplicationMode != ChoApplicationMode.Service &&
                        ApplicationMode != ChoApplicationMode.Web)
                    {
                        try
                        {
                            _rkAppRun = Registry.CurrentUser.OpenSubKey(RegRunSubKey, true);
                            if (_rkAppRun == null)
                            {
                                _rkAppRun = Registry.CurrentUser.CreateSubKey(RegRunSubKey);
                            }

                            RunAtSystemStartup(!ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.RunAtStartup);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Trace.TraceError(ex.ToString());
                        }

                        try
                        {
                            _rkAppRunOnce = Registry.CurrentUser.OpenSubKey(RegRunOnceSubKey, true);
                            if (_rkAppRunOnce == null)
                            {
                                _rkAppRunOnce = Registry.CurrentUser.CreateSubKey(RegRunOnceSubKey);
                            }

                            RunOnceAtSystemStartup(!ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.RunOnceAtStartup);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Trace.TraceError(ex.ToString());
                        }
                    }
                }

                ChoGuard.ArgumentNotNullOrEmpty(ChoGlobalApplicationSettings.Me.ApplicationConfigFilePath, "Application Config Path");

                try
                {
                    _elApplicationEventLog        = new EventLog("Application", Environment.MachineName, ChoGlobalApplicationSettings.Me.ApplicationName);
                    _elApplicationEventLog.Log    = "Application";
                    _elApplicationEventLog.Source = ChoGlobalApplicationSettings.Me.EventLogSourceName;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.TraceError(ex.ToString());
                }

                ApplicationConfigDirectory = Path.GetDirectoryName(ChoGlobalApplicationSettings.Me.ApplicationConfigFilePath);

                //Add default text trace listerner, if not defined in the configuration file
                Directory.CreateDirectory(ChoApplication.ApplicationLogDirectory);
                try
                {
                    if (_logFileName != ChoGlobalApplicationSettings.Me.LogSettings.LogFileName ||
                        _logDirectory != ChoApplication.ApplicationLogDirectory)
                    {
                        _logFileName  = ChoGlobalApplicationSettings.Me.LogSettings.LogFileName;
                        _logDirectory = ChoApplication.ApplicationLogDirectory;

                        ChoTextWriterTraceListener frxTextWriterTraceListener = new Cinchoo.Core.Diagnostics.ChoTextWriterTraceListener("Cinchoo",
                                                                                                                                        String.Format("BASEFILENAME={0};DIRECTORYNAME={1};FILEEXT={2}", ChoGlobalApplicationSettings.Me.LogSettings.LogFileName,
                                                                                                                                                      ChoApplication.ApplicationLogDirectory, ChoReservedFileExt.Txt));

                        if (_frxTextWriterTraceListener != null)
                        {
                            System.Diagnostics.Trace.Listeners.Remove(_frxTextWriterTraceListener);
                        }
                        else
                        {
                            ChoGlobalTimerServiceManager.Register("Logbackup", () =>
                            {
                                if (DateTime.Today != _logBackupDay)
                                {
                                    _logBackupDay = DateTime.Today;
                                    ChoTrace.Backup();
                                }
                            }, 60000);
                        }

                        _frxTextWriterTraceListener = frxTextWriterTraceListener;
                        System.Diagnostics.Trace.Listeners.Add(_frxTextWriterTraceListener);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.TraceError(ex.ToString());
                }

                while (_queueTraceMsg.Count > 0)
                {
                    Tuple <bool?, string> tuple = _queueTraceMsg.Dequeue();
                    System.Diagnostics.Trace.WriteLineIf(tuple.Item1 == null ? ChoGlobalApplicationSettings.Me.TurnOnConsoleOutput : tuple.Item1.Value, tuple.Item2);
                }
                _isInitialized = true;

                ChoApplication.WriteToEventLog(ChoApplication.ToString());
                //ChoApplication.WriteToEventLog(ChoGlobalApplicationSettings.Me.ToString());

                //Initialize other Framework Settings
                ChoAssembly.Initialize();
                ChoConsole.Initialize();
                ChoConfigurationManager.Initialize();
            }
        }
Example #23
0
        internal static ChoEnvironmentDetails GetEnvironmentDetails()
        {
            ChoEnvironmentDetails environmentDetails = null;

            lock (_padLock)
            {
                environmentDetails = SharedEnvironmentManager.GetEnvironmentDetails();
                if ((environmentDetails != null) && environmentDetails.Freeze)
                {
                    Environment = environmentDetails.Name;
                    ChoApplication.Trace(true, "This host is Freezed to '{0}' environment.".FormatString(environmentDetails.Name));
                    return(environmentDetails);
                }

                if (!Environment.IsNullOrWhiteSpace())
                {
                    Trace.WriteLineIf(true, "The '{0}' environment found in the configuration file.".FormatString(Environment));
                    environmentDetails = SharedEnvironmentManager.GetEnvironmentDetailsByEnvironment(Environment);
                }
                if (environmentDetails == null)
                {
                    environmentDetails = SharedEnvironmentManager.GetEnvironmentDetailsByEnvironment();
                }

                if ((environmentDetails != null) && environmentDetails.Freeze)
                {
                    ChoApplication.Trace(true, "The '{0}' environment is locked to use by designated configured machines only. No environment will be used.".FormatString(environmentDetails.Name));
                    environmentDetails = null;
                }

                return(environmentDetails);
            }
            //ChoEnvironmentDetails environmentDetails = null;

            //lock (_padLock)
            //{
            //    environmentDetails = SharedEnvironmentManager.GetEnvironmentDetails();
            //    if (environmentDetails != null && environmentDetails.Freeze)
            //    {
            //        Environment = environmentDetails.Name;
            //        ChoApplication.Trace(true, "This host is Freezed to '{0}' environment.".FormatString(environmentDetails.Name));
            //    }
            //    else
            //    {
            //        environmentDetails = SharedEnvironmentManager.GetEnvironmentDetailsByEnvironment(Environment);
            //        if (environmentDetails == null)
            //        {
            //            if (!Environment.IsNullOrWhiteSpace())
            //                Trace.WriteLineIf(true, "The '{0}' environment found in the configuration file.".FormatString(Environment));
            //            environmentDetails = SharedEnvironmentManager.GetEnvironmentDetailsByEnvironment();
            //        }
            //    }
            //}

            ////if (environmentDetails != null)
            ////{
            ////    Environment = environmentDetails.Name;
            ////    ChoApplication.Trace(true, "Using the '{0}' environment.".FormatString(Environment));
            ////    _configFilePath = environmentDetails.AppFrxFilePath;
            ////}
            ////else
            ////{
            ////    ChoApplication.Trace(true, "No Environment found for this host.");
            ////    _configFilePath = null;
            ////}

            //return environmentDetails;
        }
 static ChoInterceptableObject()
 {
     ChoAppDomain.Initialize();
     ChoApplication.Initialize();
 }
Example #25
0
        public void Initialize()
        {
            #region Get ApplicationName

            if (ApplicationName.IsNullOrWhiteSpace())
            {
                try
                {
                    ApplicationName = System.IO.Path.GetFileName(ChoAssembly.GetEntryAssemblyLocation());
                }
                catch (System.Security.SecurityException ex)
                {
                    ChoApplication.Trace(ChoTraceSwitch.Switch.TraceError, ex.ToString());
                }
            }

            #endregion Get ApplicationName

            #region Get HostName

            // Get the DNS host name of the current machine
            try
            {
                // Lookup the host name
                if (HostName.IsNullOrWhiteSpace())
                {
                    HostName = System.Net.Dns.GetHostName();
                }
            }
            catch (System.Net.Sockets.SocketException)
            {
            }
            catch (System.Security.SecurityException)
            {
                // We may get a security exception looking up the hostname
                // You must have Unrestricted DnsPermission to access resource
            }

            // Get the NETBIOS machine name of the current machine
            if (HostName.IsNullOrWhiteSpace())
            {
                try
                {
                    HostName = Environment.MachineName;
                }
                catch (InvalidOperationException)
                {
                }
                catch (System.Security.SecurityException)
                {
                    // We may get a security exception looking up the machine name
                    // You must have Unrestricted EnvironmentPermission to access resource
                }
            }

            #endregion Get HostName

            #region Get IpAddresses

            try
            {
                IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
                for (int i = 0; i < localIPs.Length; i++)
                {
                    IPAddresses.Add(localIPs[i].ToString());
                }
            }
            catch (System.Net.Sockets.SocketException)
            {
            }
            catch (System.Security.SecurityException)
            {
                // We may get a security exception looking up the hostname
                // You must have Unrestricted DnsPermission to access resource
            }

            #endregion Get IpAddresses

            if (ApplicationBehaviourSettings == null)
            {
                ApplicationBehaviourSettings = new ChoApplicationBehaviourSettings();
            }

            if (TrayApplicationBehaviourSettings == null)
            {
                TrayApplicationBehaviourSettings = new ChoTrayApplicationBehaviourSettings();
            }

            if (LogSettings == null)
            {
                LogSettings = new ChoLogSettings();
            }

            ChoApplication.RaiseGlobalApplicationSettingsOverrides(this);
            Merge(ChoGlobalApplicationSettings.Default);

            PostInitialize();
        }
Example #26
0
 public void Initialize()
 {
     ChoApplication.RaiseMetaDataFilePathSettingsOverrides(this);
     //PostInitialize();
 }
Example #27
0
        internal void PostInitialize()
        {
            if (ApplicationName.IsNullOrEmpty())
            {
                ChoEnvironment.Exit(101, "Missing ApplicationName.");
            }

            if (EventLogSourceName.IsNullOrWhiteSpace())
            {
                EventLogSourceName = System.IO.Path.GetFileName(ChoAssembly.GetEntryAssemblyLocation());
            }
            if (LogSettings.LogTimeStampFormat.IsNullOrWhiteSpace())
            {
                LogSettings.LogTimeStampFormat = "yyyy-MM-dd hh:mm:ss.fffffff";
            }

            if (LogSettings.LogFileName.IsNullOrWhiteSpace())
            {
                LogSettings.LogFileName = ChoPath.ChangeExtension(ApplicationName, ChoReservedFileExt.Log);
            }

            LogSettings.LogFileName = ChoPath.CleanFileName(LogSettings.LogFileName);
            if (Path.IsPathRooted(LogSettings.LogFileName))
            {
                LogSettings.LogFileName = Path.GetFileName(LogSettings.LogFileName);
            }

            try
            {
                DateTime.Now.ToString(LogSettings.LogTimeStampFormat);
            }
            catch (Exception ex)
            {
                ChoApplication.Trace(ChoTraceSwitch.Switch.TraceError, "Invalid LogTimeStampFormat '{0}' configured.".FormatString(LogSettings.LogTimeStampFormat));
                ChoApplication.Trace(ChoTraceSwitch.Switch.TraceError, ex.ToString());
                LogSettings.LogTimeStampFormat = "yyyy-MM-dd hh:mm:ss.fffffff";
            }

            try
            {
                string sharedEnvConfigDir = null;

                if (!AppFrxConfigFilePath.IsNullOrEmpty())
                {
                    sharedEnvConfigDir = Path.GetDirectoryName(ChoPath.GetFullPath(AppFrxConfigFilePath));
                }

                if (AppConfigFilePath.IsNullOrWhiteSpace())
                {
                    if (sharedEnvConfigDir.IsNullOrWhiteSpace())
                    {
                        ApplicationConfigFilePath = ChoPath.GetFullPath(Path.Combine(ChoReservedDirectoryName.Config, ChoPath.AddExtension(ChoPath.CleanFileName(ApplicationName), ChoReservedFileExt.Xml)));
                    }
                    else
                    {
                        ApplicationConfigFilePath = Path.Combine(sharedEnvConfigDir, ChoPath.AddExtension(ChoPath.CleanFileName(ApplicationName), ChoReservedFileExt.Xml));
                    }
                }
                else
                {
                    if (!Path.IsPathRooted(AppConfigFilePath))
                    {
                        if (sharedEnvConfigDir.IsNullOrWhiteSpace())
                        {
                            ApplicationConfigFilePath = ChoPath.GetFullPath(Path.Combine(ChoReservedDirectoryName.Config, AppConfigFilePath));
                        }
                        else
                        {
                            ApplicationConfigFilePath = Path.Combine(sharedEnvConfigDir, AppConfigFilePath);
                        }
                    }
                    else
                    {
                        ApplicationConfigFilePath = AppConfigFilePath;
                    }
                }

                ApplicationConfigDirectory = Path.GetDirectoryName(ChoPath.GetFullPath(ApplicationConfigFilePath));
                AppFrxConfigFilePath       = Path.Combine(ApplicationConfigDirectory, ChoReservedFileName.CoreFrxConfigFileName);
            }
            catch (System.Security.SecurityException ex)
            {
                // This security exception will occur if the caller does not have
                // some undefined set of SecurityPermission flags.
                ChoApplication.Trace(ChoTraceSwitch.Switch.TraceError, ex.ToString());
            }

            if (!LogSettings.LogFolder.IsNullOrWhiteSpace())
            {
                ApplicationLogDirectory = ChoString.ExpandProperties(LogSettings.LogFolder, ChoEnvironmentVariablePropertyReplacer.Instance);
            }

            if (ApplicationLogDirectory.IsNullOrWhiteSpace())
            {
                if (ChoApplication.AppEnvironment.IsNullOrWhiteSpace())
                {
                    ApplicationLogDirectory = Path.Combine(ChoPath.AssemblyBaseDirectory, ChoReservedDirectoryName.Logs);
                }
                else
                {
                    ApplicationLogDirectory = Path.Combine(ChoPath.AssemblyBaseDirectory, ChoReservedDirectoryName.Logs, ChoApplication.AppEnvironment);
                }
            }
            if (!Path.IsPathRooted(ApplicationLogDirectory))
            {
                ApplicationLogDirectory = Path.Combine(ChoPath.AssemblyBaseDirectory, ApplicationLogDirectory);
            }

            if (ChoApplication.ApplicationMode == ChoApplicationMode.Service)
            {
                TrayApplicationBehaviourSettings.TurnOn = false;
            }
        }
        private void Load(string sharedEnvironmentConfigFilePath)
        {
            BaseAppConfigDirectory = null;
            DefaultEnvironment     = null;
            EnvironmentDetails     = null;
            string backupSharedEnvironmentConfigFilePath = null;

            XmlDocument doc = new XmlDocument();

            if (!String.IsNullOrEmpty(sharedEnvironmentConfigFilePath) &&
                File.Exists(sharedEnvironmentConfigFilePath))
            {
                ChoApplication.Trace(true, "Using shared environment config file: {0}".FormatString(sharedEnvironmentConfigFilePath));
                backupSharedEnvironmentConfigFilePath = "{0}.{1}".FormatString(sharedEnvironmentConfigFilePath, ChoReservedFileExt.Cho);

                try
                {
                    if (File.Exists(backupSharedEnvironmentConfigFilePath))
                    {
                        File.SetAttributes(backupSharedEnvironmentConfigFilePath, FileAttributes.Archive);
                    }
                    using (ChoXmlDocument xmlDoc = new ChoXmlDocument(sharedEnvironmentConfigFilePath))
                    {
                        doc = xmlDoc.XmlDocument;
                    }
                    //doc.Load(sharedEnvironmentConfigFilePath);
                    doc.Save(backupSharedEnvironmentConfigFilePath);
                    if (File.Exists(backupSharedEnvironmentConfigFilePath))
                    {
                        File.SetAttributes(backupSharedEnvironmentConfigFilePath, FileAttributes.Hidden);
                    }
                }
                catch (Exception ex)
                {
                    ChoApplication.Trace(true, "Error loading shared environment config file: {0}.".FormatString(sharedEnvironmentConfigFilePath));
                    ChoApplication.Trace(true, ex.ToString());

                    doc = LoadBackupSharedEnvironmentConfigFile(backupSharedEnvironmentConfigFilePath);
                }
            }
            else if (ChoApplication.GetSharedEnvironmentConfigXml != null)
            {
                string xml = ChoApplication.GetSharedEnvironmentConfigXml();
                backupSharedEnvironmentConfigFilePath = "SharedEnvironments.{0}.{1}".FormatString(ChoReservedFileExt.Xml, ChoReservedFileExt.Cho);

                if (!xml.IsNullOrWhiteSpace())
                {
                    ChoApplication.Trace(true, "Using shared environment xml:");
                    ChoApplication.Trace(true, xml);

                    try
                    {
                        doc.LoadXml(xml);
                        doc.Save(backupSharedEnvironmentConfigFilePath);
                    }
                    catch (Exception ex)
                    {
                        ChoApplication.Trace(true, "Error loading shared environment config xml.");
                        ChoApplication.Trace(true, ex.ToString());

                        doc = LoadBackupSharedEnvironmentConfigFile(backupSharedEnvironmentConfigFilePath);
                    }
                }
            }
            LoadXml(doc);
        }
Example #29
0
        public ChoApplicationHost()
        {
            ChoApplication.ApplyFrxParamsOverrides += ((sender, e) =>
            {
                ApplyFrxParamsOverrides(e.GlobalApplicationSettings, e.MetaDataFilePathSettings);

                using (ChoCommandLineArgParser parser = new ChoCommandLineArgParser())
                {
                    parser.Parse();
                    foreach (KeyValuePair <string, string> keyValuePair in parser)
                    {
                        if (keyValuePair.Key.ToUpper() == "I")
                        {
                            ChoApplication.ServiceInstallation = true;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.HideWindow = false;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.SingleInstanceApp = false;
                            e.GlobalApplicationSettings.DoAppendProcessIdToLogDir = false;
                            e.GlobalApplicationSettings.ApplicationName = "{0}.InstallService".FormatString(e.GlobalApplicationSettings.ApplicationNameWithoutExtension);
                            e.GlobalApplicationSettings.EventLogSourceName = "{0}.InstallService".FormatString(e.GlobalApplicationSettings.EventLogSourceName);
                            e.GlobalApplicationSettings.LogSettings.LogFileName = "{0}.InstallService".FormatString(e.GlobalApplicationSettings.LogSettings.LogFileName);
                            break;
                        }
                        else if (keyValuePair.Key.ToUpper() == "U")
                        {
                            ChoApplication.ServiceInstallation = true;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.HideWindow = false;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.SingleInstanceApp = false;
                            e.GlobalApplicationSettings.DoAppendProcessIdToLogDir = false;
                            e.GlobalApplicationSettings.ApplicationName = "{0}.UninstallService".FormatString(e.GlobalApplicationSettings.ApplicationNameWithoutExtension);
                            e.GlobalApplicationSettings.EventLogSourceName = "{0}.UninstallService".FormatString(e.GlobalApplicationSettings.EventLogSourceName);
                            e.GlobalApplicationSettings.LogSettings.LogFileName = "{0}.UninstallService".FormatString(e.GlobalApplicationSettings.LogSettings.LogFileName);
                            break;
                        }
                        else if (keyValuePair.Key.ToUpper() == "S")
                        {
                            ChoApplication.ServiceInstallation = true;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.HideWindow = false;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.SingleInstanceApp = false;
                            e.GlobalApplicationSettings.DoAppendProcessIdToLogDir = false;
                            e.GlobalApplicationSettings.ApplicationName = "{0}.StartService".FormatString(e.GlobalApplicationSettings.ApplicationNameWithoutExtension);
                            e.GlobalApplicationSettings.EventLogSourceName = "{0}.StartService".FormatString(e.GlobalApplicationSettings.EventLogSourceName);
                            e.GlobalApplicationSettings.LogSettings.LogFileName = "{0}.StartService".FormatString(e.GlobalApplicationSettings.LogSettings.LogFileName);
                            break;
                        }
                        else if (keyValuePair.Key.ToUpper() == "T")
                        {
                            ChoApplication.ServiceInstallation = true;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.HideWindow = false;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.SingleInstanceApp = false;
                            e.GlobalApplicationSettings.DoAppendProcessIdToLogDir = false;
                            e.GlobalApplicationSettings.ApplicationName = "{0}.StopService".FormatString(e.GlobalApplicationSettings.ApplicationNameWithoutExtension);
                            e.GlobalApplicationSettings.EventLogSourceName = "{0}.StopService".FormatString(e.GlobalApplicationSettings.EventLogSourceName);
                            e.GlobalApplicationSettings.LogSettings.LogFileName = "{0}.StopService".FormatString(e.GlobalApplicationSettings.LogSettings.LogFileName);
                            break;
                        }
                        else if (keyValuePair.Key.ToUpper() == "P")
                        {
                            ChoApplication.ServiceInstallation = true;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.HideWindow = false;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.SingleInstanceApp = false;
                            e.GlobalApplicationSettings.DoAppendProcessIdToLogDir = false;
                            e.GlobalApplicationSettings.ApplicationName = "{0}.PauseService".FormatString(e.GlobalApplicationSettings.ApplicationNameWithoutExtension);
                            e.GlobalApplicationSettings.EventLogSourceName = "{0}.PauseService".FormatString(e.GlobalApplicationSettings.EventLogSourceName);
                            e.GlobalApplicationSettings.LogSettings.LogFileName = "{0}.PauseService".FormatString(e.GlobalApplicationSettings.LogSettings.LogFileName);
                            break;
                        }
                        else if (keyValuePair.Key.ToUpper() == "C")
                        {
                            ChoApplication.ServiceInstallation = true;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.HideWindow = false;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.SingleInstanceApp = false;
                            e.GlobalApplicationSettings.DoAppendProcessIdToLogDir = false;
                            e.GlobalApplicationSettings.ApplicationName = "{0}.ContinueService".FormatString(e.GlobalApplicationSettings.ApplicationNameWithoutExtension);
                            e.GlobalApplicationSettings.EventLogSourceName = "{0}.ContinueService".FormatString(e.GlobalApplicationSettings.EventLogSourceName);
                            e.GlobalApplicationSettings.LogSettings.LogFileName = "{0}.ContinueService".FormatString(e.GlobalApplicationSettings.LogSettings.LogFileName);
                            break;
                        }
                        else if (keyValuePair.Key.ToUpper() == "E")
                        {
                            ChoApplication.ServiceInstallation = true;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.HideWindow = false;
                            e.GlobalApplicationSettings.ApplicationBehaviourSettings.SingleInstanceApp = false;
                            e.GlobalApplicationSettings.DoAppendProcessIdToLogDir = false;
                            e.GlobalApplicationSettings.ApplicationName = "{0}.ExecuteCommand".FormatString(e.GlobalApplicationSettings.ApplicationNameWithoutExtension);
                            e.GlobalApplicationSettings.EventLogSourceName = "{0}.ExecuteCommand".FormatString(e.GlobalApplicationSettings.EventLogSourceName);
                            e.GlobalApplicationSettings.LogSettings.LogFileName = "{0}.ExecuteCommand".FormatString(e.GlobalApplicationSettings.LogSettings.LogFileName);
                            break;
                        }
                    }
                }
            });

            ChoApplication.FatalApplicationException += FatalApplicationException;

            //ChoApplication.Initialize();
            ChoGlobalApplicationSettings x = ChoGlobalApplicationSettings.Me;

            ApplyServiceInstallParamsOverrides(ChoServiceProcessInstallerSettings.Me, ChoServiceInstallerSettings.Me);
            ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();

            ChoApplication.WriteToEventLog(ChoServiceProcessInstallerSettings.Me.ToString());
            processInstaller.Account  = ChoServiceProcessInstallerSettings.Me.Account;
            processInstaller.Username = ChoServiceProcessInstallerSettings.Me.UserName;
            processInstaller.Password = ChoServiceProcessInstallerSettings.Me.Password;

            ChoApplication.WriteToEventLog(ChoServiceInstallerSettings.Me.ToString());
            ServiceInstaller serviceInstaller = new ServiceInstaller();

            serviceInstaller.DisplayName = ChoServiceInstallerSettings.Me.DisplayName.IsNullOrWhiteSpace() ? ChoGlobalApplicationSettings.Me.ApplicationNameWithoutExtension : ChoServiceInstallerSettings.Me.DisplayName;
            ServiceName = serviceInstaller.ServiceName = ChoServiceInstallerSettings.Me.ServiceName.IsNullOrWhiteSpace() ? ChoGlobalApplicationSettings.Me.ApplicationNameWithoutExtension : ChoServiceInstallerSettings.Me.ServiceName;
            serviceInstaller.StartType        = ChoServiceInstallerSettings.Me.ServiceStartMode;
            serviceInstaller.DelayedAutoStart = ChoServiceInstallerSettings.Me.DelayedAutoStart;
            serviceInstaller.Description      = ChoServiceInstallerSettings.Me.Description;

            this.Installers.Add(processInstaller);
            this.Installers.Add(serviceInstaller);
        }
Example #30
0
        public ChoApplicationHost()
        {
            Instance = this;
            //if (ChoApplication.ApplicationMode == ChoApplicationMode.NA)
            //if (!ChoApplication.IsInitialized)
            //{
            if (!ChoApplication.InternalEventsSubscriped)
            {
                ChoApplication.InternalEventsSubscriped = true;
                ChoApplication.ApplyGlobalApplicationSettingsOverridesInternal += ((sender, e) =>
                {
                    ChoServiceCommandLineArgs.OverrideFrxParams(e.Value);
                    ApplyGlobalApplicationSettingsOverrides(e.Value);
                }
                                                                                   );
                ChoApplication.AfterAppFrxSettingsLoadedInternal += ((sender, e) =>
                {
                    if (e.Value is ChoServiceInstallerSettings)
                    {
                        ChoServiceInstallerSettings o = (ChoServiceInstallerSettings)e.Value;
                        o.BeforeInstall(() => BeforeInstall());
                        o.AfterInstall(() => AfterInstall());
                        o.BeforeUninstall(() => BeforeUninstall());
                        o.AfterUninstall(() => AfterUninstall());
                    }

                    AfterAppFrxSettingsLoaded(e.Value);
                }
                                                                     );
                ChoApplication.ApplyMetaDataFilePathSettingsOverridesInternal += ((sender, e) =>
                {
                    ApplyMetaDataFilePathSettingsOverrides(e.Value);
                }
                                                                                  );
                ChoApplication.AfterNotifyIconConstructedInternal += ((sender, e) =>
                {
                    AfterNotifyIconConstructed(e.Value);
                }
                                                                      );
            }
            //ChoApplication.ApplyFrxParamsOverridesInternal += ((sender, e) =>
            //{
            //    ApplyFrxParamsOverrides(e.GlobalApplicationSettings, e.MetaDataFilePathSettings);

            //    if (_initialized) return;
            //    _initialized = true;

            //    ChoServiceCommandLineArgs.OverrideFrxParams(e);
            //});

            if (Environment.UserInteractive)
            {
                if (this.GetMainWindowObject() != null)
                {
                    if (ChoApplication.ApplicationMode == ChoApplicationMode.NA)
                    {
                        if (GetMainWindowObject() is Window ||
                            GetMainWindowObject() is Form)
                        {
                            ChoApplication.ApplicationMode = ChoApplicationMode.Windows;
                            if (GetMainWindowObject() is Window)
                            {
                                ChoApplication.WindowsAppType = ChoWindowsAppType.WPF;
                            }
                            else
                            {
                                ChoApplication.WindowsAppType = ChoWindowsAppType.WinForms;
                            }
                        }
                        else
                        {
                            ChoApplication.ApplicationMode = ChoApplicationMode.Console;
                        }
                    }
                    //if (!(this is IChoWindowApp))
                    //    throw new ChoApplicationException("ApplicationHost must derive from IChoWindowApp for Windows application.");
                }

                //ChoApplicationMode? applicationMode = ChoFrameworkCmdLineArgs.GetApplicationMode();
                //if (applicationMode != null)
                //    ChoApplication.ApplicationMode = applicationMode.Value;

                if (ChoApplication.ApplicationMode == ChoApplicationMode.Windows)
                {
                    //if (ChoApplication.WindowsAppType == ChoWindowsAppType.NA)
                    //    ChoApplication.ApplicationMode = ChoApplicationMode.Console;
                }
            }


            ChoApplication.FatalApplicationException += FatalApplicationException;

            //if (Environment.UserInteractive)
            //{
            //    if (!ChoServiceCommandLineArgs.HasServiceParams())
            //    {
            //        if (ChoApplication.ApplicationMode == ChoApplicationMode.Windows)
            //        {
            //            if (!ChoAppFrxSettings.Me.DoNotShowEnvSelectionWnd)
            //            {
            //                ChoChooseEnvironmentFrm.Show();
            //                //frm1 = new ChoChooseEnvironmentFrm();
            //                //if (frm1.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            //                //    Environment.Exit(-101);
            //            }
            //        }
            //    }
            //}
            //}
            //else
            //    ApplyFrxParamsOverrides(ChoGlobalApplicationSettings.Me, ChoMetaDataFilePathSettings.Me);

            //ChoApplication.Initialize();
            ChoGlobalApplicationSettings x = ChoGlobalApplicationSettings.Me;

            ChoApplication.WriteToEventLog(ChoServiceInstallerSettings.Me.ToString());
        }