Beispiel #1
0
 public SButton(String label)
 {
   Content = label;
   EventSink<Unit> eClickedSink = new EventSink<Unit>();
   EClicked = eClickedSink;
   Click += (sender, args) => { eClickedSink.Send(Unit.UNIT); };
 }
Beispiel #2
0
 public void TestMergeLeftBias()
 {
   var e1 = new EventSink<string>();
   var e2 = new EventSink<string>();
   var @out = new List<string>();
   Listener l = Event<string>.Merge(e1, e2).Listen(x => { @out.Add(x); });
   Transaction.RunVoid(() =>
   {
     e1.Send("left1a");
     e1.Send("left1b");
     e2.Send("right1a");
     e2.Send("right1b");
   });
   Transaction.RunVoid(() =>
   {
     e2.Send("right2a");
     e2.Send("right2b");
     e1.Send("left2a");
     e1.Send("left2b");
   });
   l.Unlisten();
   CollectionAssert.AreEqual(new[]{
           "left1a", "left1b",
           "right1a", "right1b",
           "left2a", "left2b",
           "right2a", "right2b"
       }, @out);
 }
		public void SetUp()
		{
			_span = new NuGenCountDownSpan(1, 3);
			_timer = new StubTimer();
			_timer.Interval = 1;
			_countDownBlock = new NuGenCountDownBlock(_span, _timer);
			_eventSink = new EventSink(_countDownBlock);
		}
Beispiel #4
0
 public void TestMergeSimultaneous()
 {
   var e = new EventSink<int>();
   var @out = new List<int>();
   Listener l = Event<int>.Merge(e, e).Listen(x => { @out.Add(x); });
   e.Send(7);
   e.Send(9);
   l.Unlisten();
   CollectionAssert.AreEqual(new[] { 7, 7, 9, 9 }, @out);
 }
Beispiel #5
0
 public void TestMap()
 {
   var e = new EventSink<int>();
   Event<String> m = e.Map(x => x.ToString());
   var @out = new List<string>();
   Listener l = m.Listen(x => { @out.Add(x); });
   e.Send(5);
   l.Unlisten();
   CollectionAssert.AreEqual(new[] { "5" }, @out);
 }
 public void TestHold()
 {
   var e = new EventSink<int>();
   Behavior<int> b = e.Hold(0);
   var @out = new List<int>();
   Listener l = b.Updates().Listen(new Handler<int> { Run = x => @out.Add(x) });
   e.Send(2);
   e.Send(9);
   l.Unlisten();
   CollectionAssert.AreEqual(new[] { 2, 9 }, @out.Select(x => (int)x));
 }
 public static void Init()
 {
     var eventSink = new EventSink
         {
             Action = _ => LastMessage = _
         };
     Log.Logger = new LoggerConfiguration()
         .MinimumLevel.Verbose()
         .WriteTo.Sink(eventSink)
         .CreateLogger();
 }
 static ClassWithStaticConstructor()
 {
     var eventSink = new EventSink
         {
             Action = LogEvent
         };
     var log = new LoggerConfiguration()
         .WriteTo.Sink(eventSink)
         .CreateLogger();
     Log.Logger = log;
 }
Beispiel #9
0
 public void TestSendEvent()
 {
   var e = new EventSink<int>();
   var @out = new List<int>();
   Listener l = e.Listen(x => { @out.Add(x); });
   e.Send(5);
   l.Unlisten();
   CollectionAssert.AreEqual(new[] { 5 }, @out);
   e.Send(6);
   CollectionAssert.AreEqual(new[] { 5 }, @out);
 }
Beispiel #10
0
 public void TestMergeNonSimultaneous()
 {
   var e1 = new EventSink<int>();
   var e2 = new EventSink<int>();
   var @out = new List<int>();
   Listener l = Event<int>.Merge(e1, e2).Listen(x => { @out.Add(x); });
   e1.Send(7);
   e2.Send(9);
   e1.Send(8);
   l.Unlisten();
   CollectionAssert.AreEqual(new[] { 7, 9, 8 }, @out);
 }
		public void SetUp()
		{
			_spin = new StubSpin();
			_eventSink = new EventSink(_spin);

			_item = "item";
			_item2 = "item2";
			_item3 = "item3";
			_item4 = "item4";
			_item5 = "item5";

			_spin.Items.AddRange(new string[] { _item, _item2, _item3, _item4, _item5 });
		}
Beispiel #12
0
        partial void InitializeParseDictionaries()
        {
            m_customEventSink = new EventSink(this);

            m_packetToParserMap = new Dictionary<BncsPacketId, ParseCallback>()
            {
                { BncsPacketId.EnterChat, HandleEnterChat },
                { BncsPacketId.GetChannelList, HandleGetChannelList },
                { BncsPacketId.ChatEvent, HandleChatEvent },
                { BncsPacketId.CheckAd, HandleCheckAd },
                { BncsPacketId.Ping, HandlePing },
                { BncsPacketId.ReadUserData, HandleUserProfileRequest },
                { BncsPacketId.LogonResponse, HandleLogonResponse },
                { BncsPacketId.Profile, HandleProfile },
                { BncsPacketId.LogonResponse2, HandleLogonResponse2 },
                { BncsPacketId.CreateAccount2, HandleCreateAccount2 },
                { BncsPacketId.WarcraftGeneral, HandleWarcraftGeneral },
                { BncsPacketId.NewsInfo, HandleNewsInfo },
                { BncsPacketId.AuthInfo, HandleAuthInfo },
                { BncsPacketId.AuthCheck, HandleAuthCheck },
                { BncsPacketId.AuthAccountCreate, HandleAuthAccountCreate },
                { BncsPacketId.AuthAccountLogon, HandleAuthAccountLogon },
                { BncsPacketId.AuthAccountLogonProof, HandleAuthAccountLogonProof },
                { BncsPacketId.AuthAccountChange, HandleAuthAccountChange },
                { BncsPacketId.AuthAccountChangeProof, HandleAuthAccountChangeProof },
                { BncsPacketId.Warden, HandleWarden },
                { BncsPacketId.FriendsList, HandleFriendsList },
                { BncsPacketId.FriendsAdd, HandleFriendAdded },
                { BncsPacketId.FriendsUpdate, HandleFriendUpdate },
                { BncsPacketId.FriendsRemove, HandleFriendRemoved },
                { BncsPacketId.FriendsPosition, HandleFriendMoved },
                { BncsPacketId.ClanFindCandidates, HandleClanFindCandidates },
                { BncsPacketId.ClanInviteMultiple, HandleClanInviteMultiple },
                { BncsPacketId.ClanCreationInvitation, HandleClanCreationInvitation },
                { BncsPacketId.ClanDisband, HandleDisbandClan },
                { BncsPacketId.ClanMakeChieftan, HandleClanMakeChieftan },
                { BncsPacketId.ClanInfo, HandleClanInfo },
                { BncsPacketId.ClanQuitNotify, HandleClanQuitNotify },
                { BncsPacketId.ClanInvitation, HandleClanInvitation },
                { BncsPacketId.ClanRemoveMember, HandleClanRemoveMember },
                { BncsPacketId.ClanInvitationResponse, HandleClanInvitationResponse },
                { BncsPacketId.ClanRankChange, HandleClanRankChange },
                { BncsPacketId.ClanMOTD, HandleClanMotd },
                { BncsPacketId.ClanMemberList, HandleClanMemberList },
                { BncsPacketId.ClanMemberRemoved, HandleClanMemberRemoved },
                { BncsPacketId.ClanMemberStatusChanged, HandleClanMemberStatusChanged },
                { BncsPacketId.ClanMemberRankChange, HandleClanMemberRankChange },
                { BncsPacketId.ClanMemberInformation, HandleClanMemberInformation }
            };
        }
        public void SubscribedEventIsActedOn()
        {
            var sink = new EventSink();
            var mockListener = new Mock<IEventListener>();
            mockListener.Setup(l=>l.OnGenericEvent()).Verifiable();

            EventManager.SubscribeTo<IEventListener, EventArgs>(
                h => sink.GenericEvent += h,
                h => sink.GenericEvent -= h,
                mockListener.Object,
                (l,args)=>l.OnGenericEvent()
            );

            sink.OnGenericEvent(EventArgs.Empty);
            mockListener.Verify(l=>l.OnGenericEvent(), Times.Once());
        }
 public void TestSnapshot()
 {
   var b = new BehaviorSink<int>(0);
   var trigger = new EventSink<long>();
   var @out = new List<string>();
   var l = trigger.Snapshot(b, (x, y) => x + " " + y)
       .Listen(new Handler<string> { Run = x => @out.Add(x) });
   trigger.Send(100L);
   b.Send(2);
   trigger.Send(200L);
   b.Send(9);
   b.Send(1);
   trigger.Send(300L);
   l.Unlisten();
   CollectionAssert.AreEqual(new[] { "100 0", "200 2", "300 1" }, @out);
 }
        public void SubscripingToEventDoesNotKeepItAlive()
        {
            var sink = new EventSink();
            var mockListener = new Mock<IEventListener>();
            mockListener.Setup(l => l.OnGenericEvent()).Verifiable();

            EventManager.SubscribeTo<IEventListener, EventArgs>(
                h => sink.GenericEvent += h,
                h => sink.GenericEvent -= h,
                mockListener.Object,
                (l, args) => l.OnGenericEvent()
            );

            var weakReference = new WeakReference(sink);
            sink = null;
            GC.Collect();
            weakReference.ShouldHave().Properties(x=>x.IsAlive).EqualTo(new{IsAlive=false});
        }
Beispiel #16
0
    public void Setup()
    {
        var eventSink = new EventSink
            {
                Action = LogEvent
            };

        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .WriteTo.Sink(eventSink)
            .CreateLogger();

        errors = new List<LogEvent>();
        fatals = new List<LogEvent>();
        debugs = new List<LogEvent>();
        infos = new List<LogEvent>();
        warns = new List<LogEvent>();
    }
        public void DisposingOfSubscriptionUnregistersEvent()
        {
            var sink = new EventSink();
            var mockListener = new Mock<IEventListener>();
            mockListener.Setup(l => l.OnGenericEvent()).Verifiable();

            using(EventManager.SubscribeTo<IEventListener, EventArgs>(
                h => sink.GenericEvent += h,
                h => sink.GenericEvent -= h,
                mockListener.Object,
                (l, args) => l.OnGenericEvent()
            )) {
                sink.OnGenericEvent(EventArgs.Empty);
                sink.OnGenericEvent(EventArgs.Empty);
            }

            sink.OnGenericEvent(EventArgs.Empty);
            mockListener.Verify(l => l.OnGenericEvent(), Times.Exactly(2));
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            RemotingConfiguration.Configure("Client.exe.config");

             EventSink sink = new EventSink();

             RemoteObject obj = new RemoteObject();

             // register client sink in server - subscribe to event
             obj.Status += new StatusEvent(sink.StatusHandler);

             obj.LongWorking(5000);

             // unsubscribe to event
             obj.Status -= new StatusEvent(sink.StatusHandler);

             obj.LongWorking(5000);

             Console.WriteLine("Hit to exit");
             Console.ReadLine();
        }
 public void TestLoopValueHold()
 {
   var @out = new List<string>();
   Behavior<String> value = Transaction.Run(() =>
   {
     var a = new BehaviorLoop<string>();
     Behavior<String> value_ = a.Value().Hold("onion");
     a.Loop(new Behavior<String>("cheese"));
     return value_;
   });
   var eTick = new EventSink<string>();
   Listener l = eTick.Snapshot(value).Listen(x => { @out.Add(x); });
   eTick.Send(UnitEnum.Unit);
   l.Unlisten();
   CollectionAssert.AreEqual(new[] { "cheese" }, @out);
 }
Beispiel #20
0
            protected override void OnTarget(Mobile from, object targeted)
            {
                EventSink.InvokeSkillUsed(new SkillUsedEventArgs(from, from.Skills[SkillName.Peacemaking]));

                from.RevealingAction();

                if (!(targeted is Mobile))
                {
                    from.SendLocalizedMessage(1049528); // You cannot calm that!
                }
                else if (!m_Instrument.IsChildOf(from.Backpack))
                {
                    from.SendLocalizedMessage(1062488); // The instrument you are trying to play is no longer in your backpack!
                }
                else
                {
                    m_SetSkillTime     = false;
                    from.NextSkillTime = DateTime.Now + TimeSpan.FromSeconds(10.0);

                    if (targeted == from)
                    {
                        // Standard mode : reset combatants for everyone in the area

                        if (!BaseInstrument.CheckMusicianship(from))
                        {
                            from.SendLocalizedMessage(500612); // You play poorly, and there is no effect.
                            m_Instrument.PlayInstrumentBadly(from);
                            m_Instrument.ConsumeUse(from);
                        }
                        else if (!from.CheckSkill(SkillName.Peacemaking, 0.0, 120.0))
                        {
                            from.SendLocalizedMessage(500613); // You attempt to calm everyone, but fail.
                            m_Instrument.PlayInstrumentBadly(from);
                            m_Instrument.ConsumeUse(from);
                        }
                        else
                        {
                            from.NextSkillTime = DateTime.Now + TimeSpan.FromSeconds(5.0);
                            m_Instrument.PlayInstrumentWell(from);
                            m_Instrument.ConsumeUse(from);

                            Map map = from.Map;

                            if (map != null)
                            {
                                int range = BaseInstrument.GetBardRange(from, SkillName.Peacemaking);

                                bool calmed = false;

                                foreach (Mobile m in from.GetMobilesInRange(range))
                                {
                                    if ((m is BaseCreature && ((BaseCreature)m).Uncalmable) || (m is BaseCreature && ((BaseCreature)m).AreaPeaceImmune) || m == from || !from.CanBeHarmful(m, false))
                                    {
                                        continue;
                                    }

                                    calmed = true;

                                    m.SendLocalizedMessage(500616); // You hear lovely music, and forget to continue battling!
                                    m.Combatant = null;
                                    m.Warmode   = false;

                                    if (m is BaseCreature && !((BaseCreature)m).BardPacified)
                                    {
                                        ((BaseCreature)m).Pacify(from, DateTime.Now + TimeSpan.FromSeconds(1.0));
                                    }
                                }

                                if (!calmed)
                                {
                                    from.SendLocalizedMessage(1049648); // You play hypnotic music, but there is nothing in range for you to calm.
                                }
                                else
                                {
                                    from.SendLocalizedMessage(500615); // You play your hypnotic music, stopping the battle.
                                }
                            }
                        }
                    }
                    else
                    {
                        // Target mode : pacify a single target for a longer duration

                        Mobile targ = (Mobile)targeted;

                        if (!from.CanBeHarmful(targ, false))
                        {
                            from.SendLocalizedMessage(1049528);
                            m_SetSkillTime = true;
                        }
                        else if (targ is BaseCreature && ((BaseCreature)targ).Uncalmable)
                        {
                            from.SendLocalizedMessage(1049526); // You have no chance of calming that creature.
                            m_SetSkillTime = true;
                        }
                        else if (targ is BaseCreature && ((BaseCreature)targ).BardPacified)
                        {
                            from.SendLocalizedMessage(1049527); // That creature is already being calmed.
                            m_SetSkillTime = true;
                        }
                        else if (!BaseInstrument.CheckMusicianship(from))
                        {
                            from.SendLocalizedMessage(500612); // You play poorly, and there is no effect.
                            from.NextSkillTime = DateTime.Now + TimeSpan.FromSeconds(5.0);
                            m_Instrument.PlayInstrumentBadly(from);
                            m_Instrument.ConsumeUse(from);
                        }
                        else
                        {
                            double diff  = m_Instrument.GetDifficultyFor(targ) - 10.0;
                            double music = from.Skills[SkillName.Musicianship].Value;

                            if (music > 100.0)
                            {
                                diff -= (music - 100.0) * 0.5;
                            }

                            if (!from.CheckTargetSkill(SkillName.Peacemaking, targ, diff - 25.0, diff + 25.0))
                            {
                                from.SendLocalizedMessage(1049531); // You attempt to calm your target, but fail.
                                m_Instrument.PlayInstrumentBadly(from);
                                m_Instrument.ConsumeUse(from);
                            }
                            else
                            {
                                m_Instrument.PlayInstrumentWell(from);
                                m_Instrument.ConsumeUse(from);

                                from.NextSkillTime = DateTime.Now + TimeSpan.FromSeconds(5.0);
                                if (targ is BaseCreature)
                                {
                                    BaseCreature bc = (BaseCreature)targ;

                                    from.SendLocalizedMessage(1049532); // You play hypnotic music, calming your target.

                                    targ.Combatant = null;
                                    targ.Warmode   = false;

                                    double seconds = 100 - (diff / 1.5);

                                    if (seconds > 120)
                                    {
                                        seconds = 120;
                                    }
                                    else if (seconds < 10)
                                    {
                                        seconds = 10;
                                    }

                                    bc.Pacify(from, DateTime.Now + TimeSpan.FromSeconds(seconds));
                                }
                                else
                                {
                                    from.SendLocalizedMessage(1049532); // You play hypnotic music, calming your target.

                                    targ.SendLocalizedMessage(500616);  // You hear lovely music, and forget to continue battling!
                                    targ.Combatant = null;
                                    targ.Warmode   = false;
                                }
                            }
                        }
                    }
                }
            }
Beispiel #21
0
    static async Task <IEnumerable <LogEventEx> > Send(object message, Action <SendOptions>?optionsAction = null)
    {
        var logs      = new List <LogEvent>();
        var eventSink = new EventSink
                        (
            action: logs.Add
                        );

        var loggerConfiguration = new LoggerConfiguration();

        loggerConfiguration.Enrich.WithExceptionDetails();
        loggerConfiguration.MinimumLevel.Verbose();
        loggerConfiguration.WriteTo.Sink(eventSink);
        Log.Logger = loggerConfiguration.CreateLogger();
        LogManager.Use <SerilogFactory>();

        var configuration  = ConfigBuilder.BuildDefaultConfig("SerilogTests" + message.GetType().Name);
        var serilogTracing = configuration.EnableSerilogTracing();

        serilogTracing.EnableSagaTracing();
        serilogTracing.EnableMessageTracing();
        var resetEvent = new ManualResetEvent(false);

        configuration.RegisterComponents(components => components.RegisterSingleton(resetEvent));

        var recoverability = configuration.Recoverability();

        recoverability.Delayed(settings =>
        {
            settings.TimeIncrease(TimeSpan.FromMilliseconds(1));
            settings.NumberOfRetries(1);
        });
        recoverability.Immediate(settings => { settings.NumberOfRetries(1); });

        configuration.Notifications.Errors.MessageSentToErrorQueue +=
            (sender, retry) => { resetEvent.Set(); };

        var endpoint = await Endpoint.Start(configuration);

        var sendOptions = new SendOptions();

        optionsAction?.Invoke(sendOptions);
        sendOptions.SetMessageId("00000000-0000-0000-0000-000000000001");
        sendOptions.RouteToThisEndpoint();
        await endpoint.Send(message, sendOptions);

        if (!resetEvent.WaitOne(TimeSpan.FromSeconds(5)))
        {
            throw new Exception("No Set received.");
        }

        await endpoint.Stop();

        Log.CloseAndFlush();

        return(logs.Select(x =>
                           new LogEventEx
                           (
                               messageTemplate: x.MessageTemplate,
                               level: x.Level,
                               properties: x.Properties,
                               exception: x.Exception
                           )));
    }
Beispiel #22
0
        public override bool DoActionCombat()
        {
            Mobile c = this.m_Mobile.Combatant;

            this.m_Mobile.Warmode = true;

            if (c == null || c.Deleted || !c.Alive || c.IsDeadBondedPet || !this.m_Mobile.CanSee(c) || !this.m_Mobile.CanBeHarmful(c, false) || c.Map != this.m_Mobile.Map)
            {
                // Our combatant is deleted, dead, hidden, or we cannot hurt them
                // Try to find another combatant
                if (this.AcquireFocusMob(this.m_Mobile.RangePerception, this.m_Mobile.FightMode, false, false, true))
                {
                    if (this.m_Mobile.Debug)
                    {
                        this.m_Mobile.DebugSay("Something happened to my combatant, so I am going to fight {0}", this.m_Mobile.FocusMob.Name);
                    }

                    this.m_Mobile.Combatant = c = this.m_Mobile.FocusMob;
                    this.m_Mobile.FocusMob  = null;
                }
                else
                {
                    this.m_Mobile.DebugSay("Something happened to my combatant, and nothing is around. I am on guard.");
                    this.Action = ActionType.Guard;
                    return(true);
                }
            }

            if (!this.m_Mobile.InLOS(c))
            {
                if (this.AcquireFocusMob(this.m_Mobile.RangePerception, this.m_Mobile.FightMode, false, false, true))
                {
                    this.m_Mobile.Combatant = c = this.m_Mobile.FocusMob;
                    this.m_Mobile.FocusMob  = null;
                }
            }

            if (!this.m_Mobile.StunReady && this.m_Mobile.Skills[SkillName.Wrestling].Value >= 80.0 && this.m_Mobile.Skills[SkillName.Anatomy].Value >= 80.0)
            {
                EventSink.InvokeStunRequest(new StunRequestEventArgs(this.m_Mobile));
            }

            if (!this.m_Mobile.InRange(c, this.m_Mobile.RangePerception))
            {
                // They are somewhat far away, can we find something else?
                if (this.AcquireFocusMob(this.m_Mobile.RangePerception, this.m_Mobile.FightMode, false, false, true))
                {
                    this.m_Mobile.Combatant = this.m_Mobile.FocusMob;
                    this.m_Mobile.FocusMob  = null;
                }
                else if (!this.m_Mobile.InRange(c, this.m_Mobile.RangePerception * 3))
                {
                    this.m_Mobile.Combatant = null;
                }

                c = this.m_Mobile.Combatant;

                if (c == null)
                {
                    this.m_Mobile.DebugSay("My combatant has fled, so I am on guard");
                    this.Action = ActionType.Guard;

                    return(true);
                }
            }

            if (!this.m_Mobile.Controlled && !this.m_Mobile.Summoned && !this.m_Mobile.IsParagon)
            {
                if (this.m_Mobile.Hits < this.m_Mobile.HitsMax * 20 / 100)
                {
                    // We are low on health, should we flee?
                    bool flee = false;

                    if (this.m_Mobile.Hits < c.Hits)
                    {
                        // We are more hurt than them
                        int diff = c.Hits - this.m_Mobile.Hits;

                        flee = (Utility.Random(0, 100) > (10 + diff)); // (10 + diff)% chance to flee
                    }
                    else
                    {
                        flee = Utility.Random(0, 100) > 10; // 10% chance to flee
                    }

                    if (flee)
                    {
                        if (this.m_Mobile.Debug)
                        {
                            this.m_Mobile.DebugSay("I am going to flee from {0}", c.Name);
                        }

                        this.Action = ActionType.Flee;
                        return(true);
                    }
                }
            }

            if (this.m_Mobile.Spell == null && DateTime.Now > this.m_NextCastTime && this.m_Mobile.InRange(c, 12))
            {
                // We are ready to cast a spell
                Spell  spell    = null;
                Mobile toDispel = this.FindDispelTarget(true);

                if (this.m_Mobile.Poisoned) // Top cast priority is cure
                {
                    this.m_Mobile.DebugSay("I am going to cure myself");

                    spell = new CureSpell(this.m_Mobile, null);
                }
                else if (toDispel != null) // Something dispellable is attacking us
                {
                    this.m_Mobile.DebugSay("I am going to dispel {0}", toDispel);

                    spell = this.DoDispel(toDispel);
                }
                else if (this.m_Combo != -1) // We are doing a spell combo
                {
                    spell = this.DoCombo(c);
                }
                else if ((c.Spell is HealSpell || c.Spell is GreaterHealSpell) && !c.Poisoned) // They have a heal spell out
                {
                    spell = new PoisonSpell(this.m_Mobile, null);
                }
                else
                {
                    spell = this.ChooseSpell(c);
                }

                // Now we have a spell picked
                // Move first before casting

                if (toDispel != null)
                {
                    if (this.m_Mobile.InRange(toDispel, 10))
                    {
                        this.RunFrom(toDispel);
                    }
                    else if (!this.m_Mobile.InRange(toDispel, 12))
                    {
                        this.RunTo(toDispel);
                    }
                }
                else
                {
                    this.RunTo(c);
                }

                if (spell != null)
                {
                    spell.Cast();
                }

                TimeSpan delay;

                if (spell is DispelSpell)
                {
                    delay = TimeSpan.FromSeconds(this.m_Mobile.ActiveSpeed);
                }
                else
                {
                    delay = this.GetDelay();
                }

                this.m_NextCastTime = DateTime.Now + delay;
            }
            else if (this.m_Mobile.Spell == null || !this.m_Mobile.Spell.IsCasting)
            {
                this.RunTo(c);
            }

            return(true);
        }
Beispiel #23
0
 void link_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
 {
     Context.InvokeUserCode(delegate {
         EventSink.OnLinkClicked(e.Uri);
     });
 }
Beispiel #24
0
 private void OnBehaviorInit(Interop.IElementBehaviorSite behaviorSite)
 {
     this._behaviorSite = behaviorSite;
     this._paintSite = (Interop.IHTMLPaintSite) this._behaviorSite;
     this._element = this._behaviorSite.GetElement();
     behaviorSite.RegisterNotification(0);
     behaviorSite.RegisterNotification(3);
     behaviorSite.RegisterNotification(4);
     this._eventSink = new EventSink(this);
 }
Beispiel #25
0
 void HandleLeaveNotifyEvent(object o, Gtk.LeaveNotifyEventArgs args)
 {
     Toolkit.Invoke(delegate {
         EventSink.OnMouseExited();
     });
 }
 public GpioPinEventListener()
 {
     EventSink.AddEventProcessor(EventCategory.Gpio, this);
     EventSink.AddEventListener(EventCategory.Gpio, this);
 }
Beispiel #27
0
        protected override Size GetNaturalSize()
        {
            var s = base.GetNaturalSize();

            return(new Size(EventSink.GetDefaultNaturalSize().Width, s.Height));
        }
Beispiel #28
0
 public void OnNotification(Notification notification, object handback)
 {
     EventSink.Push(new TargetedNotificationType(notification, ListenerId));
 }
 public void SetUp()
 {
     _combo     = new StubInt32Combo();
     _eventSink = new EventSink(_combo);
 }
Beispiel #30
0
        public override void OnDoubleClick(Mobile from)
        {
            if (!IsChildOf(from.Backpack))
            {
                from.SendLocalizedMessage(1042001); // That must be in your pack for you to use it.
            }
            else if (from.AccessLevel >= AccessLevel.GameMaster)
            {
                from.SendLocalizedMessage(503248); // Your godly powers allow you to place this vendor whereever you wish.

                Mobile v = new CommissionPlayerVendor(from, BaseHouse.FindHouseAt(from))
                {
                    Direction = from.Direction & Direction.Mask
                };
                v.MoveToWorld(from.Location, from.Map);

                v.SayTo(from, 503246); // Ah! it feels good to be working again.

                EventSink.InvokePlacePlayerVendor(new PlacePlayerVendorEventArgs(from, v));

                Delete();
            }
            else
            {
                BaseHouse house = BaseHouse.FindHouseAt(from);

                if (house == null)
                {
                    from.SendLocalizedMessage(503240); // Vendors can only be placed in houses.
                }
                else if (!BaseHouse.NewVendorSystem && !house.IsFriend(from))
                {
                    from.SendLocalizedMessage(503242); // You must ask the owner of this building to name you a friend of the household in order to place a vendor here.
                }
                else if (BaseHouse.NewVendorSystem && !house.IsOwner(from))
                {
                    from.SendLocalizedMessage(1062423); // Only the house owner can directly place vendors.  Please ask the house owner to offer you a vendor contract so that you may place a vendor in this house.
                }
                else if (!house.Public || !house.CanPlaceNewVendor())
                {
                    from.SendLocalizedMessage(503241); // You cannot place this vendor or barkeep.  Make sure the house is public and has sufficient storage available.
                }
                else
                {
                    BaseHouse.IsThereVendor(from.Location, from.Map, out bool vendor, out bool contract);

                    if (vendor)
                    {
                        from.SendLocalizedMessage(1062677); // You cannot place a vendor or barkeep at this location.
                    }
                    else if (contract)
                    {
                        from.SendLocalizedMessage(1062678); // You cannot place a vendor or barkeep on top of a rental contract!
                    }
                    else
                    {
                        Mobile v = new CommissionPlayerVendor(from, house)
                        {
                            Direction = from.Direction & Direction.Mask
                        };
                        v.MoveToWorld(from.Location, from.Map);

                        v.SayTo(from, 503246); // Ah! it feels good to be working again.

                        EventSink.InvokePlacePlayerVendor(new PlacePlayerVendorEventArgs(from, v));

                        Delete();
                    }
                }
            }
        }
Beispiel #31
0
        public virtual void GiveRewards()
        {
            // give rewards
            for (int i = 0; i < m_Rewards.Count; i++)
            {
                Type type = m_Rewards[i].Type;

                m_Rewards[i].GiveReward();

                if (type == null)
                {
                    continue;
                }

                Item reward;

                try
                {
                    reward = Activator.CreateInstance(type) as Item;
                }
                catch (Exception e)
                {
                    Server.Diagnostics.ExceptionLogging.LogException(e);
                    reward = null;
                }

                if (reward != null)
                {
                    if (reward.Stackable)
                    {
                        reward.Amount       = m_Rewards[i].Amount;
                        m_Rewards[i].Amount = 1;
                    }

                    for (int j = 0; j < m_Rewards[i].Amount; j++)
                    {
                        if (!m_Owner.PlaceInBackpack(reward))
                        {
                            reward.MoveToWorld(m_Owner.Location, m_Owner.Map);
                        }

                        if (m_Rewards[i].Name is int)
                        {
                            m_Owner.SendLocalizedMessage(1074360, "#" + (int)m_Rewards[i].Name); // You receive a reward: ~1_REWARD~
                        }
                        else if (m_Rewards[i].Name is string)
                        {
                            m_Owner.SendLocalizedMessage(1074360, (string)m_Rewards[i].Name); // You receive a reward: ~1_REWARD~
                        }
                        // already marked, we need to see if this gives progress to another quest.
                        if (reward.QuestItem)
                        {
                            QuestHelper.CheckRewardItem(Owner, reward);
                        }
                    }
                }
            }

            // remove quest
            if (NextQuest == null)
            {
                RemoveQuest(true);
            }
            else
            {
                RemoveQuest();
            }

            // offer next quest if present
            if (NextQuest != null)
            {
                BaseQuest quest = QuestHelper.RandomQuest(m_Owner, new Type[] { NextQuest }, StartingMobile);

                if (quest != null && quest.ChainID == ChainID)
                {
                    m_Owner.SendGump(new MondainQuestGump(quest));
                }
            }

            if (this is ITierQuest)
            {
                TierQuestInfo.CompleteQuest(Owner, (ITierQuest)this);
            }

            EventSink.InvokeQuestComplete(new QuestCompleteEventArgs(Owner, GetType()));
        }
Beispiel #32
0
 void HandleEnterNotifyEvent(object o, Gtk.EnterNotifyEventArgs args)
 {
     Toolkit.Invoke(delegate {
         EventSink.OnMouseEntered();
     });
 }
		public void SetUp()
		{
			_muConverter = new NuGenMeasureUnitsValueConverter();
			_eventSink = new EventSink(_muConverter);
		}
Beispiel #34
0
        public override bool DoActionCombat()
        {
            Mobile c = m_Mobile.Combatant;

            m_Mobile.Warmode = true;

            if (c == null || c.Deleted || !c.Alive || c.IsDeadBondedPet || !m_Mobile.CanSee(c) || !m_Mobile.CanBeHarmful(c, false) || c.Map != m_Mobile.Map)
            {
                // Our combatant is deleted, dead, hidden, or we cannot hurt them
                // Try to find another combatant

                if (AcquireFocusMob(m_Mobile.RangePerception, m_Mobile.FightMode, false, false, true))
                {
                    m_Mobile.DebugSay("Something happened to my combatant, so I am going to fight {0}", m_Mobile.FocusMob.Name);

                    m_Mobile.Combatant = c = m_Mobile.FocusMob;
                    m_Mobile.FocusMob  = null;
                }
                else
                {
                    m_Mobile.DebugSay("Something happened to my combatant, and nothing is around. I am on guard.");
                    Action = ActionType.Guard;
                    return(true);
                }
            }

            if (!m_Mobile.InLOS(c))
            {
                m_Mobile.DebugSay("I can't see my target");

                if (AcquireFocusMob(m_Mobile.RangePerception, m_Mobile.FightMode, false, false, true))
                {
                    m_Mobile.DebugSay("I will switch to {0}", m_Mobile.FocusMob.Name);
                    m_Mobile.Combatant = c = m_Mobile.FocusMob;
                    m_Mobile.FocusMob  = null;
                }
            }

            if (!Core.AOS && SmartAI && !m_Mobile.StunReady && m_Mobile.Skills[SkillName.Wrestling].Value >= 80.0 && m_Mobile.Skills[SkillName.Anatomy].Value >= 80.0)
            {
                EventSink.InvokeStunRequest(new StunRequestEventArgs(m_Mobile));
            }

            if (!m_Mobile.InRange(c, m_Mobile.RangePerception))
            {
                // They are somewhat far away, can we find something else?

                if (AcquireFocusMob(m_Mobile.RangePerception, m_Mobile.FightMode, false, false, true))
                {
                    m_Mobile.Combatant = m_Mobile.FocusMob;
                    m_Mobile.FocusMob  = null;
                }
                else if (!m_Mobile.InRange(c, m_Mobile.RangePerception * 3))
                {
                    m_Mobile.Combatant = null;
                }

                c = m_Mobile.Combatant;

                if (c == null)
                {
                    m_Mobile.DebugSay("My combatant has fled, so I am on guard");
                    Action = ActionType.Guard;

                    return(true);
                }
            }

            if (!m_Mobile.Controlled && !m_Mobile.Summoned && m_Mobile.CanFlee)
            {
                if (m_Mobile.Hits < m_Mobile.HitsMax * 20 / 100)
                {
                    // We are low on health, should we flee?

                    bool flee = false;

                    if (m_Mobile.Hits < c.Hits)
                    {
                        // We are more hurt than them

                        int diff = c.Hits - m_Mobile.Hits;

                        flee = (Utility.Random(0, 100) > (10 + diff));                               // (10 + diff)% chance to flee
                    }
                    else
                    {
                        flee = Utility.Random(0, 100) > 10;                           // 10% chance to flee
                    }

                    if (flee)
                    {
                        m_Mobile.DebugSay("I am going to flee from {0}", c.Name);

                        Action = ActionType.Flee;
                        return(true);
                    }
                }
            }

            if (m_Mobile.Spell == null && Core.TickCount - m_NextCastTime >= 0 && m_Mobile.InRange(c, Core.ML ? 10 : 12))
            {
                // We are ready to cast a spell

                Spell  spell    = null;
                Mobile toDispel = FindDispelTarget(true);

                if (m_Mobile.Poisoned)                  // Top cast priority is cure
                {
                    m_Mobile.DebugSay("I am going to cure myself");

                    spell = new CureSpell(m_Mobile, null);
                }
                else if (toDispel != null)                  // Something dispellable is attacking us
                {
                    m_Mobile.DebugSay("I am going to dispel {0}", toDispel);

                    spell = DoDispel(toDispel);
                }
                else if (SmartAI && m_Combo != -1)                  // We are doing a spell combo
                {
                    spell = DoCombo(c);
                }
                else if (SmartAI && (c.Spell is HealSpell || c.Spell is GreaterHealSpell) && !c.Poisoned)                    // They have a heal spell out
                {
                    spell = new PoisonSpell(m_Mobile, null);
                }
                else
                {
                    spell = ChooseSpell(c);
                }

                // Now we have a spell picked
                // Move first before casting

                if (SmartAI && toDispel != null)
                {
                    if (m_Mobile.InRange(toDispel, 10))
                    {
                        RunFrom(toDispel);
                    }
                    else if (!m_Mobile.InRange(toDispel, Core.ML ? 10 : 12))
                    {
                        RunTo(toDispel);
                    }
                }
                else
                {
                    RunTo(c);
                }

                if (spell != null)
                {
                    spell.Cast();
                }

                m_NextCastTime = Core.TickCount + (int)GetDelay(spell).TotalMilliseconds;
            }
            else if (m_Mobile.Spell == null || !m_Mobile.Spell.IsCasting)
            {
                RunTo(c);
            }

            m_LastTarget    = c;
            m_LastTargetLoc = c.Location;

            return(true);
        }
Beispiel #35
0
 public Widget()
 {
     eventSink = CreateEventSink ();
     eventSink.Parent = this;
     margin = new Xwt.WidgetSpacing (eventSink);
 }
Beispiel #36
0
        public virtual void Complete()
        {
            EventSink.InvokeQuestComplete(new QuestCompleteEventArgs(From, GetType()));

            this.ClearQuest(true);
        }
Beispiel #37
0
 private void OnDocumentContextChanged()
 {
     Interop.IHTMLElement parentElement = this._element.GetParentElement();
     if (this._parent == null)
     {
         if ((parentElement != null) && (this._control == null))
         {
             this.CreateControlAndDesigner();
             this.CreateControlView();
             if (this._eventSink == null)
             {
                 this._eventSink = new EventSink(this);
             }
             this.SetControlParent(parentElement);
             this.ConnectToControlAndDesigner();
         }
     }
     else if (parentElement == null)
     {
         if (this._eventSink != null)
         {
             this._eventSink.Disconnect();
             this._eventSink = null;
         }
         if (!this._dragged)
         {
             this._designerHost.Container.Remove(this._control);
             if (this._control.Parent != null)
             {
                 this._control.Parent.Controls.Remove(this._control);
             }
         }
         this._control = null;
         this._designer = null;
         this._viewElement = null;
         this._parent = null;
     }
     else if (this._control == null)
     {
         this.CreateControlAndDesigner();
         this.CreateControlView();
         this.SetControlParent(parentElement);
         this.ConnectToControlAndDesigner();
     }
     else
     {
         this.SetControlParent(parentElement);
     }
 }
		public void SetUp()
		{
			_spin = new StubSpin();
			_eventSink = new EventSink(_spin);
		}
Beispiel #39
0
        protected override void OnSizeToFit()
        {
            var s = EventSink.GetPreferredSize();

            Widget.SetFrameSize(new System.Drawing.SizeF((float)s.Width, (float)s.Height));
        }
Beispiel #40
0
        void HandleWidgetSizeRequested(object o, Gtk.SizeRequestedArgs args)
        {
            if (gettingPreferredSize)
            {
                return;
            }

            var req = args.Requisition;

            if ((enabledEvents & sizeCheckEvents) == 0)
            {
                // If no sizing event is set, it means this handler was set because there is a min size.
                if (Frontend.MinWidth != -1)
                {
                    req.Width = (int)Frontend.MinWidth;
                }
                if (Frontend.MinHeight != -1)
                {
                    req.Height = (int)Frontend.MinHeight;
                }
                return;
            }

            if (sizeCheckStep == SizeCheckStep.AdjustSize)
            {
                req.Width     = realRequestedWidth;
                req.Height    = realRequestedHeight;
                sizeCheckStep = SizeCheckStep.FinalAllocate;
            }
            else
            {
                Toolkit.Invoke(delegate {
                    if (EventSink.GetSizeRequestMode() == SizeRequestMode.HeightForWidth)
                    {
                        if ((enabledEvents & WidgetEvent.PreferredWidthCheck) != 0)
                        {
                            var w     = eventSink.OnGetPreferredWidth();
                            req.Width = (int)w.MinSize;
                        }
                        if ((enabledEvents & WidgetEvent.PreferredHeightForWidthCheck) != 0)
                        {
                            req.Height    = 1;
                            sizeCheckStep = SizeCheckStep.PreAllocate;
                        }
                        else if ((enabledEvents & WidgetEvent.PreferredHeightCheck) != 0)
                        {
                            var h         = eventSink.OnGetPreferredHeight();
                            req.Height    = (int)h.MinSize;
                            sizeCheckStep = SizeCheckStep.FinalAllocate;
                        }
                    }
                    else
                    {
                        if ((enabledEvents & WidgetEvent.PreferredHeightCheck) != 0)
                        {
                            var h      = eventSink.OnGetPreferredHeight();
                            req.Height = (int)h.MinSize;
                        }
                        if ((enabledEvents & WidgetEvent.PreferredWidthForHeightCheck) != 0)
                        {
                            req.Width     = 1;
                            sizeCheckStep = SizeCheckStep.PreAllocate;
                        }
                        else if ((enabledEvents & WidgetEvent.PreferredWidthCheck) != 0)
                        {
                            var w         = eventSink.OnGetPreferredWidth();
                            req.Width     = (int)w.MinSize;
                            sizeCheckStep = SizeCheckStep.FinalAllocate;
                        }
                    }
                });
            }
            args.Requisition = req;
        }
        public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
        {
            Mobile from = sender.Mobile;

            if (from.AccessLevel < AccessLevel.Administrator)
            {
                return;
            }

            TextRelay d = info.GetTextEntry(0);
            TextRelay h = info.GetTextEntry(1);
            TextRelay m = info.GetTextEntry(2);
            TextRelay s = info.GetTextEntry(3);

            TimeSpan duration;
            bool     shouldSet;

            string fromString = from.ToString();

            switch (info.ButtonID)
            {
            case 0:
            {
                for (int i = 0; i < m_List.Count; ++i)
                {
                    Account a = (Account)m_List[i];

                    a.SetUnspecifiedBan(from);
                }

                from.SendMessage("Duration unspecified.");
                return;
            }

            case 1:                     // infinite
            {
                duration  = TimeSpan.MaxValue;
                shouldSet = true;
                break;
            }

            case 2:                     // From D:H:M:S
            {
                if (d != null && h != null && m != null && s != null)
                {
                    try
                    {
                        duration  = new TimeSpan(Utility.ToInt32(d.Text), Utility.ToInt32(h.Text), Utility.ToInt32(m.Text), Utility.ToInt32(s.Text));
                        shouldSet = true;

                        break;
                    }
                    catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); }
                }

                duration  = TimeSpan.Zero;
                shouldSet = false;

                break;
            }

            case 3:                     // From D
            {
                if (d != null)
                {
                    try
                    {
                        duration  = TimeSpan.FromDays(Utility.ToDouble(d.Text));
                        shouldSet = true;

                        break;
                    }
                    catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); }
                }

                duration  = TimeSpan.Zero;
                shouldSet = false;

                break;
            }

            case 4:                     // From H
            {
                if (h != null)
                {
                    try
                    {
                        duration  = TimeSpan.FromHours(Utility.ToDouble(h.Text));
                        shouldSet = true;

                        break;
                    }
                    catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); }
                }

                duration  = TimeSpan.Zero;
                shouldSet = false;

                break;
            }

            case 5:                     // From M
            {
                if (m != null)
                {
                    try
                    {
                        duration  = TimeSpan.FromMinutes(Utility.ToDouble(m.Text));
                        shouldSet = true;

                        break;
                    }
                    catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); }
                }

                duration  = TimeSpan.Zero;
                shouldSet = false;

                break;
            }

            case 6:                     // From S
            {
                if (s != null)
                {
                    try
                    {
                        duration  = TimeSpan.FromSeconds(Utility.ToDouble(s.Text));
                        shouldSet = true;

                        break;
                    }
                    catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); }
                }

                duration  = TimeSpan.Zero;
                shouldSet = false;

                break;
            }

            default: return;
            }

            if (shouldSet)
            {
                for (int i = 0; i < m_List.Count; ++i)
                {
                    Account a = (Account)m_List[i];

                    a.SetBanTags(from, DateTime.Now, duration);
                }

                if (duration == TimeSpan.MaxValue)
                {
                    from.SendMessage("Duration is infinite.");
                }
                else
                {
                    from.SendMessage("Duration is {0}.", duration);
                }
            }
            else
            {
                from.SendMessage("Values improperly formatted.");
                from.SendGump(new BanDurationGump(m_List));
            }
        }
Beispiel #42
0
 void HandleWidgetFocusOutEvent(object o, Gtk.FocusOutEventArgs args)
 {
     ApplicationContext.InvokeUserCode(delegate {
         EventSink.OnLostFocus();
     });
 }
Beispiel #43
0
        public override bool DoActionCombat()
        {
            Mobile c = m_Mobile.Combatant;

            m_Mobile.Warmode = true;

            if (c == null || c.Deleted || !c.Alive || c.IsDeadBondedPet || !m_Mobile.CanSee(c) || !m_Mobile.CanBeHarmful(c, false) || c.Map != m_Mobile.Map)
            {
                // Our combatant is deleted, dead, hidden, or we cannot hurt them
                // Try to find another combatant

                if (AcquireFocusMob(m_Mobile.RangePerception, m_Mobile.FightMode, false, false, true))
                {
                    if (m_Mobile.Debug)
                    {
                        m_Mobile.DebugSay("Something happened to my combatant, so I am going to fight {0}", m_Mobile.FocusMob.Name);
                    }

                    m_Mobile.Combatant = c = m_Mobile.FocusMob;
                    m_Mobile.FocusMob  = null;
                }
                else
                {
                    m_Mobile.DebugSay("Something happened to my combatant, and nothing is around. I am on guard.");
                    Action = ActionType.Guard;
                    return(true);
                }
            }

            if (!m_Mobile.InLOS(c))
            {
                if (AcquireFocusMob(m_Mobile.RangePerception, m_Mobile.FightMode, false, false, true))
                {
                    m_Mobile.Combatant = c = m_Mobile.FocusMob;
                    m_Mobile.FocusMob  = null;
                }
            }

            if (!m_Mobile.StunReady && m_Mobile.Skills[SkillName.Wrestling].Value >= 80.0 && m_Mobile.Skills[SkillName.Anatomy].Value >= 80.0)
            {
                EventSink.InvokeStunRequest(new StunRequestEventArgs(m_Mobile));
            }

            if (!m_Mobile.InRange(c, m_Mobile.RangePerception))
            {
                // They are somewhat far away, can we find something else?

                if (AcquireFocusMob(m_Mobile.RangePerception, m_Mobile.FightMode, false, false, true))
                {
                    m_Mobile.Combatant = m_Mobile.FocusMob;
                    m_Mobile.FocusMob  = null;
                }
                else if (!m_Mobile.InRange(c, m_Mobile.RangePerception * 3))
                {
                    m_Mobile.Combatant = null;
                }

                c = m_Mobile.Combatant;

                if (c == null)
                {
                    m_Mobile.DebugSay("My combatant has fled, so I am on guard");
                    Action = ActionType.Guard;

                    return(true);
                }
            }

            if (!m_Mobile.Controlled && !m_Mobile.Summoned)
            {
                if (m_Mobile.Hits < m_Mobile.HitsMax * 20 / 100)
                {
                    // We are low on health, should we flee?

                    bool flee = false;

                    if (m_Mobile.Hits < c.Hits)
                    {
                        // We are more hurt than them

                        int diff = c.Hits - m_Mobile.Hits;

                        flee = (Utility.Random(0, 100) > (10 + diff));                             // (10 + diff)% chance to flee
                    }
                    else
                    {
                        flee = Utility.Random(0, 100) > 10;                           // 10% chance to flee
                    }

                    if (flee)
                    {
                        if (m_Mobile.Debug)
                        {
                            m_Mobile.DebugSay("I am going to flee from {0}", c.Name);
                        }

                        Action = ActionType.Flee;
                        return(true);
                    }
                }
            }

            if (m_Mobile.Spell == null && DateTime.Now > m_NextCastTime && m_Mobile.InRange(c, 12))
            {
                // We are ready to cast a spell

                Spell  spell    = null;
                Mobile toDispel = FindDispelTarget(true);

                if (m_Mobile.Poisoned)                   // Top cast priority is cure
                {
                    IPooledEnumerable eable = (IPooledEnumerable)m_Mobile.Map.GetItemsInRange(m_Mobile.Location, 1);

                    foreach (object o in eable)
                    {
                        if (o is PoisonFieldSpell.InternalItem)
                        {
                            m_Mobile.Move(m_Mobile.Direction);
                            break;
                        }
                    }
                    spell = new ArchCureSpell(m_Mobile, null);
                }
                else if (toDispel != null)                   // Something dispellable is attacking us
                {
                    spell = DoDispel(toDispel);
                }
                else if (m_Combo != -1)                   // We are doing a spell combo
                {
                    spell = DoCombo(c);
                }
                else if ((c.Spell is HealSpell || c.Spell is GreaterHealSpell) && !c.Poisoned &&
                         (!(c is BaseCreature) ||
                          (((BaseCreature)c).PoisonImmune != null && ((BaseCreature)m_Mobile).HitPoison != null &&
                           ((BaseCreature)c).PoisonImmune.Level != null && ((BaseCreature)m_Mobile).HitPoison.Level != null &&
                           ((BaseCreature)c).PoisonImmune.Level < ((BaseCreature)m_Mobile).HitPoison.Level))) // They have a heal spell out and can be poisoned
                {
                    spell = new PoisonSpell(m_Mobile, null);
                }
                else
                {
                    spell = ChooseSpell(c);
                }

                // Now we have a spell picked
                // Move first before casting

                if (toDispel != null)
                {
                    if (m_Mobile.InRange(toDispel, 10))
                    {
                        RunFrom(toDispel);
                    }
                    else if (!m_Mobile.InRange(toDispel, 12))
                    {
                        RunTo(toDispel);
                    }
                }
                else
                {
                    RunTo(c);
                }

                if (spell != null && spell.Cast())
                {
                    TimeSpan delay;

                    delay          = spell.GetCastDelay();
                    m_NextCastTime = DateTime.Now + delay;
                    m_Mobile.DebugSay("Spell Delay is " + delay);
                }
            }
            else if (m_Mobile.Spell == null || !m_Mobile.Spell.IsCasting)
            {
                RunTo(c);
            }

            return(true);
        }
 void HandleValueChanged(object sender, EventArgs e)
 {
     ApplicationContext.InvokeUserCode(delegate {
         EventSink.ValueChanged();
     });
 }
Beispiel #45
0
                protected override void OnTick()
                {
                    m_Count++;

                    DamageEntry de           = m_Creature.FindMostRecentDamageEntry(false);
                    bool        alreadyOwned = m_Creature.Owners.Contains(m_Tamer);

                    if (!m_Tamer.InRange(m_Creature, Core.AOS ? 7 : 6))
                    {
                        m_BeingTamed.Remove(m_Creature);
                        m_Tamer.NextSkillTime = Core.TickCount;
                        m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502795, m_Tamer.NetState);
                        // You are too far away to continue taming.
                        Stop();
                    }
                    else if (!m_Tamer.CheckAlive())
                    {
                        m_BeingTamed.Remove(m_Creature);
                        m_Tamer.NextSkillTime = Core.TickCount;
                        m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502796, m_Tamer.NetState);
                        // You are dead, and cannot continue taming.
                        Stop();
                    }
                    else if (!m_Tamer.CanSee(m_Creature) || !m_Tamer.InLOS(m_Creature) || !CanPath())
                    {
                        m_BeingTamed.Remove(m_Creature);
                        m_Tamer.NextSkillTime = Core.TickCount;
                        m_Tamer.SendLocalizedMessage(1049654);
                        // You do not have a clear path to the animal you are taming, and must cease your attempt.
                        Stop();
                    }
                    else if (!m_Creature.Tamable)
                    {
                        m_BeingTamed.Remove(m_Creature);
                        m_Tamer.NextSkillTime = Core.TickCount;
                        m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1049655, m_Tamer.NetState);
                        // That creature cannot be tamed.
                        Stop();
                    }
                    else if (m_Creature.Controlled)
                    {
                        m_BeingTamed.Remove(m_Creature);
                        m_Tamer.NextSkillTime = Core.TickCount;
                        m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502804, m_Tamer.NetState);
                        // That animal looks tame already.
                        Stop();
                    }
                    else if (m_Creature.Owners.Count >= BaseCreature.MaxOwners && !m_Creature.Owners.Contains(m_Tamer))
                    {
                        m_BeingTamed.Remove(m_Creature);
                        m_Tamer.NextSkillTime = Core.TickCount;
                        m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1005615, m_Tamer.NetState);
                        // This animal has had too many owners and is too upset for you to tame.
                        Stop();
                    }
                    else if (MustBeSubdued(m_Creature))
                    {
                        m_BeingTamed.Remove(m_Creature);
                        m_Tamer.NextSkillTime = Core.TickCount;
                        m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 1054025, m_Tamer.NetState);
                        // You must subdue this creature before you can tame it!
                        Stop();
                    }
                    else if (de != null && de.LastDamage > m_StartTime)
                    {
                        m_BeingTamed.Remove(m_Creature);
                        m_Tamer.NextSkillTime = Core.TickCount;
                        m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502794, m_Tamer.NetState);
                        // The animal is too angry to continue taming.
                        Stop();
                    }
                    else if (m_Count < m_MaxCount)
                    {
                        m_Tamer.RevealingAction();

                        switch (Utility.Random(3))
                        {
                        case 0:
                            m_Tamer.PublicOverheadMessage(MessageType.Regular, 0x3B2, Utility.Random(502790, 4));
                            break;

                        case 1:
                            m_Tamer.PublicOverheadMessage(MessageType.Regular, 0x3B2, Utility.Random(1005608, 6));
                            break;

                        case 2:
                            m_Tamer.PublicOverheadMessage(MessageType.Regular, 0x3B2, Utility.Random(1010593, 4));
                            break;
                        }

                        if (!alreadyOwned) // Passively check animal lore for gain
                        {
                            m_Tamer.CheckTargetSkill(SkillName.AnimalLore, m_Creature, 0.0, 120.0);
                        }

                        if (m_Creature.Paralyzed)
                        {
                            m_Paralyzed = true;
                        }
                    }
                    else
                    {
                        m_Tamer.RevealingAction();
                        m_Tamer.NextSkillTime = Core.TickCount;
                        m_BeingTamed.Remove(m_Creature);

                        if (m_Creature.Paralyzed)
                        {
                            m_Paralyzed = true;
                        }

                        if (!alreadyOwned) // Passively check animal lore for gain
                        {
                            m_Tamer.CheckTargetSkill(SkillName.AnimalLore, m_Creature, 0.0, 120.0);
                        }

                        double minSkill     = m_Creature.CurrentTameSkill + (m_Creature.Owners.Count * 6.0);
                        bool   necroMastery = DarkWolfFamiliar.CheckMastery(m_Tamer, m_Creature);

                        if (minSkill > -24.9 && necroMastery)
                        {
                            minSkill = -24.9; // 50% at 0.0?
                        }

                        minSkill += 24.9;

                        if (necroMastery || alreadyOwned ||
                            m_Tamer.CheckTargetSkill(SkillName.AnimalTaming, m_Creature, minSkill - 25.0, minSkill + 25.0))
                        {
                            if (m_Creature.Owners.Count == 0) // First tame
                            {
                                if (m_Creature is GreaterDragon)
                                {
                                    ScaleSkills(m_Creature, 0.72, 0.90, true); // 72% of original skills trainable to 90%
                                    m_Creature.Skills[SkillName.Magery].Base = m_Creature.Skills[SkillName.Magery].Cap;
                                    // Greater dragons have a 90% cap reduction and 90% skill reduction on magery
                                }
                                else if (m_Paralyzed)
                                {
                                    ScaleSkills(m_Creature, 0.86, true); // 86% of original skills if they were paralyzed during the taming
                                }
                                else
                                {
                                    ScaleSkills(m_Creature, 0.90, true); // 90% of original skills
                                }
                            }
                            else
                            {
                                ScaleSkills(m_Creature, 0.90, false); // 90% of original skills
                            }

                            if (alreadyOwned)
                            {
                                m_Tamer.SendLocalizedMessage(502797); // That wasn't even challenging.
                            }
                            else
                            {
                                m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502799, m_Tamer.NetState);
                                // It seems to accept you as master.
                            }

                            m_Creature.SetControlMaster(m_Tamer);
                            m_Creature.IsBonded = false;

                            m_Creature.OnAfterTame(m_Tamer);

                            if (!m_Creature.Owners.Contains(m_Tamer))
                            {
                                m_Creature.Owners.Add(m_Tamer);
                            }

                            PetTrainingHelper.GetAbilityProfile(m_Creature, true).OnTame();

                            EventSink.InvokeTameCreature(new TameCreatureEventArgs(m_Tamer, m_Creature));
                        }
                        else
                        {
                            m_Creature.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 502798, m_Tamer.NetState);
                            // You fail to tame the creature.
                        }
                    }
                }
 void HandleShown(object sender, EventArgs e)
 {
     ApplicationContext.InvokeUserCode(delegate {
         EventSink.OnShown();
     });
 }
 public void TestAccum()
 {
   var ea = new EventSink<int>();
   var @out = new List<int>();
   Behavior<int> sum = ea.Accum<int>(100, (a, s) => a + s);
   Listener l = sum.Value().Listen(x => { @out.Add(x); });
   ea.Send(5);
   ea.Send(7);
   ea.Send(1);
   ea.Send(2);
   ea.Send(3);
   l.Unlisten();
   CollectionAssert.AreEqual(new[] { 100, 105, 112, 113, 115, 118 }, @out);
 }
Beispiel #48
0
        public override bool DoActionCombat()
        {
            Mobile combatant = m_Mobile.Combatant;

            if (combatant == null || combatant.Deleted || combatant.Map != m_Mobile.Map)
            {
                m_Mobile.DebugSay("My combatant is gone, so my guard is up");

                Action = ActionType.Guard;

                return(true);
            }

            if (WalkMobileRange(combatant, 1, true, m_Mobile.RangeFight, m_Mobile.RangeFight))
            {
                m_Mobile.Direction = m_Mobile.GetDirectionTo(combatant);
                if (m_toDisarm == null)
                {
                    m_toDisarm = combatant.FindItemOnLayer(Layer.OneHanded);
                }
                if (m_toDisarm == null)
                {
                    m_toDisarm = combatant.FindItemOnLayer(Layer.TwoHanded);
                }
                if (m_toDisarm != null && m_toDisarm.IsChildOf(m_Mobile.Backpack))
                {
                    m_toDisarm = combatant.FindItemOnLayer(Layer.OneHanded);
                    if (m_toDisarm == null)
                    {
                        m_toDisarm = combatant.FindItemOnLayer(Layer.TwoHanded);
                    }
                }
                if (!m_Mobile.DisarmReady && m_Mobile.Skills[SkillName.Wrestling].Value >= 80.0 && m_Mobile.Skills[SkillName.ArmsLore].Value >= 80.0 && m_toDisarm != null)
                {
                    EventSink.InvokeDisarmRequest(new DisarmRequestEventArgs(m_Mobile));
                }
                if (m_toDisarm != null && m_toDisarm.IsChildOf(combatant.Backpack) && m_Mobile.NextSkillTime <= Core.Now && (m_toDisarm.LootType != LootType.Blessed && m_toDisarm.LootType != LootType.Newbied))
                {
                    m_Mobile.DebugSay("Trying to steal from combatant.");
                    m_Mobile.UseSkill(SkillName.Stealing);
                    if (m_Mobile.Target != null)
                    {
                        m_Mobile.Target.Invoke(m_Mobile, m_toDisarm);
                    }
                }
                else if (m_toDisarm == null && m_Mobile.NextSkillTime <= Core.Now)
                {
                    Container cpack = combatant.Backpack;

                    if (cpack != null)
                    {
                        Item steala = cpack.FindItemByType(typeof(Bandage));
                        if (steala != null)
                        {
                            m_Mobile.DebugSay("Trying to steal from combatant.");
                            m_Mobile.UseSkill(SkillName.Stealing);
                            if (m_Mobile.Target != null)
                            {
                                m_Mobile.Target.Invoke(m_Mobile, steala);
                            }
                        }
                        Item stealb = cpack.FindItemByType(typeof(Nightshade));
                        if (stealb != null)
                        {
                            m_Mobile.DebugSay("Trying to steal from combatant.");
                            m_Mobile.UseSkill(SkillName.Stealing);
                            if (m_Mobile.Target != null)
                            {
                                m_Mobile.Target.Invoke(m_Mobile, stealb);
                            }
                        }
                        Item stealc = cpack.FindItemByType(typeof(BlackPearl));
                        if (stealc != null)
                        {
                            m_Mobile.DebugSay("Trying to steal from combatant.");
                            m_Mobile.UseSkill(SkillName.Stealing);
                            if (m_Mobile.Target != null)
                            {
                                m_Mobile.Target.Invoke(m_Mobile, stealc);
                            }
                        }
                        Item steald = cpack.FindItemByType(typeof(MandrakeRoot));
                        if (steald != null)
                        {
                            m_Mobile.DebugSay("Trying to steal from combatant.");
                            m_Mobile.UseSkill(SkillName.Stealing);
                            if (m_Mobile.Target != null)
                            {
                                m_Mobile.Target.Invoke(m_Mobile, steald);
                            }
                        }
                        else if (steala == null && stealb == null && stealc == null && steald == null)
                        {
                            if (m_Mobile.Debug)
                            {
                                m_Mobile.DebugSay("I am going to flee from {0}", combatant.Name);
                            }

                            Action = ActionType.Flee;
                        }
                    }
                }
            }
            else
            {
                if (m_Mobile.Debug)
                {
                    m_Mobile.DebugSay("I should be closer to {0}", combatant.Name);
                }
            }

            if (m_Mobile.Hits < m_Mobile.HitsMax * 20 / 100)
            {
                // We are low on health, should we flee?

                bool flee = false;

                if (m_Mobile.Hits < combatant.Hits)
                {
                    // We are more hurt than them

                    int diff = combatant.Hits - m_Mobile.Hits;

                    flee = (Utility.Random(0, 100) > (10 + diff));                         // (10 + diff)% chance to flee
                }
                else
                {
                    flee = Utility.Random(0, 100) > 10;                       // 10% chance to flee
                }

                if (flee)
                {
                    if (m_Mobile.Debug)
                    {
                        m_Mobile.DebugSay("I am going to flee from {0}", combatant.Name);
                    }

                    Action = ActionType.Flee;
                }
            }

            return(true);
        }
		public void SetUp()
		{
			_selector = new NuGenAlignSelector(new ServiceProvider());
			_eventSink = new EventSink(_selector);
		}
Beispiel #50
0
        public virtual void FinishHarvesting(Mobile from, Item tool, HarvestDefinition def, object toHarvest, object locked)
        {
            from.EndAction(locked);

            if (!CheckHarvest(from, tool))
            {
                return;
            }

            if (!GetHarvestDetails(from, tool, toHarvest, out int tileID, out Map map, out Point3D loc))
            {
                OnBadHarvestTarget(from, tool, toHarvest);
                return;
            }

            if (!def.Validate(tileID) && !def.ValidateSpecial(tileID))
            {
                OnBadHarvestTarget(from, tool, toHarvest);
                return;
            }

            if (!CheckRange(from, def, map, loc, true))
            {
                return;
            }
            if (!CheckResources(from, tool, def, map, loc, true))
            {
                return;
            }
            if (!CheckHarvest(from, tool, def, toHarvest))
            {
                return;
            }

            if (SpecialHarvest(from, tool, def, map, loc))
            {
                return;
            }

            HarvestBank bank = def.GetBank(map, loc.X, loc.Y);

            if (bank == null)
            {
                return;
            }

            HarvestVein vein = bank.Vein;

            if (vein != null)
            {
                vein = MutateVein(from, tool, def, bank, toHarvest, vein);
            }

            if (vein == null)
            {
                return;
            }

            HarvestResource primary  = vein.PrimaryResource;
            HarvestResource fallback = vein.FallbackResource;
            HarvestResource resource = MutateResource(from, tool, def, map, loc, vein, primary, fallback);

            double skillBase = from.Skills[def.Skill].Base;

            Type type = null;

            if (CheckHarvestSkill(map, loc, from, resource, def))
            {
                type = GetResourceType(from, tool, def, map, loc, resource);

                if (type != null)
                {
                    type = MutateType(type, from, tool, def, map, loc, resource);
                }

                if (type != null)
                {
                    Item item = Construct(type, from, tool);

                    if (item == null)
                    {
                        type = null;
                    }
                    else
                    {
                        int amount        = def.ConsumedPerHarvest;
                        int feluccaAmount = def.ConsumedPerFeluccaHarvest;

                        if (item is BaseGranite)
                        {
                            feluccaAmount = 3;
                        }

                        Caddellite.OnHarvest(from, tool, this, item);

                        //The whole harvest system is kludgy and I'm sure this is just adding to it.
                        if (item.Stackable)
                        {
                            int racialAmount        = (int)Math.Ceiling(amount * 1.1);
                            int feluccaRacialAmount = (int)Math.Ceiling(feluccaAmount * 1.1);

                            bool eligableForRacialBonus = def.RaceBonus && from.Race == Race.Human;
                            bool inFelucca = map == Map.Felucca && !Siege.SiegeShard;

                            if (eligableForRacialBonus && inFelucca && bank.Current >= feluccaRacialAmount && 0.1 > Utility.RandomDouble())
                            {
                                item.Amount = feluccaRacialAmount;
                            }
                            else if (inFelucca && bank.Current >= feluccaAmount)
                            {
                                item.Amount = feluccaAmount;
                            }
                            else if (eligableForRacialBonus && bank.Current >= racialAmount && 0.1 > Utility.RandomDouble())
                            {
                                item.Amount = racialAmount;
                            }
                            else
                            {
                                item.Amount = amount;
                            }

                            // Void Pool Rewards
                            item.Amount += WoodsmansTalisman.CheckHarvest(from, type, this);
                        }

                        if (from.AccessLevel == AccessLevel.Player)
                        {
                            bank.Consume(amount, from);
                        }

                        if (Give(from, item, def.PlaceAtFeetIfFull))
                        {
                            SendSuccessTo(from, item, resource);
                        }
                        else
                        {
                            SendPackFullTo(from, item, def, resource);
                            item.Delete();
                        }

                        BonusHarvestResource bonus = def.GetBonusResource();
                        Item bonusItem             = null;

                        if (bonus != null && bonus.Type != null && skillBase >= bonus.ReqSkill)
                        {
                            if (bonus.RequiredMap == null || bonus.RequiredMap == from.Map)
                            {
                                bonusItem = Construct(bonus.Type, from, tool);
                                Caddellite.OnHarvest(from, tool, this, bonusItem, false);

                                if (Give(from, bonusItem, true))    //Bonuses always allow placing at feet, even if pack is full irregrdless of def
                                {
                                    bonus.SendSuccessTo(from);
                                }
                                else
                                {
                                    bonusItem.Delete();
                                }
                            }
                        }

                        EventSink.InvokeResourceHarvestSuccess(new ResourceHarvestSuccessEventArgs(from, tool, item, bonusItem, this));
                    }

                    OnToolUsed(from, tool, item != null);
                }

                // Siege rules will take into account axes and polearms used for lumberjacking
                if (tool is IUsesRemaining withUses && (withUses is BaseHarvestTool || withUses is Pickaxe || withUses is SturdyPickaxe || withUses is GargoylesPickaxe || Siege.SiegeShard))
                {
                    withUses.ShowUsesRemaining = true;

                    if (withUses.UsesRemaining > 0)
                    {
                        --withUses.UsesRemaining;
                    }

                    if (withUses.UsesRemaining < 1)
                    {
                        tool.Delete();
                        def.SendMessageTo(from, def.ToolBrokeMessage);
                    }
                }
            }

            if (type == null)
            {
                def.SendMessageTo(from, def.FailMessage);
            }

            OnHarvestFinished(from, tool, def, vein, bank, resource, toHarvest);
        }
Beispiel #51
0
 public WindowFrame()
 {
     eventSink = CreateEventSink ();
     eventSink.Parent = this;
 }
Beispiel #52
0
        public static bool Handle(Mobile from, string text, MessageType type)
        {
            if (text.StartsWith(Prefix) || type == MessageType.Command)
            {
                if (type != MessageType.Command)
                {
                    text = text.Substring(Prefix.Length);
                }

                int indexOf = text.IndexOf(' ');

                string   command;
                string[] args;
                string   argString;

                if (indexOf >= 0)
                {
                    argString = text.Substring(indexOf + 1);

                    command = text.Substring(0, indexOf);
                    args    = Split(argString);
                }
                else
                {
                    argString = "";
                    command   = text.ToLower();
                    args      = new string[0];
                }

                CommandEntry entry = null;
                Entries.TryGetValue(command, out entry);

                if (entry != null)
                {
                    if (from.AccessLevel >= entry.AccessLevel)
                    {
                        if (entry.Handler != null)
                        {
                            CommandEventArgs e = new CommandEventArgs(from, command, argString, args);
                            entry.Handler(e);
                            EventSink.InvokeCommand(e);
                        }
                    }
                    else
                    {
                        if (from.AccessLevel <= BadCommandIgnoreLevel)
                        {
                            return(false);
                        }

                        from.SendMessage("You do not have access to that command.");
                    }
                }
                else
                {
                    if (from.AccessLevel <= BadCommandIgnoreLevel)
                    {
                        return(false);
                    }

                    from.SendMessage("That is not a valid command.");
                }

                return(true);
            }

            return(false);
        }
Beispiel #53
0
 private void OnBehaviorDetach()
 {
     if (this._designer != null)
     {
         this._designer.Behavior = null;
         this._designer = null;
     }
     if (this._eventSink != null)
     {
         this._eventSink.Disconnect();
         this._eventSink = null;
     }
     this._element = null;
     this._viewElement = null;
     this._paintSite = null;
     this._behaviorSite = null;
     this._editor = null;
 }
 void HandleClicked(object sender, EventArgs e)
 {
     Context.InvokeUserCode(() => {
         EventSink.OnNavigateToUrl(Uri);
     });
 }
Beispiel #55
0
 private void OnContentReady()
 {
     IDesignerHost service = (IDesignerHost) this.ServiceProvider.GetService(typeof(IDesignerHost));
     if (service.Loading)
     {
         this.CreateControlAndDesigner();
         this.CreateControlView();
         this.SetControlParent(this._element.GetParentElement());
         this.ConnectToControlAndDesigner();
     }
     else
     {
         Interop.IHTMLElement parentElement = this._element.GetParentElement();
         if ((this._parent == null) && (parentElement != null))
         {
             bool flag = false;
             string attribute = (string) ((IHtmlControlDesignerBehavior) this).GetAttribute("id", true);
             if (attribute != null)
             {
                 IComponent component = this._designerHost.Container.Components[attribute];
                 if ((component != null) && (component is System.Web.UI.Control))
                 {
                     System.Web.UI.Control control = (System.Web.UI.Control) component;
                     ControlDesigner designer = (ControlDesigner) this._designerHost.GetDesigner(control);
                     if (designer != null)
                     {
                         Behavior behavior = (Behavior) designer.Behavior;
                         if (behavior.IsDragging() && !behavior.IsControlDown())
                         {
                             ((Behavior) designer.Behavior).StopDrag();
                             flag = true;
                             this._control = control;
                             this._designer = designer;
                             this.CreateControlView();
                             this.SetControlParent(parentElement);
                             this.ConnectToControlAndDesigner();
                         }
                     }
                 }
             }
             if (!flag)
             {
                 this.CreateControlAndDesigner();
                 this.CreateControlView();
                 if (this._eventSink == null)
                 {
                     this._eventSink = new EventSink(this);
                 }
                 this.SetControlParent(parentElement);
                 this.ConnectToControlAndDesigner();
             }
         }
     }
     Interop.IHTMLStyle runtimeStyle = ((Interop.IHTMLElement2) this._element).GetRuntimeStyle();
     if (runtimeStyle != null)
     {
         runtimeStyle.SetDisplay("inline-block");
     }
 }
        public void ShouldInstantiatePipelineFromValidConfiguration()
        {
            string pipelineConfiguration = @"
                {
                    ""inputs"": [
                        {  ""type"": ""EventSource"",
                            ""sources"": [
                                { ""providerName"": ""Microsoft-ServiceFabric-Services"" },
                                { ""providerName"": ""MyCompany-AirTrafficControlApplication-Frontend"" }
                            ]
                        }
                    ],

                    ""filters"": [
                        {
                            ""type"": ""metadata"",
                            ""metadata"": ""importance"",
                            ""include"": ""Level == Verbose"",
                            ""importance"": ""can be discarded""
                        }
                    ],

                    ""outputs"": [
                        {
                            ""type"": ""StdOutput"",

                            ""filters"": [
                                {
                                    ""type"": ""metadata"",
                                    ""metadata"": ""metric"",
                                    ""include"": ""ProviderName == Microsoft-ServiceFabric-Services && EventName == StatefulRunAsyncFailure"",
                                    ""metricName"": ""StatefulRunAsyncFailure"",
                                    ""metricValue"": ""1.0""
                                }
                            ]
                        }
                    ],

                    ""schemaVersion"": ""2016-08-11"",

                    ""settings"": {
                        ""maxConcurrency"": ""2"",
                        ""pipelineCompletionTimeoutMsec"": ""1000""
                    },
                    ""healthReporter"": {
                        ""type"": ""CustomHealthReporter"",
                    },
                    ""extensions"": [
                         {
                            ""category"": ""healthReporter"",
                            ""type"": ""CustomHealthReporter"",
                            ""qualifiedTypeName"": ""Microsoft.Diagnostics.EventFlow.Core.Tests.CustomHealthReporter, Microsoft.Diagnostics.EventFlow.Core.Tests""
                        }
                    ]
                }";

            try
            {
                using (var configFile = new TemporaryFile())
                {
                    configFile.Write(pipelineConfiguration);
                    ConfigurationBuilder builder = new ConfigurationBuilder();
                    builder.AddJsonFile(configFile.FilePath);
                    var configuration = builder.Build();

                    using (var pipeline = DiagnosticPipelineFactory.CreatePipeline(configuration))
                    {
                        Assert.NotNull(pipeline);

                        Assert.Equal(pipeline.Inputs.Count, 1);
                        var eventSourceInput = pipeline.Inputs.First() as EventSourceInput;
                        Assert.NotNull(eventSourceInput);

                        var expectedEventSources = new EventSourceConfiguration[2];
                        expectedEventSources[0] = new EventSourceConfiguration {
                            ProviderName = "Microsoft-ServiceFabric-Services"
                        };
                        expectedEventSources[1] = new EventSourceConfiguration {
                            ProviderName = "MyCompany-AirTrafficControlApplication-Frontend"
                        };
                        Assert.True(eventSourceInput.EventSources.SequenceEqual(expectedEventSources));

                        var metadata = new EventMetadata("importance");
                        metadata.Properties.Add("importance", "can be discarded");
                        var metadataFilter = new EventMetadataFilter(metadata);
                        metadataFilter.IncludeCondition = "Level == Verbose";
                        Assert.True(pipeline.GlobalFilters.Count == 1);
                        Assert.True(pipeline.GlobalFilters.First().Equals(metadataFilter));

                        Assert.Equal(pipeline.Sinks.Count, 1);
                        EventSink sink = pipeline.Sinks.First();

                        var stdSender = sink.Output as StdOutput;
                        Assert.NotNull(stdSender);

                        metadata = new EventMetadata("metric");
                        metadata.Properties.Add("metricName", "StatefulRunAsyncFailure");
                        metadata.Properties.Add("metricValue", "1.0");
                        metadataFilter = new EventMetadataFilter(metadata);
                        metadataFilter.IncludeCondition = "ProviderName == Microsoft-ServiceFabric-Services && EventName == StatefulRunAsyncFailure";

                        Assert.True(sink.Filters.Count == 1);
                        Assert.True(sink.Filters.First().Equals(metadataFilter));
                    }
                }
            }
            finally
            {
                TryDeleteFile(CsvHealthReporter.DefaultLogFilePrefix);
            }
        }
Beispiel #57
0
        public static void Gain(Mobile from, Skill skill, int toGain)
        {
            if (from.Region.IsPartOf <Jail>())
            {
                return;
            }

            if (from is BaseCreature && ((BaseCreature)from).IsDeadPet)
            {
                return;
            }

            if (skill.SkillName == SkillName.Focus && from is BaseCreature &&
                (!PetTrainingHelper.Enabled || !((BaseCreature)from).Controlled))
            {
                return;
            }

            if (skill.Base < skill.Cap && skill.Lock == SkillLock.Up)
            {
                var skills = from.Skills;

                if (from is PlayerMobile && Siege.SiegeShard)
                {
                    var minsPerGain = Siege.MinutesPerGain(from, skill);

                    if (minsPerGain > 0)
                    {
                        if (Siege.CheckSkillGain((PlayerMobile)from, minsPerGain, skill))
                        {
                            CheckReduceSkill(skills, toGain, skill);

                            if (skills.Total + toGain <= skills.Cap)
                            {
                                skill.BaseFixedPoint += toGain;
                            }
                        }

                        return;
                    }
                }

                if (toGain == 1 && skill.Base <= 10.0)
                {
                    toGain = Utility.Random(4) + 1;
                }

                #region Mondain's Legacy
                if (from is PlayerMobile && QuestHelper.EnhancedSkill((PlayerMobile)from, skill))
                {
                    toGain *= Utility.RandomMinMax(2, 4);
                }
                #endregion

                #region Scroll of Alacrity
                if (from is PlayerMobile && skill.SkillName == ((PlayerMobile)from).AcceleratedSkill &&
                    ((PlayerMobile)from).AcceleratedStart > DateTime.UtcNow)
                {
                    // You are infused with intense energy. You are under the effects of an accelerated skillgain scroll.
                    ((PlayerMobile)from).SendLocalizedMessage(1077956);

                    toGain = Utility.RandomMinMax(2, 5);
                }
                #endregion

                #region Skill Masteries
                else if (from is BaseCreature && !(from is Server.Engines.Despise.DespiseCreature) && (((BaseCreature)from).Controlled || ((BaseCreature)from).Summoned))
                {
                    var master = ((BaseCreature)from).GetMaster();

                    if (master != null)
                    {
                        var spell = SkillMasterySpell.GetSpell(master, typeof(WhisperingSpell)) as WhisperingSpell;

                        if (spell != null && master.InRange(from.Location, spell.PartyRange) && master.Map == from.Map &&
                            spell.EnhancedGainChance >= Utility.Random(100))
                        {
                            toGain = Utility.RandomMinMax(2, 5);
                        }
                    }
                }
                #endregion

                if (from is PlayerMobile)
                {
                    CheckReduceSkill(skills, toGain, skill);
                }

                if (!from.Player || (skills.Total + toGain <= skills.Cap))
                {
                    skill.BaseFixedPoint = Math.Min(skill.CapFixedPoint, skill.BaseFixedPoint + toGain);

                    EventSink.InvokeSkillGain(new SkillGainEventArgs(from, skill, toGain));

                    if (from is PlayerMobile)
                    {
                        UpdateGGS(from, skill);
                    }
                }
            }

            #region Mondain's Legacy
            if (from is PlayerMobile)
            {
                QuestHelper.CheckSkill((PlayerMobile)from, skill);
            }
            #endregion

            if (skill.Lock == SkillLock.Up &&
                (!Siege.SiegeShard || !(from is PlayerMobile) || Siege.CanGainStat((PlayerMobile)from)))
            {
                var info = skill.Info;

                // Old gain mechanic
                if (!Core.ML)
                {
                    var scalar = 1.0;

                    if (from.StrLock == StatLockType.Up && (info.StrGain / 33.3) * scalar > Utility.RandomDouble())
                    {
                        GainStat(from, Stat.Str);
                    }
                    else if (from.DexLock == StatLockType.Up && (info.DexGain / 33.3) * scalar > Utility.RandomDouble())
                    {
                        GainStat(from, Stat.Dex);
                    }
                    else if (from.IntLock == StatLockType.Up && (info.IntGain / 33.3) * scalar > Utility.RandomDouble())
                    {
                        GainStat(from, Stat.Int);
                    }
                }
                else
                {
                    TryStatGain(info, from);
                }
            }
        }
Beispiel #58
0
 void HandleWidgetFocusInEvent(object o, Gtk.FocusInEventArgs args)
 {
     Toolkit.Invoke(delegate {
         EventSink.OnGotFocus();
     });
 }
Beispiel #59
0
		public void TestWithoutAndWithWeakEventHandlerWithStorage()
		{
			var counter = new InstanceCounter();

			var evSrc = new EventSource();
			var evSink1 = new EventSink(counter);
			var evSink2 = new EventSink(counter);
			var evSink3 = new EventSink(counter);
			var evSink4 = new EventSink(counter);
			var evSink5 = new EventSink(counter);

			Assert.AreEqual(5, counter.Instances);

			evSrc.Changed += (evSink1.StoreTheWeakEventHandler = new WeakEventHandler(evSink1.EhChanged, (h) => evSrc.Changed -= h)); // with storage
			evSrc.Changed += (evSink1.StoreTheWeakEventHandler = new WeakEventHandler(evSink2.EhChanged, (h) => evSrc.Changed -= h)); // with storage
			evSrc.Changed += new WeakEventHandler(evSink3.EhChanged, (h) => evSrc.Changed -= h); // without storage
			evSrc.Changed += evSink4.EhChanged;
			evSrc.Changed += evSink5.EhChanged;

			evSink1 = null;
			evSink2 = null;
			evSink3 = null;
			evSink4 = null;
			evSink5 = null;

			GC.Collect();
			System.Threading.Thread.Sleep(500);
			GC.Collect();

			Assert.AreEqual(2, counter.Instances); // the 2 instances that are reachable by ordinary event handlers should be still reachable
		}
Beispiel #60
0
        internal bool DoDragDataReceived(Gdk.DragContext context, int x, int y, Gtk.SelectionData selectionData, uint info, uint time)
        {
            if (DragDropInfo.DragDataRequests == 0)
            {
                // Got the data without requesting it. Create the datastore here
                DragDropInfo.DragData         = new TransferDataStore();
                DragDropInfo.LastDragPosition = new Point(x, y);
                DragDropInfo.DragDataRequests = 1;
            }

            DragDropInfo.DragDataRequests--;

            // If multiple drag/drop data types are supported, we need to iterate through them all and
            // append the data. If one of the supported data types is not found, there's no need to
            // bail out. We must raise the event
            Util.GetSelectionData(ApplicationContext, selectionData, DragDropInfo.DragData);

            if (DragDropInfo.DragDataRequests == 0)
            {
                if (DragDropInfo.DragDataForMotion)
                {
                    // If no specific action is set, it means that no key has been pressed.
                    // In that case, use Move or Copy or Link as default (when allowed, in this order).
                    var cact = ConvertDragAction(context.Actions);
                    if (cact != DragDropAction.Copy && cact != DragDropAction.Move && cact != DragDropAction.Link)
                    {
                        if (cact.HasFlag(DragDropAction.Move))
                        {
                            cact = DragDropAction.Move;
                        }
                        else if (cact.HasFlag(DragDropAction.Copy))
                        {
                            cact = DragDropAction.Copy;
                        }
                        else if (cact.HasFlag(DragDropAction.Link))
                        {
                            cact = DragDropAction.Link;
                        }
                        else
                        {
                            cact = DragDropAction.None;
                        }
                    }

                    DragOverEventArgs da = new DragOverEventArgs(DragDropInfo.LastDragPosition, DragDropInfo.DragData, cact);
                    ApplicationContext.InvokeUserCode(delegate {
                        EventSink.OnDragOver(da);
                    });
                    OnSetDragStatus(context, (int)DragDropInfo.LastDragPosition.X, (int)DragDropInfo.LastDragPosition.Y, time, ConvertDragAction(da.AllowedAction));
                    return(true);
                }
                else
                {
                    // Use Context.Action here since that's the action selected in DragOver
                    var           cda = ConvertDragAction(context.GetSelectedAction());
                    DragEventArgs da  = new DragEventArgs(DragDropInfo.LastDragPosition, DragDropInfo.DragData, cda);
                    ApplicationContext.InvokeUserCode(delegate {
                        EventSink.OnDragDrop(da);
                    });
                    Gtk.Drag.Finish(context, da.Success, cda == DragDropAction.Move, time);
                    return(true);
                }
            }
            else
            {
                return(false);
            }
        }