Наследование: MonoBehaviour
Пример #1
0
 public Environment(IGameController gameController, EventFactory eventFactory)
 {
     _gameController = gameController;
     _eventFactory = eventFactory;
     _rnd = new Random (DateTime.Now.Millisecond);
     _ballProbability = 12;
 }
Пример #2
0
 public GameContainer(GameCore core, IGameController controller, Environment environment, bool isServer)
 {
     GameCore = core;
     EventFactory = new EventFactory (GameCore);
     GameController = controller;
     Environment = environment;
     _hasEnvironment = isServer;
 }
Пример #3
0
        public void Send <TCommand>(TCommand command, bool publishEvents = true) where TCommand : ICommand
        {
            var commandHandler = GetHandler <ICommandHandler <TCommand>, TCommand>(command);

            var events = commandHandler.Handle(command);

            if (!publishEvents)
            {
                return;
            }

            if (events != null)
            {
                foreach (var @event in events)
                {
                    var concreteEvent = EventFactory.CreateConcreteEvent(@event);
                    _eventPublisher.Publish(concreteEvent);
                }
            }
        }
Пример #4
0
        public void TwoSimultaneousEvents_InmemoryStore()
        {
            var streamId = Guid.NewGuid();
            var event1   = EventFactory.Create(streamId, new Created("Apan"));
            var event2   = EventFactory.Create(streamId, new Created("Katten"));

            using (var store = persistenceStore.CreateInMemoryConnection())
                using (var stream = store.OpenStream(streamId, 0))
                    using (var stream2 = store.OpenStream(streamId, 0))
                    {
                        stream.Add(new EventMessage {
                            Body = event1.Data
                        });
                        stream.CommitChanges(event1.EventId);

                        stream2.Add(new EventMessage {
                            Body = event2.Data
                        });
                        Assert.Throws <ConcurrencyException>(() => stream2.CommitChanges(event2.EventId));
                    }
        }
Пример #5
0
        public void OneEvent_InMemoryStoreTest()
        {
            var streamId = Guid.NewGuid();
            var event1   = EventFactory.Create(streamId, new Created("Apan"));

            using (var store = persistenceStore.CreateInMemoryConnection())
            {
                using (var stream = store.OpenStream(streamId, 0))
                {
                    stream.Add(new EventMessage {
                        Body = event1.Data
                    });
                    stream.CommitChanges(event1.EventId);
                }

                using (var stream = store.OpenStream(streamId, 0))
                {
                    stream.CommittedEvents.Count.ShouldBe(1);
                }
            }
        }
Пример #6
0
        public void stopPlay()
        {
            if (curSession != null)
            {
                lock (EmotionModel.svmFeature)
                {
                    for (int i = 0; i < videoFeatureNum; i++)
                    {
                        EmotionModel.svmFeature[i].Value = 0;
                    }
                }
                // 创建StopEvent
                StopEvent e = (StopEvent)EventFactory.createMomentEvent(curSession.SessionID, (int)mPlayer.GetPlayTime(), MomentEventType.STOP);
                storeModule.saveMomentEvent(e);
                // For Debug
                Console.WriteLine(JsonConvert.SerializeObject(e));

                mPlayer.Stop();
                isPlaying = false;
            }
        }
Пример #7
0
        public void RehydrateAggregateFailsIfEventAggregateIdMismatch()
        {
            var aggregateId  = Guid.NewGuid().ToString();
            var locationName = "location1";
            var item         = new StockItem("item1", "1");

            var contextMap = new BoundedContextModel().WithAssemblyContaining <Location>();

            var aggregateRoot    = new Location();
            var aggregateAdapter = AggregateAdapterFactory.Default.CreateAggregate(contextMap, aggregateRoot).WithId(aggregateId);

            var eventAdapterFactory = new EventFactory();

            var aggregateEventHistory = new List <IEvent>();

            aggregateEventHistory.Add(eventAdapterFactory.CreateEvent <Location, LocationCreated>(aggregateId, 1, string.Empty, string.Empty, new LocationCreated(locationName, string.Empty)));
            aggregateEventHistory.Add(eventAdapterFactory.CreateEvent <Location, AdjustedIn>(aggregateId, 2, string.Empty, string.Empty, new AdjustedIn($"adjustment_{Guid.NewGuid()}", locationName, item)));
            aggregateEventHistory.Add(eventAdapterFactory.CreateEvent <Location, MovedOut>(Guid.NewGuid().ToString(), 3, string.Empty, string.Empty, new MovedOut($"movement_{Guid.NewGuid()}", locationName, item, "toLocationName")));

            Assert.ThrowsException <ArgumentException>(() => aggregateAdapter.Rehydrate(aggregateEventHistory));
        }
Пример #8
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            if (turnContext.Activity.Text.Contains("human"))
            {
                await turnContext.SendActivityAsync($"You have requested transfer to an agent, ConversationId={turnContext.Activity.Conversation.Id}");

                var a1         = MessageFactory.Text($"first message");
                var a2         = MessageFactory.Text($"second message");
                var transcript = new Activity[] { a1, a2 };
                var context    = new { Skill = "credit cards" };

                var handoffEvent = EventFactory.CreateHandoffInitiation(turnContext, context, new Transcript(transcript));
                await turnContext.SendActivityAsync(handoffEvent);

                await turnContext.SendActivityAsync($"Agent transfer has been initiated");
            }
            else
            {
                await turnContext.SendActivityAsync(MessageFactory.Text($"Echo: {turnContext.Activity.Text}"), cancellationToken);
            }
        }
Пример #9
0
    private static IGameController MakeController(GameType type, GameCore core, EventFactory eventFactory)
    {
        IGameController controller;
        var baseController = new GameController(core, eventFactory);
        switch (type)
        {
        case GameType.Local:
            controller = baseController;
            break;
        case GameType.Streaming:
            controller = new ServerController(baseController);
            break;
        case GameType.Watching:
            controller = new ClientController(baseController);
            break;
        default:
            throw new ArgumentOutOfRangeException("GameType");
        }

        return controller;
    }
Пример #10
0
        public void Publish(HttpRequest req, HttpResponse res)
        {
            var evt       = req.ParseJSON <PublishedEvent>();
            var eventType = EventFactory.GetPublishedEventType(evt.Name);
            var evtData   = req.ParseJSON(eventType) as PublishedEvent;

            if (evtData == null || eventType == null || evtData == null)
            {
                res.SendError(StatusCode.BadRequest, "Invalid data");
                return;
            }

            var subs = _subscriptions.Where(sub => sub.SubscribedEvent == evt.Name).ToList();

            req.Server.RaiseLogEvent("info", string.Format("event published: {0}", req.RawBody));

            // loop for all subscribers have registered for push notification
            foreach (var sub in subs)
            {
                var resource = EventFactory.CreatePublishedResource(evt.Name, sub.ClientId, evtData);

                if (!string.IsNullOrEmpty(sub.Endpoint))
                {
                    try
                    {
                        WebClient.PostJsonAsync(sub.Endpoint, resource, (responseText) =>
                        {
                            req.Server.RaiseLogEvent("info", string.Format("forwarded to subscriber {0}", sub.ClientId));
                        });
                    }
                    catch { }
                }
                else
                {
                    _resources.Add(resource);
                }
            }

            res.SendJson(new { success = true });
        }
Пример #11
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var conversationStateAccessors = _conversationState.CreateProperty <LoggingConversationData>(nameof(LoggingConversationData));
            var conversationData           = await conversationStateAccessors.GetAsync(turnContext, () => new LoggingConversationData());

            var userText = turnContext.Activity.Text.ToLowerInvariant();

            if (userText.Contains("agent"))
            {
                await turnContext.SendActivityAsync("Your request will be escalated to a human agent");

                var transcript = new Transcript(conversationData.ConversationLog.Where(a => a.Type == ActivityTypes.Message).ToList());

                var evnt = EventFactory.CreateHandoffInitiation(turnContext,
                                                                new { Skill = "credit-cards" },
                                                                transcript);

                await turnContext.SendActivityAsync(evnt);
            }
            else
            {
                string replyText = $"Sorry, I cannot help you.";
                if (userText == "hi")
                {
                    replyText = "Hello!";
                }
                else
                {
                    foreach (var country in Capitals.Keys)
                    {
                        if (userText.Contains(country.ToLower()))
                        {
                            replyText = $"The capital of {country} is {Capitals[country]}";
                        }
                    }
                }

                await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);
            }
        }
Пример #12
0
 public void quitSkip()
 {
     skipEndVideoTS = getPlayTime();
     if (skipEndVideoTS > skipStartVideoTS)
     {
         lock (EmotionModel.svmFeature)
         {
             EmotionModel.svmFeature[(int)VideoFeature.FORWARDSKIP].Value = 1;
         }
         ForwardSkipEvent forwardSkipEvent = new ForwardSkipEvent(undeterminedSkipEvent);
         EventFactory.finishPeriodEvent(forwardSkipEvent, skipEndVideoTS);
         storeModule.savePeriodEvent(forwardSkipEvent);
         // for debug
         Console.WriteLine(JsonConvert.SerializeObject(forwardSkipEvent));
         lock (EmotionModel.svmFeature)
         {
             EmotionModel.svmFeature[(int)VideoFeature.FORWARDSKIP].Value = 0;
         }
     }
     else if (skipEndVideoTS < skipStartVideoTS)
     {
         lock (EmotionModel.svmFeature)
         {
             EmotionModel.svmFeature[(int)VideoFeature.REVERSESKIP].Value = 1;
         }
         ReverseSkipEvent reverseSkipEvent = new ReverseSkipEvent(undeterminedSkipEvent);
         EventFactory.finishPeriodEvent(reverseSkipEvent, skipEndVideoTS);
         storeModule.savePeriodEvent(reverseSkipEvent);
         // for debug
         Console.WriteLine(JsonConvert.SerializeObject(reverseSkipEvent));
         lock (EmotionModel.svmFeature)
         {
             EmotionModel.svmFeature[(int)VideoFeature.REVERSESKIP].Value = 0;
         }
     }
     undeterminedSkipEvent = null;
     skipStartVideoTS      = 0;
     skipEndVideoTS        = 0;
 }
Пример #13
0
        public override void fireEvent()
        {
            attacker.State = Entity.EntityState.IDLE;
            Trace.WriteLine(attacker.Name + " has attacked " + defender.Name);
            //for now, make it simple
            int damage = 10;

            //get damage based on weapon
            if (attacker is Player)
            {
                damage += ((Weapon)(((Player)attacker).EquipmentIn(EquipmentTypes.MELEE_WEAPON))).Damage;
                Trace.WriteLine("Player attacks zombie with " + ((Player)attacker).EquipmentIn(EquipmentTypes.MELEE_WEAPON) +
                                " for " + damage + " damage");
            }

            defender.Health -= damage;
            if (defender.Health <= 0)
            {
                //if it's a gun, make a NoiseEvent
                EventHandler.Instance.AddEvent(EventFactory.CreateKillEntityEvent(defender));
            }
        }
        public void TestCreateHandoffStatus()
        {
            var state        = "failed";
            var message      = "timed out";
            var handoffEvent = EventFactory.CreateHandoffStatus(new ConversationAccount(), state, message);

            Assert.AreEqual(handoffEvent.Name, HandoffEventNames.HandoffStatus);

            var stateFormEvent = (handoffEvent.Value as JObject)?.Value <string>("state");

            Assert.AreEqual(stateFormEvent, state);

            var messageFormEvent = (handoffEvent.Value as JObject)?.Value <string>("message");

            Assert.AreEqual(messageFormEvent, message);

            string status = JsonConvert.SerializeObject(handoffEvent.Value, Formatting.None);

            Assert.AreEqual(status, $"{{\"state\":\"{state}\",\"message\":\"{message}\"}}");
            Assert.IsNotNull((handoffEvent as Activity).Attachments);
            Assert.IsNotNull(handoffEvent.Id);
        }
Пример #15
0
        public async Task SendAsync <TCommand, TAggregate>(TCommand command, bool publishEvents = true)
            where TCommand : ICommand
            where TAggregate : IAggregateRoot
        {
            var commandHandler = GetHandler <ICommandHandlerAsync <TCommand>, TCommand>(command);

            var events = await commandHandler.HandleAsync(command);

            foreach (var @event in events)
            {
                var concreteEvent = EventFactory.CreateConcreteEvent(@event);

                await _eventStore.SaveEventAsync <TAggregate>((IDomainEvent)concreteEvent);

                if (!publishEvents)
                {
                    continue;
                }

                await _eventPublisher.PublishAsync(concreteEvent);
            }
        }
Пример #16
0
        public void SameSocketTag()
        {
            TagBuilder builder = new TagBuilder();

            Event firstCreateEvent = EventFactory.CreateFromXml(TestEventXml.E083_CreateSocket);

            builder.Process(firstCreateEvent);
            Event firstConnEvent = EventFactory.CreateFromXml(TestEventXml.E084_Connect);

            builder.Process(firstConnEvent);

            Event secondCreateEvent = EventFactory.CreateFromXml(TestEventXml.E141_CreateSocket);

            builder.Process(secondCreateEvent);
            Event secondConnEvent = EventFactory.CreateFromXml(TestEventXml.E142_Connect);

            builder.Process(secondConnEvent);

            Assert.That(firstCreateEvent.Tags[0], Is.SameAs(firstConnEvent.Tags[0]));
            Assert.That(secondCreateEvent.Tags[0], Is.SameAs(secondConnEvent.Tags[0]));
            Assert.That(firstCreateEvent.Tags[0], Is.Not.SameAs(secondCreateEvent.Tags[0]));
        }
    /*
     * Sets the container to contain this unit, and changes state, if the unit is within range of the target container.
     *
     * @param parent
     *      The container that will contain this unit.
     */
    public void Embark(String parent)
    {
        //Debug.Log ("HERE:" + parent);

        GameObject g = GuidList.GetGameObject(parent);

        if (g.GetComponent <ContainerController> ().GetInUse())
        {
            if (Vector3.Distance(this.transform.position, GuidList.GetGameObject(parent).transform.position) < this.gameObject.GetComponent <MoverController> ().MoveRange)
            {
                // throw the UnitEmbarksEvent event
                object[] arguments = new object[2];
                arguments [0] = this.gameObject.GetComponent <IdentityController> ().GetGuid();
                arguments [1] = GuidList.GetGameObject(parent).GetComponent <IdentityController> ().GetGuid();
                Parent        = parent;
                //Debug.Log ("HEREERE: "  + Parent);
                EventManager.Instance.AddEvent(EventFactory.CreateEvent(GEventType.UnitEmbarksEvent, arguments, 1));
            }
            gameObject.GetComponent <CircleCollider2D> ().enabled = false;
            gameObject.GetComponent <SpriteRenderer> ().enabled   = false;
        }
    }
Пример #18
0
        public Respuesta <bool> Anular(string sessionId, string company, string branch, string code, string reason)
        {
            try
            {
                ValidateLoginInfo(sessionId, Securables.WebServiceTickets);

                var empresa = GetEmpresaByCode(company);
                var linea   = string.IsNullOrEmpty(branch) ? null : GetLineaByCode(branch, empresa);
                var codigo  = code.Trim();
                if (string.IsNullOrEmpty(codigo))
                {
                    throw new ApplicationException("El codigo no puede estar vacío");
                }

                var ticket = DAOFactory.TicketDAO.FindByCode(new[] { empresa.Id }, new[] { linea != null ? linea.Id : -1 }, codigo);

                if (ticket == null)
                {
                    throw new ApplicationException("No se encontró un ticket con el código: " + code);
                }

                if (ticket.Estado == Ticket.Estados.EnCurso)
                {
                    var ciclo        = new CicloLogisticoHormigon(ticket, DAOFactory, new MessageSaver(DAOFactory));
                    var eventoCierre = EventFactory.GetCloseEvent();
                    ciclo.ProcessEvent(eventoCierre);
                }
                ticket.Anular(reason, Usuario);

                DAOFactory.TicketDAO.SaveOrUpdate(ticket);

                return(Respuesta <bool> .Create(true));
            }
            catch (Exception e)
            {
                STrace.Error("WebService Tickets", e.Message);
                return(Respuesta <bool> .CreateError(e.Message));
            }
        }
Пример #19
0
    /**
     * Allows the unit to take damage. Checks if the unit should die after
     * damage is dealt.
     *
     * @param damage
     *      The amount of damage the unit will take
     */
    public void DamageUnit(float damage, string causingTeam)
    {
        // Deal damage to the unit
        SetCurrentHealth(GetCurrentHealth() - damage);

        // Check if the unit shoud die
        if (GetCurrentHealth() <= 0 && !Dying)
        {
            // If the unit should die

            // throws the event for death
            object[] arguments = new object[5];
            arguments [0] = (this.gameObject.GetComponent <IdentityController> ()).GetGuid();
            arguments [1] = causingTeam;
            arguments [2] = this.gameObject.GetComponent <IdentityController> ().GetName();
            arguments [3] = Team.Teams[this.gameObject.GetComponent <IdentityController> ().GetTeam()].GetTeamName();
            arguments [4] = this.gameObject.GetComponent <IdentityController> ().GetFullName();

            EventManager.Instance.AddEvent(EventFactory.CreateEvent(GEventType.DieEvent, arguments));
            Dying = true;
        }
    }
Пример #20
0
        public void Send <TCommand, TAggregate>(TCommand command, bool publishEvents = true)
            where TCommand : ICommand
            where TAggregate : IAggregateRoot
        {
            var commandHandler = GetHandler <ICommandHandler <TCommand>, TCommand>(command);

            var events = commandHandler.Handle(command);

            foreach (var @event in events)
            {
                var concreteEvent = EventFactory.CreateConcreteEvent(@event);

                _eventStore.SaveEvent <TAggregate>((IDomainEvent)concreteEvent);

                if (!publishEvents)
                {
                    continue;
                }

                _eventPublisher.Publish(concreteEvent);
            }
        }
Пример #21
0
        public override void fireEvent()
        {
            mover.State = Creature.EntityState.IDLE;
            if (destination != null && destination.GameMap.IsInMap(destination.Coordinates))
            {
                //check for props and entities first
                if (destination.PropInBlock != null)
                {
                    if (!destination.PropInBlock.Passable)
                    {
                        //If it's a door and the mover is a player, then just open the door
                        if (destination.PropInBlock is Door && mover is Player)
                        {
                            destination.PropInBlock.Interact((Player)mover);
                        }
                        else if (mover is Zombie)
                        {
                            //zombies just destroy shit because they feel unloved.
                            EventHandler.Instance.AddEvent(EventFactory.CreateAttackPropEvent(mover, destination.PropInBlock));
                        }
                        mover.State = Creature.EntityState.IDLE;

                        return;
                    }
                }
                if (destination.CreatureInBlock != null)
                {
                    Creature defender = destination.CreatureInBlock;
                    if (!(mover is Zombie && defender is Zombie))
                    {
                        EventHandler.Instance.AddEvent(EventFactory.CreateAttackEvent(mover, destination.CreatureInBlock));
                    }
                    return;
                }
                mover.Location.RemoveObject(mover);
                destination.AddObject(mover);
                mover.Location = destination;
            }
        }
Пример #22
0
        private SessionModel StartSession(bool isFirstSession = false)
        {
            SessionModel activeSession;

            lock (this.ActiveSessionLock)
            {
                this.EnsureActiveSessionFinished();
                if (this.ActiveSession != null && this.ActiveSession.EventCounter > 0UL)
                {
                    lock (this.CompletedSessions)
                        this.CompletedSessions.Add(this.ActiveSession);
                }
                this.ActiveSession = LiteMetricaCore.CreateSession();
                ReportMessage.Session.Event[] eventArray;
                if (!isFirstSession)
                {
                    eventArray = new ReportMessage.Session.Event[1]
                    {
                        EventFactory.Create(ReportMessage.Session.Event.EventType.EVENT_START, (byte[])null, (string)null, (string)null)
                    }
                }
                ;
                else
                {
                    eventArray = new ReportMessage.Session.Event[3]
                    {
                        EventFactory.Create(ReportMessage.Session.Event.EventType.EVENT_FIRST, (byte[])null, (string)null, (string)null),
                        EventFactory.Create(ReportMessage.Session.Event.EventType.EVENT_START, (byte[])null, (string)null, (string)null),
                        EventFactory.Create(Config.Global.HandleFirstActivationAsUpdate ? ReportMessage.Session.Event.EventType.EVENT_UPDATE : ReportMessage.Session.Event.EventType.EVENT_INIT, (byte[])null, (string)null, (string)null)
                    }
                };
                this.Report(eventArray);
                Config.Global.LastWakeTime = new DateTime?(DateTime.UtcNow);
                activeSession = this.ActiveSession;
            }
            this.TriggerForcedSend();
            return(activeSession);
        }
    /**
     * Raises a create target event
     *
     * @param target
     *      The object to be targeted.
     */
    public void SetTargetEvent(string target, int amount)
    {
        object[] arguments = new object[4];

        arguments [0] = Owner;
        arguments [1] = target;
        arguments [2] = GetName();
        arguments [3] = amount;

        int MaxShotsAllowedToTarget = MaxShots - CurShotsTargeted;

        if (Targets.ContainsKey(target))
        {
            int currentShotsTargetedAtOne = Targets[target];
            MaxShotsAllowedToTarget += currentShotsTargetedAtOne;
        }

        if (!(target.Equals(Owner)) && (amount <= MaxShotsAllowedToTarget) && (CurShotsTargeted + amount <= CurAmmo))          //Check we are not firing at ourselves

        {
            EventFactory.ThrowEvent(GEventType.WeaponTargetEvent, arguments);
        }
    }
Пример #24
0
        public object Delete(WpsJobDeleteRequestTep request)
        {
            var  context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            bool result  = false;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/job/wps/{{Id}} DELETE Id='{0}'", request.id));

                WpsJob job = null;
                job = WpsJob.FromIdentifier(context, request.id);
                EventFactory.LogWpsJob(context, job, "Job deleted", "portal_job_delete");
                job.Delete();
                result = true;

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(new WebResponseBool(result));
        }
Пример #25
0
 // Checks prerequisites if any; returns null if successful, or an EvaluationReason if we have to
 // short-circuit due to a prerequisite failure.
 private EvaluationReason CheckPrerequisites(User user, IFeatureStore featureStore, IList <FeatureRequestEvent> events,
                                             EventFactory eventFactory)
 {
     if (Prerequisites == null || Prerequisites.Count == 0)
     {
         return(null);
     }
     foreach (var prereq in Prerequisites)
     {
         var prereqOk          = true;
         var prereqFeatureFlag = featureStore.Get(VersionedDataKind.Features, prereq.Key);
         if (prereqFeatureFlag == null)
         {
             Log.ErrorFormat("Could not retrieve prerequisite flag \"{0}\" when evaluating \"{1}\"",
                             prereq.Key, Key);
             prereqOk = false;
         }
         else
         {
             var prereqEvalResult = prereqFeatureFlag.Evaluate(user, featureStore, events, eventFactory);
             // Note that if the prerequisite flag is off, we don't consider it a match no matter
             // what its off variation was. But we still need to evaluate it in order to generate
             // an event.
             if (!prereqFeatureFlag.On || prereqEvalResult.VariationIndex == null || prereqEvalResult.VariationIndex.Value != prereq.Variation)
             {
                 prereqOk = false;
             }
             events.Add(eventFactory.NewPrerequisiteFeatureRequestEvent(prereqFeatureFlag, user,
                                                                        prereqEvalResult, this));
         }
         if (!prereqOk)
         {
             return(new EvaluationReason.PrerequisiteFailed(prereq.Key));
         }
     }
     return(null);
 }
Пример #26
0
        /// <summary>
        /// Sends impression event.
        /// </summary>
        /// <param name="experiment">The experiment</param>
        /// <param name="variation">The variation entity</param>
        /// <param name="userId">The user ID</param>
        /// <param name="userAttributes">The user's attributes</param>
        private void SendImpressionEvent(Experiment experiment, Variation variation, string userId,
                                         UserAttributes userAttributes, ProjectConfig config)
        {
            if (experiment.IsExperimentRunning)
            {
                var userEvent = UserEventFactory.CreateImpressionEvent(config, experiment, variation.Id, userId, userAttributes);
                EventProcessor.Process(userEvent);
                Logger.Log(LogLevel.INFO, $"Activating user {userId} in experiment {experiment.Key}.");

                // Kept For backwards compatibility.
                // This notification is deprecated and the new DecisionNotifications
                // are sent via their respective method calls.
                if (NotificationCenter.GetNotificationCount(NotificationCenter.NotificationType.Activate) > 0)
                {
                    var impressionEvent = EventFactory.CreateLogEvent(userEvent, Logger);
                    NotificationCenter.SendNotifications(NotificationCenter.NotificationType.Activate, experiment, userId,
                                                         userAttributes, variation, impressionEvent);
                }
            }
            else
            {
                Logger.Log(LogLevel.ERROR, @"Experiment has ""Launched"" status so not dispatching event during activation.");
            }
        }
    /**
     * Creates a new user and adds them to the specified team.
     *
     * @param permissionLevel
     *      The permission level of the user
     * @param branch
     *      The branch of the military this user is playing for
     * @param team
     *      The team the user will be added to
     * @param username
     *      The name the user wants to use
     * @param unitGuid
     *      The string form of the Guid that represents the object.
     *
     * @return
     *      True	The user was added
     *      False	The was not created because the username already exists
     */
    public static bool AddNewUser(PermissionLevel permissionLevel, MilitaryBranch branch, int team, string username, string unitGuid)
    {
        // Check if the username is used by that team
        if (Team.UsernameInUse(username))
        {
            // If the username is already in use
            //Debug.Log ("Username in use");
            // Return false because the user cannot be added.
            return(false);
        }

        object[] arguments = new object[5];
        arguments[0] = permissionLevel;
        arguments[1] = branch;
        arguments[2] = team;
        arguments[3] = username;
        arguments[4] = unitGuid;

        GEvent e = EventFactory.CreateEvent(GEventType.PlayerJoinEvent, arguments);

        EventManager.Instance.AddEvent(e);
        //Debug.Log ("User Join event raised");
        return(true);
    }
Пример #28
0
        private void ddlEvent_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlEvent.SelectedValue.GetType().Name == "DataRowView")
            {
                ddlEvent.SelectedValue = dtEvent.Rows[0]["Value"].ToString();
                return;
            }

            if (ddlEvent.SelectedValue.ToString() != String.Empty)
            {
                EnumEvent enumEvent = (EnumEvent)(Convert.ToInt32(ddlEvent.SelectedValue));

                //根据选择的动作类型,初始化不同的参数设置面板
                this.Event = EventFactory.GetEventDev(enumEvent);
            }
            else
            {
                this.Event = null;
            }

            if (this.Event != null)
            {
                this.iEventParameterSet = (IEventParameterSet)this.Event;

                this.treeViewParameter.Nodes.Clear();
                this.treeViewParameter.Nodes.Add(iEventParameterSet.GetParameterSetNode(this.FormEntity));
                this.treeViewParameter.ExpandAll();
                this.treeViewParameter.SelectedNode = iEventParameterSet.DefaultSelectedNode;
            }
            else
            {
                this.iEventParameterSet = null;
                this.treeViewParameter.Nodes.Clear();
                this.panelParameter.Controls.Clear();
            }
        }
Пример #29
0
        static void GenerateLogs()
        {
            EventFactory _e = new EventFactory("LogGeneratorSample");

            // Setup event factory with three fields
            _e.Fields.Add(new EventFieldDefinition("message", false));
            _e.Fields.Add(new EventFieldDefinition("level", false));
            _e.Fields.Add(new EventFieldDefinition("status", true));

            // Create a new event
            Event _ev = _e.NewEvent();

            // Fill the newly created event
            _ev["message"].Value = "This is a sample message";
            //_ev["level"].Value = "verbose";
            _ev["status"].SetValue(200);


            Console.WriteLine("\n" + _e.Flush());


            Console.WriteLine("\nPress any key to continue...");
            Console.ReadKey();
        }
Пример #30
0
        private async Task <DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var leavePolicyDetails = (LeavePolicyViewModel)stepContext.Options;

            if (leavePolicyDetails.LeaveOfAbscensePolicy == null)
            {
                leavePolicyDetails.LeaveOfAbscensePolicy = ((FoundChoice)stepContext.Result).Value;
            }

            //Handle bereavement leave by transferring the call to a more capable bot.
            if (leavePolicyDetails.LeaveOfAbscensePolicy == "Bereavement leave")
            {
                await stepContext.Context.SendActivityAsync(VoiceFactory.TextAndVoice(BereavementResponse, InputHints.IgnoringInput), cancellationToken);

                await Task.Delay(10000); //Temporary hack to make sure message is done reading out loud before transfer starts. Bug is tracked to fix this issue.

                //Create handoff event, passing the phone number to transfer to as context.
                var context      = new { TargetPhoneNumber = TransferNumber };
                var handoffEvent = EventFactory.CreateHandoffInitiation(stepContext.Context, context);
                await stepContext.Context.SendActivityAsync(
                    handoffEvent,
                    cancellationToken);

                return(await stepContext.EndDialogAsync());
            }
            else
            {
                //Handle other leave types with a single message.
                await stepContext.Context.SendActivityAsync(VoiceFactory.TextAndVoice(ParentalAndSabbaticalPolicyResponse, InputHints.IgnoringInput), cancellationToken);
            }

            // Restart the upstream dialog with a different message the second time around
            var promptMessage = "What else can I do for you?";

            return(await stepContext.ReplaceDialogAsync(nameof(EmployeeDialog), promptMessage, cancellationToken));
        }
Пример #31
0
 private void Subscribe(ILifecycler lifecycler)
 {
     lifecycler.End                += (EventHandler)((sender, args) => this.Lull());
     lifecycler.Resume             += (EventHandler)((sender, args) => this.Wake(false, false));
     lifecycler.Suspend            += (EventHandler)((sender, args) => this.Lull());
     lifecycler.UnhandledException += (EventHandler)((sender, args) =>
     {
         if (Adapter.IsInternalException((object)args))
         {
             return;
         }
         if (Config.Global.CrashTracking)
         {
             Config.Global.CrashTracking = false;
             this.Report(EventFactory.Create(ReportMessage.Session.Event.EventType.EVENT_CRASH, Adapter.ExtractData((object)args), (string)null, (string)null));
             Config.Global.CrashTracking = true;
             Store.Snapshot();
         }
         else
         {
             this.Lull();
         }
     });
 }
Пример #32
0
 public IrcConnection(EventFactory eventFactory, EventAggregator eventAggregator)
 {
     this.eventFactory = eventFactory;
     this.eventAggregator = eventAggregator;
 }
Пример #33
0
    private void SetGameInternal(GameType type, bool hasEnvironment)
    {
        var TextureContainer = new TextureContainer ();
        var BallFactory = new BallFactory (TextureContainer);
        var BallManager = new BallManager (BallFactory);
        var GameCore = new GameCore (BallManager);
        var EventFactory = new EventFactory (GameCore);
        var GameController = MakeController (type, GameCore, EventFactory);
        var Environment = new Environment (GameController, EventFactory);

        _container = new GameContainer (GameCore, GameController, Environment, hasEnvironment);
        HasErrors = false;
        Initialized = true;
    }
        public override EventBean Make(object[] properties)
        {
            var und = (IDictionary <string, object>)MakeUnderlying(properties);

            return(EventFactory.AdapterForTypedMap(und, EventType));
        }
Пример #35
0
 public PictureController()
 {
     eventFactory        = new EventFactory();
     pictureFactory      = new PictureFactory();
     organisationFactory = new OrganisationFactory();
 }
Пример #36
0
 public GameController(GameCore gameCore, EventFactory eventFactory)
 {
     _eventFactory = eventFactory;
     _gameCore = gameCore;
 }