示例#1
0
        internal static void Test1(ILog logger)
        {
            IList<string> myList = new List<string>();
            myList.Add("item1");
            myList.Add("item2");
            IDictionary<string, string> myDictionary = new Dictionary<string, string>();
            myDictionary["k1"] = "v1";
            myDictionary["k2"] = "v2";
            HttpField.HttpInstance.Set(HttpFieldName.ResponseHeaders, myList);
            HttpField.HttpInstance.Set(HttpFieldName.RequestHeaders, myDictionary);
            logger.Error("there's been an error");

            // log4net doesn't give exceptions any special treatment...
            // also dotnet won't generate a stacktrace for an exception til we throw it...
            logger.Error(new ArgumentException("Fake Error Thrown"));
            try
            {
                string dodgy = null;
                Console.WriteLine(dodgy.Equals("that", StringComparison.InvariantCulture));
            }
            catch (NullReferenceException e)
            {
                logger.Error(e);
            }

            HttpField.HttpInstance.Clear();
            logger.Info("non exception");
        }
示例#2
0
        static void Main( string[] args )
        {
            //---   Initialise log4net

            log4net.Config.XmlConfigurator.Configure();

            log_ = log4net.LogManager.GetLogger( typeof( Program ) );

            //---   Create the interface to Cortex

            cortex_ = CortexInterface.Instance;

            //---   Self host the WebAPI

            HttpSelfHostServer server = null;

            try
            {
                //---   Set up server configuration

                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration( _baseAddress );

                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{object_id}/{port_id}",
                    defaults: new { object_id = RouteParameter.Optional, port_id = RouteParameter.Optional }
                );

                //---   Create the server

                server = new HttpSelfHostServer( config );

                //---   Start listening

                server.OpenAsync().Wait();
                log_.Info( "Listening on " + _baseAddress + " Hit ENTER to exit..." );
                Console.ReadLine();
            }
            catch ( Exception e )
            {
                log_.Error( "Could not start server: " + e.GetBaseException().Message );
                log_.Error( "Hit ENTER to exit..." );
                Console.ReadLine();
            }
            finally
            {
                if ( server != null )
                {
                    //---   Stop listening
                    server.CloseAsync().Wait();
                }
            }
        }
示例#3
0
        /**
         * <summary>
         * Constructor with port name and open the port.
         * Also initializes servo channels to center
         * </summary>
         *
         * <param name="portName">Name of the serial port</param>
         * <param name="channels">Channels to center on construction</param>
         */
        protected MiniSSCIIServoController(string portName, ICollection<uint> channels)
        {
            log = LogManager.GetLogger(this.GetType());
            log.Debug(this.ToString() + " constructed.");

            activeChannels = channels;
            try
            {
                port = new SerialPort(portName);
                port.Open();
                port.BaudRate = 9600;
                port.NewLine = string.Empty + Convert.ToChar(13);
                port.Handshake = System.IO.Ports.Handshake.None;
                port.BaseStream.Flush();

                port.ReadTimeout = 1000;
                inactive = false;

                foreach (uint ch in channels)
                {
                    ServoMovementCommand smc = new ServoMovementCommand(ch, 128);
                    sendCommand(smc);
                }
                log.Info("Initiating all servos to center.");
            }
            catch (IOException ex)
            {
                log.Error("Could not open Servo Controller Port on " + portName, ex);
                inactive = true;
            }
        }
示例#4
0
        public Client(int id, Config cfg, SynchronizationContext ctx)
        {
            ClientStatisticsGatherer = new ClientStatisticsGatherer();

              _ctx = ctx;
              _id = id;

              Data = new TestData(this);
              IsStopped = false;

              _log = LogManager.GetLogger("Client_" + _id);
              _log.Debug("Client created");

              Configure(cfg);

              if (String.IsNullOrEmpty(_login))
              {
            const string err = "Login command is not specified!!! Can't do any test.";
            _log.Error(err);

            throw new Exception(err);
              }

              _ajaxHelper = new AjaxHelper(new AjaxConn(_login, cfg.ServerIp, cfg.AjaxPort, _ctx));
              _webSock = new WebSockConn(_login, cfg.ServerIp, cfg.WsPort, ctx);

              _webSock.CcsStateChanged += WsOnCcsStateChanged;
              _webSock.InitializationFinished += () => _testMng.GetTest<LoginTest>().OnClientInitialized();
              _testMng.SetEnv(_login, _ajaxHelper.AjaxConn, _webSock);
        }
        static SIPSoftPhoneState()
        {
            try
            {
                #region Configure logging.

                try
                {
                    log4net.Config.XmlConfigurator.Configure();
                    logger = log4net.LogManager.GetLogger(LOGGER_NAME);
                }
                catch (Exception logExcp)
                {
                    Console.WriteLine("Exception SIPSoftPhoneState Configure Logging. " + logExcp.Message);
                }

                #endregion

                if (ConfigurationManager.GetSection(SIPSOFTPHONE_CONFIGNODE_NAME) != null) {
                    m_sipSoftPhoneConfigNode = (XmlNode)ConfigurationManager.GetSection(SIPSOFTPHONE_CONFIGNODE_NAME);
                }

                if (m_sipSoftPhoneConfigNode != null) {
                    SIPSocketsNode = m_sipSoftPhoneConfigNode.SelectSingleNode(SIPSOCKETS_CONFIGNODE_NAME);
                }

                STUNServerHostname = ConfigurationManager.AppSettings[STUN_SERVER_KEY];
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPSoftPhoneState. " + excp.Message);
                throw;
            }
        }
 private void Init(NameValueCollection appSettings, string collectionUrl)
 {
     _logger = LogManager.GetLogger(GetType());
     try
     {
         collectionUrl = string.IsNullOrWhiteSpace(collectionUrl) ? null : collectionUrl.TrimEnd('/');
         var defaultUpdateUrl = collectionUrl == null ? null : string.Format("{0}/update", collectionUrl);
         var defaultQueryUrl = collectionUrl == null ? null : string.Format("{0}/query", collectionUrl);
         UpdateUrl = GetValueFromAppSettings(appSettings, SettingCollectionUpdateUrl, defaultUpdateUrl);
         QueryUrl = GetValueFromAppSettings(appSettings, SettingCollectionQueryUrl, defaultQueryUrl);
         if (UpdateUrl == null || QueryUrl == null)
         {
             throw new TypeInitializationException(GetType().FullName,
                 new ArgumentNullException(SettingCollectionUpdateUrl,
                     string.Format(
                         "The app setting {0} should be configured to the base url of a solr core/collection, e.g.: http://localhost:8983/solr/collectionName, which supports both the /update and /query request handlers. Alternatively, explicit urls can be set for query and update handlers with the app settings {1} and {2}, respectively",
                         SettingCollectionUrl, SettingCollectionQueryUrl, SettingCollectionUpdateUrl)));
         }
     }
     catch (Exception ex)
     {
         _logger.Error("Could not initialize solr configuration", ex);
         throw;
     }
 }
示例#7
0
        /// <summary>
        /// 异常日志信息
        /// </summary>
        /// <param name="text"></param>
        /// <param name="caption"></param>
        /// <param name="buttons"></param>
        /// <param name="icon"></param>
        /// <param name="ex"></param>
        /// <param name="FormType"></param>
        /// <returns></returns>
        public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, Exception ex,Type FormType)
        {
            log = LogManager.GetLogger(FormType);
            log.Error(ex);

            return DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, buttons, icon);
        }
示例#8
0
        public static String GetShortenLink(String shareLink, ILog log)
        {
            var uri = new Uri(shareLink);

            var bitly = string.Format(BitlyUrl, Uri.EscapeDataString(uri.ToString()));
            XDocument response;
            try
            {
                response = XDocument.Load(bitly);
            }
            catch (Exception e)
            {
                if (log != null) { log.Error(e); }
                throw new InvalidOperationException(e.Message, e);
            }

            var status = response.XPathSelectElement("/response/status_code").Value;
            if (status != ((int)HttpStatusCode.OK).ToString(CultureInfo.InvariantCulture))
            {
                throw new InvalidOperationException(Resources.Resource.ErrorBadRequest + " (" + status + ")");
            }

            var data = response.XPathSelectElement("/response/data/url");

            return data.Value;
        }
示例#9
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //if (log4net.LogManager.GetCurrentLoggers().Length == 0)
            {
                log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));
            }
            logger = log4net.LogManager.GetLogger(typeof(Program));

            logger.Info("LogzAppender working!!");
            logger.Info("This is another message!!");

            try
            {
                var a = 0;
                a += 0;
                var b = 5 / a;
            }
            catch (Exception ex)
            {
                logger.Error(new Dictionary<String, String>() {
                             	 { "message", "test message" },
                             	 { "gilly", "barr" }
                             }, ex);
            }

            Console.ReadKey(true);
        }
        protected void WaitForResultOfRequest(ILog logger, string workerTypeName, IOperation operation, Guid subscriptionId, string certificateThumbprint, string requestId)
        {
            OperationResult operationResult = new OperationResult();
            operationResult.Status = OperationStatus.InProgress;
            bool done = false;
            while (!done)
            {
                operationResult = operation.StatusCheck(subscriptionId, certificateThumbprint, requestId);
                if (operationResult.Status == OperationStatus.InProgress)
                {
                    string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}', the operation was found to be in process, waiting for '{3}' seconds.", workerTypeName, this.Id, requestId, FiveSecondsInMilliseconds / 1000);
                    logger.Info(logMessage);
                    Thread.Sleep(FiveSecondsInMilliseconds);
                }
                else
                {
                    done = true;
                }
            }

            if (operationResult.Status == OperationStatus.Failed)
            {
                string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}' and it failed. The code was '{3}' and message '{4}'.", workerTypeName, this.Id, requestId, operationResult.Code, operationResult.Message);
                logger.Error(logMessage);
            }
            else if (operationResult.Status == OperationStatus.Succeeded)
            {
                string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}' and it succeeded. The code was '{3}' and message '{4}'.", workerTypeName, this.Id, requestId, operationResult.Code, operationResult.Message);
                logger.Info(logMessage);
            }
        }
 /// <summary>
 /// The error.
 /// </summary>
 /// <param name="log">
 /// The log.
 /// </param>
 /// <param name="message">
 /// The message.
 /// </param>
 public static void Error(ILog log, string message)
 {
     if (log != null)
     {
         log.Error(message);
     }
 }
示例#12
0
 public static void Error(string message, Exception ex, ILog log)
 {
     if (log.IsErrorEnabled)
     {
         log.Error(message, ex);
     }
 }
示例#13
0
        static WebState() {
            try {
                #region Configure logging.

                try {

                    log4net.Config.XmlConfigurator.Configure();
                    logger = log4net.LogManager.GetLogger(LOGGER_NAME);
                }
                catch (Exception logExcp) {
                    Console.WriteLine("Exception SIPProxyState Configure Logging. " + logExcp.Message);
                }

                #endregion

                CRMStorageType = (ConfigurationManager.AppSettings[m_storageTypeKey] != null) ? StorageTypesConverter.GetStorageType(ConfigurationManager.AppSettings[m_storageTypeKey]) : StorageTypes.Unknown;
                CRMStorageConnStr = ConfigurationManager.AppSettings[m_connStrKey];

                if (CRMStorageType == StorageTypes.Unknown || CRMStorageConnStr.IsNullOrBlank()) {
                    logger.Error("The SIPSorcery.CRM.Web does not have any persistence settings configured.");
                }

                XmlNode validationRulesNode = (XmlNode)ConfigurationManager.GetSection(CUSTOMER_VALIDATION_RULES);
                if (validationRulesNode != null) {
                    foreach (XmlNode validationNode in validationRulesNode) {
                         ValidationRules.Add(validationNode.SelectSingleNode("field").InnerText, validationNode.SelectSingleNode("rule").InnerText);
                    }
                }
            }
            catch (Exception excp) {
                logger.Error("Exception WebState. " + excp.Message);
            }
        }
示例#14
0
 public static void Log(ILog logger, string message, string action)
 {
     //MDC.Set("user", ClientInfo.getInstance().LoggedUser.Name);
     log4net.GlobalContext.Properties["user"] = "******";
     log4net.GlobalContext.Properties["action"] = action;
     logger.Error(message); //now log error
 }
        public Exception404PageNotFound(string message, Exception ex)
            : base(message, ex)
        {
            log4net.GlobalContext.Properties["LogName"] = DateTime.Now.ToShortDateString().ToString();
            log = MyLogger.GetLogger(typeof(Exception404PageNotFound));

            log.Error(message, ex);
        }
 public static void LogRestError(ILog logger, IRestResponse restResponse, string errorHeading)
 {
     if (logger != null && restResponse != null)
     {
         var stringBuilder = BuildLoggingString(restResponse, errorHeading);
         logger.Error(stringBuilder.ToString());
     }
 }
示例#17
0
 internal static void LogMessages(ILog log)
 {
     log.Info("This is an info");
     log.InfoFormat("Base called at {0}", DateTime.Now);
     log.Debug("This is a debug");
     log.Warn("This is a warning");
     log.Error("This is an error");
 }
示例#18
0
 public static void Log(ILog log, Exception ex, string sMessage = null)
 {
     Console.ForegroundColor = ConsoleColor.Red;
     Console.WriteLine("{0}: ERROR ******", DateTime.Now.ToString("HH:mm:ss.fff"));
     Console.WriteLine("For additional information, please see the log file.");
     Console.ForegroundColor = ConsoleColor.White;
     log.Error(sMessage ?? ex.Message, ex);
 }
示例#19
0
 public static void Error(System.Type type, object message)
 {
     System.Diagnostics.Debug.WriteLine(message);
     logger = LogManager.GetLogger(type);
     if (!logger.Logger.Repository.Configured)
         XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(GetConfigFile() + ".config"));
     logger.Error(message);
 }
示例#20
0
 /// <summary>
 ///     Write log message to log file
 /// </summary>
 /// <param name="message"></param>
 public void LogError(string message)
 {
     ThreadContext.Properties["logPath"] = Constant.Paths.Error;
     _logger = LogManager.GetLogger(GetCaller());
     XmlConfigurator.Configure();
     _logger.Error(message);
     LogManager.GetRepository().Shutdown();
 }
示例#21
0
        public void Start()
        {
            try
            {
                // Assinar o recebimento de
                this.OnNegociosHandler = new MdsHttpClient.OnNegociosHandler(OnNegocios);
                MdsHttpClient.Instance.OnNegociosEvent += this.OnNegociosHandler;
                _running = true;

                _queueMsgs  = new Queue <MdsNegociosEventArgs>();
                _dicTrading = new Dictionary <string, MdsTradingInfo>();
                // Conectar ao streamer
                if (!this.ConnectToStreamer())
                {
                    logger.Info("Nao foi possivel conectar ao servidor Streamer");
                }

                _thProcessTrading = new Thread(new ThreadStart(this.ProcessMdsNegocios));
                _thProcessTrading.Start();
            }
            catch (Exception ex)
            {
                logger.Error("Problemas no start do StreamerManager: " + ex.Message, ex);
            }
        }
        //Get configuration data

        public IList <Home> GetMOMProjects()
        {
            log.Info("Log started");
            IList <Home> list = new List <Home>();

            try
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["STRMDConnectionString"].ConnectionString))
                {
                    conn.Open();
                    SqlCommand command = new SqlCommand("GetMOMProjects", conn);
                    command.CommandType = CommandType.StoredProcedure;
                    SqlDataReader sDr = command.ExecuteReader();
                    if (sDr != null)
                    {
                        while (sDr.Read())
                        {
                            Home model = new Home();
                            model.ProjectId   = Convert.ToString(sDr["ProjectId"]);
                            model.ProjectName = Convert.ToString(sDr["ProjectName"]);
                            list.Add(model);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //throw ex;
                log.Error(ex.Message, ex);
            }
            return(list);
        }
示例#23
0
        public void Initialize()
        {
            List <bool> RemoveServer    = new List <bool>();
            String      LocalServerName = Env.DEBUG ? "ap-imgutil2-dev" : System.Environment.MachineName;

            try
            {
                this.EnvServers = JsonConvert.DeserializeObject <List <UtilServer> >(File.ReadAllText(Env.CACHE_DIR + $"\\{Env.AppServer["name"]}.json"));
                log.Info("Deserialized Server configuration.");
            }
            catch (IOException e)
            {
                log.Error($"Cannot find JSON config file in: {Env.CACHE_DIR}");
                log.Error(e.Message);
            }
            foreach (UtilServer server in this.EnvServers)
            {
                if (server.ServerName != LocalServerName)
                {
                    RemoveServer.Add(true);
                }
                else
                {
                    RemoveServer.Add(false);
                }
            }
            for (int i = 0; i < RemoveServer.Count; i++)
            {
                if (RemoveServer[i])
                {
                    log.Info("Deleting remote server config: " + this.EnvServers[i].ServerName);
                    this.EnvServers.RemoveAt(i);
                }
            }
            if (this.EnvServers.Count == 1)
            {
                this.MyServer = this.EnvServers[0];
                log.Info("Match: " + this.MyServer.ServerName + "Instantiating Local Server Object.");
            }
            else
            {
                log.Error("Zero, or multiple servers found. \n" +
                          "Unable to instantiate local server object.");
            }
        }
示例#24
0
        public override bool LoadFromConfig(XmlNode node)
        {
            try
            {
                foreach (XmlNode level1_node in node)
                { // level1 --  "SubStorages"
                    if (level1_node.NodeType == XmlNodeType.Comment)
                    {
                        continue;
                    }


                    XmlElement level1_item = (XmlElement)level1_node;

                    if (level1_item.Name.ToLower() == "SubStorages".ToLower())
                    {
                        #region SubStorages
                        foreach (XmlNode level2_node in level1_node)
                        { // datasource
                            if (level2_node.NodeType == XmlNodeType.Comment)
                            {
                                continue;
                            }

                            XmlElement level2_item = (XmlElement)level2_node;
                            if (level2_item.Name.ToLower() == "SubStorage".ToLower())
                            {
                                string  strStorageName = level2_item.GetAttribute("Name");
                                Storage subStorage     = (Storage)ResourceManager.GetResource(strStorageName);

                                SubStorages.Add(subStorage);
                            }
                        }
                        #endregion
                    }
                }

                return(base.LoadFromConfig(node));
            }
            catch (Exception ex)
            {
                LOG.Error(string.Format("加载StorageGroup{0}出错:{1}", ResourceName, ex.Message));
                return(false);
            }
        }
示例#25
0
    protected void btn_insert(object sender, EventArgs e) //insert button
    {
        if (!Page.IsValid)
        {
            return;
        }

        try
        {
            b.User_Id = txtuserid.Text.Trim();
            // b.Name = txtname.Text;
            b.UserNamePrefix = DropDownListPrefix.SelectedValue;
            b.UserFirstName  = TextBoxFname.Text.Trim();
            b.UserMiddleName = TextBoxMname.Text.Trim();
            b.UserLastName   = TextBoxLName.Text.Trim();
            b.Department_Id  = DDLdeptname.SelectedValue;
            b.EmailId        = txtemailid.Text.Trim();
            b.InstituteId    = DDLinstitutename.SelectedValue;
            b.AutoApproved   = "Y";
            b.Role_Id        = Convert.ToInt32(DDLrolename.SelectedValue);
            b.CreatedDate    = DateTime.Now.ToString("yyyy-MM-dd");
            b.CreatedBy      = Session["UserId"].ToString();
            if (b.Role_Id == 1)
            {
                b.pubinchargedept = RadioButtonListDeparmentPubincharge.SelectedValue;
            }

            int retVal = bl.SaveDepartmentDetails(b);

            //lblStatus.Text = "";
            lblStatus.ForeColor = System.Drawing.Color.Green;
            ClientScript.RegisterStartupScript(Page.GetType(), "validation1", "<script language='javascript'>alert('User detail saved successfully');window.location='" + Request.ApplicationPath + "/UserManagement/User_manager.aspx';</script>");

            GridViewUser.Visible     = false;
            btninsert.Enabled        = false;
            btninsert.Enabled        = true;
            popupPanelBaCode.Visible = false;
            b  = null;
            bl = null;
        }
        catch (Exception ex)
        {
            log.Error(ex.StackTrace);
            log.Error(ex.Message);

            log.Error("Error!!!!!!!!!!!!!!!! ");

            ClientScript.RegisterStartupScript(Page.GetType(), "validation1", "<script language='javascript'>alert('Error!!!!!!!!!!')</script>");
        }
    }
示例#26
0
        public bool SqlExec(string stmt, bool skipLogging = false)
        {
            MySqlConnection dbConn = GetConn();

            try
            {
                MySqlCommand myCommand = dbConn.CreateCommand();
                myCommand.CommandText = stmt;
                myCommand.ExecuteNonQuery();
                if (log.IsDebugEnabled && skipLogging == false)
                {
                    log.Debug(stmt);
                }
                return(true);
            }
            catch (Exception e)
            {
                log.Error(e.Message + " " + stmt);
                return(false);
            }
            finally
            {
                if (pooled)
                {
                    dbConn.Close();
                }
            }
        }
示例#27
0
        static void Main(string[] args)
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

            Console.ForegroundColor = ConsoleColor.White;

            try
            {
                string webhook   = null;
                string token     = null;
                string channelId = _channelId;
                if (args != null)
                {
                    if (args.Length > 0)
                    {
                        webhook         = args[0];
                        _enableSlackApi = true;
                    }
                    if (args.Length > 1)
                    {
                        token = args[1];
                    }
                    if (args.Length > 2)
                    {
                        channelId = args[2];
                    }
                }

                _log.Info("Start");


                _wcApi    = new WorldCupApi();
                _slackApi = new SlackApi(webhook);

                _slackBot = new SlackBot(_slackApi, _wcApi, channelId, token, _log, () => _running = false);
                _slackBot.Start();

#if DEBUG
                string command = Constants.CMD_YESTERDAY;
                _slackBot.ExecuteCommand(command);
#endif

                while (_running)
                {
                    Thread.Sleep(1000);
                }

                _slackBot.Stop();

                _log.Info("End");
            }
            catch (Exception e) {
                _log.Error(e);
            }
        }
示例#28
0
 protected void Page_Load(object sender, EventArgs e)
 {
     InitLanguage();
     //Page.Form.Attributes.Add("enctype", "multipart/form-data");
     if (!IsPostBack)
     {
         try
         {
             Initialize();
             Search();
         }
         catch (Exception ex)
         {
             RegisterStartupScript("alert(\"" + GetJSMessage(GetResource("Title_Error"), ex.Message) + "\");");
             logger.Error("Error in Page load:", ex);
         }
     }
 }
示例#29
0
 public static void error(string message)
 {
     log4net.ILog log = log4net.LogManager.GetLogger("Test");
     if (log.IsErrorEnabled)
     {
         log.Error(message);
     }
     log = null;
 }
示例#30
0
 public static void Error(string message)
 {
     log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     if (log.IsErrorEnabled)
     {
         log.Error(message);
     }
     log = null;
 }
示例#31
0
 public void ErrorLog(Exception ex)
 {
     Task.Run(() =>
     {
         log4net.ILog log = log4net.LogManager.GetLogger(repository.Name, "Log4Net.ErrorLog");
         var msg          = ExceptionFormat(ex);
         log.Error(msg);
     });
 }
        public override void OnTestExecutionBegin(TestExecutor testExecutor, TestExecutionBeginArgs args)
        {
            LogEvent.Debug($"{MethodInfo.GetCurrentMethod().Name} {args.VirtualUser}");

            try
            {
                if (_validExecution)
                {
                    onTestExecutionBegin(testExecutor, args);
                }
            }
            catch (Exception e)
            {
                _validExecution = false;
                LogEvent.Error(e.ToString());
                throw;
            }
        }
示例#33
0
        /// <summary>
        /// Method executes as application entry point - that is -
        /// this bit of code executes before anything else in this
        /// class and application.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            _Container = new WindsorContainer();

            // This allows castle to look at the current assembly and look for implementations
            // of the IWindsorInstaller interface
            _Container.Install(FromAssembly.This());                         // Register

            ISettingsManager settings = null;

            try
            {
                // Apply the selected theme (either default or reloaded from options)
                var themeManager = _Container.Resolve <IThemesManagerViewModel>();

                settings = _Container.Resolve <ISettingsManager>();
                var appearance = _Container.Resolve <IAppearanceManager>();

                var lifeCycle = _Container.Resolve <IAppLifeCycleViewModel>();
                lifeCycle.LoadConfigOnAppStartup(settings, appearance);

                themeManager.ApplyTheme(settings.Options.GetOptionValue <string>("Appearance", "ThemeDisplayName"));

                themeManager.ApplyTheme(themeManager.SelectedTheme.Model.Name);
            }
            catch (System.Exception exp)
            {
                Logger.Error(exp);
            }

            var window = new MainWindow();
            var appVM  = _Container.Resolve <IAppViewModel>();

            appVM.SetSessionData(settings.SessionData, window);
            window.DataContext = appVM;

            // subscribe to close event messaging to application viewmodel
            window.Closing += appVM.OnClosing;

            window.Closed += delegate
            {
                // Save session data and close application
                appVM.OnClosed(window);
            };

            // When the ViewModel asks to be closed, close the window.
            // Source: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
            appVM.RequestClose += delegate
            {
                // Save session data and close application
                appVM.OnClosed(window);
            };

            window.Show();
        }
示例#34
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="msg"></param>
 /// <param name="ex"></param>
 public static void Error(object msg, Exception ex)
 {
     try
     {
         log4net.ILog log = log4net.LogManager.GetLogger("logerror");
         if (ex != null)
         {
             Task.Run(() => log.Error(msg, ex));   //异步
         }
         else
         {
             Task.Run(() => log.Error(msg));   //异步
         }
     }
     catch (Exception)
     {
     }
 }
示例#35
0
        public Bootstrapper(ILog _log)
        {
            if (_log == null)
                throw new ArgumentNullException("log is null");

            log = _log;

            if (_sessionFactory != null) {
                log.Error("Do not instantiate bootstrapper twice!");
                throw new Exception("Do not instantiate bootstrapper twice!");
            }

            _sessionFactory = CreateSessionFactory();
            if (_sessionFactory == null) {
                log.Error("Could not instantiate sessionFactory?");
                throw new Exception("Could not instantiate sessionFactory?");
            }
        }
示例#36
0
        protected override void OnStart(string[] args)
        {
            Console.WriteLine("Attempting to start LogForwardService");
            LoadConfiguration();

            Log.Debug($"Attempting to create UDPSocketComReceiver");

            try
            {
            }
            catch (Exception e)
            {
                Log.Error($"Exception beginning UDPSocketComReceiver: {e}");
            }


            Log.Debug($"Start process completed.");
        }
        public static void Error(ILog log, Exception exception, string format, params object[] @params)
        {
            if (log == null)
            {
                return;
            }

            log.Error(string.Format(format, @params), exception);
        }
示例#38
0
        } // Constructor

        #endregion

        #region PublicMethods
        /// <summary>
        /// Loop through all the header columns and see if any are missing
        /// </summary>
        /// <returns></returns>
        public bool ValidateHeader()
        {
            bool isValid = true;

            foreach (Header h in HeaderRow)
            {
                if (!h.CSVHasColumn)
                {
                    h.CSVHasColumn = CheckForColumn(h.ColumnName);
                    if (!h.CSVHasColumn)
                    {
                        log.Error($"CSV File missing column {h.ColumnName}");
                        isValid = false;
                    }
                }
            }
            return(isValid);
        } // ValidateHeader
示例#39
0
 /// <summary>
 /// 输出日志到Log4Net
 /// </summary>
 /// <param name="msg"></param>
 /// <param name="isLogConsole">是否输出到控制台</param>
 public static void Error(string msg, bool isLogConsole = false, string logger = null)
 {
     if (isLogConsole)
     {
         Console.WriteLine(msg);
     }
     log4net.ILog log = log4net.LogManager.GetLogger(logger);
     log.Error(msg);
 }
 public void Send(RdpConnection rdpConn)
 {
     writer.Flush();
     try {
         rdpConn.Send(memStream.ToArray());
     } catch (RdpFragmentationException) {
         log.Error("Failed to send packet that was too large");
     }
 }
示例#41
0
        public void LogException(Exception ex)
        {
            // get call stack
            StackTrace stackTrace = new StackTrace();

            // get calling method name
            LogNet.ILog _logger = LogNet.LogManager.GetLogger(stackTrace.GetFrame(1).GetMethod().Name);
            _logger.Error(ex.Message, ex);
        }
示例#42
0
        public void Error(string message, Exception exception, Dictionary <string, string> additionalColums = null)
        {
            System.Diagnostics.Contracts.Contract.Assert(!string.IsNullOrEmpty(message)); //message değerinin null veya boş olmadığından emin ol, yoksa exception fırlat
            System.Diagnostics.Contracts.Contract.Assert(exception != null);              //exception değerinin null veya boş olmadığından emin ol, yoksa exception fırlat

            BindAdditionalColumsIfNotEmpty(additionalColums);

            _log.Error(message, exception);
        }
示例#43
0
        static void Main(string[] args)
        {
            try
            {
                Timer PublishTimer = new Timer(PublishData, null, 0, timerSpeed);
                ConnectMQTT();

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            finally
            {
                DisconnectMQTT();
            }
        }
示例#44
0
        public static void LoadEnvironmentConfiguration()
        {
            String env = Env.CurrentRegion;

#if DEBUG
            env = "DEV";
#endif

            try
            {
                JsonConvert.DeserializeObject <Env>(File.ReadAllText($"{Env.ConfigDir}\\{env}.json"));
            }
            catch (IOException e)
            {
                logger.Error($"Cannot find JSON config file in: {Env.ConfigDir}");
                logger.Error(e.Message);
            }
        }
示例#45
0
        public string GetClientIPAddress(Guid sessionId)
        {
            string clientIPAddress = "";

            try
            {
                IPAddress clientAddress = mConnectionManager.GetClientIPAddress(sessionId);
                if (clientAddress != IPAddress.None)
                {
                    clientIPAddress = clientAddress.ToString();
                }
            }
            catch (Exception ex)
            {
                mLogger.Error("Error GetClientIPAddress", ex);
            }
            return(clientIPAddress);
        }
示例#46
0
 private void ExecuteStages()
 {
     if (Scan(_bdromPath, _mkvPath))
     {
         if (Convert())
         {
             _logger.Info("Muxing succeeded!");
         }
         else
         {
             _logger.Error("Muxing failed!");
         }
     }
     else
     {
         _logger.Error("Scanning failed!");
     }
 }
示例#47
0
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         InitLanguage();
         if (!IsPostBack)
         {
             Initialize();
             InitFactoryDropdownList();
             Search();
         }
     }
     catch (Exception ex)
     {
         RegisterStartupScript("alert(\"" + GetJSMessage(GetResource("Title_Error"), ex.Message) + "\");");
         logger.Error("Error in Page load:", ex);
     }
 }
示例#48
0
        /// <summary>
        /// Exports current batch of marked up taxa to Excel.
        /// </summary>
        private static void ExportToExcelFile(string filename)
        {
            using (ExcelPackage p = new ExcelPackage())
            {
                //set the workbook properties and add a default sheet in it
                SetWorkbookProperties(p);
                //Create a sheet
                ExcelWorksheet ws = CreateSheet(p, "Taxon Export");

                // Add column headers
                foreach (KeyValuePair <int, TaxonInternalReferences> entry in CollectionData.columnIndex)
                {
                    var cell = ws.Cells[1, entry.Key];
                    cell.Value = entry.Value.FieldName;
                    cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
                    cell.Style.Fill.BackgroundColor.SetColor(entry.Value.FillColor);
                    cell.AddComment(entry.Value.Label, "Field description");
                    ws.Column(entry.Key).Width = entry.Value.ColumnWidth;
                }

                int rowIndex = 2;
                CreateData(ws, ref rowIndex);

                //Generate file
                try
                {
                    Byte[] bin = p.GetAsByteArray();
                    File.WriteAllBytes(filename, bin);
                    log.Info("Excel export successful: " + filename);
                }
                catch (IOException ex)
                {
                    log.Error("IOException writing Excel export file", ex);
                    MessageBox.Show("Error writing Excel export file: " + ex.ToString(), "Export error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                catch (Exception ex)
                {
                    log.Error("Unhandled exception writing Excel export file", ex);
                    throw;
                }
                Globals.ThisAddIn.ResetCurrentBatch(CollectionData.DeleteAfterExport);
            }
        }
示例#49
0
        private void btnSelect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var dialog = new System.Windows.Forms.OpenFileDialog();
                dialog.Filter          = "FF14版本文件 (ffxivgame.ver)|ffxivgame.ver|FF14可执行文件 (ffxiv.exe)|ffxiv.exe|FF14_DX11可执行文件(ffxiv.exe)|ffxiv_dx11.exe";
                dialog.CheckFileExists = true;
                dialog.CheckPathExists = true;
                dialog.ValidateNames   = true;
                dialog.ShowHelp        = true;
                dialog.Title           = "请选择\"你的安装目录/最终幻想XIV/game/ffxivgame.ver\"或ffxiv.exe";
                void _(Object _sender, EventArgs _e)
                {
                    MessageBox.Show("请选择\"你的安装目录/最终幻想XIV/game/ffxivgame.ver\"或ffxiv.exe");
                }
                dialog.HelpRequest += new EventHandler(_);

                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    logger.Info($"Game file path selected: {dialog.FileName}");
                    pathSelect.Text = dialog.FileName;
                    string GamePath    = System.IO.Directory.GetParent(pathSelect.Text).ToString();
                    var    versionFile = new System.IO.StreamReader(GamePath + @"/ffxivgame.ver");
                    gameVersion = versionFile.ReadToEnd();
                    if (gameVersion.Length == 20)
                    {
                        txtVersion.Text = gameVersion;
                    }
                    else
                    {
                        txtVersion.Text = "ERROR";
                        logger.Error($"Incorrect game version file detected");
                    }
                    versionFile.Dispose();
                }
                dialog.Dispose();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
                logger.Error(error.Message);
                this.Close();
            }
        }
示例#50
0
    protected void btn_insert(object sender, EventArgs e) //insert button
    {
        User           b  = new User();
        User_Mangement bl = new User_Mangement();

        if (!Page.IsValid)
        {
            return;
        }

        try
        {
            b.Department_Id = DDLdeptname.SelectedValue;
            b.InstituteId   = DDLinstitutename.SelectedValue;
            b.AutoApproved  = DropDownListAutoApprovee.SelectedValue;

            b.Remarks   = TextBoxRemarks.Text.Trim();
            b.UpdatedBy = Session["UserId"].ToString();

            int retVal = bl.InsertDepartmentInstituteAutoAppove(b);
            if (retVal == 1)
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "validation1", "<script language='javascript'>alert('Data saved successfully');window.location='" + Request.ApplicationPath + "/UserManagement/InstDeptAutoApprove.aspx';</script>");

                btninsert.Enabled = false;
                btninsert.Enabled = true;
                b  = null;
                bl = null;
            }
            else
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "validation1", "<script language='javascript'>alert('Error!!!!!!!!!!')</script>");
            }
        }
        catch (Exception ex)
        {
            log.Error(ex.StackTrace);
            log.Error(ex.Message);

            log.Error("Error!!!!!!!!!!!!!!!! ");

            ClientScript.RegisterStartupScript(Page.GetType(), "validation1", "<script language='javascript'>alert('Error!!!!!!!!!!')</script>");
        }
    }
        /// <summary>
        /// Reads and processes any decision files in the configured folder
        /// </summary>
        /// <param name="fileReaderStrategy"></param>
        /// <param name="log"></param>
        public static void ReadDecisionFile(DecisionManager.DecisionFileReader fileReaderStrategy, ILog log)
        {
            if (fileReaderStrategy == null) throw new ArgumentNullException("fileReaderStrategy");
            if (log == null) throw new ArgumentNullException("log");

            try
            {
                // Get folder and file pattern from web.config so they're easy to update
                string folder = ConfigurationManager.AppSettings["DecisionsFolder"];
                if (String.IsNullOrEmpty(folder)) throw new ConfigurationErrorsException("DecisionsFolder setting is missing from appSettings in app.config");

                string filePattern = ConfigurationManager.AppSettings["DecisionFiles"];
                if (String.IsNullOrEmpty(filePattern)) throw new ConfigurationErrorsException("DecisionFiles setting is missing from appSettings in app.config");

                // Look in the folder, deal with and then delete each file
                var filenames = Directory.GetFiles(folder, filePattern, SearchOption.TopDirectoryOnly);
                foreach (string filename in filenames)
                {
                    // Log that we're working on this file
                    Console.WriteLine(String.Format(CultureInfo.CurrentCulture, Properties.Resources.LogReadingFile, filename));
                    log.Info(String.Format(CultureInfo.CurrentCulture, Properties.Resources.LogReadingFile, filename));

                    if (File.Exists(filename))
                    {
                        fileReaderStrategy(filename, log);

                        var delete = String.IsNullOrEmpty(ConfigurationManager.AppSettings["DeleteProcessedFiles"]);
                        try
                        {
                            if (!delete) delete = Boolean.Parse(ConfigurationManager.AppSettings["DeleteProcessedFiles"]);
                        }
                        catch (FormatException ex)
                        {
                            throw new ConfigurationErrorsException("DeleteProcessedFiles setting in app.config appSettings must be a boolean", ex);
                        }

                        if (delete)
                        {
                            Console.WriteLine(String.Format(CultureInfo.CurrentCulture, Properties.Resources.LogDeletingFile, filename));
                            log.Info(String.Format(CultureInfo.CurrentCulture, Properties.Resources.LogDeletingFile, filename));

                            File.Delete(filename);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                log.Error(ex.Message, ex);

                ex.ToExceptionless().Submit();

                return;
            }
        }
示例#52
0
        public static WeiChatReceivedContentMessage ParseWeichatXML(string xml,ILog logger=null)
        {
            WeiChatReceivedContentMessage message = new WeiChatReceivedContentMessage();
            try
            {
                logger.Info("ParseWeichatXML");
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xml);
                XmlNode contentNode = xmlDoc.SelectSingleNode("/xml/Content");
                if(contentNode!=null && !string.IsNullOrEmpty(contentNode.InnerText))
                {
                    message.Content = contentNode.InnerText.Trim();
                }
                XmlNode toUserNode = xmlDoc.SelectSingleNode("/xml/ToUserName");
                if (toUserNode != null && !string.IsNullOrEmpty(toUserNode.InnerText))
                {
                    message.ToUserName = toUserNode.InnerText.Trim();
                }

                XmlNode msgType = xmlDoc.SelectSingleNode("/xml/MsgType");
                if (msgType != null && !string.IsNullOrEmpty(msgType.InnerText))
                {
                    message.MsgType = msgType.InnerText.Trim();
                }

                XmlNode fromUserNode = xmlDoc.SelectSingleNode("/xml/FromUserName");
                if (fromUserNode != null && !string.IsNullOrEmpty(fromUserNode.InnerText))
                {
                    message.FromUserName = fromUserNode.InnerText.Trim();
                }
                XmlNode msgIdNode = xmlDoc.SelectSingleNode("/xml/MsgId");
                if (msgIdNode != null && !string.IsNullOrEmpty(msgIdNode.InnerText))
                {
                    message.MsgId = msgIdNode.InnerText.Trim();
                }
                XmlNode createTimeNode = xmlDoc.SelectSingleNode("/xml/CreateTime");
                if (createTimeNode != null && !string.IsNullOrEmpty(createTimeNode.InnerText))
                {
                    long time = 0;
                    long.TryParse( createTimeNode.InnerText, out time);
                    message.CreateTime = time;
                }
                xmlDoc = null;
            }
            catch(Exception ex)
            {
                if(logger!=null)
                {
                    logger.Error(ex);
                }
            }finally
            {
                logger.Info("Finished ParseWeichatXML");
            }
            return message;
        }
示例#53
0
        private void btnGuardar_Click(object sender, RoutedEventArgs e)
        {
            string mensaje = "";

            try
            {
                if (reglas.IsMatch(txtDescripcion.Text) && txtDescripcion.Text.Length > 3 && txtDescripcion.Text.Length < 51)
                {
                    if (txtDescripcion.Text == descripcionAntigua && chkActivo.IsChecked.Value == indActivo)
                    {
                        MessageBox.Show("Realice por lo menos un cambio", "Error");
                    }
                    else
                    {
                        if (UI.ToString() == "MasterOfMasterDesktop.UI.uiConfigMaestros")
                        {
                            cMaestrosCabecera MC = new cMaestrosCabecera();
                            MC.descripcion        = txtDescripcion.Text;
                            MC.indActivo          = chkActivo.IsChecked.Value;
                            MC.idUsuarioActualiza = 2;
                            mensaje = svc.ActualizarMaestroCabecera(MC, descripcionAntigua);
                            uiConfigMaestros CM = UI as uiConfigMaestros;
                            CM.cargarListaMaestros();
                        }
                        else
                        {
                            cMaestrosDetalle MD = new cMaestrosDetalle();
                            MD.idMaestroCabecera  = idCabecera;
                            MD.descripcion        = txtDescripcion.Text;
                            MD.indActivo          = chkActivo.IsChecked.Value;
                            MD.idUsuarioActualiza = 2;
                            mensaje = svc.ActualizarMaestroDetalle(MD, descripcionAntigua);
                            uiConfigDetalles CD = UI as uiConfigDetalles;
                            CD.cargarMDetalles(CD.id);
                        }
                        MessageBox.Show(mensaje);
                        pw.CargarMenus();

                        if (mensaje == "Modificación completada")
                        {
                            this.Close();
                            quitarEfecto();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Ingrese una descripción valida");
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
                Log.Error(Ex.Message);
            }
        }
示例#54
0
        public IHttpActionResult Get(uint id)
        {
            try
            {
                var user = _userRepo.GetUserById(id);
                if (user != null)
                {
                    return(Ok(user));
                }

                return(Ok("User Not Found!!!"));
            }

            catch (Exception ex)
            {
                log.Error("Error Occured for Id: " + id, ex);
                return(InternalServerError(ex));
            }
        }
示例#55
0
    public static void LogError(String ex, ILog logger)
    {
        //set log file anme
        log4net.GlobalContext.Properties["LogName"] = getfilePathPrefix() + "_ServerError.log";

        //configure log4net
        log4net.Config.XmlConfigurator.Configure();

        logger.Error(ex);
    }
示例#56
0
文件: Log.cs 项目: edgecomputing/cats
        public void LogAllErrorsMesseges(Exception ex,ILog log)
        {
            //assign the current exception as first object and then loop through its
            //inner exceptions till they are null
            for (var eCurrent = ex; eCurrent != null; eCurrent = eCurrent.InnerException)
            {
                log.Error(eCurrent.Message);

            }
        }
示例#57
0
        public static void Main(string[] args)
        {
            _logger=GetLogger();
            var options = new Options();
            bool arguments = Parser.Default.ParseArguments(args, options);
            if (!arguments){
                string message = options.GetUsage();
                _logger.Error(message);
                throw new ArgumentException(message);
            }
            var projectFiles = new List<string>();
            projectFiles.AddRange(Directory.GetFiles(options.SourceDir, "*.csproj", SearchOption.AllDirectories));
            projectFiles.AddRange(Directory.GetFiles(options.SourceDir, "*.vbproj", SearchOption.AllDirectories));
            var failedProjects = new List<KeyValuePair<string,string>>();
            var projects = GetProjects(projectFiles);
            _logger.Info(string.Format("Found '{0}' project(s)", projectFiles.Count));
            var pdbFiles = Directory.GetFiles(options.PDBDir, "*.pdb").ToArray();
            _logger.Info(string.Format("Found '{0}' pdb files", pdbFiles.Length));
            foreach (var pdbFile in pdbFiles){
                var currentProject = projects.FirstOrDefault(project => Path.GetFileName(project.GetOutputPdbFile()) == Path.GetFileName(pdbFile));
                if (currentProject!=null){
                    var pdbStoreManager = new PdbStoreManager(options.DbgToolsPath);
                    var srcSrvSection = CreatePdbSrcSrvSection(currentProject, pdbStoreManager, pdbFile);
                    var writeSrcSrv = pdbStoreManager.WriteSrcSrv(pdbFile, srcSrvSection);
                    var fileName = Path.GetFileNameWithoutExtension(pdbFile);
                    if (!string.IsNullOrEmpty(writeSrcSrv)){
                        failedProjects.Add(new KeyValuePair<string,string>(pdbFile,writeSrcSrv));
                        _logger.Error(fileName+"-->"+writeSrcSrv);
                    }
                    else{
                        _logger.Info(fileName+" indexed successfully!");
                    }
                }
                else{
                    failedProjects.Add(new KeyValuePair<string, string>(pdbFile,"Project not found"));
                    _logger.Error(pdbFile +"-->Project not found");
                }
            }

            if (Debugger.IsAttached)
                Console.ReadKey();
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            log4net.GlobalContext.Properties["LogName"] = DateTime.Now.ToShortDateString().ToString();
            log = MyLogger.GetLogger(typeof(MvcApplication));

            Exception ex = Server.GetLastError();

            //Checking if exception was 404
            if (ex.GetType() == typeof(HttpException))
            {
                HttpContext.Current.Server.ClearError();
                HttpContext.Current.Response.RedirectToRoute("error404");
                //throw new Exception404PageNotFound("Error 404, Page not found!", ex);
            }
            else
            {
                log.Error("Application error caught", ex);
            }
            log.Error("Application error caught", ex);
        }
 public static void ExecuteSafe(this IOperation operation, ILog log)
 {
     try
     {
         operation.Execute();
     }
     catch (Exception ex)
     {
         log.Error(string.Format("Error executing {0}", operation), ex);
     }
 }
示例#60
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            log = LogManager.GetLogger("NotifyNow");

            NotifyMessage message = null;

            try
            {
                message = NotifyMessage.ProcessArgs(args);
            }
            catch (Exception ex)
            {
                log.Error("Exception calling ProcessArgs", ex);
            }

            using (var bus = RabbitHutch.CreateBus(ConfigurationManager.ConnectionStrings["RabbitMQ"].ConnectionString))
            {
                if (String.IsNullOrEmpty(message.Message) == false)
                {
                    using (var channel = bus.OpenPublishChannel())
                    {
                        log.DebugFormat("Publishing message: {0}", message.Message);
                        channel.Publish(message);
                    }
                }

                if (SingleInstance.SingleApplication.Run())
                {
                    // First instance, create the Main Window
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    var f = new MainWindow(bus);
                    f.FormBorderStyle = FormBorderStyle.FixedToolWindow;
                    f.ShowInTaskbar = false;
                    f.StartPosition = FormStartPosition.Manual;
                    f.Location = new System.Drawing.Point(-2000, -2000);
                    f.Size = new System.Drawing.Size(1, 1);

                    Application.Run(f);
                    Application.Exit();
                }
                else
                {
                    // App already running, exit now
                    Application.Exit();
                }
            }
        }