コード例 #1
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());
            }
        }
コード例 #2
0
        public void Handle(ClipboardChangedEvent message)
        {
            try
            {
                if (!CanHandleClipboardData())
                {
                    var clipboardData = Clipboard.GetDataObject();
                    var formats       = string.Join(",", clipboardData.GetFormats());
                    _logger.Info($"Cannot handle clipboard data type: {formats}");
                    return;
                }

                var vm = BuildViewModelFromClipboard();
                if (vm == null)
                {
                    return;
                }

                SafeAddToClipboardHistory(vm);
                RebuildClipboardItems();
            }
            catch (COMException exception)
            {
                _logger.WarnFormat("Caught following exception within Handle(ClipboardChangedEvent message) operation...");
                _logger.Error(exception);
                HandleClipboardException();
            }
        }
コード例 #3
0
 public void Warn(string message, params object[] formatting)
 {
     if (_logger.IsWarnEnabled)
     {
         _logger.WarnFormat(decorate_message_with_audit_information(message), formatting);
     }
 }
コード例 #4
0
 /// <summary>
 ///		Parses an attribute intended for the particle system itself.
 /// </summary>
 /// <param name="line"></param>
 /// <param name="system"></param>
 private void ParseAttrib(string line, ParticleSystem system)
 {
     // Split params on space or tab
     char []  delims = { '\t', ' ' };
     string[] values = line.Split(delims, 2);
     // Look up first param (command setting)
     if (!system.SetParameter(values[0], values[1]))
     {
         // Attribute not supported by particle system, try the renderer
         ParticleSystemRenderer renderer = system.Renderer;
         if (renderer != null)
         {
             if (!renderer.SetParameter(values[0], values[1]))
             {
                 log.WarnFormat("Bad particle system attribute line: '{0}' in {1} (tried renderer)",
                                line, system.Name);
             }
         }
         else
         {
             // BAD command. BAD!
             log.WarnFormat("Bad particle system attribute line: '{0}' in {1} (no renderer)",
                            line, system.Name);
         }
     }
 }
コード例 #5
0
        private void AssignToReviewer(Models.JobApplication applicant)
        {
            if (applicant == null || applicant.ReviewStatus != ReviewStatus.New)
            {
                return;
            }
            var applicantService    = new JobApplicationProvider();
            var positionTypeService = new JobPositionTypeProvider();
            var reviewerService     = new ReviewerProvider();
            var ghDataStore         = GreenHouseDataStore.Instance;
            var job = ghDataStore.GetJobById(applicant.JobId);

            if (job == null || job.Status != JobStates.Open)
            {
                applicant.ReviewStatus = ReviewStatus.JobClosed;
                applicantService.Update(applicant);

                _logger.InfoFormat("Applicant {0} is closed because it's job ({1}) is either deleted or not opened", applicant.Id, job?.Id);
                return;
            }

            if (applicant.Source == ApplicantSources.Referral && AppConfigsProvider.ReferralsHandlingConfigs.IsEnabled)
            {
                applicant.ReviewStatus = ReviewStatus.HandledAsReferral;
                applicantService.Update(applicant);
                SendEmailForReferral(applicant, job);

                _logger.InfoFormat("Applicant {0} of job {1} has been handled as a referral", applicant.Id, job.Id);
                return;
            }

            var positionTypeStr = job.GetCustomFieldValue(JobCustomFields.PositionType);
            var positionType    = positionTypeService.GetList(p => p.Name == positionTypeStr).FirstOrDefault();

            if (positionType == null)
            {
                _logger.WarnFormat("Position Type '{0}' is not available.", positionTypeStr);
                return;
            }
            var selectedReviewer = GetNextReviewer(positionType);

            if (selectedReviewer == null)
            {
                _logger.WarnFormat("Can not get any reviewers for the applicant {0}. It's either because there is no reviewers configured for this position type or all reviewers all not in working hours.", applicant.Id);
                return;
            }

            selectedReviewer.RecentAssignedAt = DateTime.UtcNow;
            selectedReviewer.AssignedCount++;

            applicant.ReviewerId           = selectedReviewer.Id;
            applicant.ReviewStatus         = ReviewStatus.Assigned;
            applicant.AssignedToReviewerAt = DateTime.UtcNow;

            applicantService.Update(applicant);
            reviewerService.Update(selectedReviewer);

            _logger.InfoFormat("Applicant {0} has been assigned to reviewer {1}", applicant.Id, selectedReviewer.Id);
            SendAssignmentEmail(selectedReviewer, applicant, job);
        }
コード例 #6
0
ファイル: Startup.cs プロジェクト: asurionlabs/chatengine
        private static void ConfigureXRaySampling()
        {
            var sampling = AWSXRayRecorder.Instance.SamplingStrategy as LocalizedSamplingStrategy;

            if (sampling == null)
            {
                log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                logger.WarnFormat("Startup: Unknown Sampling Strategy.  {0}", AWSXRayRecorder.Instance.SamplingStrategy);
                return;
            }

            // TODO:
            //if (bool.TryParse(ConfigurationManager.AppSettings["XRayALL"], out bool XRayAll) && XRayAll)
            //    sampling.DefaultRule.Rate = 1.0;

            sampling.Rules.Add(new SamplingRule
            {
                Description = "Disable all HTTP OPTIONS tracing",
                HttpMethod  = "OPTIONS",
                ServiceName = "*",
                UrlPath     = "*",
                FixedTarget = 0,
                Rate        = 0.0
            }
                               );
        }
コード例 #7
0
        private void ParseArgs(IEnumerable <string> args)
        {
            var loggerRepository = _logger.Logger.Repository;

            var optionSet = new OptionSet
            {
                { "h|?|help", v => ShowHelp() },
                { "V|version", s => Environment.Exit(0) },
                { "debug", s => loggerRepository.Threshold = log4net.Core.Level.Debug },
                { "v|verbose", s => loggerRepository.Threshold = log4net.Core.Level.Info },
                { "w|warn", s => loggerRepository.Threshold = log4net.Core.Level.Warn },
                { "q|quiet", s => loggerRepository.Threshold = log4net.Core.Level.Error },
                { "s|silent", s => loggerRepository.Threshold = log4net.Core.Level.Fatal },
                { "i=|input=", s => _bdromPath = s },
                { "o=|output=", s => _mkvPath = s },
                { "y|yes", s => _replaceExistingFiles = true },
                { "n|no", s => _replaceExistingFiles = false }
            };

            var extraArgs = optionSet.Parse(args);

            if (extraArgs.Any())
            {
                _logger.WarnFormat("Unknown argument{0}: {1}", extraArgs.Count == 1 ? "" : "s", new ArgumentList(extraArgs));
            }
        }
コード例 #8
0
        internal static TopicPartitionState GetPartitionState(IZooKeeperClient zkClient, string topic, int partition)
        {
            var stateData = zkClient.ReadData <string>(GetTopicPartitionStatePath(topic, partition.ToString(CultureInfo.InvariantCulture)), true);

            if (string.IsNullOrWhiteSpace(stateData))
            {
                return(null);
            }

            TopicPartitionState partitionState;

            try
            {
                var ser    = new JavaScriptSerializer();
                var result = ser.Deserialize <Dictionary <string, object> >(stateData);
                partitionState = new TopicPartitionState()
                {
                    Leader           = int.Parse(result["leader"].ToString()),
                    Leader_Epoch     = int.Parse(result["leader_epoch"].ToString()),
                    Controller_Epoch = int.Parse(result["controller_epoch"].ToString()),
                    Verstion         = int.Parse(result["version"].ToString()),
                };

                var isrArr = result["isr"] as System.Collections.ArrayList;
                partitionState.Isr = isrArr != null?isrArr.Cast <int>().ToArray() : null;
            }
            catch (Exception exc)
            {
                Logger.WarnFormat("Unexpected error while trying to get topic partition state for topic '{0}' partition '{1}'. Error: {2} ", topic, partition, exc.FormatException());
                return(null);
            }

            return(partitionState);
        }
        /// <summary>
        /// Closes underlying ZooKeeper client
        /// </summary>
        public void Dispose()
        {
            if (this.disposed)
            {
                return;
            }

            lock (this.shuttingDownLock)
            {
                if (this.disposed)
                {
                    return;
                }

                this.disposed = true;
            }

            try
            {
                if (this._zkclient != null)
                {
                    Logger.Debug("Closing ZooKeeper client connected to " + this.Servers);
                    this._zkclient.Dispose();
                    this._zkclient = null;
                    Logger.Debug("ZooKeeper client connection closed");
                }
            }
            catch (Exception exc)
            {
                Logger.WarnFormat("Ignoring unexpected errors on closing {0}", exc.FormatException());
            }
        }
コード例 #10
0
ファイル: Main.cs プロジェクト: yanivkalfa/MultiversePlatform
        /// <summary>
        ///   Make sure that the repository thresholds are at least as high
        ///   as the level we set here.  This does not allow us to lower the
        ///   logging level.  That would be complex, because even in cases
        ///   where we don't want heavy logging, we still want to make sure
        ///   we get our status messages.
        /// </summary>
        /// <param name="loglevel"></param>
        /// <param name="force"></param>
        private static void SetLogLevel(string loglevel, bool force)
        {
            log4net.Core.Level logLevel = log4net.Core.Level.Off;
            switch (loglevel.ToLowerInvariant())
            {
            case "0":
            case "debug":
                logLevel = log4net.Core.Level.Debug;
                break;

            case "1":
            case "2":
            case "info":
                logLevel = log4net.Core.Level.Info;
                break;

            case "3":
            case "warn":
                logLevel = log4net.Core.Level.Warn;
                break;

            case "4":
            case "error":
                logLevel = log4net.Core.Level.Error;
                break;

            default:
                log.WarnFormat("Invalid log level: {0}", loglevel);
                return;
            }
            LogUtil.SetLogLevel(logLevel, force);
        }
コード例 #11
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;
            }
        }
コード例 #12
0
        /// <summary>
        ///     Adds an Entity to the static geometry.
        /// </summary>
        /// <remarks>
        ///     This method takes an existing Entity and adds its details to the
        ///     list of	elements to include when building. Note that the Entity
        ///     itself is not copied or referenced in this method; an Entity is
        ///     passed simply so that you can change the materials of attached
        ///     SubEntity objects if you want. You can add the same Entity
        ///     instance multiple times with different material settings
        ///     completely safely, and destroy the Entity before destroying
        ///     this StaticGeometry if you like. The Entity passed in is simply
        ///     used as a definition.
        ///
        ///     Note: Must be called before 'build'.
        /// </remarks>
        /// <param name=ent>The Entity to use as a definition (the Mesh and Materials</param>
        /// <param name=position>The world position at which to add this Entity</param>
        /// <param name=orientation>The world orientation at which to add this Entity</param>
        /// <param name=scale>The scale at which to add this entity</param>
        /// <param name=position>The world position at which to add this Entity</position>
        public void AddEntity(Entity ent, Vector3 position, Quaternion orientation, Vector3 scale)
        {
            Mesh msh = ent.Mesh;

            // Validate
            if (msh.IsLodManual)
            {
                log.WarnFormat("StaticGeometry.AddEntity: Manual LOD is not supported. Using only highest LOD level for mesh {0}", msh.Name);
            }

            // queue this entities submeshes and choice of material
            // also build the lists of geometry to be used for the source of lods
            for (int i = 0; i < ent.SubEntityCount; ++i)
            {
                SubEntity     se = ent.GetSubEntity(i);
                QueuedSubMesh q  = new QueuedSubMesh();

                // Get the geometry for this SubMesh
                q.submesh         = se.SubMesh;
                q.geometryLodList = DetermineGeometry(q.submesh);
                q.materialName    = se.MaterialName;
                q.orientation     = orientation;
                q.position        = position;
                q.scale           = scale;
                // Determine the bounds based on the highest LOD
                q.worldBounds = CalculateBounds(q.geometryLodList[0].vertexData, position, orientation, scale);
                queuedSubMeshes.Add(q);
            }
        }
コード例 #13
0
 /// <summary>
 /// 警告
 /// </summary>
 public static void WarnFormat(string message, params object[] args)
 {
     if (log.IsWarnEnabled)
     {
         log.WarnFormat(message, args);
     }
 }
コード例 #14
0
 public void WarnFormat(string format, params object[] args)
 {
     if (IsWarnEnabled)
     {
         log.WarnFormat(format, args);
     }
 }
コード例 #15
0
        public void AsyncRebalance(int waitRebalanceFinishTimeoutInMs = 0)
        {
            lock (this.asyncLock)
            {
                // Stop currently running rebalance
                StopRebalance();

                // Run new rebalance operation asynchronously
                Logger.Info("Asynchronously running rebalance operation");
                Task.Factory.StartNew(() => SyncedRebalance(rebalanceCancellationTokenSource));

                // Set flag to indicate that rebalance is running
                isRebalanceRunning = true;
            }

            if (waitRebalanceFinishTimeoutInMs > 0)
            {
                DateTime timeStartWait = DateTime.UtcNow;
                while (isRebalanceRunning == true)
                {
                    Logger.Info("Waiting for rebalance operation finish");
                    Thread.Sleep(100);
                    if ((DateTime.UtcNow - timeStartWait).TotalMilliseconds > waitRebalanceFinishTimeoutInMs)
                    {
                        Logger.WarnFormat("After wait more than {0} ms, the latest isRebalanceRunning:{1} ", waitRebalanceFinishTimeoutInMs, isRebalanceRunning);
                        break;
                    }
                }
                Logger.InfoFormat("Finish Wait for rebalance operation. isRebalanceRunning:{0}", isRebalanceRunning);
            }
        }
コード例 #16
0
 public override void ReadCategoryData(XmlElement configNode)
 {
     try {
         int  width      = int.Parse(GetElementText(configNode, "Width"));
         int  height     = int.Parse(GetElementText(configNode, "Height"));
         int  depth      = int.Parse(GetElementText(configNode, "Depth"));
         bool fullScreen = bool.Parse(GetElementText(configNode, "Fullscreen"));
         renderSystemName = GetElementText(configNode, "RenderSystem");
         vSync            = bool.Parse(GetElementText(configNode, "VSync"));
         antiAliasing     = GetElementText(configNode, "AntiAliasing");
         allowNVPerfHUD   = bool.Parse(GetElementText(configNode, "AllowNVPerfHUD"));
         displayMode      = new DisplayMode(Math.Max(width, minScreenWidth), Math.Max(height, minScreenHeight),
                                            depth, allowFullScreen && fullScreen);
         List <RenderSystem> renderSystems = Root.Instance.RenderSystems;
         foreach (RenderSystem r in renderSystems)
         {
             if (r.Name == renderSystemName)
             {
                 renderSystem = r;
                 break;
             }
         }
     }
     catch (Exception)
     {
         log.WarnFormat("Unable to parse DisplayConfig configuration");
     }
 }
コード例 #17
0
        public override object GetCustomAttribute(string attribute)
        {
            switch (attribute)
            {
            case "D3DDEVICE":
                return(driver.Device);

            case "HWND":
                return(windowHandle);

            case "isTexture":
                return(false);

            case "D3DZBUFFER":
                return(renderZBuffer);

            case "DDBACKBUFFER":
                return(renderSurface);

            case "DDFRONTBUFFER":
                return(renderSurface);
            }
            log.WarnFormat("There is no D3DRenderWindow custom attribute named {0}", attribute);
            return(null);
        }
コード例 #18
0
        public void Dispose()
        {
            if (this.disposed)
            {
                return;
            }

            lock (this.shuttingDownLock)
            {
                if (this.disposed)
                {
                    return;
                }

                this.disposed = true;
            }

            try
            {
                if (timer != null)
                {
                    timer.Dispose();
                    Logger.Info("shutdown scheduler");
                }
            }
            catch (Exception exc)
            {
                Logger.WarnFormat("Ignoring unexpected errors on closing", exc.FormatException());
            }
        }
コード例 #19
0
        public static void Warning(ILog log, string format, params object[] @params)
        {
            if (log == null)
            {
                return;
            }

            log.WarnFormat(format, @params);
        }
コード例 #20
0
        public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
        {
            if (args == null)
            {
                return;
            }
            if (0 == args.Length)
            {
                base.TraceEvent(eventCache, source, eventType, id, format, args);
            }


            if (string.IsNullOrWhiteSpace(source))
            {
                var frame = GetTracingStackFrame(new StackTrace());
                source = frame.GetMethod().DeclaringType.FullName;

                if (source == null)
                {
                    source = this.GetType().FullName;
                }
            }

            //_log = LogManager.GetLogger(source);
            switch (eventType)
            {
            case TraceEventType.Critical:
                _log.FatalFormat(format, args);
                break;

            case TraceEventType.Error:
                _log.ErrorFormat(format, args);
                break;

            case TraceEventType.Information:
                _log.InfoFormat(format, args);
                break;

            case TraceEventType.Resume:
            case TraceEventType.Start:
            case TraceEventType.Stop:
            case TraceEventType.Suspend:
            case TraceEventType.Transfer:
            case TraceEventType.Verbose:
                _log.DebugFormat(format, args);
                break;

            case TraceEventType.Warning:
                _log.WarnFormat(format, args);
                break;
            }
        }
コード例 #21
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            log.Warn("Hi There");
            log.WarnFormat("Hi There {0}", "Jeff");
            log.Warn(new { Hi = 2, Lo = "string", Complex = new { ComplicatedObject = true } });

            log.Error("Boom", GenerateException());
            log.Error(GenerateAggregateException());

            System.Console.ReadKey();
        }
コード例 #22
0
        private void HandleObjectPropertyHelper(long oid, Dictionary <string, object> props)
        {
            if (props.Count <= 0)
            {
                return;
            }
            ObjectNode node = worldManager.GetObjectNode(oid);

            if (node == null)
            {
                log.WarnFormat("Got stat update message for nonexistent object: {0}", oid);
                return;
            }
            node.UpdateProperties(props);
        }
コード例 #23
0
 public void CheckRetCode(FMOD.RESULT result)
 {
     if (result != FMOD.RESULT.OK)
     {
         if (result == FMOD.RESULT.ERR_INVALID_HANDLE)
         {
             log.WarnFormat("Invalid Sound Handle\n{0}", new StackTrace(true).ToString());
         }
         else
         {
             log.ErrorFormat("FMOD result: {0}\n{1}", FMOD.Error.String(result), new StackTrace(true).ToString());
             //throw new FMODException("Fmod error: ", result);
         }
     }
 }
コード例 #24
0
ファイル: Convoker.cs プロジェクト: andyhebear/DOLSharp
        /// <summary>
        /// Apply effect on target or do spell action if non duration spell
        /// </summary>
        /// <param name="target">target that gets the effect</param>
        /// <param name="effectiveness">factor from 0..1 (0%-100%)</param>
        public override void ApplyEffectOnTarget(GameLiving target, double effectiveness)
        {
            GamePlayer player = Caster as GamePlayer;

            if (player == null)
            {
                return;
            }

            INpcTemplate template = NpcTemplateMgr.GetTemplate(Spell.LifeDrainReturn);

            if (template == null)
            {
                if (log.IsWarnEnabled)
                {
                    log.WarnFormat("NPC template {0} not found! Spell: {1}", Spell.LifeDrainReturn, Spell.ToString());
                }
                MessageToCaster("NPC template " + Spell.LifeDrainReturn + " not found!", eChatType.CT_System);
                return;
            }
            GameSpellEffect effect          = CreateSpellEffect(target, effectiveness);
            TitanBrain      controlledBrain = new TitanBrain(player);

            controlledBrain.IsMainPet = false;
            controlledBrain.WalkState = eWalkState.Stay;
            summoned = new GameNPC(template);
            summoned.SetOwnBrain(controlledBrain);
            //Suncheck:
            //	Is needed, else it can cause error (i.e. /cast-command)
            if (x == 0 || y == 0)
            {
                CheckCastLocation();
            }
            summoned.X             = x;
            summoned.Y             = y;
            summoned.Z             = z;
            summoned.CurrentRegion = player.CurrentRegion;
            summoned.Heading       = (ushort)((player.Heading + 2048) % 4096);
            summoned.Realm         = player.Realm;
            summoned.CurrentSpeed  = 0;
            summoned.Size          = 10;
            summoned.Level         = 100;
            summoned.Flags        |= GameNPC.eFlags.PEACE;
            summoned.AddToWorld();
            controlledBrain.AggressionState = eAggressionState.Aggressive;
            effect.Start(summoned);
            m_growTimer = new RegionTimer((GameObject)m_caster, new RegionTimerCallback(TitanGrows), C_GROWTIMER);
        }
コード例 #25
0
 /// <summary>
 ///   Invoke a javascript method, using the browser control.
 /// </summary>
 /// <remarks>
 ///   This should only be called from the thread that created the
 ///   browser control
 /// </remarks>
 /// <param name="method"></param>
 /// <param name="args"></param>
 /// <returns></returns>
 public object InvokeScript(string method, IEnumerable <object> args)
 {
     object[] scriptingArgs = GetScriptingArgs(args);
     lock (this)
     {
         try
         {
             return(b.Document.InvokeScript(method, scriptingArgs));
         }
         catch (Exception e)
         {
             string formattedScriptCall = FormatScriptCall(method, scriptingArgs);
             log.WarnFormat("Failed to invoke script: {0} -- {1}", formattedScriptCall, e);
             throw;
         }
     }
 }
コード例 #26
0
ファイル: Convoker.cs プロジェクト: andyhebear/DOLSharp
        /// <summary>
        /// Apply effect on target or do spell action if non duration spell
        /// </summary>
        /// <param name="target">target that gets the effect</param>
        /// <param name="effectiveness">factor from 0..1 (0%-100%)</param>
        public override void ApplyEffectOnTarget(GameLiving target, double effectiveness)
        {
            GamePlayer player = Caster as GamePlayer;

            if (player == null)
            {
                return;
            }

            INpcTemplate template = NpcTemplateMgr.GetTemplate(Spell.LifeDrainReturn);

            if (template == null)
            {
                if (log.IsWarnEnabled)
                {
                    log.WarnFormat("NPC template {0} not found! Spell: {1}", Spell.LifeDrainReturn, Spell.ToString());
                }
                MessageToCaster("NPC template " + Spell.LifeDrainReturn + " not found!", eChatType.CT_System);
                return;
            }

            Point2D summonloc;

            beffect = CreateSpellEffect(target, effectiveness);
            {
                summonloc = target.GetPointFromHeading(target.Heading, 64);

                BrittleBrain controlledBrain = new BrittleBrain(player);
                controlledBrain.IsMainPet = false;
                summoned = new GameNPC(template);
                summoned.SetOwnBrain(controlledBrain);
                summoned.X             = summonloc.X;
                summoned.Y             = summonloc.Y;
                summoned.Z             = target.Z;
                summoned.CurrentRegion = target.CurrentRegion;
                summoned.Heading       = (ushort)((target.Heading + 2048) % 4096);
                summoned.Realm         = target.Realm;
                summoned.CurrentSpeed  = 0;
                summoned.Level         = 1;
                summoned.Size          = 10;
                summoned.AddToWorld();
                controlledBrain.AggressionState = eAggressionState.Passive;
                GameEventMgr.AddHandler(summoned, GameLivingEvent.Dying, new DOLEventHandler(GuardDie));
                beffect.Start(Caster);
            }
        }
コード例 #27
0
 public static void Enter(object lockable)
 {
     if (!System.Threading.Monitor.TryEnter(lockable, 3000))
     {
         try {
             System.Threading.Monitor.Enter(lockHolders);
             log.WarnFormat("Failed to acquire lock on {0} from {1}", lockable.GetHashCode(), new StackTrace(true));
             foreach (object key in lockHolders.Keys)
             {
                 log.InfoFormat("Lock on {0} held by: {1}", key, lockHolders[key]);
             }
             throw new Exception("ACK!");
         } finally {
             System.Threading.Monitor.Exit(lockHolders);
         }
     }
     try {
         System.Threading.Monitor.Enter(lockHolders);
         lockHolders[lockable.GetHashCode()] = new StackTrace(true);
     } finally {
         System.Threading.Monitor.Exit(lockHolders);
     }
 }
コード例 #28
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="executionPath">Path to the emulator</param>
        /// <param name="executionArgs">Arguments to the emulator with replacement variables</param>
        /// <param name="argReplacements">String of the form "$VAR=val;$VAR2=val", will be inserted into execution args</param>
        public Command(String executionPath, String executionArgs = "", String argReplacements = null)
        {
            mLogger = LogManager.GetLogger(GetType().Name);

            if (!String.IsNullOrEmpty(argReplacements))
            {
                if (argReplacements.Contains("<") && argReplacements.Contains(";") && argReplacements.Contains(">"))
                {
                    ExecutionArguments = HandleArgumentReplacements(executionArgs, argReplacements);
                }
                else
                {
                    mLogger.WarnFormat("Replacement argument string was not in the correct format! Required format: \"<VAR>=VAL;<VAR2>=VAL2;etc\". Supplied replacement string was {0}", argReplacements);
                    ExecutionArguments = executionArgs;
                }
            }
            else
            {
                ExecutionArguments = executionArgs;
            }

            ExecutionPath = executionPath;
            IsValidCommand = true;
        }
コード例 #29
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 };
        }
コード例 #30
0
ファイル: Log.cs プロジェクト: zevinganez/code-o-matic
 /// <summary>
 /// Logs a formatted message string with the <see cref="F:log4net.Core.Level.Warn"/> 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.Warn(System.Object,System.Exception)"/>
 /// methods instead.
 /// </para>
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Warn(System.Object)"/>
 /// <seealso cref="P:log4net.ILog.IsWarnEnabled"/>
 public static void WarnFormat(string format, object arg0, ILog log)
 {
     log.WarnFormat(format, arg0);
 }
コード例 #31
0
ファイル: Log.cs プロジェクト: zevinganez/code-o-matic
 /// <summary>
 /// Logs a formatted message string with the <see cref="F:log4net.Core.Level.Warn"/> 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.Warn(System.Object)"/>
 /// methods instead.
 /// </para>
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Warn(System.Object,System.Exception)"/>
 /// <seealso cref="P:log4net.ILog.IsWarnEnabled"/>
 public static void WarnFormat(IFormatProvider provider, string format, object[] args, ILog log)
 {
     log.WarnFormat(provider, format, args);
 }
コード例 #32
0
 public void WarnFormat(string format, params object[] args)
 {
     _logger.WarnFormat(format, args);
 }
コード例 #33
0
ファイル: Log.cs プロジェクト: zevinganez/code-o-matic
 /// <summary>
 /// Logs a formatted message string with the <see cref="F:log4net.Core.Level.Warn"/> 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 message string with the <see cref="F:log4net.Core.Level.Warn"/> 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.Warn(System.Object)"/>
 /// methods instead.
 /// </para>
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Warn(System.Object,System.Exception)"/>
 /// <seealso cref="P:log4net.ILog.IsWarnEnabled"/>
 public static void WarnFormat(string format, object[] args, ILog log)
 {
     log.WarnFormat(CultureInfo.InvariantCulture, format, args);
 }
コード例 #34
0
 public void WarnFormat(System.IFormatProvider provider, string format, params object[] args)
 {
     _logger.WarnFormat(provider, format, args);
 }
コード例 #35
0
        /// <summary>
        /// Perform sync of users from Google Calendar to Exchnage until there are no more
        /// users to sync. This can be called from a worker thread.
        /// </summary>
        public void SyncUsers()
        {
            ExchangeUser user;
            int          userCount = 0;
            string       login     = string.Empty;

            errorThreshold = ConfigCache.ServiceErrorCountThreshold;
            errorCount     = 0;

            while (exchangeUsers.Count > 0)
            {
                lock ( lockObject )
                {
                    if (exchangeUsers.Count == 0)
                    {
                        break;
                    }
                    else
                    {
                        user = exchangeUsers[0];
                        exchangeUsers.RemoveAt(0);
                    }
                }

                try
                {
                    userCount++;

                    login = user.Email.ToLower();

                    DateTime modifiedDate = modifiedDateUtil.GetModifiedDateForUser(login);
                    DateTime currentDate  = DateUtil.NowUtc;

                    // Pick a window to synchronize for:
                    //
                    // [-N, +2N] days where N is settable in the config file
                    //
                    // Scanning back in time is necessary so that we pickup changes to meetings and events that were
                    // made invisible.
                    //
                    // TODO: The window we're syncing for should also be used when we modify events in Exchange
                    // so we only modify events in the window.

                    DateTime      start      = currentDate.AddDays(-ConfigCache.GCalSyncWindow);
                    DateTime      end        = currentDate.AddDays(2 * ConfigCache.GCalSyncWindow);
                    DateTimeRange syncWindow = new DateTimeRange(start, end);

                    log.InfoFormat("Processing user {0} for {1}", login, syncWindow);

                    EventFeed feed = gcalGateway.QueryGCal(
                        user.Email,
                        GCalVisibility.Private,
                        ConfigCache.FreeBusyDetailLevel,
                        modifiedDate,
                        syncWindow);

                    // if feed is null, then that means no calendar items changed for the user since we last queried.
                    if (feed == null)
                    {
                        log.DebugFormat(
                            "Calendar has not changed for user {0}.  User will not be synced this round.",
                            login);

                        continue;
                    }

                    if (!ValidateFeed(feed))
                    {
                        /* No Google App Feed was returned,  skip to next user */
                        log.WarnFormat(
                            "GCal feed could not be read for '{0}'.  This user may not have activated their account or may be inactive." +
                            "For resources the admin must share their calendars for the domain and set correctly the timezone.",
                            login);

                        continue;
                    }

                    log.InfoFormat("Calendar Query returned {0} events", feed.Entries.Count);

                    using (BlockTimer freeBusyTimer = new BlockTimer("WriteFreeBusy"))
                    {
                        /* User and feed retrieval was succesful, merge the two datasources down into Exchange */
                        freeBusyWriter.SyncUser(user, feed, exchangeGateway, syncWindow);
                    }

                    // Only update the modified time if we sync'd
                    modifiedDateUtil.UpdateUserModifiedTime(login, currentDate);
                }
                catch (Exception ex)
                {
                    Interlocked.Increment(ref errorCount);

                    log.Error(string.Format(
                                  "Error occured while executing sync process for user '{0}'. [running error count={1}]", login, errorCount),
                              ex);
                }

                if (errorCount > errorThreshold)
                {
                    throw new GCalExchangeException(
                              GCalExchangeErrorCode.GenericError,
                              "Error threshold has been surpassed, aborting sync process.");
                }
            }

            log.InfoFormat("User synchronization complete.  {0} users processed.", userCount);
        }
コード例 #36
0
ファイル: Logger.cs プロジェクト: camalot/droidexplorer
 /// <summary>
 /// Logs the warning.
 /// </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 LogWarning( Type type, IFormatProvider provider, string format, params object[] args )
 {
     Log = LogManager.GetLogger ( type );
     Log.WarnFormat ( provider, format, args );
 }
コード例 #37
0
        private void RestartApplication(DeploymentContext context, ILog logger)
        {
            string virtualDirectoryPath = null;
            string[] websitePath = context.Package.Title.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
            if (websitePath.Length > 1)
            {
                virtualDirectoryPath = string.Join("/", websitePath.Skip(1).ToArray());
            }
            using (var website = FindVirtualDirectory("localhost", websitePath[0], virtualDirectoryPath))
            {
                if (website == null)
                {
                    logger.WarnFormat("No such IIS website found: '{0}'", context.Package.Id);
                }
                var appPoolId = website.Properties["AppPoolId"].Value;

                using (var applicationPool = new DirectoryEntry("IIS://localhost/W3SVC/AppPools/" + appPoolId))
                {
                    logger.InfoFormat("Stopping AppPool {0}...", appPoolId);
                    applicationPool.Invoke("Stop");
                    logger.InfoFormat("Starting AppPool {0}...", appPoolId);
                    applicationPool.Invoke("Start");
                }
            }
        }
コード例 #38
0
ファイル: Log.cs プロジェクト: kreyraria/Orion
 public void Warn(string format, params object[] args)
 {
     _fileLog.WarnFormat(format, args);
 }