コード例 #1
1
ファイル: Log.cs プロジェクト: icedream/modernminas-launcher
        public static void Init()
        {
            _log = LogManager.GetLogger("AppDomain");

            var _fa =
                new FileAppender()
                {
                    Layout = new log4net.Layout.PatternLayout("%timestamp [%thread] %-5level %logger - %message%newline"),
                    File = Path.Combine(Environment.CurrentDirectory, "update.log"),
                    AppendToFile = false
                };
            _fa.ActivateOptions();
            BasicConfigurator.Configure(
                _fa,
                new ConsoleAppender()
            );

            AppDomain.CurrentDomain.AssemblyLoad += (sender, e) =>
            {
                _log.DebugFormat("Assembly load: {0}", e.LoadedAssembly.FullName);
            };
            AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
            {
                _log.Info("Process exiting.");
            };
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                _log.ErrorFormat("Unhandled exception: {0}", e.ExceptionObject.ToString());
            };
        }
コード例 #2
0
        /// <summary>
        ///   Pulls xml configuration from embedded location and applies it.
        ///   Then it configures a file appender to the specified output directory if one is provided.
        /// </summary>
        /// <param name="outputDirectory">The output directory.</param>
        /// <param name="excludeLoggerNames">Loggers, such as a verbose logger, to exclude from this.</param>
        public static void configure(string outputDirectory = null, params string[] excludeLoggerNames)
        {
            GlobalContext.Properties["pid"] = System.Diagnostics.Process.GetCurrentProcess().Id;

            var xmlConfigFile = Path.Combine(ApplicationParameters.InstallLocation, "log4net.config.xml");

            if (File.Exists(xmlConfigFile))
            {
                XmlConfigurator.ConfigureAndWatch(new FileInfo(xmlConfigFile));
                _logger.DebugFormat("Configured Log4Net configuration from file ('{0}').", xmlConfigFile);
            }
            else
            {
                var assembly = Assembly.GetExecutingAssembly();
                var resource = ApplicationParameters.Log4NetConfigurationResource;
                if (Platform.get_platform() != PlatformType.Windows)
                {
                    // it became much easier to do this once we realized that updating the current mappings is about impossible.
                    resource = resource.Replace("log4net.", "log4net.mono.");
                }
                Stream xmlConfigStream = assembly.get_manifest_stream(resource);

                XmlConfigurator.Configure(xmlConfigStream);

                _logger.DebugFormat("Configured Log4Net configuration ('{0}') from assembly {1}", resource, assembly.FullName);
            }

            if (!string.IsNullOrWhiteSpace(outputDirectory))
            {
                set_file_appender(outputDirectory, excludeLoggerNames);
            }
        }
コード例 #3
0
        /// <summary>
        /// Commits the offsets of all messages consumed so far.
        /// </summary>
        public void CommitOffsets()
        {
            this.EnsuresNotDisposed();
            if (this.GetZkClient() == null)
            {
                return;
            }
            try
            {
                foreach (KeyValuePair <string, IDictionary <int, PartitionTopicInfo> > topic in topicRegistry)
                {
                    var topicDirs = new ZKGroupTopicDirs(this.config.GroupId, topic.Key);
                    foreach (KeyValuePair <int, PartitionTopicInfo> partition in topic.Value)
                    {
                        var newOffset = partition.Value.ConsumeOffset;
                        try
                        {
                            if (partition.Value.ConsumeOffsetValid)
                            {
                                // Save offsets unconditionally. Kafka's latestOffset for a particular topic-partition can go backward
                                // if a follwer which is not fully caught up becomes a leader. We still need to save the conumed offsets even then.
                                //skip only if we are trying to commit the same offset

                                if (newOffset != partition.Value.CommitedOffset)
                                {
                                    try
                                    {
                                        ZkUtils.UpdatePersistentPath(GetZkClient(),
                                                                     topicDirs.ConsumerOffsetDir + "/" +
                                                                     partition.Value.PartitionId, newOffset.ToString());
                                        partition.Value.CommitedOffset = newOffset;
                                    }
                                    catch (Exception ex)
                                    {
                                        Logger.ErrorFormat("error in CommitOffsets UpdatePersistentPath : {0}", ex.FormatException());
                                    }
                                }
                            }
                            else
                            {
                                Logger.InfoFormat("Skip committing offset {0} for topic {1} because it is invalid (ZK session is disconnected)", newOffset, partition);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.WarnFormat("exception during CommitOffsets: {0}", ex.FormatException());
                        }

                        if (Logger.IsDebugEnabled)
                        {
                            Logger.DebugFormat("Commited offset {0} for topic {1}", newOffset, partition);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("error in CommitOffsets : {0}", ex.FormatException());
            }
        }
コード例 #4
0
 public override void Verbose(string message)
 {
     if (_logger.Logger.IsEnabledFor(Level.Verbose))
     {
         _logger.DebugFormat("Verbose: {0}", message);
     }
 }
コード例 #5
0
 public void Debug(string message, params object[] formatting)
 {
     if (_logger.IsDebugEnabled)
     {
         _logger.DebugFormat(decorate_message_with_audit_information(message), formatting);
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PartitionTopicInfo"/> class.
 /// </summary>
 /// <param name="topic">
 /// The topic.
 /// </param>
 /// <param name="brokerId">
 /// The broker ID.
 /// </param>
 /// <param name="partition">
 /// The broker's partition.
 /// </param>
 /// <param name="chunkQueue">
 /// The chunk queue.
 /// </param>
 /// <param name="consumedOffset">
 /// The consumed offset value.
 /// </param>
 /// <param name="fetchedOffset">
 /// The fetched offset value.
 /// </param>
 /// <param name="fetchSize">
 /// The fetch size.
 /// </param>
 public PartitionTopicInfo(
     string topic,
     int brokerId,
     int partitionId,
     BlockingCollection <FetchedDataChunk> chunkQueue,
     long consumedOffset,
     long fetchedOffset,
     int fetchSize,
     long commitedOffset)
 {
     this.Topic             = topic;
     this.PartitionId       = partitionId;
     this.chunkQueue        = chunkQueue;
     this.BrokerId          = brokerId;
     this.consumedOffset    = consumedOffset;
     this.fetchedOffset     = fetchedOffset;
     this.NextRequestOffset = fetchedOffset;
     this.FetchSize         = fetchSize;
     this.commitedOffset    = commitedOffset;
     if (Logger.IsDebugEnabled)
     {
         Logger.DebugFormat("initial CommitedOffset  of {0} is {1}", this, commitedOffset);
         Logger.DebugFormat("initial consumer offset of {0} is {1}", this, consumedOffset);
         Logger.DebugFormat("initial fetch offset of {0} is {1}", this, fetchedOffset);
     }
 }
コード例 #7
0
        public override void handleGETRequest(HttpProcessor p)
        {
            if (p.http_url.Equals("/Test.png"))
            {
                Stream fs = File.Open("../../Test.png", FileMode.Open);

                p.writeSuccess("image/png");
                fs.CopyTo(p.outputStream.BaseStream);
                p.outputStream.BaseStream.Flush();
            }

            logger.DebugFormat("request: {0}", p.http_url);
            p.writeSuccess();
            p.outputStream.WriteLine("<html><body><h1>Gerador Relatorios</h1>");
            p.outputStream.WriteLine("<br>Current Time: " + DateTime.Now.ToString());
            //p.outputStream.WriteLine("url : {0}", p.http_url);

            p.outputStream.WriteLine("<p><br><form method=post action=/form>");
            foreach (BaseParam parametro in _config.Parametros)
            {
                if (!String.IsNullOrEmpty(parametro.OnDemand))
                {
                    p.outputStream.WriteLine("<br>&nbsp;<br><input type=submit name=\"" + parametro.FunctionName + "\" value=\"" + parametro.Subject + "\">");
                }
            }
            p.outputStream.WriteLine("</form></p>");
            p.outputStream.WriteLine("</body></html>");
        }
コード例 #8
0
ファイル: FixServerAcceptor.cs プロジェクト: radtek/Gradual
        public virtual void OnMessage(QuickFix.FIX44.ApplicationMessageRequest message, SessionID session)
        {
            try
            {
                string sessionID = session.ToString();
                string applReqID = message.ApplReqID.ToString();
                logger.InfoFormat("SessionID[{0}]: ApplicationMessageRequest ApplReqID[{1}]", sessionID, applReqID);

                // Acrescenta o sessionID do cliente para controle
                applReqID = applReqID + "|" + sessionID;
                message.Set(new QuickFix.Fields.ApplReqID(applReqID));

                string[] quebraApplReqID = applReqID.Split("-".ToCharArray());
                string   channelID       = quebraApplReqID[1];

                logger.DebugFormat("SessionID[{0}]: ApplicationMessageRequest enviando para ChannelID[{1}] msg[{2}]",
                                   sessionID, channelID, message.ToString());
                bool bRet = Session.SendToTarget(message, _dctSessionsFixChannels[channelID]);
                if (!bRet)
                {
                    logger.ErrorFormat("SessionID[{0}]: Falha ApplicationMessageRequest msg[{1}]", sessionID, message.ToString());
                }
            }
            catch (Exception ex)
            {
                logger.Error("onMessage(ApplicationMessageRequest): " + ex.Message, ex);
            }
        }
コード例 #9
0
        /// <summary>
        /// Add a property to the query to be updated to the given value.
        /// </summary>
        /// <param name="propertyName">The name of the property to add</param>
        /// <param name="propertyNamespace">The Xml namespace of the property</param>
        /// <param name="propertyValue">The value for the property</param>
        public void AddUpdateProperty(
            string propertyName,
            string propertyNamespace,
            string propertyValue)
        {
            char namespacePrefix = ' ';

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Adding {0}:{1} = \"{2}\"",
                                propertyNamespace,
                                propertyName,
                                propertyValue);
            }

            namespacePrefix = FindOrAddNamespace(propertyNamespace);

            //  <property's namespace prefix : property's name>
            //      property's value
            //  </property's namespace prefix : property's name>
            updateXml.AppendFormat(
                "<{0}:{1}>{2}</{0}:{1}>",
                namespacePrefix,
                propertyName,
                propertyValue);
        }
コード例 #10
0
        private MessageAndOffset MakeNextOuter()
        {
            if (!this.Messages.Skip(topIterPosition).Any())
            {
                return(AllDone());
            }

            Message newMessage = this.Messages.ElementAt(topIterPosition);

            lastMessageSize = newMessage.Size;
            topIterPosition++;
            switch (newMessage.CompressionCodec)
            {
            case CompressionCodecs.NoCompressionCodec:
                Logger.DebugFormat(
                    "Message is uncompressed. Valid byte count = {0}",
                    currValidBytes);
                innerIter       = null;
                innerDone       = true;
                currValidBytes += 4 + newMessage.Size;
                return(new MessageAndOffset(newMessage, currValidBytes));

            default:
                Logger.DebugFormat("Message is compressed. Valid byte count = {0}", currValidBytes);
                innerIter = CompressionUtils.Decompress(newMessage, this.PartitionId).GetEnumerator();
                innerDone = !innerIter.MoveNext();
                return(MakeNext());
            }
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: hoxily/Wuziqi
 static void Main(string[] args)
 {
     Logger = LogManager.GetLogger("default");
     try
     {
         Logger.DebugFormat("Server powered up");
         Logger.DebugFormat("Loading configuration");
         ConfigManager.LoadConfigs();
         string addr = ConfigManager.GetConfig("GameServer.ListenAddress");
         string port = ConfigManager.GetConfig("GameServer.ListenPort");
         Logger.DebugFormat("Trying to listen at {0}:{1}", addr, port);
         TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Parse(addr), Convert.ToInt32(port)));
         listener.Start();
         while (true)
         {
             TcpClient client = listener.AcceptTcpClient();
             ClientServant servant = new ClientServant(client);
             Program.Logger.DebugFormat("New client connected from: {0}", servant.ClientIPEndPoint);
             servant.Start();
         }
     }
     catch (Exception e)
     {
         Logger.FatalFormat("Unhandled exception: {0}, stacktrace: {1}", e.Message, e.StackTrace);
         Logger.Fatal("Server shutdown");
     }
 }
コード例 #12
0
 /// <summary>
 /// Report a success to the throttler. Should be called after successfully getting a feed.
 /// </summary>
 /// <returns>void</returns>
 public void ReportSuccess()
 {
     log.DebugFormat("Success reported, resetting the delay to 0");
     lock (lockObject)
     {
         delay = 0;
     }
 }
コード例 #13
0
 public void RebuildIfFinishedLoading(ExtensionMessage msg, bool loadingState)
 {
     if (!loadingState)
     {
         log.DebugFormat("StaticGeometryHelper.RebuildIfFinishedLoading: Rebuilding because loadingState is {0}", loadingState);
         Rebuild();
     }
 }
コード例 #14
0
 /// <summary>
 /// On service start
 /// </summary>
 /// <param name="args"></param>
 protected override void OnStart(string[] args)
 {
     System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
     this._modelInitializer          = new Timer();
     this._modelInitializer.Interval = 500;
     this._modelInitializer.Elapsed += new System.Timers.ElapsedEventHandler(this.ModelInintializerElapsed);
     this._modelInitializer.Enabled  = true;
     log.DebugFormat(@"Model initializer enabled");
 }
コード例 #15
0
        /// <summary>
        /// Read the data files and set up the MATLAB component.
        /// Would like to do this in a static constructor, but we don't have access to a
        /// HttpRequest object at that time, so it's not clear how to map the paths.
        /// </summary>
        private void init()
        {
            HttpRequest request   = this.Context.Request;
            string      dataDir   = request.MapPath("Data");
            string      schemaDir = request.MapPath("Schema");

            _logger.Debug("Loading SpecificPower.xml");
            string specificPowerDataFile   = Path.Combine(dataDir, "SpecificPower.xml");
            string specificPowerSchemaFile = Path.Combine(schemaDir, "SpecificPower.xsd");

            specificPowerData = new SpecificPowerDataManager(specificPowerDataFile, specificPowerSchemaFile);

            inputPowerCalc = new InputPowerCalculator(specificPowerData.Data);

            _logger.Debug("Loading Coolers.xml");
            string coolerDataFile   = Path.Combine(dataDir, "Coolers.xml");
            string coolerSchemaFile = Path.Combine(schemaDir, "Coolers.xsd");

            coolers = new CoolerCollection(coolerDataFile, coolerSchemaFile);
            foreach (Cooler c in coolers)
            {
                c.InputPowerCalculator = inputPowerCalc;
            }
            _logger.DebugFormat("{0} coolers loaded", coolers.Count);

            _logger.Debug("Loading Materials.xml");
            string materialsDataFile   = Path.Combine(dataDir, "Materials.xml");
            string materialsSchemaFile = Path.Combine(schemaDir, "Materials.xsd");

            materials = new MaterialsCollection(materialsDataFile, materialsSchemaFile);
            _logger.DebugFormat("{0} materials loaded", materials.Count);

            _logger.Debug("Loading Problems.xml");
            string problemsDataFile   = Path.Combine(dataDir, "Problems.xml");
            string problemsSchemaFile = Path.Combine(schemaDir, "Problems.xsd");

            problems = new ProblemCollection(problemsDataFile, problemsSchemaFile);
            _logger.DebugFormat("{0} problems loaded", problems.Count);

            _logger.Debug("Loading MathGates.xml");
            string mathGateDataFile   = Path.Combine(dataDir, "MathGates.xml");
            string mathGateSchemaFile = Path.Combine(schemaDir, "MathGates.xsd");

            mathGates = new MathGateCollection(mathGateDataFile, mathGateSchemaFile);
            _logger.DebugFormat("{0} math gates loaded", mathGates.Count);

            _logger.Debug("Initializing Optimizer");
            optimizer = new Optimizer(coolers, materials);
            _logger.Debug("Initializaing SolutionChecker");
            solutionChecker = new SolutionChecker(problems);

            _logger.Debug("Initializaing SteadyStateSimulator");
            sim = new SteadyStateSimulator();
            _logger.Debug("Initializing API");
            api = new API();
        }
コード例 #16
0
 public void Dump()
 {
     log.DebugFormat("--------------------------------------------------");
     log.DebugFormat("Material Bucket {0}", materialName);
     log.DebugFormat("Geometry buckets: {0}", geometryBucketList.Count);
     foreach (GeometryBucket gbucket in geometryBucketList)
     {
         gbucket.Dump();
     }
 }
コード例 #17
0
        public void process()
        {
            // we can't use a StreamReader for input, because it buffers up extra data on us inside it's
            // "processed" view of the world, and we want the data raw after the headers
            inputStream = new BufferedStream(socket.GetStream());

            // we probably shouldn't be using a streamwriter for all output from handlers either
            outputStream = new StreamWriter(new BufferedStream(socket.GetStream()));
            try {
                parseRequest();
                readHeaders();
                if (http_method.Equals("GET"))
                {
                    handleGETRequest();
                }
                else if (http_method.Equals("POST"))
                {
                    handlePOSTRequest();
                }
            } catch (Exception e) {
                logger.DebugFormat("Exception: " + e.ToString());
                writeFailure();
            }
            outputStream.Flush();
            // bs.Flush(); // flush any remaining output
            inputStream = null; outputStream = null; // bs = null;
            socket.Close();
        }
コード例 #18
0
        private void _processEmail(TOEmail email)
        {
            EmailNotaCorretagemInfo info = new EmailNotaCorretagemInfo();

            try
            {
                // Inserir no BD
                info.ArquivoNota       = email.Msg.FileAttach;
                info.Bolsa             = email.Exchange;
                info.DtRegistroEmail   = DateTime.Now;
                info.EmailDestinatario = email.Msg.To;
                if (!string.IsNullOrEmpty(email.Msg.Cc))
                {
                    info.EmailDestinatarioCc = email.Msg.Cc;
                }
                if (!string.IsNullOrEmpty(email.Msg.Cco))
                {
                    info.EmailDestinatarioCco = email.Msg.Cco;
                }
                info.Assunto     = email.Msg.Subject;
                info.Body        = email.Msg.Body;
                info.EmailOrigem = email.Msg.From;
                info.Status      = email.Status;
                info.DescStatus  = email.DescStatus;

                if (!string.IsNullOrEmpty(email.IdCliente))
                {
                    info.IdCliente = Convert.ToInt32(email.IdCliente);
                }

                if (!email.Status.Equals(StatusInfo.ERRO) && !string.IsNullOrEmpty(email.Msg.To))
                {
                    logger.DebugFormat("===> SendEmail: IDCliente[{0}] Emails:[{1}] Subject:[{2}]", info.IdCliente, email.Msg.To, email.Msg.Subject);
                    SpiderMail.SendEmail(_cfg, email.Msg);
                }
                else
                {
                    logger.DebugFormat("===> SendEmail: Email com ERRO ou destinatario vazio. IDCliente[{0}], Emails:[{1}] Subject:[{2}]", info.IdCliente, email.Msg.To, email.Msg.Subject);
                }
                if (_db != null)
                {
                    _db.InserirEmailNotaCorretagem(info);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Erro no envio dos emails: " + ex.Message, ex);
                info.Status     = StatusInfo.ERRO;
                info.DescStatus = ex.Message;
                if (_db != null)
                {
                    _db.InserirEmailNotaCorretagem(info);
                }
            }
        }
コード例 #19
0
        /// <summary>
        /// Initialize wrapper
        /// </summary>
        public static void Initialize()
        {
            _model = new MsSqlAuditorModel();
            _model.Initialize();

            _storage = _model.DefaultVaultProcessor.CurrentStorage;

            _serviceDataUpdateTimeout = _model.Settings.SystemSettings.ServiceDataUpdateTimeout;
            _serviceRunJobsTimeout    = _model.Settings.SystemSettings.ServiceRunJobsTimeout;
            _serviceStarted           = DateTime.Now;

            _scheduleJobProcessor    = new ScheduleJobProcessor(_storage);
            _connectionsManager      = new ConnectionsManager(_model);
            _scheduleSettingsManager = new ScheduleSettingsManager(_storage);

            _runningTasks          = new ConcurrentDictionary <string, string>();
            _databaseNodeInstances = new ConcurrentDictionary <long, NodeInstanceRow>();
            _serviceNodeInstances  = new ConcurrentDictionary <long, NodeInstanceRow>();

            _serviceSchedules  = new ConcurrentDictionary <long, ScheduleSettingsRow>();
            _databaseSchedules = new ConcurrentDictionary <long, ScheduleSettingsRow>();
            _connectionGroups  = new List <ConnectionGroupInfo>();

            LoadFromDB(true);
            log.DebugFormat(
                @"Active scheduled Instances:'{0}'  Active schedules: '{1}'",
                _serviceNodeInstances.Count,
                _serviceSchedules.Count
                );
        }
        /// <summary>
        ///     Opens a config file on disk.
        /// </summary>
        /// <param name="configFilePath">Path to external config file.</param>
        /// <param name="log">Log4Net ILog implementation</param>
        /// <returns>
        ///     Settings parsed from <paramref name="configFilePath" />.
        /// </returns>
        private static Settings LoadConfigurationFromFile(string configFilePath, ILog log)
        {
            log.DebugFormat("Attempting to load settings from external configuration file '{0}'", configFilePath);
            var fileMap = new ConfigurationFileMap(configFilePath);
            var configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
            var section = (NewRelicConfigurationSection) configuration.GetSection("newRelic");
            var settingsFromConfig = Settings.FromConfigurationSection(section, log);
            log.DebugFormat("Settings loaded successfully");

            return settingsFromConfig;
        }
コード例 #21
0
ファイル: HanReader.cs プロジェクト: dagsunde/AMS_2
        public bool read(byte data)
        {
            bool retVal = false;

            if (reader.Read(data))
            {
                bytesRead = reader.GetRawData(buffer, 0, 512);
                if (debug)
                {
                    log.DebugFormat("Got valid DLMS data ({0} bytes):", bytesRead);
                    debugPrint(buffer, 0, bytesRead);
                }

                /*
                 *  Data should start with E6 E7 00 0F
                 *  and continue with four bytes for the InvokeId
                 */
                if (bytesRead < 9)
                {
                    if (debug)
                    {
                        log.Debug("Invalid HAN data: Less than 9 bytes received");
                    }
                    retVal = false;
                }
                else if (
                    buffer[0] != 0xE6 ||
                    buffer[1] != 0xE7 ||
                    buffer[2] != 0x00 ||
                    buffer[3] != 0x0F
                    )
                {
                    if (debug)
                    {
                        log.Debug("Invalid HAN data: Start should be E6 E7 00 0F");
                    }
                    retVal = false;
                }

                if (debug)
                {
                    log.Debug("HAN data is valid");
                }
                listSize = getInt(0, buffer, 0, bytesRead);
                retVal   = true;
            }

            return(retVal);
        }
コード例 #22
0
        static void Main(string[] args)
        {
            GlobalContext.Properties["LogFileName"] = CurrentAssembly.ProcessNameBase;
            log4net.Config.XmlConfigurator.Configure();


            _modelInitializer          = new Timer();
            _modelInitializer.Interval = 500;
            _modelInitializer.Elapsed += new System.Timers.ElapsedEventHandler(ModelInintializerElapsed);
            _modelInitializer.Enabled  = true;
            log.DebugFormat(
                @"Initialize storage..."
                );

            Console.ReadKey();
        }
コード例 #23
0
ファイル: FixDropCopy.cs プロジェクト: radtek/Gradual
        public void FromAdmin(QuickFix.Message msg, QuickFix.SessionID s)
        {
            string errormsg = "Error: ";

            try
            {
                string msgType = msg.Header.GetField(Tags.MsgType);
                if (msgType == MsgType.LOGON)
                {
                    QuickFix.FIX44.Logon logonMsg = msg as QuickFix.FIX44.Logon;
                    if (logonMsg != null)
                    {
                        // Validates sender & target compids
                        string sndCompID = s.SenderCompID;
                        string tgtCompID = s.TargetCompID;
                        string password  = logonMsg.IsSetField(96)? logonMsg.GetString(96): string.Empty;

                        logger.DebugFormat("snd[{0}] tgt[{1}] pwd[{2}]", sndCompID, tgtCompID, password);
                        if (!_validateLogon(sndCompID, tgtCompID, password))
                        {
                            logger.Info("Não foi possivel autenticar sessao acceptor");
                            QuickFix.FIX44.Logout logout = new QuickFix.FIX44.Logout();
                            logout.Set(new Text("This 4.4 session was not authorized"));
                            Session.SendToTarget(logout, s);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errormsg += ex.Message;
                logger.Error("FromAdmin: " + ex.Message, ex);
            }
        }
コード例 #24
0
ファイル: GameKeepComponent.cs プロジェクト: mywebext/DOL
        /// <summary>
        /// save component in DB
        /// </summary>
        public override void SaveIntoDatabase()
        {
            DBKeepComponent obj = null;
            bool            New = false;

            if (InternalID != null)
            {
                obj = GameServer.Database.FindObjectByKey <DBKeepComponent>(InternalID);
            }
            if (obj == null)
            {
                obj = new DBKeepComponent();
                New = true;
            }
            obj.KeepID     = AbstractKeep.KeepID;
            obj.Heading    = ComponentHeading;
            obj.Health     = Health;
            obj.X          = this.ComponentX;
            obj.Y          = this.ComponentY;
            obj.ID         = this.ID;
            obj.Skin       = this.Skin;
            obj.CreateInfo = m_CreateInfo;

            if (New)
            {
                GameServer.Database.AddObject(obj);
                InternalID = obj.ObjectId;
                log.DebugFormat("Added new component {0} for keep ID {1}, skin {2}, health {3}", ID, AbstractKeep.KeepID, Skin, Health);
            }
            else
            {
                GameServer.Database.SaveObject(obj);
            }
            base.SaveIntoDatabase();
        }
コード例 #25
0
        private void CheckMessage(HttpMessage httpMessage, ExpectedMessageContainer.MessageTypes theMessageType)
        {
            try
            {
                log.DebugFormat("expectedMessageIndex {0}", expectedMessageIndex);

                if (expectedMessageIndex > expectedMessages.Count)
                {
                    throw new System.InvalidOperationException("expectedMessageIndex "
                                                               + expectedMessageIndex
                                                               + " > expectedMessages.Count"
                                                               + expectedMessages.Count);
                }

                ExpectedMessageContainer expectedMessage = expectedMessages[expectedMessageIndex];

                Assert.True(expectedMessage.messageType == theMessageType, "Message type does not match");

                // perform comparisons that are generic to all HttpMessages
                Assert.Equal(expectedMessage.message.HttpVersion, httpMessage.HttpVersion);

                // if we expected a zero length body then we expect that
                // the actual message has a null body since it was never set
                if (expectedMessage.message.Body.Length == 0)
                {
                    Assert.True(httpMessage.Body == null);
                }
                else
                {
                    Assert.Equal(expectedMessage.message.Body.Length, httpMessage.Body.Length);
                }

                if (theMessageType == ExpectedMessageContainer.MessageTypes.HttpRequest)
                {
                    HttpRequest expected = (HttpRequest)expectedMessage.message;
                    HttpRequest request  = (HttpRequest)httpMessage;

                    Assert.Equal(expected.Url, request.Url);
                    Assert.Equal(expected.Method, request.Method);
                }
                else
                {
                    HttpStatus expected = (HttpStatus)expectedMessage.message;
                    HttpStatus status   = (HttpStatus)httpMessage;

                    Assert.Equal(expected.StatusCode, status.StatusCode);
                }

                // move to the next message
                expectedMessageIndex++;

                log.Debug("message matched");
            } catch (System.Exception e)
            {
                // catch exceptions because the HttpSessionMonitor code will drop them

                log.Error("caught exception", e);
                Assert.True(false);
            }
        }
コード例 #26
0
        /// <summary>
        /// When we interact with lord, we display all possible options
        /// </summary>
        /// <param name="player">The player object</param>
        /// <returns></returns>
        public override bool Interact(GamePlayer player)
        {
            if (!base.Interact(player))
            {
                return(false);
            }

            if (this.Component == null)
            {
                return(false);
            }

            if (InCombat || Component.AbstractKeep.InCombat)
            {
                player.Out.SendMessage("You can't talk to the lord while under siege.", eChatType.CT_System, eChatLoc.CL_SystemWindow);
                log.DebugFormat("KEEPWARNING: {0} attempted to interact with {1} of {2} while keep or lord in combat.", player.Name, Name, Component.AbstractKeep.Name);
                return(false);
            }

            if (GameServer.ServerRules.IsAllowedToClaim(player, CurrentRegion))
            {
                player.Out.SendMessage("Would you like to [Claim Keep] now? Or maybe [Release Keep]?", eChatType.CT_System, eChatLoc.CL_PopupWindow);
            }

            return(true);
        }
コード例 #27
0
        /// <summary>
        /// Executes the provided IWindowsServices and supports automatic installation using the command line params -install / -uninstall
        /// </summary>
        /// <param name="args"></param>
        /// <param name="createServices">Function which provides a WindowsServiceCollection of services to execute</param>
        /// <param name="configureContext">Optional application context configuration</param>
        /// <param name="installationSettings">Optional installer configuration with semi-sensible defaults</param>
        /// <param name="registerContainer">Optionally register an IoC container</param>
        /// <param name="agentSettingsManager">Optionally provide agent settings </param>
        public WindowsServiceRunner(string[] args,
            Func<IWindowsService[]> createServices,
            Action<ApplicationContext> configureContext = null,
            Action<System.ServiceProcess.ServiceInstaller,
            ServiceProcessInstaller> installationSettings = null,
            Func<IIocContainer> registerContainer = null,
            IAgentSettingsManager agentSettingsManager = null,
            Action<ApplicationContext,string> notify=null)
        {
            _notify = notify ?? ((ctx,message) => { });
            var log = LogManager.GetLogger(typeof (WindowsServiceRunner));
            _args = args;
            _context = new ApplicationContext();
            _createServices = createServices;
            _agentSettingsManager = agentSettingsManager;
            _logger = log;
            _configureContext = configureContext ?? (ctx => {  });
            _context.ConfigureInstall = installationSettings ?? ((serviceInstaller, serviceProcessInstaller) => { });
            _context.Container = registerContainer;

            if (registerContainer==null)
            {
                throw new ArgumentException("Binding container is null");
            }
            if (registerContainer != null)
            {
                _logger.DebugFormat("container is " + registerContainer.ToString());
            }
        }
コード例 #28
0
ファイル: Logger.cs プロジェクト: qkxyk/hxcore
        /// <summary>
        /// 输出普通日志
        /// </summary>
        /// <param name="level"></param>
        /// <param name="format"></param>
        /// <param name="args"></param>
        private void Log(LoggerLevel level, string format, params object[] args)
        {
            switch (level)
            {
            case LoggerLevel.Debug:
                _Logger4net.DebugFormat(format, args);
                break;

            case LoggerLevel.Info:
                _Logger4net.InfoFormat(format, args);
                break;

            case LoggerLevel.Warn:
                _Logger4net.WarnFormat(format, args);
                break;

            case LoggerLevel.Error:
                _Logger4net.ErrorFormat(format, args);
                break;

            case LoggerLevel.Fatal:
                _Logger4net.FatalFormat(format, args);
                break;
            }
        }
コード例 #29
0
        private static void PublishData(object state)
        {
            string topicName;
            double baseMultiplier;
            double value;

            try
            {
                baseMultiplier = System.DateTime.Now.TimeOfDay.TotalSeconds / 1000;

                if (_mqttClient != null)
                {
                    if (_mqttClient.IsConnected)
                    {
                        log.Info("Publishing Values");

                        for (int i = 1; i <= itemCount; i++)
                        {
                            value = i * baseMultiplier;

                            topicName = topicRoot + i.ToString("D6");

                            log.DebugFormat("Publish {0} on topic {1}", value.ToString(), topicName);

                            _mqttClient.Publish(topicName, System.Text.UTF8Encoding.UTF8.GetBytes(value.ToString()), 1, false);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
コード例 #30
0
 /// <summary>
 /// 调试
 /// </summary>
 public static void DebugFormat(string message, params object[] args)
 {
     if (log.IsDebugEnabled)
     {
         log.DebugFormat(message, args);
     }
 }
コード例 #31
0
 public void DebugFormat(string format, params object[] args)
 {
     if (IsDebugEnabled)
     {
         log.DebugFormat(format, args);
     }
 }
コード例 #32
0
        /// <summary>
        /// Generates a response from a GCalRequest
        /// </summary>
        /// <returns></returns>
        public string GenerateResponse()
        {
            /* Create a string builder to hold the text for the response */
            StringBuilder result = new StringBuilder(4096);

            /* Create an exchange provider */
            ExchangeService gateway = new ExchangeService(
                ConfigCache.ExchangeServerUrl,
                ConfigCache.ExchangeUserLogin,
                ConfigCache.ExchangeUserPassword);

            /* Return the exchangers from the GCal Request that was passed in */
            DateTimeRange    range         = new DateTimeRange(request.UTCStartDate, request.UTCEndDate);
            ExchangeUserDict exchangeUsers = gateway.SearchByEmail(range, request.ExchangeUsers);

            /* Create the header of the request */
            result.AppendFormat("['{0}','{1}',", request.VersionNumber, request.MessageId);

            result.AppendFormat("['_ME_AddData','{0}/{1}','{2}'",
                                DateUtil.FormatDateForGoogle(request.StartDate),
                                DateUtil.FormatDateForGoogle(request.EndDate),
                                DateUtil.FormatDateTimeForGoogle(request.Since));

            /* Flag for inserting commas */
            bool firstUser = true;

            result.Append(",[");

            foreach (ExchangeUser user in exchangeUsers.Values)
            {
                /* Don't add a comma if this is the first user */
                if (!firstUser)
                {
                    result.Append(",");
                }

                /* Add the user's credentials */
                string email = ConfigCache.MapToExternalDomain(user.Email);
                result.AppendFormat("'{0}','{1}','{2}',[",
                                    user.DisplayName,
                                    email,
                                    (int)user.AccessLevel);

                GenerateResponseForTimeBlocks(user,
                                              result);

                result.Append("]");
                firstUser = false;
            }

            result.Append("]");
            result.Append("]");
            result.Append("]");

            log.Info("GCal Free/Busy response successfully generated.");
            log.DebugFormat("Response = {0}", result);

            return(result.ToString());
        }
 private static Settings GetSettingsFromAppConfig(ILog log)
 {
     log.Debug("No external configuration path given, attempting to load settings from from default configuration file");
     var section = (NewRelicConfigurationSection) ConfigurationManager.GetSection("newRelic");
     var settingsFromAppConfig = Settings.FromConfigurationSection(section,log);
     log.DebugFormat("Settings loaded successfully");
     return settingsFromAppConfig;
 }
コード例 #34
0
ファイル: PxSqlCommand.cs プロジェクト: trygu/PxWeb
        /// <summary>
        /// Execute a select-statement and return the query result as a "System.Data DataSet".
        /// </summary>
        /// <param name="selectString">The SQL query (select).</param>
        /// <returns>A "System.Data DataSet" with the data result from the query.</returns>
        public DataSet ExecuteSelect(string selectString) {

            // Check SQL param
            if (String.IsNullOrEmpty(selectString)) {
                throw new BugException("Error PxSqlClient.PxSqlCommand.ExecuteSelect: Parameter \"selectString\" is empty/null!");
            }
            log.Debug(selectString);

            if(selectString.Contains(";"))
            {
                throw new BugException("Error PxSqlClient.PxSqlCommand.ExecuteSelect: Parameter \"selectString\" contains semicolon");
            }
            #if DEBUG
                System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
                stopWatch.Start();
            #endif
            DataSet pxDataSet = new DataSet();
            using (DbDataAdapter pxDataAdapter = myDbVendor.GetDbDataAdapter(selectString)) {
                
                pxDataAdapter.Fill(pxDataSet);
                //TODO: Check for pxDataAdapter.FillError???
            }

            #if DEBUG
                stopWatch.Stop();
                logTime.DebugFormat("    Completed " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in ms = {0} for sql = {1}", stopWatch.ElapsedMilliseconds, selectString);
            #endif

            return pxDataSet;
        }
コード例 #35
0
        public static void Debug(ILog log, string format, params object[] @params)
        {
            if (log == null)
            {
                return;
            }

            log.DebugFormat(format, @params);
        }
コード例 #36
0
        /// <summary>
        /// Write the list of cohorts at a site to a log.
        /// </summary>
        public static void WriteSiteCohorts(ILog       log,
            ActiveSite site)
        {
            if (cohorts == null)
                cohorts = Model.Core.GetSiteVar<ISiteCohorts>("Succession.BiomassCohorts");

            int count = 0;  // # of species with cohorts
            foreach (ISpeciesCohorts speciesCohorts in cohorts[site])
            {
                string cohort_list = "";
                foreach (ICohort cohort in speciesCohorts)
                {
                    cohort_list += string.Format(", {0} yrs ({1})", cohort.Age, cohort.Biomass);
                }
                log.DebugFormat("      {0}{1}", speciesCohorts.Species.Name, cohort_list);
                count += 1;
            }
            if (count == 0)
                log.DebugFormat("      (no cohorts)");
        }
コード例 #37
0
ファイル: LogHelper.cs プロジェクト: zszqwe/UCsoft
 /// <summary>
 /// Log4Net调试记录封装  2014-08-28 14:58:50 By 唐有炜
 /// </summary>
 /// <param name="message"></param>
 /// <param name="ex"></param>
 /// <returns></returns>
 public static void Debug(string message, Exception ex)
 {
     if (logdebug.IsDebugEnabled)
     {
         if (!string.IsNullOrEmpty(message) && ex == null)
         {
             logdebug.DebugFormat("<br/>【附加信息】 : {0}<br>", new object[] { message });
         }
         else if (!string.IsNullOrEmpty(message) && ex != null)
         {
             string errorMsg = BeautyErrorMsg(ex);
             logdebug.DebugFormat("<br/>【附加信息】 : {0}<br>{1}", new object[] { message, errorMsg });
         }
         else if (string.IsNullOrEmpty(message) && ex != null)
         {
             string errorMsg = BeautyErrorMsg(ex);
             logdebug.Debug(errorMsg);
         }
     }
 }
コード例 #38
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CustomizationManagerBase&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="composer">The composer.</param>
        /// <param name="fileSystem">The file system.</param>
        protected CustomizationManagerBase(IDirectoryBasedComposer composer, IFileSystem fileSystem)
        {
            if (composer == null) throw new ArgumentNullException("composer");
            if (fileSystem == null) throw new ArgumentNullException("fileSystem");

            _composer = composer;
            _fileSystem = fileSystem;
            Log = LogManager.GetLogger(GetType());

            Customizers = new List<ICustomizeReactorInitialization>();

            if (Log.IsDebugEnabled) Log.DebugFormat("There were {0} customizers found", Customizers.Count());
        }
コード例 #39
0
 public AuthenticationHttpMoudle()
 {
     _logger = new DefaultLoggerFactory().GetLogger();
     _logger.DebugFormat("AuthenticationHttpMoudle创建新的实例");
     _userService = ServiceLocationHandler.Resolver<IUserService>();
     _desCrypto = new DesCrypto("hhyjuuhd", "mmnjikjh");
     _systemAuthenticationHandlers = new List<IAuthenticationHandler>();
     _systemAuthenticationHandlers.Add(new DefaultAuthenticationHandler());
     _customAuthenticationHandlers = new List<IAuthenticationHandler>();
     var customHandler = ServiceLocationHandler.Resolver<IAuthenticationHandler>(false);
     if (customHandler != null)
         _customAuthenticationHandlers.Add(customHandler);
 }
コード例 #40
0
        public EdgeAreasAndBulbsPointGenerator(string directory, string filename)
        {
            _log = LogManager.GetLogger(GetType());

            _log.Info("Loading edge areas from file");

            var listReader = new AreaListReader(directory, filename);

            _edgeAreas = listReader
                .GetAreas()
                .ToList();
            _log.DebugFormat("Loaded {0:N0} edge areas", _edgeAreas.Count);
        }
コード例 #41
0
ファイル: Program.cs プロジェクト: richard-green/NotifyNow
        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();
                }
            }
        }
コード例 #42
0
ファイル: PluginDriver.cs プロジェクト: MutonUfoAI/pgina
        public PluginDriver()
        {
            m_logger = LogManager.GetLogger(string.Format("PluginDriver:{0}", m_sessionId));

            m_properties = new SessionProperties(m_sessionId);

            // Add the user information object we'll be using for this session
            UserInformation userInfo = new UserInformation();
            m_properties.AddTrackedSingle<UserInformation>(userInfo);

            // Add the plugin tracking object we'll be using for this session
            PluginActivityInformation pluginInfo = new PluginActivityInformation();
            pluginInfo.LoadedAuthenticationGatewayPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthenticationGateway>();
            pluginInfo.LoadedAuthenticationPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthentication>();
            pluginInfo.LoadedAuthorizationPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthorization>();
            m_properties.AddTrackedSingle<PluginActivityInformation>(pluginInfo);

            m_logger.DebugFormat("New PluginDriver created");
        }
コード例 #43
0
        private void ExecuteScriptIfFoundInPackage(DeploymentContext context, string scriptPath, ILog logger)
        {
            var file = context.Package.GetFiles().SingleOrDefault(f => f.Path.Equals(scriptPath, StringComparison.InvariantCultureIgnoreCase));

            if (file == null)
            {
                return;
            }

            logger.DebugFormat("Found script {0}, executing...", scriptPath);

            try
            {
                LoadAndExecuteScript(context, Path.Combine(context.WorkingFolder, file.Path), logger);
            }
            catch (Exception ex)
            {
                logger.Fatal("Failed executing powershell script " + file.Path, ex);
            }
        }
コード例 #44
0
        protected override void OnStart(string[] args)
        {
            log = LogManager.GetLogger(typeof(ATStrategySvc));

            if (serviceHost != null)
            {
                log.Info("Service restarting");
                serviceHost.Close();
            }

            log.Info("Loading configuration");
            Dictionary<string, string> settings = GetConfiguration();
            log.DebugFormat("Loaded {0} configuration values", settings.Count);

            serviceHost = new ServiceHost(new AlgoTrader.strategy.ThreeDucksStrategy(settings));

            //serviceHost = new ServiceHost(typeof(AlgoTrader.strategy.ThreeDucksStrategy));
            log.Info("Service starting");
            serviceHost.Open();
            log.Info("Service started");
        }
コード例 #45
0
 static MemCacheProvider()
 {
     log = LogManager.GetLogger(typeof (MemCacheProvider));
     var configs = ConfigurationManager.GetSection("memcache") as MemCacheConfig[];
     if (configs != null)
     {
         var myWeights = new ArrayList();
         var myServers = new ArrayList();
         foreach (MemCacheConfig config in configs)
         {
             myServers.Add(string.Format("{0}:{1}", config.Host, config.Port));
             if (log.IsDebugEnabled)
             {
                 log.DebugFormat("adding config for memcached on host {0}", config.Host);
             }
             if (config.Weight > 0)
             {
                 myWeights.Add(config.Weight);
             }
         }
         servers = (string[]) myServers.ToArray(typeof (string));
         weights = (int[]) myWeights.ToArray(typeof (int));
     }
 }
コード例 #46
0
ファイル: BaseLog.cs プロジェクト: wra222/testgit
 public static void LoggingInfo(ILog logger, string format, params object[] args)
 {
     
      logger.DebugFormat(format, args);
 }
コード例 #47
0
ファイル: BaseLog.cs プロジェクト: wra222/testgit
 public static void LoggingEnd(ILog logger, string methodName)
 {
    
     logger.DebugFormat("END:   {0}()", methodName);
     //logger.DebugFormat("END:   {0}::{1}()", method.DeclaringType, method.Name);
 }
コード例 #48
0
 public void Print(string response, ILog log)
 {
     log.DebugFormat("Json:\n{0}", JsonConverter.ToPrettyJson(response));
 }
コード例 #49
0
 private static void DumpWebsiteProperties(DirectoryEntry website, ILog logger)
 {
     foreach(string propertyName in website.Properties.PropertyNames)
     {
         var propertyValueCollection = website.Properties[propertyName];
         if (propertyValueCollection != null)
         {
             if (propertyValueCollection.Count == 1)
             {
                 logger.DebugFormat("{0}={1}", propertyName, propertyValueCollection.Value);
             } else if (propertyValueCollection.Count > 0)
             {
                 foreach(var value in propertyValueCollection)
                 {
                     logger.DebugFormat("{0}={1}", propertyName, value);
                 }
             }
         }
     }
 }
コード例 #50
0
        private static string DetermineServiceName(DeploymentContext context, string pathToExecutable, ILog logger)
        {
            var serviceName = context.MetaData != null
                                  ? context.MetaData.ServiceName
                                  : GetServiceNameForExecutable(context, pathToExecutable);

            if (string.IsNullOrWhiteSpace(serviceName))
            {
                serviceName = context.Package.Id;
            }
            logger.DebugFormat("Service name is '{0}'", serviceName);
            return serviceName;
        }
コード例 #51
0
ファイル: XInputDll.cs プロジェクト: CheesyKek/ScpToolkit
        /// <summary>
        ///     Initializes library.
        /// </summary>
        static XInputDll()
        {
            Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            Log.InfoFormat("Library loaded by process {0} [{1}]",
                Process.GetCurrentProcess().ProcessName,
                Process.GetCurrentProcess().MainWindowTitle);

            var myself = Assembly.GetExecutingAssembly().GetName();
            var myPath = Assembly.GetExecutingAssembly().Location;
            var myName = Path.GetFileName(myPath);

            Log.InfoFormat("Initializing library {0} [{1}]", myName, myself.Version);

            try
            {
                var basePath = BasePath;
                Log.DebugFormat("ScpToolkit bin path: {0}", basePath);
                var controlPath = ScpControlPath;
                Log.DebugFormat("ScpControl bin path: {0}", controlPath);

                // resolve assembly dependencies
                AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
                {
                    var asmName = new AssemblyName(args.Name).Name;
                    var asmPath = Path.Combine(basePath, string.Format("{0}.dll", asmName));

                    Log.DebugFormat("Loading assembly {0} from {1}", asmName, asmPath);

                    return Assembly.LoadFrom(asmPath);
                };

                var scpControl = Assembly.LoadFrom(controlPath);
                var scpProxyType = scpControl.GetType("ScpControl.ScpProxy");

                Proxy = Activator.CreateInstance(scpProxyType);

                Proxy.Start();
            }
            catch (Exception ex)
            {
                Log.FatalFormat("Error during library initialization: {0}", ex);
                return;
            }

            // if no custom path specified by user, use DLL in system32 dir
            var xinputPath = !string.IsNullOrEmpty(XInputDllPath) && File.Exists(XInputDllPath)
                ? XInputDllPath
                : Path.Combine(Environment.SystemDirectory, myName);
            Log.DebugFormat("Original XInput DLL path: {0}", xinputPath);

            NativeDllHandle = Kernel32Natives.LoadLibrary(xinputPath);

            if (NativeDllHandle == IntPtr.Zero)
            {
                Log.FatalFormat("Couldn't load native DLL: {0}", new Win32Exception(Marshal.GetLastWin32Error()));
                return;
            }

            Log.Info("Library initialized");
        }
コード例 #52
0
ファイル: Program.cs プロジェクト: ermau/Gablarski
        static void Main(string[] args)
        {
            if (RaygunKey[0] != '{')
                Raygun = new RaygunClient (RaygunKey);

            AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
                if (StartupLog != null)
                    StartupLog.Error ("Fatal Error", (Exception)e.ExceptionObject);

                if (Raygun != null)
                    Raygun.Send ((Exception) e.ExceptionObject, null, Settings.CurrentSettings);

                MessageBox.Show ("Unexpected error" + Environment.NewLine + (e.ExceptionObject as Exception).ToDisplayString(),
                                 "Unexpected error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            };

            //AutomaticErrorReporter errors = new AutomaticErrorReporter();
            //errors.Add (new GablarskiErrorReporter (typeof(Program).Assembly));

            log4net.Config.XmlConfigurator.Configure ();
            StartupLog = LogManager.GetLogger ("Startup");
            StartupLog.DebugFormat ("PID: {0}", Process.GetCurrentProcess().Id);

            FileInfo program = new FileInfo (Process.GetCurrentProcess().MainModule.FileName);
            Environment.CurrentDirectory = program.Directory.FullName;

            string useLocalValue = ConfigurationManager.AppSettings["useLocalDatabase"];
            bool useLocal;
            Boolean.TryParse (useLocalValue, out useLocal);

            StartupLog.DebugFormat ("Local files: {0}", useLocal);
            StartupLog.DebugFormat ("Setting up databases..");

            ClientData.Setup (useLocal);

            StartupLog.DebugFormat ("Databases setup.");

            CheckForUpdates();

            StartupLog.Debug ("Starting key retrieval");
            var keyCancelSource = new CancellationTokenSource();
            Key = ClientData.GetCryptoKeyAsync (keyCancelSource.Token);
            Key.ContinueWith (t => StartupLog.DebugFormat ("Key retrieval: {0}{1}{2}", t.Status, Environment.NewLine, t.Exception));

            SetupFirstRun();

            if (Settings.Nickname == null)
                PersonalSetup();

            if (!ShowKeyProgress (keyCancelSource))
                return;

            ResourceWebRequestFactory.Register();

            Application.EnableVisualStyles ();
            Application.SetCompatibleTextRenderingDefault (false);

            //SetupSocial();

            /*MainWindow window = new MainWindow();
            window.Show();*/

            var m = new MainForm();
            m.Show();

            UpdateTaskbarServers();

            if (args.Length > 0) {
                int id;
                if (Int32.TryParse (args[0], out id)) {
                    ServerEntry server = Servers.GetEntries ().FirstOrDefault (s => s.Id == id);
                    if (server == null) {
                        if (!m.ShowConnect (true))
                            return;
                    } else
                        m.Connect (server);
                } else {
                    Uri server = new Uri (args[0]);
                    m.Connect (server.Host, (server.Port != -1) ? server.Port : 42912);
                }
            } else if (Settings.ShowConnectOnStart) {
                if (!m.ShowConnect (true))
                    return;
            }

            /*System.Windows.Application app = new System.Windows.Application();
            app.Run (window);*/

            Application.Run (m);

            Settings.Save();
        }
コード例 #53
0
ファイル: Logger.cs プロジェクト: camalot/droidexplorer
 /// <summary>
 /// Logs the debug.
 /// </summary>
 /// <param name="type">The type.</param>
 /// <param name="provider">The provider.</param>
 /// <param name="format">The format.</param>
 /// <param name="args">The args.</param>
 public static void LogDebug( Type type, IFormatProvider provider, string format, params object[] args )
 {
     Log = LogManager.GetLogger ( type );
     Log.DebugFormat ( provider, format, args );
 }
コード例 #54
0
ファイル: Log.cs プロジェクト: zevinganez/code-o-matic
 /// <summary>
 /// Logs a formatted message string with the <see cref="F:log4net.Core.Level.Debug"/> level.
 /// </summary>
 /// <param name="format">A String containing zero or more format items</param>
 /// <param name="args">An Object array containing zero or more objects to format</param>
 /// <param name="log">The log.</param>
 /// <overloads>Log a formatted string with the <see cref="F:log4net.Core.Level.Debug"/> level.</overloads>
 /// <remarks>
 /// 	<para>
 /// The message is formatted using the <c>String.Format</c> method. See
 /// <see cref="M:System.String.Format(System.String,System.Object[])"/> for details of the syntax of the format string and the behavior
 /// of the formatting.
 /// </para>
 /// 	<para>
 /// This method does not take an <see cref="T:System.Exception"/> object to include in the
 /// log event. To pass an <see cref="T:System.Exception"/> use one of the <see cref="M:log4net.ILog.Debug(System.Object,System.Exception)"/>
 /// methods instead.
 /// </para>
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Debug(System.Object)"/>
 /// <seealso cref="P:log4net.ILog.IsDebugEnabled"/>
 public static void DebugFormat(string format, object[] args, ILog log)
 {
     log.DebugFormat(CultureInfo.InvariantCulture, format, args);
 }
コード例 #55
0
ファイル: Log.cs プロジェクト: zevinganez/code-o-matic
 /// <summary>
 /// Logs a formatted message string with the <see cref="F:log4net.Core.Level.Debug"/> level.
 /// </summary>
 /// <param name="provider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information</param>
 /// <param name="format">A String containing zero or more format items</param>
 /// <param name="args">An Object array containing zero or more objects to format</param>
 /// <param name="log">The log.</param>
 /// <remarks>
 /// 	<para>
 /// The message is formatted using the <c>String.Format</c> method. See
 /// <see cref="M:System.String.Format(System.String,System.Object[])"/> for details of the syntax of the format string and the behavior
 /// of the formatting.
 /// </para>
 /// 	<para>
 /// This method does not take an <see cref="T:System.Exception"/> object to include in the
 /// log event. To pass an <see cref="T:System.Exception"/> use one of the <see cref="M:log4net.ILog.Debug(System.Object,System.Exception)"/>
 /// methods instead.
 /// </para>
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Debug(System.Object)"/>
 /// <seealso cref="P:log4net.ILog.IsDebugEnabled"/>
 public static void DebugFormat(IFormatProvider provider, string format, object[] args, ILog log)
 {
     log.DebugFormat(provider, format, args);
 }
コード例 #56
0
ファイル: Log.cs プロジェクト: zevinganez/code-o-matic
 /// <summary>
 /// Logs a formatted message string with the <see cref="F:log4net.Core.Level.Debug"/> level.
 /// </summary>
 /// <param name="format">A String containing zero or more format items</param>
 /// <param name="arg0">An Object to format</param>
 /// <param name="log">The log.</param>
 /// <remarks>
 /// 	<para>
 /// The message is formatted using the <c>String.Format</c> method. See
 /// <see cref="M:System.String.Format(System.String,System.Object[])"/> for details of the syntax of the format string and the behavior
 /// of the formatting.
 /// </para>
 /// 	<para>
 /// This method does not take an <see cref="T:System.Exception"/> object to include in the
 /// log event. To pass an <see cref="T:System.Exception"/> use one of the <see cref="M:log4net.ILog.Debug(System.Object,System.Exception)"/>
 /// methods instead.
 /// </para>
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Debug(System.Object)"/>
 /// <seealso cref="P:log4net.ILog.IsDebugEnabled"/>
 public static void DebugFormat(string format, object arg0, ILog log)
 {
     log.DebugFormat(format, arg0);
 }
コード例 #57
0
ファイル: MainWindow.xaml.cs プロジェクト: Lucasvo1/FHVGame
        // NB : Best to call this function from the windows Loaded event or after showing the window
        // (otherwise window is just positioned to fill the secondary monitor rather than being maximised).
        public static void MaximizeToSecondaryMonitor(this Window window, ILog Log)
        {
            Log.Debug("Try to maximize window on secondary screen");

            var secScreen = System.Windows.Forms.Screen.AllScreens.Where(s => !s.Primary).FirstOrDefault();
            if (secScreen != null)
            {
                Log.DebugFormat("Secondary-Screen: {0}, {1}, width: {2}, height: {3}", secScreen, secScreen.DeviceName, secScreen.WorkingArea.Width, secScreen.WorkingArea.Height);
            }
            else
            {
                Log.DebugFormat("No secondary screen detected");
            }

            Log.DebugFormat("Total screens: {0}", System.Windows.Forms.Screen.AllScreens.Count());
            Log.DebugFormat("Total 2nd screens: {0}", System.Windows.Forms.Screen.AllScreens.Where(s => !s.Primary).Count());

            if (secScreen != null)
            {
                if (!window.IsLoaded)
                    window.WindowStartupLocation = WindowStartupLocation.Manual;

                var workingArea = secScreen.WorkingArea;
                window.Left = workingArea.X;
                window.Top = workingArea.Top;
                window.Width = workingArea.Width;
                window.Height = workingArea.Height;
                // If window isn't loaded then maxmizing will result in the window displaying on the primary monitor
                if (window.IsLoaded)
                {
                    Log.Warn("Window wasn't loaded - load on Primary monitor!");
                    window.WindowState = WindowState.Maximized;
                }
            }
        }
コード例 #58
0
ファイル: Program.cs プロジェクト: krippendorf/RelayCard
        /// <summary>
        /// Application's Entry Point.
        /// </summary>
        /// <param name="args">See usage (--help).</param>
        protected static void Main(string[] args)
        {
            /* configure loggging */
            var consoleAppender = new log4net.Appender.ConsoleAppender { Layout = new log4net.Layout.SimpleLayout() };
            log4net.Config.BasicConfigurator.Configure(consoleAppender);
            var rootLogger = ((Hierarchy)LogManager.GetRepository()).Root;
            rootLogger.Level = Level.Info;

            consoleLog = LogManager.GetLogger("ConradRelayCardUtil");

            /* parse RuntimeOptions */
            if (!Parser.Default.ParseArguments(args, RuntimeOptions))
            {
                return;
            }

            if (RuntimeOptions.OptionDebug)
            {
                rootLogger.Level = Level.Debug;
            }

            /* create card instance and initialize with serial port from RuntimeOptions*/
            consoleLog.DebugFormat("Setting card port to {0}", RuntimeOptions.SerialPortName);
            conradCard = new Conrad8RelayCard(RuntimeOptions.SerialPortName);

            /* init card if not DoNotInit*/
            if (!RuntimeOptions.OptionDoNotInit)
            {
                try
                {
                    consoleLog.Debug("Initializing card(s)");
                    var numberOfCards = conradCard.InitializeCard();
                    consoleLog.InfoFormat("Found ({0}) card(s)", numberOfCards);
                }
                catch (Exception ex)
                {
                    consoleLog.Error("Could not initialize card(s)", ex);
                    return;
                }
            }
            else
            {
                consoleLog.Debug("Option 'DoNotInit'has been set, card not initialized");
            }

            switch (RuntimeOptions.CommandOption)
            {
                case CommandOption.Getport:
                    GetPort();
                    break;

                case CommandOption.Setport:
                    SetPort();
                    break;
                case CommandOption.HardwareTest:
                    HardwareTest();
                    break;
                case CommandOption.SetSingle:
                    SetSingle();
                    break;
                case CommandOption.DelSingle:
                    DelSingle();
                    break;
                case CommandOption.Toggle:
                    Toggle();
                    break;
                default:
                    Console.WriteLine("Invalid command or not implemented.");
                    break;
            }
        }
コード例 #59
0
ファイル: Roaming.cs プロジェクト: MutonUfoAI/pgina
        public BooleanResult get(Dictionary<string,string> settings, string username, string password)
        {
            m_logger = LogManager.GetLogger(String.Format("pgSMB2[Roaming:{0}]", username));
            if (!UserCanBeUsed(username))
            {
                // user exists and was not created by pgina
                m_logger.InfoFormat("user {0} does already exist on this system and does not contain a comment of \"pGina created pgSMB2\"", username);
                return new BooleanResult() { Success = true };
            }
            if (!Connect2share(settings["SMBshare"], username, password, Convert.ToUInt32(settings["ConnectRetry"]), false))
            {
                return new BooleanResult() { Success = false, Message = string.Format("Unable to connect to {0}", settings["RoamingSource"]) };
            }
            try
            {
                if (!Directory.Exists(settings["RoamingSource"]))
                {
                    try
                    {
                        Directory.CreateDirectory(settings["RoamingSource"]);
                    }
                    catch (Exception ex)
                    {
                        m_logger.DebugFormat("CreateDirectory({0}) failed {1}", settings["RoamingSource"], ex.Message);
                    }
                }
                string remote_file = settings["RoamingSource"] + "\\" + settings["Filename"];
                if (File.Exists(remote_file) || File.Exists(remote_file + ".bak"))
                {
                    // there is a remote file
                    Boolean loadprofile = true;
                    // what file to use ?
                    if (File.Exists(remote_file))
                    {
                        settings.Add("Filename_real", settings["Filename"]);
                    }
                    else
                    {
                        settings.Add("Filename_real", settings["Filename"] + ".bak");
                        remote_file += ".bak";
                    }

                    // is there a local roaming profile (there shouldnt be any)
                    string ProfDir = GetExistingUserProfile(username, password);
                    // is this a temp profile
                    if (!String.IsNullOrEmpty(ProfDir))
                    {
                        Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4 userinfo4 = new Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4();
                        if (Abstractions.WindowsApi.pInvokes.UserGet(username, ref userinfo4))
                        {
                            if (userinfo4.comment.EndsWith(" tmp"))
                            {
                                m_logger.InfoFormat("delete temp profile {0}", ProfDir);
                                DirectoryDel(ProfDir, 3);
                            }
                        }
                    }
                    if (File.Exists(ProfDir + "\\ntuser.dat")) //worst case "\\ntuser.dat"
                    {
                        // there is a local profile of this user
                        // we need to compare the write date between the profile and the compressed remote roaming profile
                        // to be sure that we dont overwrite a newer profile with an old one
                        // possibly reason is a BSOD/hard reset ...
                        m_logger.Debug("User " + username + " still own a lokal profile UTCdate:" + File.GetLastWriteTimeUtc(ProfDir + "\\ntuser.dat"));
                        m_logger.Debug("User " + username + " compressed remote profile UTCdate:" + File.GetLastWriteTimeUtc(remote_file));
                        if (DateTime.Compare(File.GetLastWriteTimeUtc(ProfDir + "\\ntuser.dat"), File.GetLastWriteTimeUtc(remote_file)) >= 0)
                        {
                            m_logger.DebugFormat("the local profile ('{0}') is newer/equal than the remote one, im not downloading the remote one", ProfDir);
                            loadprofile = false;
                        }
                        else
                        {
                            m_logger.Debug("the local profile is older than the remote one");
                        }
                    }
                    if (!userAdd(settings, username, password, "pGina created pgSMB2"))
                    {
                        userDel(settings, username, password);
                        return new BooleanResult() { Success = false, Message = string.Format("Unable to add user {0}", username) };
                    }
                    if (loadprofile)
                    {
                        if (!GetProfile(ref settings, username, password))
                        {
                            return new BooleanResult() { Success = false, Message = string.Format("Unable to get the Profile {0} from {1}", settings["Filename"], settings["RoamingSource"]) };
                        }

                        if (!Connect2share(settings["SMBshare"], null, null, 0, true))
                        {
                            m_logger.WarnFormat("unable to disconnect from {0}", settings["RoamingSource"]);
                        }

                        if (!SetACL(settings["UserProfilePath"], username, password, Convert.ToUInt32(settings["MaxStore"]), Convert.ToUInt32(settings["ConnectRetry"])))
                        {
                            userDel(settings, username, password);
                            return new BooleanResult() { Success = false, Message = string.Format("Unable to set ACL for user {0}", username) };
                        }
                    }
                }
                else
                {
                    m_logger.DebugFormat("there is no {0}\\{1} or {2}\\{3}{4}", settings["RoamingSource"], settings["Filename"], settings["RoamingSource"], settings["Filename"], ".bak");

                    if (!userAdd(settings, username, password, "pGina created pgSMB2"))
                    {
                        userDel(settings, username, password);
                        return new BooleanResult() { Success = false, Message = string.Format("Unable to add user {0}", username) };
                    }
                }
            }
            catch (Exception ex)
            {
                return new BooleanResult() { Success = false, Message = string.Format("Unable to get the Roaming Profile from {0}\nError: {1}", settings["RoamingSource"], ex.Message) };
            }
            finally
            {
                if (!Connect2share(settings["SMBshare"], null, null, 0, true))
                {
                    m_logger.WarnFormat("unable to disconnect from {0}", settings["RoamingSource"]);
                }
            }

            return new BooleanResult() { Success = true };
        }
コード例 #60
0
ファイル: Logger.cs プロジェクト: rafael-tomita/ge-3-log
 public static void Log(string texto, params object[] args)
 {
     log = LogManager.GetLogger(args[0].ToString());
     log.DebugFormat(texto,args);
 }