Example #1
0
        public bool Start(HostControl hc)
        {
            mqtt.MqttConnect(serveur, clientid);
            mqtt = new Mqttclient_handler();
            foreach (var tokv in topicsStr.Split(';'))
            {
                string topicname = tokv.Split('=')[0];
                string topicvalue = tokv.Split('=')[1];
                mqtt.subscribe(topicvalue, 0);
                // topicNames.Add(topicvalue, topicname);
            }

            t = new Timer(WriteMessages, null, 10000, 10 * 60000);

            // Console.WriteLine("mqtt isconnected : {0}", mqtt.IsConnected);
            mqtt.OnMessageArrived += (Mqttclient_handler sender, MessPublishEventArgs e) =>
            {
                Console.WriteLine("at {0} from {1} : {2}", e.Message.Date, e.Message.Topic, e.Message.GetStringMessage());
                if (!messagesByTopic.ContainsKey(e.Message.Topic))
                    messagesByTopic.Add(e.Message.Topic, new List<MqttMessage>());
                messagesByTopic[e.Message.Topic].Add(e.Message);
                if (messagesByTopic[e.Message.Topic].Count > 20)
                {
                    SaveMessages(messagesByTopic[e.Message.Topic], e.Message.Topic, FileType.csv);
                    messagesByTopic[e.Message.Topic].Clear();
                }
            };
            return true;
         /*  do
            {
                Thread.Sleep(50);
            } while (true);*/
        }
Example #2
0
        public bool Start(HostControl hostControl)
        {
            _log.Info("SampleService Starting...");

            hostControl.RequestAdditionalTime(TimeSpan.FromSeconds(10));

            Thread.Sleep(1000);

            if(_throwOnStart)
            {
                _log.Info("Throwing as requested");
                throw new InvalidOperationException("Throw on Start Requested");
            }

            ThreadPool.QueueUserWorkItem(x =>
                {
                    Thread.Sleep(3000);

                    if(_throwUnhandled)
                        throw new InvalidOperationException("Throw Unhandled In Random Thread");

                    _log.Info("Requesting stop");

                    hostControl.Stop();
                });
            _log.Info("SampleService Started");

            return true;
        }
Example #3
0
        public bool Stop(HostControl hostControl)
        {
            if (app != null)
                app.Dispose();

            return true;
        }
        /// <summary>
        /// Starts the specified host control.
        /// </summary>
        /// <param name="hostControl">The host control.</param>
        /// <returns></returns>
        public virtual bool Start(HostControl hostControl)
        {
            ShutdownWatcher.Token.Register(hostControl.Stop);
            JobHost.Start();

            return true;
        }
Example #5
0
 public bool Stop(HostControl hostControl)
 {
     _log.Info("stop service");
     _serviceHost.Close();
     _serviceHost = null;
     return true;
 }
Example #6
0
            public bool Start(HostControl hostControl)
            {
                Log.Info("Starting Service...");

                var Config = Configuration.LoadFromFile("Jobs.xml");

                foreach (var config in Config.Jobs)
                {
                    if (!config.Enabled) continue;

                    var job = config.GenerateJob();

                    var trigger = TriggerBuilder.Create()
                        .ForJob(job)
                        .WithCronSchedule(config.CronTrigger)
                        .StartNow()
                        .Build();

                    this.scheduler.ScheduleJob(job, trigger);
                }

                this.scheduler.Start();

                return true;
            }
Example #7
0
        public bool Start(HostControl hostControl)
        {
            _log = HostLogger.Get<SampleService>();

            _log.Info("SampleService Starting...");

            hostControl.RequestAdditionalTime(TimeSpan.FromSeconds(10));

            Thread.Sleep(1000);

            ThreadPool.QueueUserWorkItem(x =>
                {
    //                Thread.Sleep(3000);

  //                  _log.Info("Requesting a restart!!!");

//                    hostControl.Restart();

//                _log.Info("Dying an ungraceful death");
//
//                throw new InvalidOperationException("Oh, what a world.");
                });
            _log.Info("SampleService Started");

            return true;
        }
        public bool Stop(HostControl hostControl)
        {
            OnStopping(hostControl);

            Logger.Get(GetType())
                  .InfoFormat("Stopping {0} Service Buses for hosted service: {1}", _instances.Length, _serviceName);

            try
            {
                Parallel.ForEach(_instances, instance => instance.Dispose());

                _disposed = true;

                OnStopped(hostControl);

                Logger.Get(GetType())
                      .InfoFormat("Stopped {0} Service Buses for hosted service: {1}", _instances.Length, _serviceName);
            }
            catch (Exception ex)
            {
                OnStopFailed(hostControl, ex);
                throw;
            }

            return true;
        }
        public bool Start(HostControl hostControl)
        {
            try
            {
                _bus = ServiceBusFactory.New(x =>
                    {
                        // just support everything by default
                        x.UseMsmq();
                        x.UseRabbitMq();
                        x.UseJsonSerializer();

                        // move this to app.config
                        x.ReceiveFrom(_controlQueueUri);
                        x.SetConcurrentConsumerLimit(_consumerLimit);

                        x.Subscribe(s =>
                            {
                                s.Consumer(() => new ScheduleMessageConsumer(_scheduler));
                                s.Consumer(() => new CancelScheduledMessageConsumer(_scheduler));
                            });
                    });

                _scheduler.JobFactory = new MassTransitJobFactory(_bus);
            }
            catch (Exception)
            {
                _scheduler.Shutdown();
                throw;
            }

            _scheduler.Start();

            return true;
        }
Example #10
0
 public void Start(HostControl hostControl)
 {
     isRunning = true;
     this.hostControl = hostControl;
     channel.BeginReceive(new TimeSpan(0, 0, 0, ConfigurationSettings.PollingTimeout));
     Console.WriteLine("Service started");
 }
        public bool Start(HostControl hostControl)
        {
            OnStarting(hostControl);

            Logger.Get(GetType())
                  .InfoFormat("Creating {0} Service Buses for hosted service: {1}", _instances.Length, _serviceName);

            try
            {
                Parallel.ForEach(_instances, instance => instance.Start(_transportConfigurator));

                OnStarted(hostControl);

                Logger.Get(GetType())
                      .InfoFormat("Created {0} Service Buses for hosted service: {1}", _instances.Length, _serviceName);

                return true;
            }
            catch (Exception ex)
            {
                Parallel.ForEach(_instances, instance => instance.Dispose());

                OnStartFailed(hostControl, ex);
                throw;
            }
        }
        public bool Start(HostControl hostControl)
        {
            _log.Info("Creating bus...");

            _sagaRepository = GetSagaRepository();

            ITrackingEventWriter writer = GetTrackingEventWriter();

            _busControl = Bus.Factory.CreateUsingRabbitMq(x =>
            {
                var host = x.Host(GetHostAddress(), h =>
                {
                    h.Username(ConfigurationManager.AppSettings["RabbitMQUsername"]);
                    h.Password(ConfigurationManager.AppSettings["RabbitMQPassword"]);
                });

                x.ReceiveEndpoint(host, ConfigurationManager.AppSettings["BookingStateQueueName"], e =>
                {
                    e.StateMachineSaga(_stateMachine, _sagaRepository);
                });

                x.ReceiveEndpoint(host, ConfigurationManager.AppSettings["EventTrackingQueueName"], e =>
                {
                    e.Consumer(() => new EventTrackingConsumer(writer));
                });
            });

            _log.Info("Starting bus...");

            _busHandle = _busControl.Start();

            TaskUtil.Await(() => _busHandle.Ready);

            return true;
        }
        public bool Start(HostControl hostControl)
        {
            this.startHostControl = hostControl;

            myCallback = new Win32.ServiceControlHandlerEx(ServiceControlHandler);
            var serviceStatusHandle = Win32.RegisterServiceCtrlHandlerEx(DummyService.ServiceName,
                                                                            myCallback,
                                                                            IntPtr.Zero);
            var deviceInterface = new Win32.DEV_BROADCAST_DEVICEINTERFACE();
            int size = Marshal.SizeOf(deviceInterface);
            deviceInterface.dbcc_size = size;
            deviceInterface.dbcc_devicetype = Win32.DBT_DEVTYP_DEVICEINTERFACE;
            IntPtr buffer = default(IntPtr);
            buffer = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(deviceInterface, buffer, true);
            deviceEventHandle = Win32.RegisterDeviceNotification(serviceStatusHandle,
                                                                    buffer,
                                                                    Win32.DEVICE_NOTIFY_SERVICE_HANDLE |
                                                                    Win32.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
            if (deviceEventHandle == IntPtr.Zero)
            {
                // TODO handle error
            }
            return true;
        }
Example #14
0
 public bool Stop(HostControl hc)
 {
     mqtt.Dispose();
     t.Dispose();
     t = null;
     return true;
 }
Example #15
0
        void WatchForExitKey(HostControl hostControl)
        {
            while (!_terminate)
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(1));

                char ch;

                try
                {
                    if (!Console.KeyAvailable)
                        continue;

                    var tmp = Console.ReadKey();
                    ch = tmp.KeyChar;
                }
                catch (InvalidOperationException)
                {
                    // console input is redirected

                    var tmp = Console.In.Read();
                    if (tmp == -1)
                        continue;

                    ch = (char)tmp;
                }

                if (ch == 'q')
                {
                    Stop(hostControl);
                    Environment.Exit(0);
                }
            }
        }
Example #16
0
        public bool Start(HostControl hostControl)
        {
            if (string.IsNullOrEmpty(TestConfig.Instance.ServerUrl))
            {
                throw new Exception("Url为空 无法启动服务器");
            }

            Pioneer.WxSdk.SdkSetup.MessageTokenGetter = (dic) =>
            {

                PublicAccount pa = new PublicAccount();

                pa.EncryptionKey = TestConfig.Instance.EncryptionKey;
                pa.MessageToken = TestConfig.Instance.Token;
                pa.AppId = TestConfig.Instance.AppId;
                return pa;
            };

            SdkSetup.RegisterListener(new WxSdk.Message.DefaultMessageListener());

            StartOptions so = new StartOptions();
            so.Urls.Add(TestConfig.Instance.ServerUrl);

            innerHost = WebApp.Start(so, builder =>
            {
                builder.Use(new MessageModel().ProcessRequest);
            });

            logger.Info("监听地址:" + TestConfig.Instance.ServerUrl);

            logger.Info("启动成功");

            return true;
        }
        /// <summary>
        /// Start the service
        /// </summary>
        /// <param name="hostControl">the topshelf host</param>
        /// <returns>always returns true</returns>
        public bool Start(HostControl hostControl)
        {
            _sampleMessageSubscriber.Start();

            _logger.Info("Prototype .NET Micro Service Started");
            return true;
        }
Example #18
0
        public bool Start(HostControl hostControl)
        {
            var container = IocBootstrapper.Instance;
            var subscriber = container.GetInstance<ISubscriber>();

            // Find all message handlers in running process
            var handlers = container.GetAllInstances<IMessageHandler>();
            var responders = container.GetAllInstances<IResponse>();

            logger.Info(handlers.Count() + " message handlers found. Listening...");

            logger.Info(responders.Count() + " responder found. Listening...");

            //Start to subscribe (async) for all message handlers
            foreach (var handler in handlers)
            {
                for (int i = 0; i < ConfigHelper.MaxThreads; i++)
                {
                    subscriber.Subscribe(handler);
                }
            }

            foreach (var responder in responders)
            {
                for (int i = 0; i < ConfigHelper.MaxThreads; i++)
                {
                    responder.StartRespond(subscriber);
                }
            }

            return true;
        }
Example #19
0
        public bool Stop(HostControl hostControl)
        {
            _cancel.Cancel();
            _task.Wait();

            return true;
        }
        public bool Start(HostControl hostControl)
        {
            EventLog.WriteEntry(EventSource, "Opening Web Api Service.");
            _server.OpenAsync();

            return true;
        }
        public bool Start(HostControl hostControl)
        {
            if (WebAppHolder == null)
            {

                WebAppHolder = WebApp.Start
                (
                    Host,
                    appBuilder =>
                    {
                        new StartupConfig().Configure(appBuilder, Kernel);
                    }
                );

                NinjectHelper.Kernel = Kernel;
                BuildingQuartzMetadataSqLite1090();

                //IScheduler scheduler = SchedulerServer.InicializarScheduler();

                //scheduler.ScheduleJob(SchedulerServer.BuildJogDetail<WorkflowJob>("5DD5243A-52A8-4A38-BBD5-1D21AAAB7536", "Carrefour"), SchedulerServer.BuildTrigger("0 0/10 * * * ?"));

                //scheduler.ScheduleJob(SchedulerServer.BuildJogDetail<WorkflowJob>("649D4A31-31E5-48B4-9E5C-9CDB17584F77", "Carrefour"), SchedulerServer.BuildTrigger("0 0/30 * * * ?"));

                //scheduler.ScheduleJob(SchedulerServer.BuildJogDetail<WorkflowJob>("A9BF0D2D-C75B-4D67-BFA6-F99D3ACCD5AD", "Bayer"), SchedulerServer.BuildTrigger("0 0/1 * * * ?"));

            }

            return true;
        }
Example #22
0
        public bool Stop(HostControl hostControl)
        {
            if (null != _server)
                _server.Dispose();

            return true;
        }
Example #23
0
 public bool Stop(HostControl hostControl) {
     foreach (var c in this.Clients) {
         c.Value.OnProcessed -= Processed;
     }
     this.Holder.OnDataReceived -= Holder_OnDataReceived;
     return true;
 }
Example #24
0
        public bool Start(HostControl hostControl)
        {
            _bus = ServiceBusFactory.New(x =>
                {
                    x.UseRabbitMq();
                    x.ReceiveFrom("rabbitmq://localhost/demo/member-service");

                    x.Subscribe(s =>
                        {
                            s.Consumer(() => new SaveMemberAddressConsumer());
                            s.Consumer(() => new AddressValidationConsumer());

                            s.StateMachineSaga(_stateMachine, _stateMachineRepository, c =>
                                {
                                    c.Correlate(_stateMachine.AddressAdded,
                                        (state, message) => state.OriginatingCommandId == message.CommandId)
                                     .SelectCorrelationId(message => message.EventId);

                                    c.Correlate(_stateMachine.AddressApproved,
                                        (state, message) => state.MemberId == message.MemberId);
                                });
                        });
                });

            return true;
        }
 public bool Stop(HostControl hostControl)
 {
     bool stop = _service.Stop(hostControl);
     if (stop)
         _lifetimeScope.Dispose();
     return stop;
 }
        public bool Start(HostControl hostControl)
        {
            var container = new Container(cfg => cfg.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.AssembliesFromApplicationBaseDirectory();
                    scan.AddAllTypesOf(typeof (IConsumer));
                }));

            try
            {
                _Bus = ServiceBusFactory.New(sbc =>
                    {
                        sbc.UseRabbitMq();
                        sbc.ReceiveFrom(ConfigurationManager.AppSettings["RabbitMQEndPoint"]);
                        sbc.Subscribe(x => x.LoadFrom(container));
                        sbc.Validate();
                    });

                container.Inject(_Bus);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
            return true;
        }
        public bool Start(HostControl hostControl)
        {
            _log.InfoFormat("Starting Subscriber Activity Service");

            var started = new List<ServiceControl>();

            try
            {
                _services = _serviceBootstrappers.Select(x => x.CreateService()).ToList();

                _log.InfoFormat("Starting {0} services", _services.Count());

                foreach (ServiceControl activityService in _services)
                {
                    hostControl.RequestAdditionalTime(TimeSpan.FromMinutes(1));
                    StartService(hostControl, activityService);

                    started.Add(activityService);
                }

                return true;
            }
            catch (Exception ex)
            {
                _log.Error("Service failed to start", ex);

                Parallel.ForEach(started, service =>
                    {
                        hostControl.RequestAdditionalTime(TimeSpan.FromMinutes(1));
                        StopService(hostControl, service);
                    });

                throw;
            }
        }
 public bool Stop(HostControl hostControl)
 {
     _cancel.Cancel();
     //_queueManager.Stop(TimeSpan.FromSeconds(30)).Wait();
     _task.Wait();
     return true;
 }
        public bool Start(HostControl hostControl)
        {
            _log.Info("Creating bus...");

            _busControl = Bus.Factory.CreateUsingRabbitMq(x =>
            {
                IRabbitMqHost host = x.Host(new Uri(ConfigurationManager.AppSettings["RabbitMQHost"]), h =>
                {
                    h.Username("guest");
                    h.Password("guest");
                });

                x.ReceiveEndpoint(host, ConfigurationManager.AppSettings["ServiceQueueName"],
                    e => { e.Consumer<RequestConsumer>(); });

                x.ReceiveEndpoint(host, ConfigurationManager.AppSettings["ValidationAddress"],
                    e => { e.Consumer<ValidateConsumer>(); });
            });

            _log.Info("Starting bus...");

            _busControl.Start();

            return true;
        }
        public bool Start(HostControl hostControl)
        {
            _log.InfoFormat($"Starting {GetType().GetDisplayName()}");

            var started = new List<ServiceControl>();

            try
            {
                var scanner = new ServiceAssemblyScanner();

                List<AssemblyRegistration> registrations = scanner.GetAssemblyRegistrations().ToList();

                _log.Info($"Found {registrations.Count} assembly registrations");
                foreach (var registration in registrations)
                {
                    _log.Info($"Assembly: {registration.Assembly.GetName().Name}");
                    foreach (var type in registration.Types)
                        _log.Info($"  Type: {type.GetTypeName()}");
                }

                var busFactoryType = scanner.GetHostBusFactoryType();
                if (busFactoryType == null)
                    throw new ConfigurationException("A valid transport assembly was not found.");

                _bootstrapperScope = CreateBootstrapperScope(registrations, busFactoryType);

                var bootstrappers = _bootstrapperScope.Resolve<IEnumerable<IServiceBootstrapper>>();

                List<ServiceControl> services = bootstrappers.Select(x => x.CreateService()).ToList();

                Parallel.ForEach(services, serviceControl =>
                {
                    hostControl.RequestAdditionalTime(TimeSpan.FromMinutes(1));

                    StartService(hostControl, serviceControl);

                    lock (started)
                    {
                        started.Add(serviceControl);
                    }
                });

                _services.AddRange(started);

                return true;
            }
            catch (Exception ex)
            {
                _log.Error("Service failed to start", ex);

                Parallel.ForEach(started, service =>
                {
                    hostControl.RequestAdditionalTime(TimeSpan.FromMinutes(1));
                    StopService(hostControl, service);
                });

                throw;
            }
        }