Exemplo n.º 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 (Exception ex)
            {
                ChoTrace.Error(ex);
                ChoTrace.Error(msgObject.State.ToString());
                asyncResult.SetAsFailed(ex, true);
            }
        }
Exemplo n.º 2
0
 private static void OnTimerServiceCallback(object state)
 {
     lock (_padLock)
     {
         try
         {
             foreach (ChoGlobalTimerServiceData globalTimerServiceData in _callbacks.Values)
             {
                 if (globalTimerServiceData.IsPeriodElapsed())
                 {
                     try
                     {
                         globalTimerServiceData.Run();
                     }
                     catch (ChoFatalApplicationException)
                     {
                         throw;
                     }
                     catch (Exception ex)
                     {
                         ChoTrace.Error(ex);
                         //ChoProfile.RegisterIfNotExists(globalTimerServiceData.Name, new ChoBufferProfileEx(ChoFileProfileSettings.GetFullPath(ChoReservedDirectoryName.Others,
                         //    ChoPath.AddExtension(typeof(ChoGlobalTimerServiceManager).FullName, ChoReservedFileExt.Err)),
                         //    "Errors found..."));
                         //ChoProfile.GetContext(globalTimerServiceData.Name).AppendIf(ChoTrace.ChoSwitch.TraceError, ex);
                     }
                 }
             }
         }
         catch (TimeoutException tex)
         {
             ChoTrace.Error(tex);
         }
     }
 }
        private static void Refresh()
        {
            try
            {
                LoadFile();
            }
            catch (Exception ex)
            {
                ChoTrace.Error(ex);

                try
                {
                    string newFile = ChoPath.AddExtension(MetaDataFilepath, ChoReservedFileExt.Err);
                    if (File.Exists(newFile))
                    {
                        File.Delete(newFile);
                    }
                    File.Move(MetaDataFilepath, newFile);

                    ChoXmlDocument.CreateXmlFileIfEmpty(MetaDataFilepath);
                    LoadFile();
                }
                catch (Exception innerEx)
                {
                    ChoTrace.Error(innerEx);
                }
            }
        }
Exemplo n.º 4
0
        private void OnTimerCallback(object state)
        {
            if (_isStopped || _isPaused)
            {
                _resumeEvent.WaitOne();
            }

            try
            {
                if (_timerServiceCallback != null)
                {
                    _timerServiceCallback.Run((T)state, _timeout);
                }
                //new Action<T>(OnTimerServiceCallback).WaitFor((T)state, _timeout);
            }
            catch (TimeoutException ex)
            {
                if (!_silent)
                {
                    throw new ChoTimerServiceException(String.Format("{1}: Timeout [{0} ms] elapsed prior to completion of the method.", _timeout, _name), ex);
                }
                else
                {
                    ChoTrace.Error(String.Format("Timeout [{0} ms] elapsed prior to completion of the method.", _timeout));
                }
            }

            Thread.Sleep(_period);
        }
Exemplo n.º 5
0
        public static void InvokeEx <T>(this MulticastDelegate source, object target, T args,
                                        Action <Delegate> removeHandler = null)
            where T : EventArgs
        {
            MulticastDelegate handler = source;

            if (handler != null)
            {
                foreach (Delegate invokeHandler in handler.GetInvocationList())
                {
                    try
                    {
                        invokeHandler.DynamicInvoke(new object[] { target, args });
                    }
                    catch (ChoFatalApplicationException)
                    {
                        throw;
                    }
                    catch (Exception ex)
                    {
                        ChoTrace.Error(ex);
                        if (removeHandler != null)
                        {
                            removeHandler(invokeHandler);
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        private void HandleDisconnected()
        {
            //if (_socket != null && _socket.IsConnected())
            //    return;
            if (_reconnectTimer == null)
            {
                return;
            }

            ChoTrace.Info("Got disconnected, launching reconnect timer.");
            _reconnectTimer.Change(ReconnectInterval, Timeout.Infinite);
            if (_socket != null)
            {
                try
                {
                    _socket.Close();
                }
                catch (Exception err)
                {
                    ChoTrace.Error("Failed to close socket.", err);
                }
                _socket = null;
                RaiseDisconnected();
            }
        }
Exemplo n.º 7
0
        public static void Register(Type type)
        {
            if (type == null)
            {
                return;
            }

            foreach (MethodInfo methodInfo in type.GetMethods())
            {
                ChoObjectFormatHandlerAttribute objectFormatterAttribute = methodInfo.GetCustomAttribute <ChoObjectFormatHandlerAttribute>();
                if (objectFormatterAttribute == null)
                {
                    continue;
                }

                try
                {
                    AddOrReplace(objectFormatterAttribute.TargetType,
                                 objectFormatterAttribute.FormatName.IsNullOrEmpty() ? ChoObjectFormatHandlerAttribute.DEFAULT_HANDLER_NAME : objectFormatterAttribute.FormatName,
                                 methodInfo.CreateDelegate <Func <object, string> >());
                }
                catch (ChoFatalApplicationException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    ChoTrace.Error(ex);
                }
            }
        }
Exemplo n.º 8
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                Byte[] payload = _serverSocket.EndReceive(ar, ref _localEP);

                IdentifyMessageType(payload);
                if (_messageType == null || _messageType.Value == ChoNetMessageType.Raw)
                {
                    EventHandler <ChoNetMessageEventArgs> rawMessageReceived = RawMessageReceived;
                    if (rawMessageReceived != null)
                    {
                        rawMessageReceived(this, new ChoNetMessageEventArgs(null, payload));
                    }
                }
                else if (_messageType.Value == ChoNetMessageType.Xml)
                {
                    try
                    {
                        ChoNetMessage msg = (ChoNetMessage)_encoding.GetString(payload).ToObjectFromXml(); // ChoObject.XmlDeserialize<ChoNetMessage>(_encoding.GetString(payload));
                        if (!PreProcessMessage(msg))
                        {
                            EventHandler <ChoNetMessageEventArgs> messageReceived = MessageReceived;
                            if (messageReceived != null)
                            {
                                messageReceived(this, new ChoNetMessageEventArgs(msg, null));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ChoTrace.Error(ex.ToString());
                    }
                }
                else if (_messageType.Value == ChoNetMessageType.Binary)
                {
                    try
                    {
                        ChoNetMessage msg = (ChoNetMessage)ChoObject.Deserialize(payload);
                        if (!PreProcessMessage(msg))
                        {
                            EventHandler <ChoNetMessageEventArgs> messageReceived = MessageReceived;
                            if (messageReceived != null)
                            {
                                messageReceived(this, new ChoNetMessageEventArgs(msg, null));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ChoTrace.Error(ex.ToString());
                    }
                }
            }
            finally
            {
                _recieveResult = _serverSocket.BeginReceive(ReceiveCallback, null);
            }
        }
Exemplo n.º 9
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
            {
            }


            this._alwaysOnTopContextMenuItem.Checked = ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.AlwaysOnTop;
            AlwaysOnTop();

            this._runAtStartupContextMenuItem.Checked = ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.RunOnceAtStartup;
            RunAtStartup();

            this._showInTaskbarContextMenuItem.Checked = ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.ShowInTaskbar;
            ShowInTaskbar();

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

            if (!ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn)
            {
                _showContextMenuItem.Checked = !ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.HideWindow;
                ToggleShowContextMenuItem();
            }
            else
            {
                _showContextMenuItem.Checked = !ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.HideMainWindowAtStartup;
                ToggleShowContextMenuItem();

                if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.HideTrayIconWhenMainWindowShown)
                {
                    this.NotifyIcon.Visible = false;
                }
            }
        }
Exemplo n.º 10
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            IPEndPoint ep      = null;
            var        args    = (object[])ar.AsyncState;
            var        session = (UdpClient)args[0];
            var        local   = (IPEndPoint)args[1];

            try
            {
                Byte[] payload = session.EndReceive(ar, ref ep);

                EventHandler <ChoUDPMessageEventArgs> rawMessageReceived = RawMessageReceived;
                EventHandler <ChoUDPMessageEventArgs> messageReceived    = MessageReceived;
                if (rawMessageReceived != null)
                {
                    rawMessageReceived(this, new ChoUDPMessageEventArgs(null, payload));
                }
                else if (messageReceived != null)
                {
                    IdentifyMessageType(payload);
                    if (_messageType == null)
                    {
                        if (rawMessageReceived != null)
                        {
                            rawMessageReceived(this, new ChoUDPMessageEventArgs(null, payload));
                        }
                    }
                    else if (_messageType.Value == ChoUDPMessageType.Xml)
                    {
                        try
                        {
                            ChoScalarObject scalarObject = (ChoScalarObject)ChoObject.XmlDeserialize <ChoScalarObject>(_encoding.GetString(payload));
                            MessageReceived(this, new ChoUDPMessageEventArgs(scalarObject, null));
                        }
                        catch (Exception ex)
                        {
                            ChoTrace.Error(ex.ToString());
                        }
                    }
                    else
                    {
                        try
                        {
                            ChoScalarObject scalarObject = (ChoScalarObject)ChoObject.Deserialize(payload);
                            MessageReceived(this, new ChoUDPMessageEventArgs(scalarObject, null));
                        }
                        catch (Exception ex)
                        {
                            ChoTrace.Error(ex.ToString());
                        }
                    }
                }
            }
            finally
            {
                _recieveResult = session.BeginReceive(ReceiveCallback, args);
            }
        }
Exemplo n.º 11
0
        private void ReceivedDataReady(IAsyncResult ar)
        {
            ChoConnectionState st = ar.AsyncState as ChoConnectionState;

            try
            {
                st.Connection.EndReceive(ar);
                //Im considering the following condition as a signal that the
                //remote host droped the connection.
                if (st.Connection.Available == 0)
                {
                    return;
                }
                else
                {
                    try
                    {
                        _provider.OnReceiveData(st);
                    }
                    catch (ChoFatalApplicationException)
                    {
                        throw;
                    }
                    catch
                    {
                        //report error in the provider
                    }
                    //Resume ReceivedData callback loop
                    if (st.Connection.Connected)
                    {
                        try
                        {
                            st.Connection.BeginReceive(st.Buffer, 0, 0, SocketFlags.None,
                                                       ReceivedDataReady, st);
                        }
                        catch (Exception innerEx)
                        {
                            ChoTrace.Error(innerEx);
                            HandleDisconnected();
                        }
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                HandleDisconnected();
            }
            catch (ChoFatalApplicationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                ChoTrace.Error(ex);
                HandleDisconnected();
            }
        }
Exemplo n.º 12
0
 public static void LogExceptions(this Task task)
 {
     task.ContinueWith(t =>
     {
         var aggException = t.Exception.Flatten();
         foreach (var exception in aggException.InnerExceptions)
         {
             ChoTrace.Error(exception);
         }
     },
                       TaskContinuationOptions.OnlyOnFaulted);
 }
Exemplo n.º 13
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                Byte[] payload = _listener.EndReceive(ar, ref _groupEP);

                EventHandler <ChoUDPMessageEventArgs> rawMessageReceived = RawMessageReceived;
                EventHandler <ChoUDPMessageEventArgs> messageReceived    = MessageReceived;
                if (rawMessageReceived != null)
                {
                    rawMessageReceived(this, new ChoUDPMessageEventArgs(null, payload));
                }
                else if (messageReceived != null)
                {
                    IdentifyMessageType(payload);
                    if (_messageType == null)
                    {
                        if (rawMessageReceived != null)
                        {
                            rawMessageReceived(this, new ChoUDPMessageEventArgs(null, payload));
                        }
                    }
                    else if (_messageType.Value == ChoUDPMessageType.Xml)
                    {
                        try
                        {
                            ChoScalarObject scalarObject = (ChoScalarObject)ChoObject.XmlDeserialize <ChoScalarObject>(_encoding.GetString(payload));
                            MessageReceived(this, new ChoUDPMessageEventArgs(scalarObject, null));
                        }
                        catch (Exception ex)
                        {
                            ChoTrace.Error(ex.ToString());
                        }
                    }
                    else
                    {
                        try
                        {
                            ChoScalarObject scalarObject = (ChoScalarObject)ChoObject.Deserialize(payload);
                            MessageReceived(this, new ChoUDPMessageEventArgs(scalarObject, null));
                        }
                        catch (Exception ex)
                        {
                            ChoTrace.Error(ex.ToString());
                        }
                    }
                }
            }
            finally
            {
                _recieveResult = _listener.BeginReceive(ReceiveCallback, null);
            }
        }
Exemplo n.º 14
0
        protected virtual void Dispose(bool disposing)
        {
            if (_isDisposed)
            {
                return;
            }

            _isDisposed = true;
            var result = ChoMpr.WNetCancelConnection2(_networkShareName, ChoMpr.CONNECT_UPDATE_PROFILE, true);

            if (result != 0 && TraceErrors)
            {
                ChoTrace.Error(new ChoWin32Exception(result, "Error disconnecting to '{0}' remote share".FormatString(_networkShareName)));
            }
        }
        private static void Refresh()
        {
            try
            {
                lock (_padLock)
                {
                    _propDict.Clear();
                }

                if (ChoMetaDataFilePathSettings.Me != null)
                {
                    _metaDataFilepath = ChoMetaDataFilePathSettings.Me.OverridenCmdLineArgMetaDataFilePath;
                }

                if (!ChoAppFrxSettings.Me.DisableMetaDataConfig)
                {
                    ChoXmlDocument.CreateXmlFileIfEmpty(_metaDataFilepath);
                    _metaDataChangeWatcher = new ChoAppConfigurationChangeFileWatcher(META_DATA_KEY, _metaDataFilepath, _includeFiles);
                    _metaDataChangeWatcher.SetConfigurationChangedEventHandler(META_DATA_FILE_WATCHER_KEY,
                                                                               (sender, e) =>
                    {
                        Refresh();
                    });
                }

                if (!_metaDataFilepath.IsNullOrWhiteSpace() && File.Exists(_metaDataFilepath))
                {
                    using (ChoXmlDocument xmlDocument = new ChoXmlDocument(_metaDataFilepath))
                    {
                        _rootNode     = xmlDocument.XmlDocument.DocumentElement;
                        _includeFiles = xmlDocument != null ? xmlDocument.IncludeFiles : null;
                    }
                }
            }
            catch (Exception ex)
            {
                ChoTrace.Error(ex.ToString());
                //throw;
            }
        }
Exemplo n.º 16
0
        internal void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChangedInternal;

            if (handler != null)
            {
                foreach (PropertyChangedEventHandler propertyChangedEventHandler in handler.GetInvocationList())
                {
                    try
                    {
                        propertyChangedEventHandler((MarshalByRefObject)this, new PropertyChangedEventArgs(name));
                    }
                    catch (ChoFatalApplicationException)
                    {
                    }
                    catch (Exception ex)
                    {
                        ChoTrace.Error(ex);
                    }
                }
            }
        }
Exemplo n.º 17
0
        public static void Save(XmlNode xmlNode, string xmlFilePath, XmlWriterSettings xws)
        {
            ChoGuard.ArgumentNotNull(xmlNode, "XmlDocument");
            ChoGuard.ArgumentNotNullOrEmpty(xmlFilePath, "XmlFilePath");

            if (xmlNode is XmlDocumentFragment)
            {
                xws.OmitXmlDeclaration = true;
                xws.ConformanceLevel   = ConformanceLevel.Auto;
                xws.Indent             = false;
            }
            try
            {
                //using (FileStream fs = File.Create(xmlFilePath))
                //using (FileStream fs = new FileStream(xmlFilePath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                //{
                using (StreamWriter sw = new StreamWriter(xmlFilePath, false))
                {
                    // Create a XMLTextWriter that will send its output to a memory stream (file)
                    using (XmlWriter xtw = XmlTextWriter.Create(sw, xws))
                    {
                        // Set the formatting property of the XML Text Writer to indented
                        // the text writer is where the indenting will be performed
                        //if (indentOutput)
                        //    xtw.Formatting = Formatting.Indented;

                        // write dom xml to the xmltextwriter
                        xmlNode.WriteContentTo(xtw);
                        // Flush the contents of the text writer
                        // to the memory stream, which is simply a memory file
                        xtw.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                ChoTrace.Error(ex);
            }
        }
Exemplo n.º 18
0
        internal void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChangedInternal;

            if (handler != null)
            {
                foreach (PropertyChangedEventHandler propertyChangedEventHandler in handler.GetInvocationList())
                {
                    try
                    {
                        propertyChangedEventHandler((MarshalByRefObject)this, new PropertyChangedEventArgs(name));
                    }
                    catch (ChoFatalApplicationException)
                    {
                        throw;
                    }
                    catch (Exception ex)
                    {
                        ChoTrace.Error(ex);
                    }

                    foreach (string depends in ChoPropertyDependsOnCache.Instance.GetDependsOn(GetType(), name))
                    {
                        try
                        {
                            propertyChangedEventHandler((MarshalByRefObject)this, new PropertyChangedEventArgs(depends));
                        }
                        catch (ChoFatalApplicationException)
                        {
                            throw;
                        }
                        catch (Exception ex)
                        {
                            ChoTrace.Error(ex);
                        }
                    }
                }
            }
        }
Exemplo n.º 19
0
        private void Refresh()
        {
            if (ChoAppFrxSettings.Me.DisableMetaDataConfig)
            {
                return;
            }

            try
            {
                LoadFile();
            }
            catch (ChoFatalApplicationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                ChoTrace.Error(ex);

                try
                {
                    string newFile = ChoPath.AddExtension(MetaDataFilePath, ChoReservedFileExt.Err);
                    if (File.Exists(newFile))
                    {
                        File.Delete(newFile);
                    }
                    File.Move(MetaDataFilePath, newFile);

                    ChoXmlDocument.CreateXmlFileIfEmpty(MetaDataFilePath);
                    LoadFile();
                }
                catch (Exception innerEx)
                {
                    ChoTrace.Error(innerEx);
                }
            }
        }
        private static void Refresh()
        {
            try
            {
                lock (_padLock)
                {
                    _propDict.Clear();
                }

                if (ChoMetaDataFilePathSettings.Me != null)
                {
                    _metaDataFilepath = ChoMetaDataFilePathSettings.Me.OverridenConfigurationMetaDataFilePath;
                }

                ChoXmlDocument.CreateXmlFileIfEmpty(_metaDataFilepath);
                _configurationChangeWatcher = new ChoAppConfigurationChangeFileWatcher("meta-data_configurations", _metaDataFilepath, _includeFiles);
                _configurationChangeWatcher.SetConfigurationChangedEventHandler("ChoMetaDataManager_Watcher",
                                                                                (sender, e) =>
                {
                    Refresh();
                });

                if (!_metaDataFilepath.IsNullOrWhiteSpace() && File.Exists(_metaDataFilepath))
                {
                    using (ChoXmlDocument xmlDocument = new ChoXmlDocument(_metaDataFilepath))
                    {
                        _rootNode     = xmlDocument.XmlDocument.DocumentElement;
                        _includeFiles = xmlDocument != null ? xmlDocument.IncludeFiles : null;
                    }
                }
            }
            catch (Exception ex)
            {
                ChoTrace.Error(ex.ToString());
                throw;
            }
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
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);
            }
        }
Exemplo n.º 23
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);
        }