Exemplo n.º 1
0
        private static void createCommand(IoTDAClient client)
        {
            CreateCommandRequest req = new CreateCommandRequest
            {
                InstanceId = "1a7ffc5c-d89c-44dd-8265-b1653d951ce0",
                DeviceId   = "5eeb1fefbc61700402bc35f9_1211211",
                Body       = new DeviceCommandRequest()
                {
                    ServiceId   = "b1224afb-e9f0-4916-8220-b6bab568e888",
                    CommandName = "ON_OFF",
                    Paras       = JObject.Parse("{\"value\":\"ON\"}")
                }
            };

            try
            {
                var resp = client.CreateCommand(req);
                Console.WriteLine(resp);
            }
            catch (RequestTimeoutException requestTimeoutException)
            {
                Console.WriteLine(requestTimeoutException.ErrorMessage);
            }
            catch (ServiceResponseException clientRequestException)
            {
                Console.WriteLine(clientRequestException.HttpStatusCode);
                Console.WriteLine(clientRequestException.ErrorCode);
                Console.WriteLine(clientRequestException.ErrorMsg);
            }
            catch (ConnectionException connectionException)
            {
                Console.WriteLine(connectionException.ErrorMessage);
            }
        }
    public static void Execute(this IDbCommandExecutor executor, CreateCommandRequest request, Action <IDbCommand> execute)
    {
        ArgumentNullException.ThrowIfNull(executor);
        var requests = new ExecuteCommandRequest(request, execute).ItemToArray();

        executor.Execute(requests);
    }
Exemplo n.º 3
0
        public async Task <CreateCommandResponse> Post(CreateCommandRequest request)
        {
            if (!await batchRepository.DoesBatchExist(request.BatchId))
            {
                throw Err.BatchNotFound(request.BatchId);
            }

            var step = await stepRepository.Get(request.BatchId, request.StepName);

            if (step == null)
            {
                throw Err.StepNotFound(request.StepName);
            }

            if (await commandRepository.DoesCommandExist(request.BatchId, request.StepName, request.CommandName))
            {
                throw Err.CommandAlreadyExists(request.CommandName);
            }

            var command = request.ConvertTo <Core.Entities.Command>();

            command.StepId = step.Id;

            await commandRepository.Create(command);

            return(new CreateCommandResponse());
        }
Exemplo n.º 4
0
    public static IDbCommand CreateCommand(this IDbConnection connection, CreateCommandRequest request)
    {
        var command = connection.CreateCommand();

        command.Initialize(request);
        return(command);
    }
    public ExecuteCommandRequest(CreateCommandRequest createCommandRequest, Action <IDbCommand> execute)
    {
        ArgumentNullException.ThrowIfNull(createCommandRequest);
        ArgumentNullException.ThrowIfNull(execute);

        CreateCommandRequest = createCommandRequest;
        Execute = execute;
    }
    public ExecuteCommandAsyncRequest(CreateCommandRequest createCommandRequest, Func <DbCommand, Task> execute)
    {
        Assert.IsNotNull(createCommandRequest);
        Assert.IsNotNull(execute);

        CreateCommandRequest = createCommandRequest;
        Execute = execute;
    }
    public static int ExecuteNonQuery(this IDbCommandExecutor executor, CreateCommandRequest request)
    {
        ArgumentNullException.ThrowIfNull(executor);
        var affectedRows = 0;

        executor.Execute(request, command => affectedRows = command.ExecuteNonQuery());
        return(affectedRows);
    }
Exemplo n.º 8
0
    public ExecuteReaderRequest(CreateCommandRequest createCommandRequest, CommandBehavior commandBehavior, CancellationToken cancellationToken)
    {
        Assert.IsNotNull(createCommandRequest);

        CreateCommandRequest = createCommandRequest;
        CommandBehavior      = commandBehavior;
        CancellationToken    = cancellationToken;
    }
    public ExecuteCommandAsyncRequest(CreateCommandRequest createCommandRequest, Func <DbCommand, Task> execute)
    {
        ArgumentNullException.ThrowIfNull(createCommandRequest);
        ArgumentNullException.ThrowIfNull(execute);

        CreateCommandRequest = createCommandRequest;
        Execute = execute;
    }
    public static DbCommand CreateCommand(this DbConnection connection, CreateCommandRequest request)
    {
        ArgumentNullException.ThrowIfNull(connection);
        var command = connection.CreateCommand();

        command.Initialize(request);
        return(command);
    }
Exemplo n.º 11
0
        /// <summary>
        /// 下发设备命令
        /// </summary>
        public async Task <CreateCommandResponse> CreateCommandAsync(CreateCommandRequest createCommandRequest)
        {
            Dictionary <string, string> urlParam = new Dictionary <string, string>();

            urlParam.Add("device_id", createCommandRequest.DeviceId.ToString());
            string              urlPath  = HttpUtils.AddUrlPath("/v5/iot/{project_id}/devices/{device_id}/commands", urlParam);
            SdkRequest          request  = HttpUtils.InitSdkRequest(urlPath, "application/json", createCommandRequest);
            HttpResponseMessage response = await DoHttpRequestAsync("POST", request);

            return(JsonUtils.DeSerialize <CreateCommandResponse>(response));
        }
Exemplo n.º 12
0
        public void Create_Command_Should_Throw_With_Invalid_Batch_Id()
        {
            // Arrange
            batchRepository.DoesBatchExist(Arg.Any <string>())
            .Returns(false);

            var request = new CreateCommandRequest
            {
                BatchId = TestBatchId
            };

            // Act / Assert
            var exception = Assert.ThrowsAsync <HttpError>(() => Sut.Post(request));

            exception.ErrorCode.Should().Be(HttpStatusCode.NotFound.ToString());
            exception.Message.Should().Be("Batch TestBatch not found");
        }
Exemplo n.º 13
0
    internal static void Initialize(this IDbCommand command, CreateCommandRequest request)
    {
        command.CommandType = request.CommandType;
        command.CommandText = request.CommandText;

        if (request.CommandTimeout != null)
        {
            command.CommandTimeout = request.CommandTimeout.Value;
        }

        command.Transaction = request.Transaction;

        if (request.Parameters != null)
        {
            command.Parameters.AddRange(request.Parameters);
        }
    }
Exemplo n.º 14
0
        public void Create_Command_Should_Throw_With_Invalid_Step_Name()
        {
            // Arrange
            batchRepository.DoesBatchExist(Arg.Any <string>())
            .Returns(true);

            stepRepository.Get(Arg.Any <string>(), Arg.Any <string>())
            .ReturnsNull();

            var request = new CreateCommandRequest
            {
                StepName = TestStepName
            };

            // Act / Assert
            var exception = Assert.ThrowsAsync <HttpError>(() => Sut.Post(request));

            exception.ErrorCode.Should().Be(HttpStatusCode.NotFound.ToString());
            exception.Message.Should().Be("Step TestStep not found");
        }
Exemplo n.º 15
0
        public void Create_Command_Should_Throw_With_Invalid_Command_Name()
        {
            // Arrange
            batchRepository.DoesBatchExist(Arg.Any <string>())
            .Returns(true);

            stepRepository.Get(Arg.Any <string>(), Arg.Any <string>())
            .Returns(new Step());

            commandRepository.DoesCommandExist(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>())
            .Returns(true);

            var request = new CreateCommandRequest
            {
                CommandName = TestCommandName
            };

            // Act / Assert
            var exception = Assert.ThrowsAsync <HttpError>(() => Sut.Post(request));

            exception.ErrorCode.Should().Be(HttpStatusCode.Conflict.ToString());
            exception.Message.Should().Be("Command TestCommand already exists");
        }
Exemplo n.º 16
0
        /// <summary>
        /// Submitting URL to plagiarism scan
        /// </summary>
        /// <param name="url">The url containing the content to scan</param>
        /// <param name="options">Process Options: include http callback and add custom fields to the process</param>
        /// <exception cref="UnauthorizedAccessException">The login-token is undefined or expired</exception>
        /// <exception cref="ArgumentOutOfRangeException">The input URL scheme is different than HTTP or HTTPS</exception>
        /// <returns>The newly created process</returns>
        public CopyleaksProcess CreateByUrl(Uri url, ProcessOptions options = null)
        {
            if (this.Token == null)
            {
                throw new UnauthorizedAccessException("Empty token!");
            }
            else
            {
                this.Token.Validate();
            }

            if (url.Scheme != "http" && url.Scheme != "https")
            {
                throw new ArgumentOutOfRangeException(nameof(url), "Allowed protocols: HTTP, HTTPS");
            }

            using (HttpClient client = new HttpClient())
            {
                client.SetCopyleaksClient(HttpContentTypes.Json, this.Token);

                CreateCommandRequest req = new CreateCommandRequest()
                {
                    URL = url.AbsoluteUri
                };

                HttpResponseMessage msg;
                // Submitting the URL
                HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(req),
                    Encoding.UTF8,
                    HttpContentTypes.Json);

                if (options != null)
                {
                    options.AddHeaders(client);
                }

                msg = client.PostAsync(string.Format("{0}/{1}/{2}", Resources.ServiceVersion, this.Product.ToName(), "create-by-url"), content).Result;

                if (!msg.IsSuccessStatusCode)
                {
                    throw new CommandFailedException(msg);
                }

                string json = msg.Content.ReadAsStringAsync().Result;

                CreateResourceResponse response;
                try
                {
                    var dateTimeConverter = new IsoDateTimeConverter {
                        DateTimeFormat = "dd/MM/yyyy HH:mm:ss"
                    };
                    response = JsonConvert.DeserializeObject <CreateResourceResponse>(json, dateTimeConverter);
                }
                catch (Exception e)
                {
                    throw new Exception("JSON=" + json, e);
                }
                if (options == null)
                {
                    return(new CopyleaksProcess(this.Token, this.Product, response, null));
                }
                else
                {
                    return(new CopyleaksProcess(this.Token, this.Product, response, options.CustomFields));
                }
            }
        }
Exemplo n.º 17
0
 public ExecuteNonReaderRequest(CreateCommandRequest createCommandRequest, CancellationToken cancellationToken)
 {
     CreateCommandRequest = createCommandRequest;
     CancellationToken    = cancellationToken;
 }