Esempio n. 1
0
        public void Handle(FutureEventScheduledEvent futureEventScheduledEvent, IMessageMetadata messageMetadata)
        {
            var message = futureEventScheduledEvent;
            Guid scheduleId = message.Id;
            Guid aggregateId = message.Event.SourceId;

            var description = $"Aggregate {typeof(TAggregate).Name} id = {aggregateId} scheduled future event " +
                              $"{scheduleId} with payload type {message.Event.GetType().Name} on time {message.RaiseTime}\r\n" +
                              $"Future event: {message.ToPropsString()}";

            var scheduleKey = CreateScheduleKey(scheduleId, aggregateId, description);

            var command = new RaiseScheduledDomainEventCommand(message.Id, message.SourceId, Guid.NewGuid());
            var metadata = messageMetadata.CreateChild(command.Id,
                                                                new ProcessEntry(GetType().Name, 
                                                                                 "Scheduling raise future event command",
                                                                                 "FutureEventScheduled event occured"));

            var confirmationEventType = typeof(IMessageMetadataEnvelop<>).MakeGenericType(message.Event.GetType());

            var scheduleEvent = new ScheduleCommand(command,
                                                    scheduleKey,
                                                    new ExtendedExecutionOptions(message.RaiseTime,
                                                                                 confirmationEventType, 
                                                                                 message.Event.SourceId,
                                                                                 nameof(DomainEvent.SourceId)),
                                                    metadata);

            _schedulerActorRef.Handle(scheduleEvent);
        }
Esempio n. 2
0
        public void SetUp()
        {
            Clock.Reset();

            Command <Order> .AuthorizeDefault = (order, command) => true;

            disposables = new CompositeDisposable
            {
                Disposable.Create(Clock.Reset)
            };

            schedule = GetScheduleDelegate();

            commandsScheduled = new ConcurrentBag <IScheduledCommand>();
            commandsDelivered = new ConcurrentBag <IScheduledCommand>();

            var configuration = new Configuration()
                                .TraceScheduledCommands() // trace to console
                                .TraceScheduledCommands(
                onScheduling: _ => { },
                onScheduled: c => commandsScheduled.Add(c),
                onDelivering: _ => { },
                onDelivered: c => commandsDelivered.Add(c));

            Configure(configuration);

            disposables.Add(ConfigurationContext.Establish(configuration));
        }
        public void SetUp()
        {
            Clock.Reset();

            disposables = new CompositeDisposable
            {
                Disposable.Create(Clock.Reset)
            };

            schedule = GetScheduleDelegate();

            commandsScheduled = new ConcurrentBag<IScheduledCommand>();
            commandsDelivered = new ConcurrentBag<IScheduledCommand>();

            var configuration = new Configuration()
                .TraceScheduledCommands() // trace to console
                .TraceScheduledCommands(
                    onScheduling: _ => { },
                    onScheduled: c => commandsScheduled.Add(c),
                    onDelivering: _ => { },
                    onDelivered: c => commandsDelivered.Add(c));

            Configure(configuration, d => disposables.Add(d));

            disposables.Add(ConfigurationContext.Establish(configuration));
        }
Esempio n. 4
0
    public async Task ShouldReturnFailedResult_Because_UserGroupIsZero()
    {
        DefaultUser.SetNarfuGroup(0);
        var command = new ScheduleCommand(GetScheduleService());
        var message = GenerateMessageWithPayload(DefaultUser.Id, DefaultUser.Id, command.Trigger, DateTime.ToString("d"));

        var result = await command.Execute(message, DefaultUser);

        result.Should().BeOfType <FailedResult>();
        result.Message.Should().NotBeNullOrEmpty();
    }
Esempio n. 5
0
    public async Task ShouldReturnSuccessfulResult()
    {
        var command = new ScheduleCommand(GetScheduleService());
        var message = GenerateMessageWithPayload(DefaultUser.Id, DefaultUser.Id, command.Trigger, DateTime.ToString("d"));

        var result = await command.Execute(message, DefaultUser);

        result.Should().BeOfType <SuccessfulResult>();
        result.Message.Should().NotBeNullOrEmpty();
        result.Keyboard.Should().NotBeNull();
    }
        public void Execute(ScheduleCommand c)
        {
            Guard.ForNull(c);

            if (c.ClientIds.Count > 1 || c.ScheduleInstructions.Count > 1)
            {
                throw new NotSupportedException("Sorry, multiple clients or instructions is not supported now.");
            }


            ApplyChange(new CommandScheduled(c.CommandToExecute, c.ClientIds.First(), c.ScheduleInstructions.First()));
        }
        /// <summary>
        /// This method will tell OvrStream to begin hiding the title provided.
        /// </summary>
        /// <param name="titleId">The ID <see cref="Title"/> to hide.</param>
        /// <param name="queue">The queue to use for this action.</param>
        /// <param name="cancellationToken">A cancellation token used to propagate notification that the operation should be canceled.</param>
        public async Task HideTitleAsync(string titleId, string queue, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            ScheduleCommand command = new ScheduleCommand
            {
                Action = "animateout+override",
                Id     = titleId,
                Queue  = queue,
            };

            await InvokeMethodAsync("scheduleCommandXml", new object[] { command.ToString() }, cancellationToken);
        }
        public int ExportUpdatePeriod = 24; // En heures

        public void InitTimos()
        {
            CResultAErreur result = CResultAErreur.True;

            string strServeurUrl = TimosServerURL;
            int    nTcpChannel   = 0;
            string strBindTo     = "";

            string strRadiuServerUrl = RadiusServerURL;
            uint   nRadiusPort       = (uint)RadiusServerPort;
            string strSharedKey      = RadiusSharedKey;

            int nUpdatePeriod = ExportUpdatePeriod;

            try
            {
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

                AuthenticationService.Init(strRadiuServerUrl, nRadiusPort, strSharedKey);

                result = CSC2iMultitiersClient.Init(nTcpChannel, strServeurUrl, strBindTo);

                LifetimeServices.LeaseTime            = new TimeSpan(0, 5, 0);
                LifetimeServices.LeaseManagerPollTime = new TimeSpan(0, 5, 0);
                LifetimeServices.SponsorshipTimeout   = new TimeSpan(0, 3, 0);
                LifetimeServices.RenewOnCallTime      = new TimeSpan(0, 8, 0);

                C2iSponsor.EnableSecurite();

                /*TcpChannel channel = new TcpChannel();
                 * ChannelServices.RegisterChannel(channel, false);*/

                if (!result)
                {
                    result.EmpileErreur("Erreur lors de l'initialisation");
                }

                // Configuration des Schedulers
                // ATTENTION : Dans le cas de plusieurs serveurs (load balancing par exemple) il faut locker le traitement dans la commande appelée
                ScheduleCommand.RunEvery(1, PeriodUnit.Hour, "TimosWebApp/ExportService.TraiteListeExports", new Dictionary <string, object>(), new DateTime(2021, 06, 01, 01, 00, 00), null);

                /*/ DEBUG ONLY
                 * ScheduleCommand.RunEvery(1, PeriodUnit.Minute, "TimosWebApp/ExportService.UpdateAllExports", new Dictionary<string, object>(), null, null);
                 * //*/
            }
            catch (Exception e)
            {
                result.EmpileErreur(e.Message);
            }
        }
Esempio n. 9
0
        public ScheduleCommandShould()
        {
            var entities = new List <ScheduleEntity>
            {
                new ScheduleEntity {
                    ExampleDateTime = new DateTimeOffset(2018, 6, 19, 18, 0, 0, 0, TimeSpan.Zero)
                },
                new ScheduleEntity {
                    ExampleDateTime = new DateTimeOffset(2018, 6, 21, 16, 0, 0, 0, TimeSpan.Zero)
                },
            };

            _repositoryMock.Setup(x => x.List(It.IsAny <DataItemPolicy <ScheduleEntity> >())).Returns(entities);
            _scheduleCommand = new ScheduleCommand(_repositoryMock.Object);
        }
        /// <summary>
        /// This method sends a list of variable updates to the title provided.
        /// </summary>
        /// <param name="titleId">The ID <see cref="Title"/> to update.</param>
        /// <param name="variables">A dictionary of variables with the key begin the variable name.</param>
        /// <param name="cancellationToken">A cancellation token used to propagate notification that the operation should be canceled.</param>
        public async Task UpdateVariablesAsync(string titleId, IReadOnlyDictionary <string, string> variables, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            ScheduleCommand command = new ScheduleCommand
            {
                Action = "update",
                Id     = titleId,
                Queue  = "Alert",
                Data   = variables.Select(kvp => new XmlVariable {
                    Name = kvp.Key, Value = kvp.Value
                }).ToArray(),
            };

            await InvokeMethodAsync("scheduleCommandXml", new object[] { command.ToString() }, cancellationToken);
        }
Esempio n. 11
0
    void ShowSchedule()
    {
        lit_horraire.Text = " ";
        lbl_activite.Text = " ";
        string          Activtity = ddl_choix_horraire.SelectedValue;
        string          no_act    = " ";
        string          jour      = " ";
        string          date      = " ";
        string          heure     = " ";
        string          precision = " ";
        MySqlCommand    ScheduleCommand;
        MySqlDataReader ScheduleReader;

        Connection.Open();
        //while (QuestionReader.Read())
        if (Connection != null)
        {
            ScheduleCommand             = Connection.CreateCommand();
            ScheduleCommand.CommandText = "Select NumeroActivite from activites where TitreActivite ='" + Activtity + "'";
            ScheduleReader = ScheduleCommand.ExecuteReader();
            if (ScheduleReader.Read())
            {
                no_act            = (ScheduleReader["NumeroActivite"]).ToString();
                lbl_activite.Text = Activtity;
            }
            ScheduleReader.Close();
            ScheduleCommand             = Connection.CreateCommand();
            ScheduleCommand.CommandText = "Select Jour, Date, Heure, Precisions from horaires where NumeroActivite ='" + no_act + "'";
            ScheduleReader = ScheduleCommand.ExecuteReader();
            while (ScheduleReader.Read())
            {
                jour              = ScheduleReader["Jour"].ToString();
                date              = ScheduleReader["Date"].ToString();
                heure             = ScheduleReader["Heure"].ToString();
                precision         = ScheduleReader["Precisions"].ToString();
                lit_horraire.Text = lit_horraire.Text + "<p>" + "Jour(s) : " + jour + " / " + "Date(s) : " + date + " / " + "Heure(s) : " + heure + " / " + "Précision(s) :" + precision + "</p>";
            }
            Connection.Close();
        }
        else
        {
            //connexion non réussie
            Response.Redirect("default.aspx");
        }
    }
Esempio n. 12
0
        public IActionResult Create(ScheduleCommand entity)
        {
            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

              // Create the table if it doesn't exist.
            CloudTable table = tableClient.GetTableReference("myschedules");
            table.CreateIfNotExists();

            // Create a new entity.
            entity.PartitionKey = "ROOM1";
            entity.RowKey = Guid.NewGuid().ToString();
            entity.IsScheduled = true;
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(entity);

            // Execute the insert operation.
            table.Execute(insertOperation);

            return RedirectToAction("Index");
        }
Esempio n. 13
0
        public IActionResult Create(ScheduleCommand entity)
        {
            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the table if it doesn't exist.
            CloudTable table = tableClient.GetTableReference("myschedules");

            table.CreateIfNotExists();

            // Create a new entity.
            entity.PartitionKey = "ROOM1";
            entity.RowKey       = Guid.NewGuid().ToString();
            entity.IsScheduled  = true;
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(entity);

            // Execute the insert operation.
            table.Execute(insertOperation);

            return(RedirectToAction("Index"));
        }
    void AddSchedule()
    {
        if (Page.IsValid)
        {
            string Jour                = txt_jour1.Text;
            string Date                = txt_date.Text;
            string Heure               = txt_heure_debut.Text;
            string Precision           = txt_precisions.Text;
            string NumeroActiviteAjout = " ";


            MySqlCommand ScheduleCommand;
            Connection.Open();

            NumeroActiviteAjout = Schedule();

            lbl_date_confirm.Visible    = true;
            ScheduleCommand             = Connection.CreateCommand();
            ScheduleCommand.CommandText = "INSERT into horaires  (Jour, Date, Heure, Precisions, NumeroActivite) values('" + Jour + "','" + Date + "','" + Heure + "','" + Precision + "','" + NumeroActiviteAjout + "')";
            ScheduleCommand.ExecuteNonQuery();
            Connection.Close();
        }
    }
Esempio n. 15
0
        public async Task<RouteSchedules> ScheduleAsync(string routeTag, DateTime date, string agencyTag = null)
        {
            var command = new ScheduleCommand(routeTag);
            if (agencyTag != null)
            {
                command.AgencyTag = agencyTag;
            }

            return await command.ExecuteAsync();
        }
Esempio n. 16
0
        public SmartPlugModule(ISmartPlug plug,
                               IConsumptionReporter consumptionReporter,
                               IPlugStateReporter plugStateReporter,
                               ITimelineReporter timelineReporter
                               ) : base("plugs")
        {
            _smartPlug           = plug;
            _consumptionReporter = consumptionReporter;
            _plugStateReporter   = plugStateReporter;
            _timelineReporter    = timelineReporter;

            Post("/activate", _ =>
            {
                var request = this.Bind <ActivatePlugRequest>();
                var plugId  = _smartPlug.Activate(request.Name);
                return(new
                {
                    Name = request.Name,
                    PlugId = plugId
                });
            });

            Post("/{plugId:guid}/deactivate", _ =>
            {
                Guid plugId = _.plugId;
                _smartPlug.Deactivate(plugId);
                return(new OkResponse());
            });

            Post("/{plugId:guid}/reactivate", _ =>
            {
                Guid plugId = _.plugId;
                _smartPlug.Reactivate(plugId);
                return(new OkResponse());
            });

            Post("/{plugId:guid}/calibrate", _ =>
            {
                Guid plugId = _.plugId;
                _smartPlug.Calibrate(plugId);
                return(new OkResponse());
            });

            Post("/credentials/reset", _ =>
            {
                _smartPlug.ResetCredentials();
                return(new OkResponse());
            });

            Get("/", _ => GetListOfPlugStates());

            Get("/{plugId:guid}", _ =>
            {
                Guid plugId = _.plugId;
                return(GetPlugState(plugId));
            });

            Post("/{plugId:guid}/try-turn-on", _ =>
            {
                Guid plugId = _.plugId;
                _smartPlug.TryTurnOn(plugId);
                return(new OkResponse());
            });

            Post("/{plugId:guid}/try-turn-off", _ =>
            {
                Guid plugId = _.plugId;
                _smartPlug.TryTurnOff(plugId);
                return(new OkResponse());
            });

            Post("/{plugId:guid}/rename", _ =>
            {
                Guid plugId = _.plugId;
                var request = this.Bind <RenameRequest>();
                _smartPlug.Rename(request.NewName, plugId);
                return(new OkResponse());
            });

            Post("/{plugId:guid}/scheduling/turn-on", _ =>
            {
                Guid plugId         = _.plugId;
                var scheduleRequest = this.Bind <ScheduleRequest>();

                var scheduleCommand = new ScheduleCommand(CommandType.TurnOn, TimeSpan.FromSeconds(scheduleRequest.SecondsInFuture));
                _smartPlug.ScheduleTurnOn(scheduleCommand, plugId);
                return(GetEstimatedActionTimeResponse(scheduleCommand.Description));
            });

            Post("/{plugId:guid}/scheduling/turn-off", _ =>
            {
                Guid plugId         = _.plugId;
                var scheduleRequest = this.Bind <ScheduleRequest>();

                var scheduleCommand = new ScheduleCommand(CommandType.TurnOff, TimeSpan.FromSeconds(scheduleRequest.SecondsInFuture));
                _smartPlug.ScheduleTurnOff(scheduleCommand, plugId);
                return(GetEstimatedActionTimeResponse(scheduleCommand.Description));
            });

            Get("/{plugId:guid}/reports/consumption", _ =>
            {
                Guid plugId = _.plugId;
                var report  = _consumptionReporter
                              .GetConsumptionReport(plugId /*, startTime: DateTime.UtcNow.AddMinutes(-15)*/)
                              .ToList();
                if (!report.Any())
                {
                    //TODO retornar potência e corrente para plotar no gráfico
                    return(new ConsumptionReportResponse
                    {
                        Data = new ConsumptionResponse[0]
                    });
                }

                var consumptionReadings = report
                                          .Where(x => x.ConsumptionInWatts > 0)
                                          .Select(x => x.ConsumptionInWatts)
                                          .ToList();
                var hours = consumptionReadings.Count / 720d; //every 5 seconds in 1 hour
                var kWh   = consumptionReadings.Any()
                    ? consumptionReadings.Average() / 1000 * hours
                    : 0;

                var firstReading = report.First().TimeStamp;
                return(new ConsumptionReportResponse
                {
                    kWh = kWh,
                    Data = report
                           .Select(x => new ConsumptionResponse
                    {
                        Current = x.Current,
                        Power = x.ConsumptionInWatts,
                        Time = (int)(x.TimeStamp - firstReading).TotalSeconds
                    }).ToArray()
                });
            });

            Get("/{plugId:guid}/reports/timeline", _ =>
            {
                Guid plugId  = _.plugId;
                var timeline = _timelineReporter.LoadTimeLine(plugId);
                var response = new TimelineResponse
                {
                    Events = timeline?.EventDescriptions?
                             .OrderByDescending(x => x.Sequence)
                             .Select(x => new EventResponse
                    {
                        Title       = x.Title,
                        Description = x.Description,
                        TimeStamp   = x.TimeStamp
                    }).ToArray() ?? new EventResponse[0]
                };
                return(response);
            });
        }
Esempio n. 17
0
 private void Schedule(ScheduleCommand message)
 {
     Schedule(() => QuartzJob.Create(message.Key, message.Command, message.CommandMetadata, message.Options),
              message.Options.RunAt,
              message.Key);
 }
Esempio n. 18
0
 public void ActionScheduled(ScheduleCommand command, Guid plugId)
 {
     AppendEvent(plugId, new OperationScheduled(command.Type, command.TimeInFuture));
 }
Esempio n. 19
0
 public Schedule(ScheduleViewModel scheduleViewModel)
 {
     DataContext = scheduleViewModel;
     Command     = new ScheduleCommand(this);
     InitializeComponent();
 }
Esempio n. 20
0
        /// <summary>
        /// Loads the schedule from file.
        /// </summary>
        /// <returns></returns>
        private void LoadScheduleFromFile()
        {
            // Get the schedule XML
            XmlDocument scheduleXml = GetScheduleXml();

            // Parse the schedule xml
            XmlNodeList nodes = scheduleXml["schedule"].ChildNodes;

            // Are there any nodes in the document
            if (nodes.Count == 0)
            {
                SetEmptySchedule();
                return;
            }

            // We have nodes, go through each one and add them to the layoutschedule collection
            foreach (XmlNode node in nodes)
            {
                // Node name
                if (node.Name == "dependants")
                {
                    // Do nothing for now
                }
                else if (node.Name == "command")
                {
                    // Try to get the command using the code
                    try
                    {
                        // Pull attributes from layout nodes
                        XmlAttributeCollection attributes = node.Attributes;

                        ScheduleCommand command = new ScheduleCommand();
                        command.Date       = DateTime.Parse(attributes["date"].Value, CultureInfo.InvariantCulture);
                        command.Code       = attributes["code"].Value;
                        command.ScheduleId = int.Parse(attributes["scheduleid"].Value);

                        // Add to the collection
                        _commands.Add(command);
                    }
                    catch (Exception e)
                    {
                        Trace.WriteLine(new LogMessage("ScheduleManager - LoadScheduleFromFile", e.Message), LogType.Error.ToString());
                    }
                }
                else if (node.Name == "overlays")
                {
                    // Parse out overlays and load them into their own schedule
                    foreach (XmlNode overlayNode in node.ChildNodes)
                    {
                        _overlaySchedule.Add(ParseNodeIntoScheduleItem(overlayNode));
                    }
                }
                else
                {
                    _layoutSchedule.Add(ParseNodeIntoScheduleItem(node));
                }
            }

            // Clean up
            nodes       = null;
            scheduleXml = null;

            // We now have the saved XML contained in the _layoutSchedule object
        }