예제 #1
0
        public PyProcessContext(IScriptContext scriptContext,
                                dynamic processHandler,
                                ProcessFactory processFactory,
                                string command,
                                string commandArguments,
                                string workingDirectory,
                                ICommandParameters commandParameters)
        {
            _commandParameters = commandParameters;
            _scriptContext     = scriptContext;
            _command           = command;
            _commandArguments  = commandArguments;
            _workingDirectory  = workingDirectory;
            _processFactory    = processFactory;
            var processContext = _processFactory.CreateProcessContext(command,
                                                                      commandArguments,
                                                                      workingDirectory);

            _processHandler           = processHandler;
            processContext.OnMessage += (message) =>
            {
                _processHandler.OnMessage(message);
                //  Console.WriteLine(message);
            };
            processContext.OnError += (message) =>
            {
                _processHandler.OnError(message);
            };
            _processHandler.OnInit(this, _commandParameters);
            _processContext = processContext;
        }
        private ISensorQueryTargetParameters SynthesizeParameters(ICommandParameters parameters)
        {
            var customParameters = parameters[Parameter.Custom];

            if (customParameters.IsIEnumerable())
            {
                var queryParameters = new SensorQueryTargetParameters();

                var any = false;

                foreach (CustomParameter parameter in customParameters.ToIEnumerable())
                {
                    any = true;

                    queryParameters[parameter.Name] = parameter.Value;
                }

                if (any)
                {
                    return(queryParameters);
                }
            }

            return(null);
        }
예제 #3
0
 public MethodCommandWrapper(MethodInfo methodInfo, IServiceProvider serviceProvider)
 {
     m_MethodInfo        = methodInfo;
     m_ServiceProvider   = serviceProvider;
     m_CommandParameters = serviceProvider.GetRequiredService <ICurrentCommandContextAccessor>().Context.Parameters;
     m_ParametersTypes   = m_MethodInfo.GetParameters().GetParametersTypes();
 }
        internal override async Task AddSensorInternalAsync(ICommandParameters internalParams, int index, CancellationToken token)
        {
            var deviceId = (int)internalParams[Parameter.Id];

            int?tmpId = (int?)internalParams[Parameter.TmpId];

            //If it's our first request (not the case when adding excesive values)
            if (index == 0)
            {
                if (tmpId == null)
                {
                    tmpId = await GetTmpIdAsync(deviceId, internalParams, token).ConfigureAwait(false);
                }

                internalParams[Parameter.TmpId]         = tmpId.Value;
                ((BaseParameters)internalParams).Cookie = true;
            }

            await client.AddObjectInternalDefaultAsync(internalParams, token).ConfigureAwait(false);

            //If it's our first request (not the case when adding excesive values)
            if (index == 0)
            {
                var progressParameters = new AddSensorProgressParameters(deviceId, tmpId.Value, true);
                var progress           = await client.ObjectEngine.GetObjectAsync <AddSensorProgress>(progressParameters, token : token).ConfigureAwait(false);

                await client.ValidateAddSensorProgressResultAsync(deviceId, progress, true, token).ConfigureAwait(false);
            }
        }
        //######################################
        // AddSensorInternal
        //######################################

        internal override void AddSensorInternal(ICommandParameters internalParams, int index, CancellationToken token)
        {
            var deviceId = (int)internalParams[Parameter.Id];

            int?tmpId = (int?)internalParams[Parameter.TmpId];

            //If it's our first request (not the case when adding excesive values)
            if (index == 0)
            {
                if (tmpId == null)
                {
                    tmpId = GetTmpId(deviceId, internalParams, token);
                }

                internalParams[Parameter.TmpId]         = tmpId.Value;
                ((BaseParameters)internalParams).Cookie = true;
            }

            client.AddObjectInternalDefault(internalParams, token);

            //If it's our first request (not the case when adding excesive values)
            if (index == 0)
            {
                var progressParameters = new AddSensorProgressParameters(deviceId, tmpId.Value, true);
                var progress           = client.ObjectEngine.GetObject <AddSensorProgress>(progressParameters, token: token);

                ResponseParser.ValidateAddSensorProgressResult(progress, true);
            }
        }
예제 #6
0
 public PyProcessContext(IScriptContext scriptContext,
     dynamic processHandler,
     ProcessFactory processFactory,
     string command,
     string commandArguments,
     string workingDirectory,
     ICommandParameters commandParameters)
 {
     _commandParameters = commandParameters;
     _scriptContext = scriptContext;
     _command = command;
     _commandArguments = commandArguments;
     _workingDirectory = workingDirectory;
     _processFactory = processFactory;
     var processContext = _processFactory.CreateProcessContext(command,
         commandArguments,
         workingDirectory);
     _processHandler = processHandler;
     processContext.OnMessage += (message) =>
     {
         _processHandler.OnMessage(message);
         //  Console.WriteLine(message);
     };
     processContext.OnError += (message) =>
     {
         _processHandler.OnError(message);
     };
     _processHandler.OnInit(this, _commandParameters);
     _processContext = processContext;
 }
        public void SetupPark_Throws_Exception_When_Parameters_Are_Missing(string commandAsString)
        {
            // arrange
            Exception resultException = null;

            // act
            try
            {
                _commandParameters = _commandExtractor.ExtractFromCommandString(commandAsString);
            }
            catch (Exception exception)
            {
                if (exception.InnerException != null && exception.InnerException.GetType() == typeof(ArgumentException))
                {
                    resultException = exception.InnerException;
                }
                else
                {
                    resultException = exception;
                }
            }

            // assert
            Assert.IsInstanceOfType(resultException, typeof(ArgumentException));
        }
예제 #8
0
 public CommandContext(ICommandLogger logger,
                         ICommandParameters parameters,
                         ICommand command)
 {
     this.Logger = logger;
     this.Parameters = parameters;
     this.Command = command;
 }
        public string Execution(ICommandParameters command)
        {
            if (command.Name != "SetupPark" && VehicleInPark == null)
            {
                return("The vehicle park has not been set up");
            }

            switch (command.Name)
            {
            case "SetupPark":
                return("Vehicle park created");

            case "Рark":
                switch (command.Parameters["type"])
                {
                case "car":
                    return(VehicleInPark.InsertCar(
                               new Car(command.Parameters["licensePlate"], command.Parameters["owner"],
                                       int.Parse(command.Parameters["hours"])), int.Parse(command.Parameters["sector"]),
                               int.Parse(command.Parameters["place"]),
                               DateTime.Parse(command.Parameters["time"], null,
                                              System.Globalization.DateTimeStyles.RoundtripKind))); //why round trip kind??

                case "motorbike":
                    return(VehicleInPark.InsertMotorbike(
                               new MotorBike(command.Parameters["licensePlate"], command.Parameters["owner"],
                                             int.Parse(command.Parameters["hours"])), int.Parse(command.Parameters["sector"]),
                               int.Parse(command.Parameters["place"]),
                               DateTime.Parse(command.Parameters["time"], null,
                                              System.Globalization.DateTimeStyles.RoundtripKind))); //stack overflow says this

                case "truck":
                    return(VehicleInPark.InsertTruck(
                               new Truck(command.Parameters["licensePlate"], command.Parameters["owner"],
                                         int.Parse(command.Parameters["hours"])), int.Parse(command.Parameters["sector"]),
                               int.Parse(command.Parameters["place"]),
                               DateTime.Parse(command.Parameters["time"], null,
                                              System.Globalization.DateTimeStyles.RoundtripKind))); //I wanna know
                }
                break;

            case "Exit": return(VehicleInPark.ExitVehicle(command.Parameters["licensePlate"],
                                                          DateTime.Parse(command.Parameters["time"], null,
                                                                         System.Globalization.DateTimeStyles.RoundtripKind),
                                                          decimal.Parse(command.Parameters["money"])));

            case "Status": return(VehicleInPark.GetStatus());

            case "FindVehicle": return(VehicleInPark.FindVehicle(command.Parameters["licensePlate"]));

            case "VehiclesByOwner": return(VehicleInPark.FindVehiclesByOwner(command.Parameters["owner"]));

            default: throw new IndexOutOfRangeException("Invalid command.");
            }

            return("");
        }
예제 #10
0
 public void Configure(ICommandParameters commandlineParamters)
 {
     _IpAddress   = commandlineParamters.ParamAfterSwitch("IpAddress");
     _mask        = commandlineParamters.ParamAfterSwitch("Mask");
     _Gateway     = commandlineParamters.ParamAfterSwitch("Gateway");
     _DNS         = commandlineParamters.ParamAfterSwitch("DNS");
     _Name        = commandlineParamters.ParamAfterSwitch("Name");
     _adapterName = commandlineParamters.ParamAfterSwitch("AdapterName");
 }
        //AddSensorInternal

        internal virtual void AddSensorInternal(ICommandParameters internalParams, int index, CancellationToken token)
        {
            if (index == 0)
            {
                //Validate the sensor type
                GetTmpId((int)internalParams[Parameter.Id], internalParams, token);
            }

            client.AddObjectInternalDefault(internalParams, token);
        }
        internal virtual async Task AddSensorInternalAsync(ICommandParameters internalParams, int index, CancellationToken token)
        {
            if (index == 0)
            {
                //Validate the sensor type
                await GetTmpIdAsync((int)internalParams[Parameter.Id], internalParams, token).ConfigureAwait(false);
            }

            await client.AddObjectInternalDefaultAsync(internalParams, token).ConfigureAwait(false);
        }
예제 #13
0
 public PyRunner(string command, string script, string args, string workingDirectory,
                 ICommandParameters commandParameters)
 {
     this.command          = command;
     this.script           = script;
     this.args             = args;
     this.workingDirectory = workingDirectory;
     _processFactory       = new ProcessFactory();
     _commandParameters    = commandParameters;
 }
예제 #14
0
        internal string ExecuteRequest(ICommandParameters parameters, Func <HttpResponseMessage, string> responseParser = null)
        {
            if (parameters is IMultiTargetParameters)
            {
                return(ExecuteMultiRequest(p => GetPrtgUrl((ICommandParameters)p), (IMultiTargetParameters)parameters, responseParser));
            }

            var url = GetPrtgUrl(parameters);

            var response = ExecuteRequest(url, responseParser);

            return(response);
        }
        public void StatusReturnStatusCommand(string commandAsString)
        {
            //arange

            //act

            _result = _extractor.ExtractFromCommandString(commandAsString);
            //assert

            Assert.IsInstanceOfType(_result, typeof(ICommand));
            Assert.AreEqual("Status", _result.Name);
            Assert.AreEqual(0, _result.Parameters.Count);
        }
예제 #16
0
        internal async Task <PrtgResponse> ExecuteRequestAsync(ICommandParameters parameters, Func <HttpResponseMessage, Task <PrtgResponse> > responseParser = null, CancellationToken token = default(CancellationToken))
        {
            if (parameters is IMultiTargetParameters)
            {
                return(await ExecuteMultiRequestAsync(p => GetPrtgUrl((ICommandParameters)p), (IMultiTargetParameters)parameters, token, responseParser).ConfigureAwait(false));
            }

            var url = GetPrtgUrl(parameters);

            var response = await ExecuteRequestAsync(url, token, responseParser).ConfigureAwait(false);

            return(response);
        }
        public void SetupParkReturnsParkComand()
        {
            // arrange

            // act
            _result = _extractor.ExtractFromCommandString(Inputs.CreateDefaultPark);

            // assert
            Assert.IsInstanceOfType(_result, typeof(ICommand));
            Assert.AreEqual("SetupPark", _result.Name);
            Assert.AreEqual(3.ToString(), _result.Parameters["sectors"]);
            Assert.AreEqual(5.ToString(), _result.Parameters["placesPerSector"]);
        }
예제 #18
0
        internal async Task <string> ExecuteRequestAsync(ICommandParameters parameters, Func <HttpResponseMessage, Task <string> > responseParser = null)
        {
            if (parameters is IMultiTargetParameters)
            {
                return(await ExecuteMultiRequestAsync(p => GetPrtgUrl((ICommandParameters)p), (IMultiTargetParameters)parameters, responseParser).ConfigureAwait(false));
            }

            var url = GetPrtgUrl(parameters);

            var response = await ExecuteRequestAsync(url, responseParser).ConfigureAwait(false);

            return(response);
        }
예제 #19
0
        internal PrtgResponse ExecuteRequest(ICommandParameters parameters, Func <HttpResponseMessage, PrtgResponse> responseParser = null, CancellationToken token = default(CancellationToken))
        {
            if (parameters is IMultiTargetParameters)
            {
                return(ExecuteMultiRequest(p => GetPrtgUrl((ICommandParameters)p), (IMultiTargetParameters)parameters, token, responseParser));
            }

            var url = GetPrtgUrl(parameters);

            var response = ExecuteRequest(url, token, responseParser);

            return(response);
        }
        protected async Task <int?> GetTmpIdAsync(int deviceId, ICommandParameters internalParams, CancellationToken token)
        {
            //Purposely not validating the QueryTarget for addsensor2; when adding the sensor for real we don't really need it, and
            //current evidence suggestly we can simply just ignore it
            var tmpIdParameters = new BeginAddSensorQueryParameters(deviceId, internalParams[Parameter.SensorType].ToString(), SynthesizeParameters(internalParams));
            var tmpId           = await client.GetAddSensorTmpIdAsync(tmpIdParameters, token).ConfigureAwait(false);

            if (tmpId == null)
            {
                throw new PrtgRequestException($"Failed to add sensor for sensor type '{internalParams[Parameter.SensorType]}': type was not valid or you do not have sufficient permissions on the specified object.");
            }

            return(tmpId);
        }
예제 #21
0
        public MethodCommandWrapper(MethodInfo methodInfo, IServiceProvider serviceProvider)
        {
            m_MethodInfo      = methodInfo ?? throw new ArgumentNullException(nameof(methodInfo));
            m_ServiceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
            var contextAccessor = serviceProvider.GetRequiredService <ICurrentCommandContextAccessor>();

            var context = contextAccessor.Context;

            if (context == null)
            {
                throw new InvalidOperationException("contextAccessor.Context was null");
            }

            m_CommandParameters = context.Parameters;
            m_ParametersTypes   = m_MethodInfo.GetParameters().GetParametersTypes();
        }
        public void NullOrEmptyInputThrowsException(string commandAsString)
        {
            // Arrange
            Exception expectedResult = null;

            // Act
            try
            {
                _result = _extractor.ExtractFromCommandString(commandAsString);
            }
            catch (ArgumentException exception)
            {
                expectedResult = exception;
            }

            // Assert
            Assert.IsInstanceOfType(expectedResult, typeof(ArgumentException));
        }
        public void StatusThrowsArgumentExeption(string commandAsString)
        {
            // arrange
            Exception expectedExeption = null;

            // act
            try
            {
                _result = _extractor.ExtractFromCommandString(commandAsString);
            }
            catch (ArgumentException exeption)
            {
                expectedExeption = exeption;
            }

            // assert
            Assert.IsInstanceOfType(expectedExeption, typeof(ArgumentException));
        }
예제 #24
0
        internal PrtgResponse ExecuteRequest(ICommandParameters parameters, Func <HttpResponseMessage, PrtgResponse> responseParser = null, CancellationToken token = default(CancellationToken))
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters), "Parameters cannot be null.");
            }

            if (parameters is IMultiTargetParameters)
            {
                return(ExecuteMultiRequest(p => GetRequestMessage((ICommandParameters)p), (IMultiTargetParameters)parameters, token, responseParser));
            }

            var url = GetRequestMessage(parameters);

            var response = ExecuteRequest(url, token, responseParser);

            return(response);
        }
        public void SetupPark_Throws_Exception_With_Incorrect_Parameter_Values(string commandAsString)
        {
            // arrange
            Exception resultException = null;

            // act
            try
            {
                _commandParameters = _commandExtractor.ExtractFromCommandString(commandAsString);
            }
            catch (Exception exception)
            {
                resultException = exception.InnerException;
            }

            // assert
            Assert.IsInstanceOfType(resultException, typeof(ArgumentOutOfRangeException));
        }
예제 #26
0
        internal async Task <PrtgResponse> ExecuteRequestAsync(ICommandParameters parameters, Func <HttpResponseMessage, Task <PrtgResponse> > responseParser = null, CancellationToken token = default(CancellationToken))
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters), "Parameters cannot be null.");
            }

            if (parameters is IMultiTargetParameters)
            {
                return(await ExecuteMultiRequestAsync(p => GetRequestMessage((ICommandParameters)p), (IMultiTargetParameters)parameters, token, responseParser).ConfigureAwait(false));
            }

            var url = GetRequestMessage(parameters);

            var response = await ExecuteRequestAsync(url, token, responseParser).ConfigureAwait(false);

            return(response);
        }
예제 #27
0
        public static async Task <object[]> GetServiceOrCommandParameter(
            IEnumerable <Type> types, IServiceProvider serviceProvider, ICommandParameters commandParameters)
        {
            object[] values            = new object[types.Count()];
            int      commandParamIndex = 0;

            for (int i = 0; i < values.Length; i++)
            {
                Type type = types.ElementAt(i);

                // try get service
                values[i] = serviceProvider.GetService(type);

                // parse command parameter value if the type is not a service
                if (values[i] == null)
                {
                    values[i] = await commandParameters.GetAsync(commandParamIndex ++, type);
                }
            }

            return(values);
        }
예제 #28
0
 public PyRunner(string command, string script, string args, string workingDirectory,
     ICommandParameters commandParameters)
 {
     this.command = command;
     this.script = script;
     this.args = args;
     this.workingDirectory = workingDirectory;
      _processFactory = new ProcessFactory();
      _commandParameters = commandParameters;
 }
예제 #29
0
 private PrtgRequestMessage GetRequestMessage(ICommandParameters parameters) =>
 new PrtgRequestMessage(prtgClient.ConnectionDetails, parameters.Function, parameters);
예제 #30
0
 public void Handle(ICommandParameters parameters)
 {
     Handle((CommandParameters)parameters);
 }
 internal static bool IsAddSensor(ICommandParameters parameters) => parameters.Function == CommandFunction.AddSensor5;
예제 #32
0
        private async Task AddObjectWithExcessiveValueAsync(List <KeyValuePair <Parameter, object> > lengthLimit, ICommandParameters internalParams)
        {
            var limitParam = lengthLimit.First();

            var limit = limitParam.Key.GetEnumAttribute <LengthLimitAttribute>().Length;

            if (limitParam.Value.IsIEnumerable())
            {
                var list = limitParam.Value.ToIEnumerable().ToList();

                var count = list.Count();

                if (count > limit)
                {
                    for (int i = 0; i < count; i += limit)
                    {
                        var thisRequest = list.Skip(i).Take(limit);

                        internalParams[limitParam.Key] = thisRequest;

                        await RequestEngine.ExecuteRequestAsync(internalParams).ConfigureAwait(false);
                    }
                }
                else
                {
                    await RequestEngine.ExecuteRequestAsync(internalParams).ConfigureAwait(false);
                }
            }
            else
            {
                throw new NotImplementedException($"Don't know how to handle {nameof(LengthLimitAttribute)} applied to value of type {limitParam.Value.GetType()}");
            }
        }
예제 #33
0
 private PrtgUrl GetPrtgUrl(ICommandParameters parameters) =>
 new PrtgUrl(prtgClient.ConnectionDetails, parameters.Function, parameters);