Beispiel #1
0
        public async Task Run(IContainer ioc)
        {
            using (var db = ioc.GetInstance <CardDatabaseContext>())
            {
                await db.Database.MigrateAsync();

                Log.Information("Updating Database Using Activity Log Queue...");
                var activityLog = await db.MigrationLog.AsQueryable()
                                  .Where(log => !log.IsDone)
                                  .OrderBy(log => log.DateAdded)
                                  .AsAsyncEnumerable()
                                  .ToArrayAsync()
                ;

                foreach (var act in activityLog.Select((act, i) => (ActLog: act, Index: i)))
                {
                    await(OnStarting?.Invoke(this, new UpdateEventArgs(act.ActLog, act.Index, activityLog.Length)) ?? Task.CompletedTask);
                    await act.ActLog.ToCommand().Run(ioc);

                    act.ActLog.IsDone = true;
                    await(OnEnding?.Invoke(this, new UpdateEventArgs(act.ActLog, act.Index + 1, activityLog.Length)) ?? Task.CompletedTask);
                }
                Log.Information("Done!");
                await db.SaveChangesAsync();
            }
        }
        public void Start(IPAddress address, int port)
        {
            if (IsClosing || IsWorking)
            {
                throw new InvalidOperationException("Listener must be closed before executing Start method.");
            }
            if (address is null || port == 0)
            {
                throw new ArgumentNullException();
            }

            OnStarting?.Invoke(this, new ListenerEventArgs {
                Server = this, UtcTime = DateTime.UtcNow
            });

            // IP Check
            if (
                NetworkInterface
                .GetAllNetworkInterfaces()
                .Where(interf =>
                       interf.OperationalStatus == OperationalStatus.Up)
                .Select(interf => new
            {
                uni = interf.GetIPProperties().UnicastAddresses,
                multi = interf.GetIPProperties().MulticastAddresses
            })
                .Where(item =>
                       item.uni.Where(ip => ip.Address == address).Count() > 0 ||
                       item.multi.Where(ip => ip.Address == address).Count() > 0
                       )
                .Count() == 0
                )
            {
                throw new ArgumentException("This IP address isn't assigned to active interface");
            }

            IPEndPoint endpoint = new IPEndPoint(address, port);

            this.socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            this.socket.Bind(endpoint);
            this.socket.Listen(50);

            CurrentPassword = GeneratePassword();

            OnStarted.Invoke(
                this,
                new ListenerEventArgs {
                Server = this, UtcTime = DateTime.UtcNow
            }
                );

            new Thread(() =>
            {
                while (!IsClosing)
                {
                    socket.BeginAccept(new AsyncCallback(AcceptCallback), socket);
                }
            });
        }
Beispiel #3
0
        /*
         * Start / Stop.
         */

        public void Start()
        {
            if (IsStarted)
            {
                throw new ContextException(ContextExceptionType.ContextAlreadyStarted);
            }

            InitializeExtensions();
            InitializeModules();

            OnStarting?.Invoke();
            OnContextStarting?.Invoke(this);

            IsStarted = true;

            OnStarted?.Invoke();
            OnContextStarted?.Invoke(this);
        }
 public void Execute(OnStarting pipelineEvent)
 {
     _events.OnStarting(this, new PipelineEventEventArgs(pipelineEvent));
 }
 public override Task OnLogEnding(UpdateEventArgs args) => OnStarting?.Invoke(this, args) ?? Task.CompletedTask;
Beispiel #6
0
 private protected void __OnStarting(T server) => OnStarting?.Invoke(server);
Beispiel #7
0
        /// <summary>
        /// 启动NodeServer
        /// </summary>
        public Task StartAsync()
        {
            logger.LogInformation("Server is loading services.");

            LoadServices();

            logger.LogInformation("Server load services success.");

            server.OnRecieveLoginRequest += new RecieveLoginRequestDelegate(async(loginAuthInfo) =>
            {
                var loginInfo = new LoginRequestInfo()
                {
                    Body          = loginAuthInfo.Body,
                    Attachments   = loginAuthInfo.Attachments,
                    RemoteAddress = loginAuthInfo.RemoteAddress
                };
                var loginAuthResult = await loginValidator.Validate(loginInfo);
                return(new LoginResponseData()
                {
                    AuthIdentity = loginAuthResult.AuthIdentity,
                    Attachments = loginAuthResult.Attachments,
                    AuthFailedMessage = loginAuthResult.AuthFailedMessage,
                    AuthResult = loginAuthResult.AuthResult,
                    AuthStatusCode = loginAuthResult.AuthStatusCode
                });
            });

            server.OnRecieveServiceRequest += new RecieveServiceRequestDelegate(async(byte[] message, IDictionary <string, byte[]> attachments, LoginState loginState) =>
            {
                var serviceProcessTimeBegin = DateTime.Now;
                var serviceRequest          = await serializer.DeserializeAsync(protocolStackFactory.ServiceRequestType, message) as IServiceRequest;

                RouteDescription route = null;
                try
                {
                    route = RouteManager.GetRoute(serviceRequest.ServiceId, serviceRequest.ActionId);
                }
                catch (RouteNotFoundException ex)
                {
                    logger.LogError(ex, $"RouteManager.GetRoute has error, route is not exist. ServiceId={serviceRequest.ServiceId}, ActionId={serviceRequest.ActionId}, ExceptionMessage={ex.Message}");
                    return(await CreateServiceExceptionResponseDataAsync(ServiceExceptionKeys.SERVICE_NOT_EXIST_ERROR));
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, $"RouteManager.GetRoute has error, ServiceId={serviceRequest.ServiceId}, ActionId={serviceRequest.ActionId}, ExceptionMessage={ex.Message}");
                    return(await CreateSystemExceptionResponseDataAsync(SystemExceptionKeys.SYSTEM_ERROR));
                }

                logger.LogDebug($"Get route info. ServiceId={route.ServiceId}, ActionId={route.ActionId}, ServiceType={route.ServiceType}, ActionType={route.ActionType}");

                var context = new ServiceContext(config.Host, config.Port, loginState.Identity, loginState.RemoteAddress, route, serviceRequest.ParamList, attachments);

                var serviceProcessResult = await serviceProcessor.ProcessAsync(context);

                logger.LogInformation($"Service process used time: {DateTime.Now - serviceProcessTimeBegin}, ServiceId={serviceRequest.ServiceId}, ActionId={serviceRequest.ActionId}");

                return(new ResponseData()
                {
                    Attachments = serviceProcessResult.Attachments,
                    Data = await serializer.SerializeAsync(serviceProcessResult.ServiceResponse)
                });
            });

            logger.LogInformation("Server is binding.");

            OnStarting?.Invoke(new NodeServerStartEventArg(config.Host, config.Port, RouteManager.GetAllRoutes()));

            return(server.StartAsync().ContinueWith(task =>
            {
                if (task.Exception != null)
                {
                    logger.LogError(task.Exception, $"Server start has error. Host={config.Host}, Port={config.Port}, ExceptionMessage={task.Exception.InnerException.Message}, ExceptionStackTrace={task.Exception.InnerException.StackTrace}");
                    return;
                }
                logger.LogInformation($"Server listen port {config.Port}");
                OnStarted?.Invoke(new NodeServerStartEventArg(config.Host, config.Port, RouteManager.GetAllRoutes()));
            }));
        }
Beispiel #8
0
        private void ChangeState(ListenerState newState)
        {
            // Check that only allowed state changes are made
            switch (State)
            {
            case ListenerState.uninitialized:
                if (!(newState == ListenerState.initializing || newState == ListenerState.faulted))
                {
                    throw new Exception("Invalid state change. Uninitialized->" + newState.ToString());
                }
                break;

            case ListenerState.initializing:
                if (!(newState == ListenerState.initialized || newState == ListenerState.faulted))
                {
                    throw new Exception("Invalid state change. Initializing->" + newState.ToString());
                }
                break;

            case ListenerState.initialized:
                if (!(newState == ListenerState.starting || newState == ListenerState.faulted))
                {
                    throw new Exception("Invalid state change. Initialized->" + newState.ToString());
                }
                break;

            case ListenerState.starting:
                if (!(newState == ListenerState.started || newState == ListenerState.stopping || newState == ListenerState.faulted))
                {
                    throw new Exception("Invalid state change. Starting->" + newState.ToString());
                }
                break;

            case ListenerState.started:
                if (!(newState == ListenerState.stopping || newState == ListenerState.faulted || newState == ListenerState.starting))
                {
                    throw new Exception("Invalid state change. Started->" + newState.ToString());
                }
                break;

            case ListenerState.stopping:
                if (!(newState == ListenerState.stopped || newState == ListenerState.faulted))
                {
                    throw new Exception("Invalid state change. Stopping->" + newState.ToString());
                }
                break;

            case ListenerState.stopped:
                if (!(newState == ListenerState.faulted))
                {
                    throw new Exception("Invalid state change. Stopped->" + newState.ToString());
                }
                break;

            default:
                throw new Exception("Invalid state change");
            }

            // Raise event
            switch (newState)
            {
            case ListenerState.initializing:
                if (OnInitializing != null)
                {
                    OnInitializing.Invoke();
                }
                break;

            case ListenerState.initialized:
                if (OnInitialized != null)
                {
                    OnInitialized.Invoke();
                }
                break;

            case ListenerState.starting:
                if (OnStarting != null)
                {
                    OnStarting.Invoke();
                }
                break;

            case ListenerState.started:
                if (OnStarted != null)
                {
                    OnStarted.Invoke();
                }
                break;

            case ListenerState.stopping:
                if (OnStopping != null)
                {
                    OnStopping.Invoke();
                }
                break;

            case ListenerState.stopped:
                if (OnStopped != null)
                {
                    OnStopped.Invoke();
                }
                break;

            case ListenerState.faulted:
                if (OnFaulted != null)
                {
                    OnFaulted.Invoke();
                }
                break;
            }

            State = newState;
        }
 public override bool Start(string folder)
 {
     OnStarting?.Invoke(this);
     return(base.Start(folder));
 }
Beispiel #10
0
 public IBuilder StartUpOperations()
 {
     OnStarting?.Invoke(this, null);
     _vehicle.Add(string.Format("Car Model name :{0}", _brandName));
     return(this);
 }
Beispiel #11
0
 protected virtual void RaiseOnStarting() => OnStarting?.Invoke(this, new EventArgs());
 public void Start()
 {
     _isActive = true;
     OnStarting?.Invoke(this, EventArgs.Empty);
 }
Beispiel #13
0
 public void Start()
 {
     OnStarting?.Invoke(this, new EventArgs());
     OnStarted?.Invoke(this, new EventArgs());
 }