Example #1
0
        private void QueueMessageHandler(IChoQueuedMsgServiceObject <ChoExecutionServiceData> msgObject)
        {
            if (msgObject == null ||
                !ChoGuard.IsArgumentNotNullOrEmpty(msgObject.State)
                )
            {
                return;
            }

            ChoAsyncResult asyncResult = msgObject.State.Result as ChoAsyncResult;

            try
            {
                object retValue = msgObject.State.Func.Run(msgObject.State.Parameters, msgObject.State.Timeout, msgObject.State.MaxNoOfRetry, msgObject.State.SleepBetweenRetry);
                asyncResult.SetAsSuccess(retValue, true);
            }
            catch (ThreadAbortException)
            {
                Thread.ResetAbort();
                ChoTrace.Error("Thread aborted." + msgObject.State.ToString());
                asyncResult.SetAsAborted(true);
            }
            catch (ChoFatalApplicationException fex)
            {
                ChoTrace.Error(fex);
                ChoTrace.Error(msgObject.State.ToString());
                asyncResult.SetAsFailed(fex, true);
                ChoEnvironment.Exit(-1, fex);
            }
            catch (Exception ex)
            {
                ChoTrace.Error(ex);
                ChoTrace.Error(msgObject.State.ToString());
                asyncResult.SetAsFailed(ex, true);
            }
        }
Example #2
0
        public static void WaitAllEx(
            IWorkItemResult[] passedWorkItemResults)
        {
            ArrayList workItemResults        = new ArrayList(passedWorkItemResults);
            ArrayList pendingWorkItemResults = new ArrayList();

            int prevCount = workItemResults.Count;

            while (workItemResults.Count > 0)
            {
                foreach (IWorkItemResult workItemResult in workItemResults)
                {
                    if (!workItemResult.IsCompleted)
                    {
                        pendingWorkItemResults.Add(workItemResult);
                    }
                }
                workItemResults = new ArrayList(pendingWorkItemResults);
                pendingWorkItemResults.Clear();

                if (workItemResults.Count == 0)
                {
                    return;
                }
                if (prevCount != workItemResults.Count)
                {
                    prevCount = workItemResults.Count;
                    ChoTrace.WriteLineIf(ChoTrace.ChoSwitch.TraceVerbose, String.Format("Waiting for {0} thread(s) to complete...", workItemResults.Count));
                    Thread.Sleep(1000);
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }
Example #3
0
        protected override object Execute(object value, out bool isHandled)
        {
            isHandled = false;
            if (Script.IsNullOrWhiteSpace())
            {
                return(value);
            }

            string script           = ResolveText(Script);
            string arguments        = !Arguments.IsNullOrWhiteSpace() ? "{0} {1}".FormatString(value.ToNString(), ResolveText(Arguments)) : value.ToNString();
            string workingDirectory = WorkingDirectory.IsNullOrWhiteSpace() ? ChoApplication.ApplicationBaseDirectory : ResolveText(WorkingDirectory);

            //Create temp script file
            _tmpFileName = Path.ChangeExtension(ChoPath.GetTempFileName(), ChoReservedFileExt.JS);
            File.WriteAllText(_tmpFileName, script);
            ChoTrace.DebugFormat("{0}: Temp file created at '{1}'", Name, _tmpFileName);

            using (ChoProcess p = new ChoProcess("cscript.exe", "{0} {1} //Nologo".FormatString(_tmpFileName, arguments)))
            {
                p.WorkingDirectory = workingDirectory;

                return(p.Execute().StdOut);
            }
        }
Example #4
0
 public virtual void OnConfigurationStateChanged(object cmdInstruction, object tag)
 {
     try
     {
         if (_eventHandlerList != null)
         {
             int          counter = 0;
             WaitHandle[] handles = new WaitHandle[_eventHandlerList.Count];
             ChoConfigurationStateChangedEventArgs eventData = EventData;
             foreach (ChoConfigurationStateChangedEventHandler callback in _eventHandlerList.ToValuesArray())
             {
                 if (callback != null)
                 {
                     handles[counter++] = callback.BeginInvoke(this, new ChoConfigurationStateChangedEventArgs(_configsectionName, cmdInstruction, tag), null, null).AsyncWaitHandle;
                 }
             }
             WaitHandle.WaitAll(handles);
         }
     }
     catch (Exception ex)
     {
         ChoTrace.Write(ex);
     }
 }
Example #5
0
        private static Assembly LoadAssemblyFromResource(string name)
        {
            //Assembly thisAssembly = Assembly.GetEntryAssembly();

            foreach (Assembly thisAssembly in ChoAssembly.GetLoadedAssemblies())
            {
                if (thisAssembly.IsDynamic)
                {
                    continue;
                }
                try
                {
                    //Load form Embedded Resources - This Function is not called if the Assembly is in the Application Folder
                    var resources = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(name));
                    if (resources.Count() > 0)
                    {
                        var resourceName = resources.First();
                        using (Stream stream = thisAssembly.GetManifestResourceStream(resourceName))
                        {
                            if (stream == null)
                            {
                                return(null);
                            }
                            var block = new byte[stream.Length];
                            stream.Read(block, 0, block.Length);
                            return(Assembly.Load(block));
                        }
                    }
                }
                catch (Exception ex)
                {
                    ChoTrace.Error(ex);
                }
            }
            return(null);
        }
Example #6
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);
            }
        }
Example #7
0
        public static void Register()
        {
            foreach (MethodInfo methodInfo in GetShellExtensionMethods())
            {
                ChoShellExtensionContextMenuAttribute attr = methodInfo.GetCustomAttribute <ChoShellExtensionContextMenuAttribute>();
                if (attr == null)
                {
                    continue;
                }

                string        methodName            = methodInfo.Name;
                string        fileType              = attr.FileType;
                string        menuText              = attr.MenuText;
                string        shellKeyName          = attr.ShellKeyName;
                string        icon                  = attr.Icon;
                StringBuilder additionalCmdLineArgs = new StringBuilder();

                foreach (string addCmdLineArg in attr.AdditionalCommandLineArgs.NSplit('%', false))
                {
                    if (addCmdLineArg.StartsWith("%") && addCmdLineArg.EndsWith("%") &&
                        !addCmdLineArg.StartsWith("%%") && !addCmdLineArg.EndsWith("%%"))
                    {
                        additionalCmdLineArgs.AppendFormat(@"%{0}%", addCmdLineArg);
                    }
                    else
                    {
                        additionalCmdLineArgs.AppendFormat(@"{0}", addCmdLineArg);
                    }
                }

                string z = additionalCmdLineArgs.ToString();
                additionalCmdLineArgs.Clear();
                foreach (string addCmdLineArg in z.SplitNTrim())
                {
                    //if (addCmdLineArg.StartsWith("%") && addCmdLineArg.EndsWith("%")
                    //    && !addCmdLineArg.StartsWith("%%") && !addCmdLineArg.EndsWith("%%"))
                    //    additionalCmdLineArgs.AppendFormat(@" ""%{0}%""", addCmdLineArg);
                    //else
                    additionalCmdLineArgs.AppendFormat(@" ""{0}""", addCmdLineArg);
                }
                string menuCommand = string.Format("\"{0}\" {3}{1}{3} {2} {4}\"%1\"", ChoPath.ToShortFileName(ChoApplication.EntryAssemblyLocation), methodName, additionalCmdLineArgs, SHELL_EXT_CMD_DELIMITER,
                                                   attr.DefaultArgPrefix);

                menuText     = menuText.IsNullOrWhiteSpace() ? methodName : menuText;
                shellKeyName = shellKeyName.IsNullOrWhiteSpace() ? methodName : shellKeyName;
                if (icon.IsNullOrWhiteSpace())
                {
                    if (attr.IconResourceFilePath.IsNullOrWhiteSpace())
                    {
                        icon = "{0},{1}".FormatString(ChoPath.ToShortName(ChoApplication.EntryAssemblyLocation), attr.IconIndex);
                    }
                    else
                    {
                        icon = "{0},{1}".FormatString(ChoPath.ToShortName(attr.IconResourceFilePath), attr.IconIndex);
                    }
                }

                ChoShellExtension.Register(fileType, shellKeyName, menuText, menuCommand, icon);
                ChoTrace.WriteLine("Shell Extensions registered successfully.");
            }
        }
Example #8
0
        void Me_ConfigChanged(object sender, EventArgs e)
        {
            if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn)
            {
                if (!ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TooltipText.IsNullOrWhiteSpace())
                {
                    this.NotifyIcon.Text = ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TooltipText;
                }
                if (!ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.BalloonTipText.IsNullOrWhiteSpace())
                {
                    this.NotifyIcon.BalloonTipText = ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.BalloonTipText;
                }

                if (!ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TrayIcon.IsNullOrWhiteSpace() &&
                    File.Exists(ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TrayIcon))
                {
                    try
                    {
                        NotifyIcon.Icon = Icon.ExtractAssociatedIcon(ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TrayIcon);
                    }
                    catch (Exception ex)
                    {
                        ChoTrace.Error(ex.ToString());
                    }
                }
            }
            else
            {
            }

            if (_hasWindow)
            {
                this._alwaysOnTopContextMenuItem.Checked = ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.AlwaysOnTop;
                AlwaysOnTop();
            }

            if (_hasWindow)
            {
                this._showInTaskbarContextMenuItem.Checked = ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.ShowInTaskbar;
                ShowInTaskbar();
            }

            this.NotifyIcon.Visible = ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn;

            if (_hasWindow)
            {
                if (!ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn)
                {
                    //_showMainWndMenuItem.Checked = !ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.HideWindow;
                    _isMainWindowOpen = !ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.HideWindow;
                    ToggleShowContextMenuItem();
                }
                else
                {
                    //_showMainWndMenuItem.Checked = !ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.HideMainWindowAtStartup;
                    _isMainWindowOpen = !ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.HideMainWindowAtStartup;
                    ToggleShowContextMenuItem();

                    if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.HideTrayIconWhenMainWindowShown)
                    {
                        this.NotifyIcon.Visible = false;
                    }
                }
            }
        }
Example #9
0
        private static void SyncFileWriter(object state)
        {
            FileProfileItem item;

            while (true)
            {
                try
                {
                    object queueObject = null;
                    if (_messageQ.Count > 0)
                    {
                        queueObject = _messageQ.Dequeue();
                    }
                    else
                    {
                        _newMsgArrived.WaitOne();
                        continue;
                    }

                    item = (FileProfileItem)queueObject;
                    if (item.IsFlushMsg)
                    {
                        break;
                    }

                    switch (item.Operation)
                    {
                    case FileOperation.WriteLine:
                    {
                        using (StreamWriter Writer = new StreamWriter(new FileStream(item.FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
                            Writer.WriteLine(item.Msg);
                        break;
                    }

                    case FileOperation.Write:
                    {
                        using (StreamWriter Writer = new StreamWriter(new FileStream(item.FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
                            Writer.Write(item.Msg);
                        break;
                    }

                    case FileOperation.Clean:
                        if (File.Exists(item.FileName))
                        {
                            using (StreamWriter logFile = new StreamWriter(item.FileName))
                            {
                            }
                        }
                        break;

                    case FileOperation.Move:
                        if (File.Exists(item.TargetFileName))
                        {
                            File.Delete(item.TargetFileName);
                        }
                        if (File.Exists(item.FileName))
                        {
                            File.Move(item.FileName, item.TargetFileName);
                        }
                        break;
                    }
                }
                catch (ThreadAbortException)
                {
                    Thread.ResetAbort();
                }
                catch (Exception ex)
                {
                    ChoTrace.Write(ex);
                }
            }
        }
Example #10
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 #11
0
        /// <summary>
        /// Creates instances for all performance counter members in the given type.
        /// </summary>
        /// <remarks>
        /// The type must have the PerformanceCounterCategory attribute set. Each performance counter
        /// member must be static and tagged with a PerformanceCounter attribute.
        /// </remarks>
        /// <param name="type">Type to instantiate counters</param>
        /// <param name="instance">Instance to assign performance counters to.</param>
        /// <returns><b>True</b> if counters were created successfully, <b>false</b> otherwise.</returns>
        private static bool CreateCounters(Type type, object instance)
        {
            // get category attribute
            ChoPerformanceCounterCategoryAttribute performanceCounterCategoryAttribute = type.GetCustomAttribute <ChoPerformanceCounterCategoryAttribute>(true);

            // we don't have performance counter category, we are done
            if (performanceCounterCategoryAttribute == null)
            {
                return(false);
            }

            string categoryName = performanceCounterCategoryAttribute.CategoryName;

            bool result = false;

            try
            {
                if (PerformanceCounterCategory.Exists(categoryName))
                {
                    // get the category type
                    PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName);

                    foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
                    {
                        if (fieldInfo.FieldType != typeof(ChoPerformanceCounter))
                        {
                            continue;
                        }

                        try
                        {
                            ChoPerformanceCounterAttribute performanceCounterAttribute = fieldInfo.GetCustomAttribute <ChoPerformanceCounterAttribute>();
                            if (performanceCounterAttribute == null)
                            {
                                continue;
                            }

                            if (performanceCounterAttribute.MachineName.IsNullOrEmpty() ||
                                (!performanceCounterAttribute.MachineName.IsNullOrEmpty() && String.Compare(performanceCounterAttribute.MachineName, Environment.MachineName, true) == 0))
                            {
                                if (fieldInfo.IsStatic && fieldInfo.GetValue(instance) != null)
                                {
                                    continue;
                                }

                                string instanceName = ChoPerformanceCounter.DefaultInstanceName;
                                // use a default instance name if the the counter does not have one and the category is marked MultiInstance
                                if (category.CategoryType == PerformanceCounterCategoryType.MultiInstance)
                                {
                                    instanceName = performanceCounterAttribute.CounterInstanceName.IsNullOrEmpty() ? instanceName : performanceCounterAttribute.CounterInstanceName;
                                }

                                // assign the performance counter
                                fieldInfo.SetValue(instance, new ChoPerformanceCounter(categoryName, performanceCounterAttribute.CounterName, performanceCounterAttribute.CounterType, instanceName, false));
                            }
                        }
                        catch (Exception innerEx)
                        {
                            ChoTrace.Error(innerEx);
                        }
                    }

                    foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
                    {
                        if (propertyInfo.PropertyType != typeof(ChoPerformanceCounter))
                        {
                            continue;
                        }

                        try
                        {
                            if (!propertyInfo.CanWrite || propertyInfo.GetIndexParameters().Length > 0)
                            {
                                continue;
                            }

                            ChoPerformanceCounterAttribute performanceCounterAttribute = propertyInfo.GetCustomAttribute <ChoPerformanceCounterAttribute>();
                            if (performanceCounterAttribute == null)
                            {
                                continue;
                            }

                            if (performanceCounterAttribute.MachineName.IsNullOrEmpty() ||
                                (!performanceCounterAttribute.MachineName.IsNullOrEmpty() && String.Compare(performanceCounterAttribute.MachineName, Environment.MachineName, true) == 0))
                            {
                                if (propertyInfo.GetSetMethod(true).IsStatic&& propertyInfo.GetValue(instance, null) != null)
                                {
                                    continue;
                                }

                                // use a default instance name if the the counter does not have one and the category is marked MultiInstance
                                string instanceName = ChoPerformanceCounter.DefaultInstanceName;
                                // use a default instance name if the the counter does not have one and the category is marked MultiInstance
                                if (category.CategoryType == PerformanceCounterCategoryType.MultiInstance)
                                {
                                    instanceName = performanceCounterAttribute.CounterInstanceName.IsNullOrEmpty() ? instanceName : performanceCounterAttribute.CounterInstanceName;
                                }

                                // assign the performance counter
                                propertyInfo.SetValue(instance, new ChoPerformanceCounter(categoryName, performanceCounterAttribute.CounterName, performanceCounterAttribute.CounterType, instanceName, false), null);
                            }
                        }
                        catch (Exception innerEx)
                        {
                            ChoTrace.Error(innerEx);
                        }
                    }
                    result = true;
                }
            }
            catch (Exception outerEx)
            {
                ChoTrace.Error(outerEx);
            }

            return(result);
        }