Beispiel #1
0
        private void InvokeStateChanged(ServiceTask serviceTask, ServiceState state)
        {
            if (StateChanged != null) 
                StateChanged(this, new ServiceStateEventArgs(serviceTask, state));

            OnStateChanged(serviceTask, state);
        }
Beispiel #2
0
 public void Start()
 {
     switch ( this.State)
     {
         case ServiceState.Shiny:
         case ServiceState.Stopped:
             this.State = ServiceState.Starting;
             _serviceWorker = Task.Factory.StartNew(() => _serviceTask(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
             _serviceWorker.ContinueWith((t) =>
                                             {
                                                 Debugger.Launch();
                                                 this.State = ServiceState.Stopped;
                                                 Console.WriteLine(t.Exception.Message);
                                             }, TaskContinuationOptions.OnlyOnFaulted);
             this.State = ServiceState.Running;
             break;
         case ServiceState.Starting:
             // wait till state is started, then return
             break;
         case ServiceState.Stopping:
             // wait till state is stopped, then call self
             break;
         case ServiceState.Running:
             // already running, continue quietly
             break;
     }
 }
Beispiel #3
0
        /// <summary>
        /// 重启托管服务
        /// </summary>
        /// <returns>
        /// 托管服务状态响应
        /// </returns>
        public ServiceStateResponse Restart()
        {
            ServiceStateResponse response = new ServiceStateResponse() { State = ServiceState.Unknown };

              State = ServiceState.Restarting;
              response = Stop();
              response = Start();

              return response;
        }
Beispiel #4
0
        public void Start()
        {
            if (state == ServiceState.Started)
                throw new InvalidOperationException("The service is already initialized.");

            try {
                OnStart();
                state = ServiceState.Started;

                if (Started != null)
                    Started(this, EventArgs.Empty);
            } catch(Exception e) {
                Logger.Error(e);
                SetErrorState(e);
                throw;
            }
        }
Beispiel #5
0
        private static void TryHandleConsoleInput(IWindowsService service, ConsoleKey key, ref ServiceState state)
        {
            switch (key)
            {
                case ConsoleKey.Q:
                    state = ServiceState.Stopped;
                    break;

                case ConsoleKey.P:
                    service.OnPause();
                    state = ServiceState.Paused;
                    break;

                case ConsoleKey.R:
                    service.OnContinue();
                    state = ServiceState.Running;
                    break;
            }
        }
    //---------------------------------------------------------------------------------------------
    //---------------------------------------------------------------------------------------------

    private void ProcessServiceState(ServiceState serviceState)
    {
      _serviceState = serviceState;

      //----- Update Button State -----
      UpdateUserInterface();

      switch (_serviceState)
      {
        case ServiceState.Stopped:
          break;

        case ServiceState.StartPending:
          string[] args = null;
          _service.Start(args);
          ProcessServiceState(ServiceState.Running);
          break;

        case ServiceState.Running:
          break;

        case ServiceState.PausePending:
          _service.Pause();
          ProcessServiceState(ServiceState.Paused);
          break;

        case ServiceState.Paused:
          break;

        case ServiceState.ContinuePending:
          _service.Continue();
          ProcessServiceState(ServiceState.Running);
          break;

        case ServiceState.StopPending:
          _service.Stop();
          ProcessServiceState(ServiceState.Stopped);
          break;
      }
    }
		string GetStateDescription(ServiceState state)
		{
			switch (state)
			{
				case ServiceState.NotInstalled:
					return "未加载";
				case ServiceState.Running:
					return "运行中";
				case ServiceState.Disabled:
					return "已禁用";
				case ServiceState.LoadingError:
					return "加载错误";
				case ServiceState.UnInitialized:
					return "未初始化";
				case ServiceState.Unload:
					return "已卸载";
				case ServiceState.TypeLoaded:
					return "类型已加载";
				default:
					return "未知";
			}
		}
Beispiel #8
0
        private ServiceState state; // определяет текущее состояние службы

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Инициализирует новый экземпляр класса
        /// </summary>
        public ServiceStatus()
        {
            mutex = new _Mutex();
            state = ServiceState.Default;
        }
Beispiel #9
0
        // Token: 0x06001130 RID: 4400 RVA: 0x00053214 File Offset: 0x00051414
        internal static ServiceState ReadDirectComponentState(string targetServerFqdn, MultiValuedProperty <string> adComponentStates, ServerComponentStateSources sourcesToUse, string component, ServiceState defaultState, out List <ServerComponentStates.ItemEntry> returnLocalStates, out List <ServerComponentStates.ItemEntry> returnRemoteStates)
        {
            if (!ServerComponentStates.IsValidName(component))
            {
                throw new ArgumentException(DirectoryStrings.ComponentNameInvalid);
            }
            List <ServerComponentStates.ItemEntry> reconciledStates = ServerComponentStates.GetReconciledStates(targetServerFqdn, adComponentStates, sourcesToUse, component, out returnLocalStates, out returnRemoteStates);

            return(ServerComponentStates.GetEffectiveState(reconciledStates, defaultState));
        }
Beispiel #10
0
    protected override void OnStart(string[] args)
    {
        var state = new ServiceState(cancellationTokenSource.Token, waitHandle);

        serviceThread.Start(state);
    }
Beispiel #11
0
 public virtual void ServiceStateChanged(ServiceState newState)
 {
     switch (newState)
     {
         case ServiceState.Paused:
             m_previouslyEnabled = m_logEntryQueue.Enabled;
             m_logEntryQueue.Enabled = false;
             break;
         case ServiceState.Resumed:
             m_logEntryQueue.Enabled = m_previouslyEnabled;
             break;
         case ServiceState.Shutdown:
             Dispose();
             break;
     }
 }
        /// <summary>Stopping and starting services required to uninstall MSUs.</summary>
        /// <param name="ServiceName"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public static bool ServiceAction(string ServiceName, ServiceState status)
        {
            var serviceaction = false;

            sc.ServiceName = ServiceName;
            var check = ServiceControllerStatus.Stopped;
            try
            {
                switch (status)
                {
                    case ServiceState.Stop:
                        check = ServiceControllerStatus.Stopped;
                        sc.Stop();
                        break;

                    case ServiceState.Start:
                        check = ServiceControllerStatus.Running;
                        sc.Start();
                        break;
                }
                sc.WaitForStatus(check);
                serviceaction = true;
            }
            catch (InvalidOperationException ex)
            {
                Logger.Log(ex, AppName);
            }

            return serviceaction;
        }
        private int OnControl(Expression<Action> expression, ServiceState starting = 0, ServiceState completed = 0, ServiceState failed = 0)
        {
            if (IsOverriden(expression))
            {
                if (starting != 0)
                {
                    SetServiceStatus(starting);
                }

                try
                {
                    var action = expression.Compile();
                    action();
                }
                catch (Win32Exception ex)
                {
                    if (failed != 0)
                    {
                        SetServiceStatus(failed);
                    }

                    return ex.NativeErrorCode;
                }

                if (completed != 0)
                {
                    SetServiceStatus(completed);
                }

                return 0;
            }
            else
            {
                return ERROR_CALL_NOT_IMPLEMENTED;
            }
        }
Beispiel #14
0
 // Token: 0x06001142 RID: 4418 RVA: 0x00053A88 File Offset: 0x00051C88
 private static ServiceState GetEffectiveState(List <ServerComponentStates.ItemEntry> stateData, ServiceState defaultState)
 {
     if (stateData.Count == 0)
     {
         return(defaultState);
     }
     if (stateData.Any((ServerComponentStates.ItemEntry item) => item.State == ServiceState.Inactive))
     {
         return(ServiceState.Inactive);
     }
     if (stateData.Any((ServerComponentStates.ItemEntry item) => item.State == ServiceState.Draining))
     {
         return(ServiceState.Draining);
     }
     return(ServiceState.Active);
 }
Beispiel #15
0
 public TweetsService(IUnitOfWork unitOfWork)
 {
     _unitOfWork = unitOfWork;
     State       = new ServiceState();
 }
Beispiel #16
0
        // Token: 0x0600113C RID: 4412 RVA: 0x000535BC File Offset: 0x000517BC
        public static MultiValuedProperty <string> UpdateRemoteState(MultiValuedProperty <string> componentStates, string requester, string component, ServiceState state)
        {
            if (!ServerComponentStates.IsValidName(component))
            {
                throw new ArgumentException(DirectoryStrings.ComponentNameInvalid);
            }
            if (!ServerComponentStates.IsValidName(requester))
            {
                throw new ArgumentException(DirectoryStrings.RequesterNameInvalid);
            }
            MultiValuedProperty <string> multiValuedProperty = new MultiValuedProperty <string>();

            if (componentStates != null)
            {
                foreach (string text in componentStates)
                {
                    ServerComponentStates.ItemEntry itemEntry;
                    if (ServerComponentStates.TryParseRemoteStateString(text, out itemEntry) && (!string.Equals(itemEntry.Component, component, StringComparison.OrdinalIgnoreCase) || !string.Equals(itemEntry.Requester, requester, StringComparison.OrdinalIgnoreCase)))
                    {
                        multiValuedProperty.Add(text);
                    }
                }
            }
            multiValuedProperty.Add(string.Format("1:{0}:{1}:{2}:{3}", new object[]
            {
                component,
                requester,
                (int)state,
                DateTime.UtcNow.Ticks
            }));
            return(multiValuedProperty);
        }
Beispiel #17
0
 // Token: 0x0600113D RID: 4413 RVA: 0x000536B4 File Offset: 0x000518B4
 private static string FormLocalString(ServiceState state, DateTime timeStamp)
 {
     return(string.Format("1:{0}:{1}", (int)state, timeStamp.Ticks));
 }
Beispiel #18
0
        // Token: 0x0600113B RID: 4411 RVA: 0x000533AC File Offset: 0x000515AC
        private static void LogTransition(string component, string requester, ServiceState state)
        {
            if (state != ServiceState.Active)
            {
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_ServerComponentStateSetOffline, Environment.MachineName, new object[]
                {
                    component,
                    requester,
                    state.ToString()
                });
                return;
            }
            bool flag = false;
            List <ServerComponentStates.ItemEntry> list        = null;
            List <ServerComponentStates.ItemEntry> localStates = ServerComponentStates.GetLocalStates(null, ServerComponentStates.ServerWideOfflineComponentId);

            foreach (ServerComponentStates.ItemEntry itemEntry in localStates)
            {
                if (itemEntry.State != ServiceState.Active && !string.Equals(itemEntry.Requester, requester, StringComparison.OrdinalIgnoreCase))
                {
                    flag = true;
                    break;
                }
            }
            if (!flag && !string.Equals(component, ServerComponentStates.ServerWideOfflineComponentId, StringComparison.OrdinalIgnoreCase))
            {
                list = ServerComponentStates.GetLocalStates(null, component);
                foreach (ServerComponentStates.ItemEntry itemEntry2 in list)
                {
                    if (itemEntry2.State != ServiceState.Active && !string.Equals(itemEntry2.Requester, requester, StringComparison.OrdinalIgnoreCase))
                    {
                        flag = true;
                        break;
                    }
                }
            }
            if (!flag)
            {
                DateTime dateTime = DateTime.UtcNow;
                foreach (ServerComponentStates.ItemEntry itemEntry3 in localStates)
                {
                    if (itemEntry3.State != ServiceState.Active && itemEntry3.Timestamp < dateTime)
                    {
                        dateTime = itemEntry3.Timestamp;
                    }
                }
                if (list != null)
                {
                    foreach (ServerComponentStates.ItemEntry itemEntry4 in list)
                    {
                        if (itemEntry4.State != ServiceState.Active && itemEntry4.Timestamp < dateTime)
                        {
                            dateTime = itemEntry4.Timestamp;
                        }
                    }
                }
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_ServerComponentStateSetOnline, Environment.MachineName, new object[]
                {
                    component,
                    requester,
                    dateTime
                });
            }
        }
Beispiel #19
0
        // Token: 0x0600113A RID: 4410 RVA: 0x0005338C File Offset: 0x0005158C
        private static bool IsRemoteComponentOnlineInternal(string fqdn, MultiValuedProperty <string> componentStates, ServerComponentEnum serverComponent)
        {
            ServiceState serviceState = ServerComponentStates.ReadEffectiveComponentState(fqdn, componentStates, ServerComponentStates.GetComponentId(serverComponent), ServiceState.Active);

            return(serviceState == ServiceState.Active);
        }
Beispiel #20
0
        // Token: 0x06001138 RID: 4408 RVA: 0x000532B8 File Offset: 0x000514B8
        public static void UpdateLocalState(string targetServerFqdn, string requester, string component, ServiceState state)
        {
            if (!ServerComponentStates.IsValidName(component))
            {
                throw new ArgumentException(DirectoryStrings.ComponentNameInvalid);
            }
            if (!ServerComponentStates.IsValidName(requester))
            {
                throw new ArgumentException(DirectoryStrings.RequesterNameInvalid);
            }
            string subkey = string.Format("{0}\\{1}", "SOFTWARE\\Microsoft\\ExchangeServer\\v15\\ServerComponentStates", component);

            using (RegistryKey localMachineKey = ServerComponentStates.GetLocalMachineKey(targetServerFqdn))
            {
                using (RegistryKey registryKey = localMachineKey.CreateSubKey(subkey))
                {
                    ServerComponentStates.LogTransition(component, requester, state);
                    registryKey.SetValue(requester, ServerComponentStates.FormLocalString(state, DateTime.UtcNow));
                }
            }
        }
 private void SendServiceStateChangedResponse(ServiceState currentState)
 {
     ServiceResponse response = new ServiceResponse("SERVICESTATECHANGED");
     response.Attachments.Add(new ObjectState<ServiceState>(Name, currentState));
     SendResponse(response);
 }
Beispiel #22
0
        // Token: 0x0600112C RID: 4396 RVA: 0x00053128 File Offset: 0x00051328
        public static ServiceState ReadEffectiveComponentState(string targetServerFqdn, MultiValuedProperty <string> adComponentStates, ServerComponentStateSources sourcesToUse, string component, ServiceState defaultState, out bool serverWideIsInactive, out List <ServerComponentStates.ItemEntry> returnLocalStates, out List <ServerComponentStates.ItemEntry> returnRemoteStates)
        {
            if (!ServerComponentStates.IsValidName(component))
            {
                throw new ArgumentException(DirectoryStrings.ComponentNameInvalid);
            }
            if (sourcesToUse == (ServerComponentStateSources)0)
            {
                throw new ArgumentException("sourcesToUse argument must have at least one source");
            }
            serverWideIsInactive = false;
            List <ServerComponentStates.ItemEntry> reconciledStates = ServerComponentStates.GetReconciledStates(targetServerFqdn, adComponentStates, sourcesToUse, component, out returnLocalStates, out returnRemoteStates);

            if (!string.Equals(component, ServerComponentStates.MonitoringComponentId, StringComparison.OrdinalIgnoreCase) && !string.Equals(component, ServerComponentStates.RecoveryActionsEnabledComponentId, StringComparison.OrdinalIgnoreCase))
            {
                ServiceState effectiveState;
                if (string.Equals(component, ServerComponentStates.ServerWideOfflineComponentId, StringComparison.OrdinalIgnoreCase))
                {
                    effectiveState = ServerComponentStates.GetEffectiveState(reconciledStates, ServiceState.Active);
                    if (effectiveState != ServiceState.Active)
                    {
                        serverWideIsInactive = true;
                    }
                    return(effectiveState);
                }
                List <ServerComponentStates.ItemEntry> list;
                List <ServerComponentStates.ItemEntry> list2;
                List <ServerComponentStates.ItemEntry> reconciledStates2 = ServerComponentStates.GetReconciledStates(targetServerFqdn, adComponentStates, sourcesToUse, ServerComponentStates.ServerWideOfflineComponentId, out list, out list2);
                effectiveState = ServerComponentStates.GetEffectiveState(reconciledStates2, ServiceState.Active);
                if (effectiveState != ServiceState.Active)
                {
                    serverWideIsInactive = true;
                    return(ServiceState.Inactive);
                }
            }
            return(ServerComponentStates.GetEffectiveState(reconciledStates, defaultState));
        }
Beispiel #23
0
 protected virtual void OnStateChanged(ServiceTask serviceTask, ServiceState serviceState)
 {
 }
Beispiel #24
0
        // Token: 0x0600112D RID: 4397 RVA: 0x000531D8 File Offset: 0x000513D8
        public static ServiceState ReadEffectiveComponentState(string targetServerFqdn, MultiValuedProperty <string> adComponentStates, ServerComponentStateSources sourcesToUse, string component, ServiceState defaultState)
        {
            bool flag;
            List <ServerComponentStates.ItemEntry> list;
            List <ServerComponentStates.ItemEntry> list2;

            return(ServerComponentStates.ReadEffectiveComponentState(targetServerFqdn, adComponentStates, sourcesToUse, component, defaultState, out flag, out list, out list2));
        }
Beispiel #25
0
 public virtual void Unloading()
 {
     State = ServiceState.Unloading;
 }
Beispiel #26
0
 internal ServiceStateChangedEventArgs(ServiceState previous, ServiceState current)
 {
     Previous = previous;
     Current  = current;
 }
        private static bool WaitForServiceStatus(IntPtr service, ServiceState waitStatus, ServiceState desiredStatus)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();

            QueryServiceStatus(service, status);
            if (status.dwCurrentState == desiredStatus) return true;

            int dwStartTickCount = Environment.TickCount;
            int dwOldCheckPoint = status.dwCheckPoint;

            while (status.dwCurrentState == waitStatus)
            {
                // Do not wait longer than the wait hint. A good interval is
                // one tenth the wait hint, but no less than 1 second and no
                // more than 10 seconds.

                int dwWaitTime = status.dwWaitHint / 10;

                if (dwWaitTime < 1000) dwWaitTime = 1000;
                else if (dwWaitTime > 10000) dwWaitTime = 10000;

                Thread.Sleep(dwWaitTime);

                // Check the status again.

                if (QueryServiceStatus(service, status) == 0) break;

                if (status.dwCheckPoint > dwOldCheckPoint)
                {
                    // The service is making progress.
                    dwStartTickCount = Environment.TickCount;
                    dwOldCheckPoint = status.dwCheckPoint;
                }
                else
                {
                    if (Environment.TickCount - dwStartTickCount > status.dwWaitHint)
                    {
                        // No progress made within the wait hint
                        break;
                    }
                }
            }
            return (status.dwCurrentState == desiredStatus);
        }
Beispiel #28
0
        private static bool WaitForServiceStatus(IntPtr service, ServiceState waitStatus, ServiceState desiredStatus)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();

            QueryServiceStatus(service, status);
            if (status.dwCurrentState == desiredStatus)
            {
                return(true);
            }

            int count = 0;

            while (count < 60)
            {
                Thread.Sleep(1000);
                QueryServiceStatus(service, status);
                if (status.dwCurrentState == desiredStatus)
                {
                    return(true);
                }
                else
                {
                    count++;
                }
            }
            return(false);
        }
Beispiel #29
0
 // Token: 0x0600112E RID: 4398 RVA: 0x000531F6 File Offset: 0x000513F6
 public static ServiceState ReadEffectiveComponentState(string targetServerFqdn, MultiValuedProperty <string> adComponentStates, string component, ServiceState defaultState)
 {
     return(ServerComponentStates.ReadEffectiveComponentState(targetServerFqdn, adComponentStates, ServerComponentStateSources.All, component, defaultState));
 }
Beispiel #30
0
        void SetState(ServiceState newState)
        {
            ServiceState oldState = _state;

            _state = newState;

            try
            {
                if (StateChanged != null) StateChanged(this, new ServiceHostStateChangedEventArgs(oldState, newState));
            }
            catch (Exception)
            {
                // Ignore exceptions; doing anything else is liable to cause problems in one
                // of the many places the state is changed.
            }
        }
Beispiel #31
0
        private static bool WaitForServiceStatus(IntPtr service, ServiceState waitStatus, ServiceState desiredStatus)
        {
            var status = new SERVICE_STATUS();

            QueryServiceStatus(service, status);
            if (status.dwCurrentState == desiredStatus)
            {
                return(true);
            }

            int dwStartTickCount = Environment.TickCount;
            int dwOldCheckPoint  = status.dwCheckPoint;

            while (status.dwCurrentState == waitStatus)
            {
                // Do not wait longer than the wait hint. A good interval is
                // one tenth the wait hint, but no less than 1 second and no
                // more than 10 seconds.

                int dwWaitTime = status.dwWaitHint / 10;

                if (dwWaitTime < 1000)
                {
                    dwWaitTime = 1000;
                }
                else if (dwWaitTime > 10000)
                {
                    dwWaitTime = 10000;
                }

                Thread.Sleep(dwWaitTime);

                // Check the status again.

                if (QueryServiceStatus(service, status) == 0)
                {
                    break;
                }

                if (status.dwCheckPoint > dwOldCheckPoint)
                {
                    // The service is making progress.
                    dwStartTickCount = Environment.TickCount;
                    dwOldCheckPoint  = status.dwCheckPoint;
                }
                else
                {
                    if (Environment.TickCount - dwStartTickCount > status.dwWaitHint)
                    {
                        // No progress made within the wait hint
                        break;
                    }
                }
            }
            return(status.dwCurrentState == desiredStatus);
        }
        public List<ServiceInfo> AllServices(ServiceState status)
        {
            var list = new List<ServiceInfo>();
            var stat = (int)status;

            var services = r.Run(r.Services.OrderByDescending("idx_date").Where(s => s.State == stat)).ToList();
            foreach (var item in services)
            {
                var info = item.ToServiceInfo();
                info.IsDisconnect = (item.State != (int)ServiceState.Running) || IsDisconnect(info.LastPingDate);
                list.Add(info);
            }

            return list;
        }
Beispiel #33
0
 /// <summary>
 /// Get the Win32 services for the SCM.
 /// </summary>
 /// <param name="service_state">The state of the services to return.</param>
 /// <param name="service_types">The types of services to return.</param>
 /// <returns>The list of services.</returns>
 /// <remarks>SCM must have been opened with EnumerateService access.</remarks>
 public IEnumerable <Win32Service> GetServices(ServiceState service_state, ServiceType service_types)
 {
     return(GetServices(service_state, service_types, true).Result);
 }
Beispiel #34
0
        private static bool WaitForServiceStatus(IntPtr service, ServiceState waitStatus, ServiceState desiredStatus)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();

            QueryServiceStatus(service, status);
            if (status.dwCurrentState == desiredStatus)
            {
                return true;
            }

            int count = 0;
            while (count<60)
            {
                 Thread.Sleep(1000);
                 QueryServiceStatus(service, status);
                 if (status.dwCurrentState == desiredStatus)
                 {
                     return true;
                 }
                 else
                 {
                     count++;
                 }
            }
            return false;
        }
Beispiel #35
0
 /// <summary>
 /// Constructs an instance from the parameters passed.
 /// </summary>
 /// <param name="serviceName">The service name.</param>
 /// <param name="state">The service's current state.</param>
 /// <param name="startMode">The service start mode.</param>
 public RemoteServiceInfo(string serviceName, ServiceState state, RemoteServiceStartMode startMode)
 {
     this.ServiceName = serviceName;
     this.State       = state;
     this.StartMode   = startMode;
 }
Beispiel #36
0
 // Token: 0x0600112F RID: 4399 RVA: 0x00053202 File Offset: 0x00051402
 public static ServiceState ReadEffectiveComponentState(ServerComponentEnum serverComponent, ServiceState defaultState)
 {
     return(ServerComponentStates.ReadEffectiveComponentState(null, null, ServerComponentStateSources.Registry, ServerComponentStates.GetComponentId(serverComponent), defaultState));
 }
Beispiel #37
0
        void ThreadMain()
        {
            ServiceHostImplementation host = new ServiceHostImplementation(_reactor, _defaultEnvironment, _services);

            _reactor.AddPermanentHandle(_stateRequestEvent, StateRequestEventFired);
            _reactor.AddRepeatingTimer(new TimeSpan(0, 0, 10), ExceptionWaitTimer, null);

            bool permanentServicesOpened = OpenListOfServices(_permanentServices, host,
                ServiceExceptionKind.DuringPermanentOpen, ServiceExceptionKind.DuringPermanentOpenAbort);

            try
            {
                SortServices(_services);
            }
            catch (Exception ex)
            {
                if (UnhandledException != null) UnhandledException(this,
                    new ServiceExceptionEventArgs(ServiceExceptionKind.DuringPermanentOpen, ex));

                permanentServicesOpened = false;
            }

            bool running = true;

            while (running)
            {
                _reactor.RunLoopIteration();

                ServiceStateRequest request = _pendingRequest;
                _pendingRequest = ServiceStateRequest.None;

                switch (request)
                {
                    case ServiceStateRequest.Open:
                        if (permanentServicesOpened) OpenWasRequested();
                        break;

                    case ServiceStateRequest.Close:
                        if (permanentServicesOpened) CloseWasRequested();
                        break;

                    case ServiceStateRequest.Shutdown:
                        running = false;
                        break;
                }
            }

            if (_state == ServiceState.Up)
            {
                CloseAll();
                _state = ServiceState.Down;
            }

            if (permanentServicesOpened) CloseListOfServices(_permanentServices, host, ServiceExceptionKind.DuringPermanentClose);
        }
Beispiel #38
0
 /// <inheritdoc/>
 public void SetAggregatedServiceState(ServiceState serviceState) => _aggregatedServiceState = serviceState;
 public void UpdateServiceStatus(string guid, ServiceState state)
 {
     var status = (int)state;
     r.Run(r.Services.GetAll(guid, "idx_guid").OrderByDescending(s => s.LastPingDate).Limit(1).Update(s => new ServiceModel { State = status }));
 }
Beispiel #40
0
 public static IBinder AsBinder(this ServiceState ss)
 {
     return(null);
 }
 public SyncRelayStateTask(ServiceState state)
 => _state = state;
Beispiel #42
0
 public virtual void AfterLoading()
 {
     State = ServiceState.Running;
 }
 public ServiceHostStateChangedEventArgs(ServiceState oldState, ServiceState newState)
 {
     _oldState = oldState;
     _newState = newState;
 }
Beispiel #44
0
 public virtual void BeforeLoading()
 {
     State = ServiceState.Normal;
 }
Beispiel #45
0
        public async Task Start(CancellationToken cancellationToken)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("DnsService");
            }

            if (_state != ServiceState.Stopped)
            {
                throw new InvalidOperationException($"{_appName} is already running.");
            }

            _state = ServiceState.Starting;

            try
            {
                if (_stats == null)
                {
                    string statsFolder = Path.Combine(ConfigFolder, "stats");

                    if (!Directory.Exists(statsFolder))
                    {
                        Directory.CreateDirectory(statsFolder);
                    }

                    _stats = new StatsManager(_log);
                }

                /* Initialize DnsServer with Default configuration */
                _dnsServer = new DnsServerAsync()
                {
                    StatsManager = _stats,
                    //ServerDomain = Environment.MachineName.ToLower(),
                    //AllowRecursion = true,
                    //AllowRecursionOnlyForPrivateNetworks = true,
                };

                LoadEnvironmentSettings();

                LoadZoneFiles();

                // TODO: A quoi ca sert?
                if (_configDisabledZones != null)
                {
                    foreach (string domain in _configDisabledZones)
                    {
                        _dnsServer.AuthoritativeZoneRoot.DisableZone(domain);
                        SaveZoneFile(domain);
                    }
                }
                var blockListUri = new[] {
                    "https://dbl.oisd.nl/",
                    "https://phishing.army/download/phishing_army_blocklist_extended.txt",
                    "https://tspprs.com/dl/crypto",
                    "https://tspprs.com/dl/tracking",
                    "https://tspprs.com/dl/spotify",
                    "https://raw.githubusercontent.com/CHEF-KOCH/Audio-fingerprint-pages/master/AudioFp.txt",
                    "https://raw.githubusercontent.com/CHEF-KOCH/Canvas-fingerprinting-pages/master/Canvas.txt",
                    "https://raw.githubusercontent.com/CHEF-KOCH/WebRTC-tracking/master/WebRTC.txt",
                    "https://raw.githubusercontent.com/CHEF-KOCH/CKs-FilterList/master/HOSTS/Game.txt",
                    "https://raw.githubusercontent.com/CHEF-KOCH/NSABlocklist/master/HOSTS",
                    "https://raw.githubusercontent.com/deathbybandaid/piholeparser/master/Subscribable-Lists/ParsedBlacklists/AakList.txt",
                    "https://raw.githubusercontent.com/deathbybandaid/piholeparser/master/Subscribable-Lists/ParsedBlacklists/Prebake-Obtrusive.txt",
                    "https://jasonhill.co.uk/pfsense/ytadblock.txt"
                }.Select(url => new Uri(url));

                _blockListUrls.AddRange(blockListUri);

                // UpdateBlockLists();

                await _dnsServer.Start(cancellationToken);

                _state = ServiceState.Running;
            }
            catch (Exception ex)
            {
                _log.Write("Failed to start DNS Web Service (v" + _currentVersion + ")\r\n" + ex.ToString());
                throw;
            }
        }
Beispiel #46
0
 /// <summary>
 /// Class constructor.
 /// </summary>
 public Heartbeat(IErrorHandler errorHandler, Config config, ILogger logger, ServiceStats serviceStats, ServiceState serviceState)
 {
     _errorHandler             = errorHandler;
     _config                   = config;
     _logger                   = logger;
     _serviceStats             = serviceStats;
     _serviceState             = serviceState;
     _timer                    = new SimpleTimer(Timer_Callback, 1000, false, true, true);
     _udpClient                = new UdpClient();
     _endPoint                 = new IPEndPoint(IPAddress.Broadcast, 5002);
     _configuredInterfaceNames = new HashSet <string>(_config.InterfaceNames);
     _discoveredInterfaces     = new List <NetworkInterface>();
 }
Beispiel #47
0
 public virtual void AfterUnloading()
 {
     State = ServiceState.Unloaded;
 }
        public async Task <IActionResult> Index([FromBody] AltinnCoreApiModel model, string org, string service, Guid instanceId, ApiMode apiMode)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            ApiResult apiResult = new ApiResult();

            // Getting the Service Specific Implementation contained in external DLL migrated from TUL
            IServiceImplementation serviceImplementation = _execution.GetServiceImplementation(org, service, false);

            // Create and populate the RequestContext object and make it available for the service implementation so
            // service developer can implement logic based on information about the request and the user performing
            // the request
            RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, Guid.Empty);

            requestContext.UserContext = await _userHelper.GetUserContext(HttpContext);

            requestContext.Reportee = requestContext.UserContext.Reportee;
            if (Request.Headers.Keys.Contains(VALIDATION_TRIGGER_FIELD))
            {
                requestContext.ValidationTriggerField = Request.Headers[VALIDATION_TRIGGER_FIELD];
            }

            // Get the serviceContext containing all metadata about current service
            ServiceContext serviceContext = _execution.GetServiceContext(org, service, false);

            // Assign the Requestcontext to the serviceImplementation so
            // service developer can use the information in any of the service events that is called
            serviceImplementation.SetContext(requestContext, serviceContext, null, ModelState);

            // Set the platform services to the ServiceImplementation so the AltinnCore service can take
            // use of the plattform services
            serviceImplementation.SetPlatformServices(_platformSI);

            ViewBag.PlatformServices = _platformSI;

            dynamic serviceModel = ParseApiBody(serviceImplementation.GetServiceModelType(), out apiResult, model);

            if (serviceModel == null)
            {
                // The parsing did not create any result
                Response.StatusCode = 403;
                return(new ObjectResult(apiResult));
            }

            serviceImplementation.SetServiceModel(serviceModel);

            // ServiceEvent 2: HandleGetDataEvent
            // Runs the event where the service developer can implement functionality to retrieve data from internal/external sources
            // based on the data in the service model
            await serviceImplementation.RunServiceEvent(ServiceEventType.DataRetrieval);

            // RunService 3: Calcuation
            await serviceImplementation.RunServiceEvent(ServiceEventType.Calculation);

            // ServiceEvent 3: HandleCalculationEvent
            // Perform Calculation defined by the service developer
            // Only perform when the mode is to create a new instance or to specific calculate
            if (apiMode.Equals(ApiMode.Calculate) || apiMode.Equals(ApiMode.Create))
            {
                if (apiMode.Equals(ApiMode.Calculate))
                {
                    // Returns a updated Service model with new calculated data.
                    return(Ok(serviceModel));
                }
            }

            // Run the model Validation that handles validation defined on the model
            TryValidateModel(serviceModel);

            // ServiceEvent 4: HandleValidationEvent
            // Perform additional Validation defined by the service developer. Runs when the ApiMode is set to Validate or Complete.
            if (apiMode.Equals(ApiMode.Validate) || apiMode.Equals(ApiMode.Complete))
            {
                await serviceImplementation.RunServiceEvent(AltinnCore.ServiceLibrary.Enums.ServiceEventType.Validation);
            }

            // If ApiMode is only validate the instance should not be created and only return any validation errors
            if (apiMode.Equals(ApiMode.Validate) || (!ModelState.IsValid && !apiMode.Equals(ApiMode.Create)))
            {
                MapModelStateToApiResultForClient(ModelState, apiResult, serviceContext);

                if (apiResult.Status.Equals(ApiStatusType.ContainsError))
                {
                    if (apiMode.Equals(ApiMode.Validate))
                    {
                        Response.StatusCode = 202;
                    }
                    else
                    {
                        Response.StatusCode = 400;
                    }

                    return(new ObjectResult(apiResult));
                }

                return(Ok(apiResult));
            }

            // Save Formdata to database
            this._form.SaveFormModel(
                serviceModel,
                instanceId,
                serviceImplementation.GetServiceModelType(),
                org,
                service,
                requestContext.UserContext.ReporteeId,
                Guid.Empty);

            if (apiMode.Equals(ApiMode.Complete))
            {
                ServiceState currentState = _workflowSI.MoveServiceForwardInWorkflow(instanceId, org, service, requestContext.UserContext.ReporteeId);
                Response.StatusCode   = 200;
                apiResult.InstanceId  = instanceId;
                apiResult.Status      = ApiStatusType.Ok;
                apiResult.NextStepUrl = _workflowSI.GetUrlForCurrentState(instanceId, org, service, currentState.State);
                apiResult.NextState   = currentState.State;
                return(new ObjectResult(apiResult));
            }

            apiResult.InstanceId = instanceId;
            apiResult.Status     = ApiStatusType.Ok;
            if (!requestContext.RequiresClientSideReleoad)
            {
                return(Ok(apiResult));
            }

            {
                Response.StatusCode = 303;
                return(new ObjectResult(apiResult));
            }
        }
Beispiel #49
0
 public virtual void Loading()
 {
     State = ServiceState.Loading;
 }
Beispiel #50
0
        private int OnControl(Expression <Action> expression, ServiceState starting = 0, ServiceState completed = 0, ServiceState failed = 0)
        {
            if (IsOverriden(expression))
            {
                if (starting != 0)
                {
                    SetServiceStatus(starting);
                }

                try
                {
                    var action = expression.Compile();
                    action();
                }
                catch (Win32Exception ex)
                {
                    if (failed != 0)
                    {
                        SetServiceStatus(failed);
                    }

                    return(ex.NativeErrorCode);
                }

                if (completed != 0)
                {
                    SetServiceStatus(completed);
                }

                return(0);
            }
            else
            {
                return(ERROR_CALL_NOT_IMPLEMENTED);
            }
        }
Beispiel #51
0
        private void WaitServiceStateChange(Service svc, ServiceState ss)
        {
            DateTime StopTime;

            StopTime = DateTime.Now.AddSeconds((double)TimeoutUpDown.Value);
            while ((svc.ServiceState != ss) && (DateTime.Now < StopTime))
            {
                System.Diagnostics.Debug.WriteLine(svc.ServiceState.ToString());
                System.Diagnostics.Debug.WriteLine(StopTime.ToLongTimeString());
                System.Threading.Thread.Sleep(250);
                svc.Refresh();
            }
        }
Beispiel #52
0
        public async Task <IActionResult> CompleteAndSendIn(string org, string app, int partyId, Guid instanceGuid, string view)
        {
            // Dependency Injection: Getting the Service Specific Implementation based on the app parameter data store
            // Will compile code and load DLL in to memory for AltinnCore
            IServiceImplementation serviceImplementation = _execution.GetServiceImplementation(org, app, false);

            // Get the serviceContext containing all metadata about current app.
            ServiceContext serviceContext = _execution.GetServiceContext(org, app, false);

            // Create and populate the RequestContext object and make it available for the service implementation so
            // app developer can implement logic based on information about the request and the user performing
            // the request
            RequestContext requestContext = await PopulateRequestContext(instanceGuid);

            serviceImplementation.SetPlatformServices(_platformSI);

            // Assign data to the ViewBag so it is available to the service views or service implementation
            PopulateViewBag(org, app, instanceGuid, 0, requestContext, serviceContext, _platformSI);

            // Getting the Form Data
            Instance instance = await _instance.GetInstance(app, org, requestContext.UserContext.PartyId, instanceGuid);

            Guid.TryParse(instance.Data.Find(m => m.ElementType == FORM_ID).Id, out Guid dataId);
            object serviceModel = _data.GetFormData(instanceGuid, serviceImplementation.GetServiceModelType(), org, app, requestContext.UserContext.PartyId, dataId);

            serviceImplementation.SetServiceModel(serviceModel);

            ViewBag.FormID         = instanceGuid;
            ViewBag.ServiceContext = serviceContext;

            serviceImplementation.SetContext(requestContext, serviceContext, null, ModelState);
            await serviceImplementation.RunServiceEvent(ServiceEventType.Validation);

            ApiResult apiResult = new ApiResult();

            if (ModelState.IsValid)
            {
                ServiceState currentState = _workflowSI.MoveServiceForwardInWorkflow(instanceGuid, org, app, requestContext.UserContext.PartyId);

                if (currentState.State == WorkflowStep.Archived)
                {
                    Instance archivedInstance = await _instance.ArchiveInstance(serviceModel, serviceImplementation.GetServiceModelType(), app, org, requestContext.UserContext.PartyId, instanceGuid);

                    apiResult.NextState = currentState.State;
                    apiResult.Instance  = archivedInstance;
                }
            }

            ModelHelper.MapModelStateToApiResult(ModelState, apiResult, serviceContext);

            if (apiResult.Status.Equals(ApiStatusType.ContainsError))
            {
                Response.StatusCode = 202;
            }
            else
            {
                Response.StatusCode = 200;
            }

            return(new ObjectResult(apiResult));
        }
Beispiel #53
0
 public void ChangeState(ServiceState state)
 {
     this.ServiceControl.ChangeState (state);
     this.State = state;
 }
Beispiel #54
0
 public Service(string name, ServiceState state)
 {
     Name  = name;
     State = state;
 }
        protected void SetServiceStatus(ServiceState currentState, int win32ExitCode = 0, int serviceSpecificExitCode = 0, int checkPoint = 0, int waitHint = 30000)
        {
            if (DispatcherHandle != IntPtr.Zero)
            {
                ServiceStatus status = new ServiceStatus
                {
                    dwServiceType = ServiceType.OwnProcess,
                    dwCurrentState = currentState,
                    dwControlsAccepted = this.ControlsAccepted,
                    dwWin32ExitCode = win32ExitCode,
                    dwServiceSpecificExitCode = serviceSpecificExitCode,
                    dwCheckPoint = checkPoint,
                    dwWaitHint = waitHint
                };

                SetServiceStatus(DispatcherHandle, ref status);
            }

            if (currentState == ServiceState.Stopped)
            {
                Stopped.Set();
            }
            else
            {
                Stopped.Reset();
            }
        }
Beispiel #56
0
 protected ServiceBase()
 {
     _state = ServiceState.None;
 }
Beispiel #57
0
        protected void SetErrorState(Exception e)
        {
            errorState = new ErrorStateException(e);
            state = ServiceState.Error;

            if (Error != null)
                Error(this, EventArgs.Empty);
        }
Beispiel #58
0
 public virtual void Start()
 {
     _state = ServiceState.Running;
     Task.Run(async() => await ProcessAsync());
 }
Beispiel #59
0
        public void Stop()
        {
            if (state != ServiceState.Stopped) {
                try {
                    OnStop();
                    state = ServiceState.Stopped;

                    if (Stopped != null)
                        Stopped(this, EventArgs.Empty);
                } catch(Exception e) {
                    Logger.Error(e);
                    SetErrorState(e);
                    throw;
                }
            }
        }
Beispiel #60
0
 void IServiceSubscriber.StateChanged(ServiceState state)
 {
     OnStateChanged(state);
 }