コード例 #1
0
 /// <summary>
 /// Set/Remove the running executable to run once at system startup
 /// </summary>
 /// <param name="remove">true, it remove the application from running at system startup.</param>
 /// <returns>true, if the operation is successfull. Otherwise, false.</returns>
 public static bool RunOnceAtSystemStartup(bool remove)
 {
     if (HttpContext.Current == null)
     {
         string appLocation = ChoAssembly.GetEntryAssembly().Location;
         return(RunOnceAtSystemStartup(ChoGlobalApplicationSettings.Me.ApplicationName, appLocation, remove));
     }
     return(true);
 }
コード例 #2
0
ファイル: ChoEnvironment.cs プロジェクト: lanicon/Cinchoo
 public static string ToFullyQualifiedCommandLineArgs()
 {
     if (CommandLineArgs != null)
     {
         return("{0} {1}".FormatString(ChoAssembly.GetEntryAssembly().Location, String.Join(" ",
                                                                                            CommandLineArgs.Select((x) => x.Contains(' ') ? "\"{0}\"".FormatString(x) : x))));
     }
     else
     {
         return("{0} {1}".FormatString(ChoAssembly.GetEntryAssembly().Location, String.Empty));
     }
 }
コード例 #3
0
        static ChoAppDomain()
        {
            //ChoApplication.Initialize();
            //ChoApplication.RaiseApplyFrxParamsOverrides(true);
            ChoAssembly.Initialize();
            RegisterAppDomainEvents();
            string envPath = ChoEnvironmentSettings.GetConfigFilePath();
            ChoGlobalApplicationSettings x = ChoGlobalApplicationSettings.Me;

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

            _Load();
        }
コード例 #4
0
ファイル: ChoService.cs プロジェクト: commodus/Cinchoo
        public ChoService()
        {
            try
            {
                //Dicover Service Installer
                Assembly entryAssembly = ChoAssembly.GetEntryAssembly();

                Type runInstallerType = null;
                if (entryAssembly != null)
                {
                    foreach (Type type in entryAssembly.GetTypes())
                    {
                        RunInstallerAttribute runInstallerAttribute = type.GetCustomAttribute <RunInstallerAttribute>();
                        if (runInstallerAttribute == null)
                        {
                            continue;
                        }

                        if (typeof(ChoApplicationHost).IsAssignableFrom(type))
                        {
                            runInstallerType = type;
                            break;
                        }
                    }
                }


                if (runInstallerType != null)
                {
                    _host = Activator.CreateInstance(runInstallerType) as ChoApplicationHost;
                }
                else
                {
                    ChoApplication.WriteToEventLog("No type found with RunInstallerAttribute in the entry assembly.");
                }
            }
            catch (ChoFatalApplicationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                ChoApplication.WriteToEventLog(ex.ToString());
            }
        }
コード例 #5
0
        private void PrintHeader()
        {
            string applicationName = ApplicationName;

            if (applicationName.IsNullOrWhiteSpace())
            {
                applicationName = ChoGlobalApplicationSettings.Me.ApplicationName;
            }

            string version = ChoAssembly.GetEntryAssembly().GetName().Version.ToString();

            ChoConsole.WriteLine("{0} [Version {1}]".FormatString(applicationName, version));

            if (!Copyright.IsNullOrWhiteSpace())
            {
                ChoConsole.WriteLine(Copyright);
            }

            ChoConsole.WriteLine();
        }
コード例 #6
0
        //public static event EventHandler<ChoEventArgs<ChoPathEventArgs>> ResolveFullPath;

        #endregion Shared Data Members (Private)

        #region Constructors

        static ChoPath()
        {
            try
            {
                HttpContext ctx = HttpContext.Current;
                if (ctx == null)
                {
                    _assemblyBaseDirectory = Path.GetDirectoryName(ChoAssembly.GetEntryAssembly().Location);
                }
                else
                {
                    _assemblyBaseDirectory = HttpContext.Current.Request.PhysicalApplicationPath;
                }
            }
            catch (ChoFatalApplicationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                ChoApplication.Trace(true, ex.ToString());
            }
        }
コード例 #7
0
ファイル: ChoNotifyIcon.cs プロジェクト: lanicon/Cinchoo
        public ChoNotifyIcon(IContainer container)
        {
            if (container == null)
            {
                _notifyIcon = new NotifyIcon();
            }
            else
            {
                _notifyIcon = new NotifyIcon(container);
            }

            _font  = new Font(ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.FontSettings.FontName, ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.FontSettings.FontSize);
            _color = ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.FontSettings.FontColor;
            Assembly entryAssembly = ChoAssembly.GetEntryAssembly();

            if (entryAssembly != null)
            {
                _defaultIcon = Icon.ExtractAssociatedIcon(entryAssembly.Location);
            }

            _timer          = new Timer();
            _timer.Interval = 100;
            _timer.Tick    += new System.EventHandler(this.timerTick);
        }
コード例 #8
0
 /// <summary>
 /// Default Constructor
 /// </summary>
 public ChoTextTraceListener()
 {
     _baseFileName = ChoAssembly.GetEntryAssembly().GetName().Name;
     Init();
 }
コード例 #9
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;
            }
        }
コード例 #10
0
        protected void PrintHeader()
        {
            if (ChoCommandLineParserSettings.Me.DoNotShowHeader)
            {
                return;
            }

            if (Silent)
            {
                return;
            }

            lock (_padLock)
            {
                if (_isHeaderPrinted)
                {
                    return;
                }
                _isHeaderPrinted = true;
            }

            string applicationName = ApplicationName;

            if (applicationName.IsNullOrWhiteSpace())
            {
                applicationName = ChoAssembly.GetAssemblyTitle();
                if (applicationName.IsNullOrWhiteSpace())
                {
                    applicationName = ChoApplication.EntryAssemblyFileName;
                    //if (Assembly.GetEntryAssembly() != null && !Assembly.GetEntryAssembly().FullName.IsNullOrWhiteSpace()
                    //    && Assembly.GetEntryAssembly().FullName.IndexOf(',') > 0)
                    //    applicationName = Assembly.GetEntryAssembly().FullName.SplitNTrim(',')[0]; // EntryAssemblyFileName; //ChoGlobalApplicationSettings.Me.ApplicationName;
                }
            }
            if (applicationName.IsNullOrWhiteSpace())
            {
                applicationName = "Unknown";
            }

            string version = Version;

            if (version.IsNullOrWhiteSpace())
            {
                version = ChoAssembly.GetEntryAssembly().GetName().Version.ToString();
            }

            Console.WriteLine("{0} [Version {1}]".FormatString(applicationName, version));

            string copyright = Copyright;

            if (copyright.IsNullOrWhiteSpace())
            {
                copyright = ChoAssembly.GetAssemblyCopyright();
            }

            if (!copyright.IsNullOrWhiteSpace())
            {
                Console.WriteLine(copyright);
            }

            string description = Description;

            if (description.IsNullOrWhiteSpace())
            {
                description = ChoAssembly.GetAssemblyDescription();
            }

            if (!description.IsNullOrWhiteSpace())
            {
                Console.WriteLine(Environment.NewLine);
                Console.WriteLine(description);
            }

            if (!AdditionalInfo.IsNullOrWhiteSpace())
            {
                Console.WriteLine(Environment.NewLine);
                Console.WriteLine(AdditionalInfo);
            }

            Console.WriteLine();
        }
コード例 #11
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();
        }
コード例 #12
0
        /// <summary>
        /// Create the NotifyIcon UI, the ContextMenu for the NotifyIcon and an Exit menu item.
        /// </summary>
        private void InitializeContext(IChoWinFormApp windowApp)
        {
            this._components            = new System.ComponentModel.Container();
            this.NotifyIcon             = new System.Windows.Forms.NotifyIcon(this._components);
            this._notifyIconContextMenu = GetContextMenu(windowApp);
            if (windowApp != null)
            {
                this._mainFormWindow = windowApp.MainFormWindow;
            }

            this.NotifyIcon.DoubleClick += new System.EventHandler(this.notifyIcon_DoubleClick);

            this.NotifyIcon.Icon = windowApp != null ? windowApp.TrayIcon : null;
            if (this.NotifyIcon.Icon == null)
            {
                Assembly entryAssembly = ChoAssembly.GetEntryAssembly();
                if (entryAssembly != null)
                {
                    this.NotifyIcon.Icon = Icon.ExtractAssociatedIcon(entryAssembly.Location);
                }
            }

            this.NotifyIcon.Text = windowApp != null ? (windowApp.TooltipText.IsNullOrWhiteSpace() ? ChoGlobalApplicationSettings.Me.ApplicationName : windowApp.TooltipText) : ChoGlobalApplicationSettings.Me.ApplicationName;

            string defaultBaloonTipText = "{0} is running...".FormatString(ChoGlobalApplicationSettings.Me.ApplicationName);

            this.NotifyIcon.BalloonTipText = windowApp != null ? (windowApp.BalloonTipText.IsNullOrWhiteSpace() ? defaultBaloonTipText : windowApp.BalloonTipText) : defaultBaloonTipText;

            this.NotifyIcon.ContextMenu = _notifyIconContextMenu;
            this.NotifyIcon.Visible     = true;

            if (this._mainFormWindow != null)
            {
                _mainWPFWindow.Show();
                ChoWindowsManager.HideConsoleWindow();
                ChoWindowsManager.MainWindowHandle = this._mainFormWindow.Handle;
                _mainFormWindow.Closed            += new EventHandler(mainForm_Closed);
                _mainFormWindow.Closing           += new System.ComponentModel.CancelEventHandler(mainForm_Closing);
                _mainFormWindow.Resize            += new EventHandler(mainForm_Resize);
            }
            else if (this._mainWPFWindow != null)
            {
                ChoWindowsManager.HideConsoleWindow();
                _mainWPFWindow.Visibility = Visibility.Hidden;
                _mainWPFWindow.Show();
                WindowInteropHelper windowInteropHelper = new WindowInteropHelper(_mainWPFWindow);
                ChoWindowsManager.MainWindowHandle = windowInteropHelper.Handle;

                //_mainWPFWindow.Show();
                //_mainWPFWindow.SourceInitialized += new EventHandler(mainWPFWindow_SourceInitialized);
                //ChoWindowsManager.MainWindowHandle = this._mainWPFWindow;
                //_mainFormWindow.Closed += new EventHandler(mainForm_Closed);
                //_mainFormWindow.Closing += new System.ComponentModel.CancelEventHandler(mainForm_Closing);
                //_mainFormWindow.Resize += new EventHandler(mainForm_Resize);
            }

            if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn)
            {
                if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.HideMainWindowAtStartup)
                {
                    this._showContextMenuItem.Checked = false;
                    ToggleShowContextMenuItem();
                }
            }
            else
            {
                ShowMainWindow();
            }

            ChoGlobalApplicationSettings.Me.ObjectChanged += new EventHandler(Me_ConfigChanged);

            Me_ConfigChanged(null, null);
            if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn)
            {
                if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.HideMainWindowAtStartup)
                {
                    HideMainWindow();
                }
                else
                {
                    HideMainWindow();
                    ShowMainWindow();
                }
            }
        }
コード例 #13
0
        private static void InitializeAppInfo()
        {
            RaiseApplyFrxParamsOverrides();

            try
            {
                EntryAssemblyLocation = ChoAssembly.GetEntryAssembly().Location;
                EntryAssemblyFileName = System.IO.Path.GetFileName(EntryAssemblyLocation);
            }
            catch (System.Security.SecurityException ex)
            {
                // This security exception will occur if the caller does not have
                // some undefined set of SecurityPermission flags.
                Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());
            }

            if (!ServiceInstallation)
            {
                if (ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.SingleInstanceApp)
                {
                    Func <bool> verifyAnotherInstanceRunning = VerifyAnotherInstanceRunning;
                    if (verifyAnotherInstanceRunning != null)
                    {
                        bool instanceExists = verifyAnotherInstanceRunning();
                        if (instanceExists)
                        {
                            RaiseErrorOrActivateFirstInstance();
                        }
                    }
                    else
                    {
                        bool createdNew = true;
                        _singleInstanceMutex = new Mutex(true, ChoGlobalApplicationSettings.Me.ApplicationName, out createdNew);
                        if (!createdNew)
                        {
                            RaiseErrorOrActivateFirstInstance();
                        }
                    }
                }

                if (!ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn)
                {
                    if (ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.HideWindow)
                    {
                        ChoWindowsManager.Hide();
                    }
                    else
                    {
                        ChoWindowsManager.Show();

                        ChoWindowsManager.AlwaysOnTop(ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.AlwaysOnTop);

                        if (!ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.AlwaysOnTop)
                        {
                            if (ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.BringWindowToTop)
                            {
                                ChoWindowsManager.BringWindowToTop();
                            }
                        }
                        //ChoWindowManager.ShowInTaskbar(ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.ShowInTaskbar);
                    }
                }

                if (ChoApplicationHost.ApplicationContext != null)
                {
                    ChoApplicationHost.ApplicationContext.Visible = ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn;
                }
            }

            #region Check for Unmanaged Code Permission Available

            // check whether the unmanaged code permission is available to avoid three potential stack walks
            SecurityPermission unmanagedCodePermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
            // avoid a stack walk by checking for the permission on the current assembly. this is safe because there are no
            // stack walk modifiers before the call.
            if (SecurityManager.IsGranted(unmanagedCodePermission))
            {
                try
                {
                    unmanagedCodePermission.Demand();
                    UnmanagedCodePermissionAvailable = true;
                }
                catch (SecurityException ex)
                {
                    Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());
                }
            }

            #endregion Check for Unmanaged Code Permission Available

            #region Get AppDomainName

            try
            {
                AppDomainName = AppDomain.CurrentDomain.FriendlyName;
            }
            catch (Exception ex)
            {
                Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());
            }

            #endregion Get AppDomainName

            #region Get ProcessId, ProcessName

            if (UnmanagedCodePermissionAvailable)
            {
                try
                {
                    ProcessId = ChoKernel32Core.GetCurrentProcessId();
                }
                catch (Exception ex)
                {
                    Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());

                    try
                    {
                        ProcessId = Process.GetCurrentProcess().Id;
                    }
                    catch { }
                }

                try
                {
                    ProcessFilePath = GetProcessName();
                }
                catch (Exception ex)
                {
                    Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());
                }
            }
            else
            {
                try
                {
                    ProcessId = Process.GetCurrentProcess().Id;
                }
                catch { }

                Trace(ChoTrace.ChoSwitch.TraceError, "Failed to retrieve value due to unmanaged code permission denied.");
            }

            #endregion Get ProcessId, ProcessName

            ApplicationLogDirectory = ChoGlobalApplicationSettings.Me.ApplicationLogDirectory;

            if (!ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.SingleInstanceApp)
            {
                if (ChoGlobalApplicationSettings.Me.DoAppendProcessIdToLogDir)
                {
                    ApplicationLogDirectory = Path.Combine(ApplicationLogDirectory, ProcessId.ToString());
                }
            }

            Directory.CreateDirectory(ApplicationLogDirectory);
        }
コード例 #14
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();
            }
        }
コード例 #15
0
        private void PreInitializeContext(ChoApplicationHost appHost)
        {
            if (appHost != null)
            {
                //if (ChoFrameworkCmdLineArgs.GetApplicationMode() != null
                //    && ChoFrameworkCmdLineArgs.GetApplicationMode().Value == ChoApplicationMode.Console
                if (ChoApplication.ApplicationMode == ChoApplicationMode.Console &&
                    !ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn
                    /*&& _mainForm != null */)
                {
                    _mainForm = null;
                    //ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn = false;
                    return;
                }

                if (!ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.DisableDefaultDoubleClickEvent)
                {
                    this.NotifyIcon.DoubleClick += new System.EventHandler(this.notifyIcon_DoubleClick);
                }
                if (!ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.DisableDefaultClickEvent)
                {
                    this.NotifyIcon.Click += new System.EventHandler(this.notifyIcon_Click);
                }

                //System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                System.Windows.Forms.Application.ThreadException += new ThreadExceptionEventHandler(ChoApplication.Application_ThreadException);
                if (_mainForm is Form)
                {
                    ChoApplication.WindowsAppType = ChoWindowsAppType.WinForms;
                    this._mainFormWindow          = (Form)_mainForm;
                }
                else if (_mainForm is Window)
                {
                    ChoApplication.WindowsAppType = ChoWindowsAppType.WPF;
                    this._mainWPFWindow           = (Window)_mainForm;

                    //System.Windows.Application app = appHost.ApplicationObject as System.Windows.Application;
                    //if (app == null)
                    //    app = new ChoWPFDefaultApplication();

                    //app.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(ChoApplication.Current_DispatcherUnhandledException);
                    //app.Run(_mainWPFWindow);
                }
                //else
                //    throw new ApplicationException("MainWindow object is not a valid object. Must be either Form or Window type.");
            }

            //this.NotifyIcon.DoubleClick += new System.EventHandler(this.notifyIcon_DoubleClick);

            //this.NotifyIcon.Icon = windowApp != null ? windowApp.TrayIcon : null;
            if (this.NotifyIcon.Icon == null)
            {
                Assembly entryAssembly = ChoAssembly.GetEntryAssembly();
                if (entryAssembly != null)
                {
                    this.NotifyIcon.Icon = Icon.ExtractAssociatedIcon(entryAssembly.Location);
                }
            }

            //this.NotifyIcon.Text = windowApp != null ? (windowApp.TooltipText.IsNullOrWhiteSpace() ? ChoGlobalApplicationSettings.Me.ApplicationName : windowApp.TooltipText) : ChoGlobalApplicationSettings.Me.ApplicationName;
            if (this.NotifyIcon.Text.IsNullOrWhiteSpace())
            {
                this.NotifyIcon.Text = ChoGlobalApplicationSettings.Me.ApplicationName;
            }

            if (this.NotifyIcon.BalloonTipText.IsNullOrWhiteSpace())
            {
                this.NotifyIcon.BalloonTipText = _defaultTrayTipMsg;
            }

            if (this.NotifyIcon.ContextMenu == null)
            {
                this.NotifyIcon.ContextMenuStrip = _defaultContextMenu;
            }
        }
コード例 #16
0
        //[ChoSingletonInstanceInitializer]
        public void Initialize()
        {
            if (_initialized)
            {
                return;
            }

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

                _initialized = true;

                try
                {
                    EntryAssemblyLocation = ChoAssembly.GetEntryAssembly().Location;
                    EntryAssemblyFileName = System.IO.Path.GetFileName(EntryAssemblyLocation);
                }
                catch (System.Security.SecurityException ex)
                {
                    // This security exception will occur if the caller does not have
                    // some undefined set of SecurityPermission flags.
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine(ex.ToString());
                    }
                }

                try
                {
                    AppEnvironment = ConfigurationManager.AppSettings["appEnvironment"];
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.ToString());
                }

                try
                {
                    SharedEnvironmentConfigFilePath = ConfigurationManager.AppSettings["sharedEnvironmentConfigFilePath"];
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.ToString());
                }

                try
                {
                    if (ConfigurationManager.AppSettings["appConfigPath"].IsNullOrWhiteSpace())
                    {
                        ApplicationConfigFilePath = System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
                    }
                    else
                    {
                        ApplicationConfigFilePath = ConfigurationManager.AppSettings["appConfigPath"].Trim();
                    }
                }
                catch (System.Security.SecurityException ex)
                {
                    // This security exception will occur if the caller does not have
                    // some undefined set of SecurityPermission flags.
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine(ex.ToString());
                    }
                }

                try
                {
                    ApplicationBaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                }
                catch (System.Security.SecurityException ex)
                {
                    // This security exception will occur if the caller does not have
                    // some undefined set of SecurityPermission flags.
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine(ex.ToString());
                    }
                }

                #region Check for Unmanaged Code Permission Available

                // check whether the unmanaged code permission is available to avoid three potential stack walks
                SecurityPermission unmanagedCodePermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                // avoid a stack walk by checking for the permission on the current assembly. this is safe because there are no
                // stack walk modifiers before the call.
                if (SecurityManager.IsGranted(unmanagedCodePermission))
                {
                    try
                    {
                        unmanagedCodePermission.Demand();
                        UnmanagedCodePermissionAvailable = true;
                    }
                    catch (SecurityException e)
                    {
                        if (ChoTrace.ChoSwitch.TraceError)
                        {
                            Trace.WriteLine(ChoApplicationException.ToString(e));
                        }
                    }
                }

                #endregion Check for Unmanaged Code Permission Available

                EventLogSourceName = ChoApplicationSettings.State.EventLogSourceName;

                #region GetApplicationName

                try
                {
                    ApplicationName = ChoApplicationSettings.State.ApplicationId;
                }
                catch (System.Security.SecurityException ex)
                {
                    // This security exception will occur if the caller does not have
                    // some undefined set of SecurityPermission flags.
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine(ex.ToString());
                    }

                    try
                    {
                        ApplicationName = System.IO.Path.GetFileName(EntryAssemblyLocation);
                    }
                    catch (System.Security.SecurityException e)
                    {
                        ChoTrace.Error(ChoApplicationException.ToString(e));
                    }
                }

                ApplicationNameWithoutExtension = Path.GetFileNameWithoutExtension(ApplicationName);
                if (!ChoApplicationSettings.State.LogFolder.IsNullOrWhiteSpace())
                {
                    ApplicationLogDirectory = ChoApplicationSettings.State.LogFolder;
                }
                else if (ChoApplicationSettings.State.UseApplicationDataFolderAsLogFolder)
                {
                    ApplicationLogDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ApplicationNameWithoutExtension, ChoReservedDirectoryName.Logs);
                }
                else
                {
                    ApplicationLogDirectory = Path.Combine(ApplicationBaseDirectory, ChoReservedDirectoryName.Logs);
                }

                #endregion GetApplicationName

                #region Get AppDomainName

                try
                {
                    AppDomainName = AppDomain.CurrentDomain.FriendlyName;
                }
                catch (Exception ex)
                {
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine(ex.ToString());
                    }
                }

                #endregion Get AppDomainName

                #region Get ProcessId, ProcessName

                if (UnmanagedCodePermissionAvailable)
                {
                    try
                    {
                        ProcessId = ChoKernel32Core.GetCurrentProcessId();
                    }
                    catch (Exception ex)
                    {
                        if (ChoTrace.ChoSwitch.TraceError)
                        {
                            Trace.WriteLine(ex.ToString());
                        }
                    }

                    try
                    {
                        ProcessFilePath = GetProcessName();
                    }
                    catch (Exception ex)
                    {
                        if (ChoTrace.ChoSwitch.TraceError)
                        {
                            Trace.WriteLine(ex.ToString());
                        }
                    }
                }
                else
                {
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine("Failed to retrieve value due to unmanaged code permission denied.");
                    }
                }

                #endregion Get ProcessId, ProcessName

                #region Get HostName

                // Get the DNS host name of the current machine
                try
                {
                    // Lookup the host name
                    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

                ApplyFrxParamsOverrides.Raise(this, null);
            }
        }
コード例 #17
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;
            }
        }