Ejemplo n.º 1
0
 /// <inheritdoc/>
 public void Apply(OpenApiParameter parameter, ParameterFilterContext context)
 {
     //
     // fix current bug where properties are not added correctly
     // Lookup property schema in schema repo
     //
     if (context.PropertyInfo != null)
     {
         // Query was passed a parameter with properties
         var propertySchema = context.SchemaRepository.Schemas
                              .Where(p => p.Key.EqualsIgnoreCase(context.ParameterInfo.ParameterType.Name))
                              .SelectMany(p => p.Value.Properties)
                              .Where(p => p.Key.EqualsIgnoreCase(context.PropertyInfo.Name))
                              .FirstOrDefault();
         if (propertySchema.Value != null)
         {
             // Replace parameter definition with property schema
             parameter.Name = propertySchema.Key;
             // Quick and dirty clone of the schema for the parameter
             parameter.Schema = JsonConvertEx.DeserializeObject <OpenApiSchema>(
                 JsonConvertEx.SerializeObject(propertySchema.Value));
         }
         parameter.Required = context.PropertyInfo
                              .GetCustomAttributes(typeof(RequiredAttribute), true)
                              .Any();
         AdjustSchema(context.PropertyInfo.PropertyType, parameter.Schema);
     }
     else if (context.ParameterInfo != null)
     {
         // Query was passed a parameter with properties
         AdjustSchema(context.ParameterInfo.ParameterType, parameter.Schema);
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Upload results
        /// </summary>
        /// <param name="discovered"></param>
        /// <param name="timestamp"></param>
        /// <param name="request"></param>
        /// <param name="diagnostics"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        private async Task SendDiscoveryResultsAsync(DiscoveryRequest request,
                                                     List <ApplicationRegistrationModel> discovered, DateTime timestamp,
                                                     object diagnostics, CancellationToken ct)
        {
            _logger.Information("Uploading {count} results...", discovered.Count);
            var messages = discovered
                           .SelectMany(server => server.Endpoints
                                       .Select(registration => new DiscoveryEventModel {
                Application  = server.Application,
                Registration = registration,
                TimeStamp    = timestamp
            }))
                           .Append(new DiscoveryEventModel {
                Registration = null,     // last
                Result       = new DiscoveryResultModel {
                    DiscoveryConfig = request.Configuration,
                    Id           = request.Request.Id,
                    Context      = request.Request.Context,
                    RegisterOnly = request.Mode == DiscoveryMode.Off,
                    Diagnostics  = diagnostics == null ? null :
                                   JToken.FromObject(diagnostics)
                },
                TimeStamp = timestamp
            })
                           .Select((discovery, i) => {
                discovery.Index = i;
                return(discovery);
            })
                           .Select(discovery => Encoding.UTF8.GetBytes(
                                       JsonConvertEx.SerializeObject(discovery)));
            await Task.Run(() => _events.SendAsync(
                               messages, ContentTypes.DiscoveryEvents), ct);

            _logger.Information("{count} results uploaded.", discovered.Count);
        }
        /// <summary>
        /// helper to invoke service
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="R"></typeparam>
        /// <param name="service"></param>
        /// <param name="registration"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        private async Task <R> CallServiceOnSupervisor <T, R>(string service,
                                                              EndpointRegistrationModel registration, T request)
        {
            if (registration == null)
            {
                throw new ArgumentNullException(nameof(registration));
            }
            if (registration.Endpoint == null)
            {
                throw new ArgumentNullException(nameof(registration.Endpoint));
            }
            if (string.IsNullOrEmpty(registration.SupervisorId))
            {
                throw new ArgumentNullException(nameof(registration.SupervisorId));
            }
            var sw       = Stopwatch.StartNew();
            var deviceId = SupervisorModelEx.ParseDeviceId(registration.SupervisorId,
                                                           out var moduleId);
            var result = await _client.CallMethodAsync(deviceId, moduleId, service,
                                                       JsonConvertEx.SerializeObject(new {
                endpoint = registration.Endpoint,
                request
            }));

            _logger.Debug("Calling supervisor service '{service}' on {deviceId}/{moduleId} " +
                          "took {elapsed} ms and returned {result}!", service, deviceId, moduleId,
                          sw.ElapsedMilliseconds, result);
            return(JsonConvertEx.DeserializeObject <R>(result));
        }
Ejemplo n.º 4
0
        /// <inheritdoc/>
        public async Task <HistoryReadNextResponseApiModel <JToken> > HistoryReadRawNextAsync(
            EndpointApiModel endpoint, HistoryReadNextRequestApiModel request,
            CancellationToken ct)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }
            if (string.IsNullOrEmpty(endpoint.Url))
            {
                throw new ArgumentNullException(nameof(endpoint.Url));
            }
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (string.IsNullOrEmpty(request.ContinuationToken))
            {
                throw new ArgumentNullException(nameof(request.ContinuationToken));
            }
            var response = await _methodClient.CallMethodAsync(_deviceId, _moduleId,
                                                               "HistoryReadNext_V2", JsonConvertEx.SerializeObject(new {
                endpoint,
                request
            }), null, ct);

            return(JsonConvertEx.DeserializeObject <HistoryReadNextResponseApiModel <JToken> >(response));
        }
Ejemplo n.º 5
0
        public void SendReceiveJsonTestWithVariousChunkSizes(int chunkSize)
        {
            var fixture = new Fixture();

            var expectedMethod      = fixture.Create <string>();
            var expectedContentType = fixture.Create <string>();
            var expectedRequest     = JsonConvertEx.SerializeObject(new {
                test1 = fixture.Create <string>(),
                test2 = fixture.Create <long>()
            });
            var expectedResponse = JsonConvertEx.SerializeObject(new {
                test1 = fixture.Create <byte[]>(),
                test2 = fixture.Create <string>()
            });
            var server = new TestServer(chunkSize, (method, buffer, type) => {
                Assert.Equal(expectedMethod, method);
                Assert.Equal(expectedContentType, type);
                Assert.Equal(expectedRequest, Encoding.UTF8.GetString(buffer));
                return(Encoding.UTF8.GetBytes(expectedResponse));
            });
            var result = server.CreateClient().CallMethodAsync(
                fixture.Create <string>(), fixture.Create <string>(), expectedMethod,
                Encoding.UTF8.GetBytes(expectedRequest), expectedContentType).Result;

            Assert.Equal(expectedResponse, Encoding.UTF8.GetString(result));
        }
Ejemplo n.º 6
0
 /// <inheritdoc/>
 public void WriteXmlElement(string property, XmlElement value)
 {
     if (value == null)
     {
         WriteNull(property);
     }
     else
     {
         if (!string.IsNullOrEmpty(property))
         {
             _writer.WritePropertyName(property);
         }
         if (PerformXmlSerialization || UseAdvancedEncoding)
         {
             var json = JsonConvertEx.SerializeObject(value);
             _writer.WriteRawValue(json);
         }
         else
         {
             // Back compat to json encoding
             var xml = value.OuterXml;
             _writer.WriteValue(Encoding.UTF8.GetBytes(xml));
         }
     }
 }
Ejemplo n.º 7
0
        public void SetContent <T>(T sourceObject, Encoding encoding, MediaTypeHeaderValue mediaType)
        {
            var content = JsonConvertEx.SerializeObject(sourceObject);

            this.requestContent.Content = new StringContent(content, encoding, mediaType.MediaType);
            this.ContentType            = mediaType;
        }
Ejemplo n.º 8
0
        /// <inheritdoc/>
        public async Task <ValueWriteResponseApiModel> NodeValueWriteAsync(EndpointApiModel endpoint,
                                                                           ValueWriteRequestApiModel request, CancellationToken ct)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }
            if (string.IsNullOrEmpty(endpoint.Url))
            {
                throw new ArgumentNullException(nameof(endpoint.Url));
            }
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (request.Value == null)
            {
                throw new ArgumentNullException(nameof(request.Value));
            }
            var response = await _methodClient.CallMethodAsync(_deviceId, _moduleId,
                                                               "ValueWrite_V2", JsonConvertEx.SerializeObject(new {
                endpoint,
                request
            }), null, ct);

            return(JsonConvertEx.DeserializeObject <ValueWriteResponseApiModel>(response));
        }
Ejemplo n.º 9
0
        /// <inheritdoc/>
        public async Task <BrowsePathResponseApiModel> NodeBrowsePathAsync(EndpointApiModel endpoint,
                                                                           BrowsePathRequestApiModel request, CancellationToken ct)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }
            if (string.IsNullOrEmpty(endpoint.Url))
            {
                throw new ArgumentNullException(nameof(endpoint.Url));
            }
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (request.BrowsePaths == null || request.BrowsePaths.Count == 0 ||
                request.BrowsePaths.Any(p => p == null || p.Length == 0))
            {
                throw new ArgumentNullException(nameof(request.BrowsePaths));
            }
            var response = await _methodClient.CallMethodAsync(_deviceId, _moduleId,
                                                               "BrowsePath_V2", JsonConvertEx.SerializeObject(new {
                endpoint,
                request
            }), null, ct);

            return(JsonConvertEx.DeserializeObject <BrowsePathResponseApiModel>(response));
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Send as json
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="client"></param>
 /// <param name="messages"></param>
 /// <param name="eventSchema"></param>
 /// <returns></returns>
 public static Task SendJsonEventAsync <T>(this IEventClient client, IEnumerable <T> messages,
                                           string eventSchema)
 {
     return(client.SendEventAsync(messages.Select(message =>
                                                  Encoding.UTF8.GetBytes(JsonConvertEx.SerializeObject(message))),
                                  ContentMimeType.Json, eventSchema, "utf-8"));
 }
Ejemplo n.º 11
0
            public async Task <string> CallMethodAsync(string deviceId,
                                                       string moduleId, string method, string json, TimeSpan?timeout = null)
            {
                var processed = await _server.ProcessAsync(
                    JsonConvertEx.DeserializeObject <MethodChunkModel>(json));

                return(JsonConvertEx.SerializeObject(processed));
            }
Ejemplo n.º 12
0
 /// <inheritdoc/>
 public Task HandleSampleAsync(MonitoredItemSampleModel sample)
 {
     // Set timestamp as source timestamp
     // TODO: Make configurable
     sample.Timestamp = sample.SourceTimestamp;
     return(_client.SendAsync(Encoding.UTF8.GetBytes(
                                  JsonConvertEx.SerializeObject(sample))));
 }
 /// <summary>
 /// Create with creation options
 /// </summary>
 /// <param name="imageName"></param>
 /// <param name="createOptions"></param>
 /// <returns></returns>
 public static EdgeAgentModuleSettingsModel Create(string imageName,
                                                   CreateContainerParameters createOptions = null)
 {
     return(new EdgeAgentModuleSettingsModel {
         Image = imageName,
         CreateOptions = createOptions == null ? "" :
                         JsonConvertEx.SerializeObject(createOptions)
     });
 }
Ejemplo n.º 14
0
            /// <inheritdoc/>
            public async Task <byte[]> InvokeAsync(byte[] payload, string contentType)
            {
                var data = JsonConvertEx.DeserializeObject <MethodChunkModel>(
                    Encoding.UTF8.GetString(payload));

                data = await _server.ProcessAsync(data);

                return(Encoding.UTF8.GetBytes(JsonConvertEx.SerializeObject(data)));
            }
Ejemplo n.º 15
0
        /// <inheritdoc/>
        public async Task <PublishStartResultModel> NodePublishStartAsync(
            EndpointModel endpoint, PublishStartRequestModel request)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (request.Item == null)
            {
                throw new ArgumentNullException(nameof(request.Item));
            }
            if (string.IsNullOrEmpty(request.Item.NodeId))
            {
                throw new ArgumentNullException(nameof(request.Item.NodeId));
            }

            var error = await TestPublishNodeAsync(endpoint, request);

            if (error != null)
            {
                return(new PublishStartResultModel {
                    ErrorInfo = error
                });
            }

            GetUserNamePassword(endpoint.User, out var user, out var password);
            var content = new PublishNodesRequestModel {
                EndpointUrl = endpoint.Url,
                Password    = password,
                UserName    = user,
                UseSecurity = endpoint.SecurityMode != SecurityMode.None,
                OpcNodes    = new List <PublisherNodeModel> {
                    new PublisherNodeModel {
                        Id = ToPublisherNodeId(request.Item.NodeId),
                        OpcPublishingInterval =
                            request.Item.PublishingInterval,
                        OpcSamplingInterval =
                            request.Item.SamplingInterval
                    }
                }
            };

            if (_client == null)
            {
                await StartAsync();
            }
            var(errorInfo, _) = await _client.CallMethodAsync("PublishNodes",
                                                              JsonConvertEx.SerializeObject(content), request.Header?.Diagnostics);

            return(new PublishStartResultModel {
                ErrorInfo = errorInfo
            });
        }
Ejemplo n.º 16
0
        /// <inheritdoc/>
        public Task HandleMessageAsync(DataSetMessageModel message)
        {
            var properties = new Dictionary <string, string>()
            {
                [CommonProperties.EventSchemaType] =
                    MessageSchemaTypes.NetworkMessageModelJson
            };

            return(_client.SendAsync(Encoding.UTF8.GetBytes(
                                         JsonConvertEx.SerializeObject(message)), properties));
        }
Ejemplo n.º 17
0
        /// <inheritdoc/>
        public async Task <PublishStartResultModel> NodePublishStartAsync(
            string endpointId, PublishStartRequestModel request)
        {
            if (string.IsNullOrEmpty(endpointId))
            {
                throw new ArgumentNullException(nameof(endpointId));
            }
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (request.Item == null)
            {
                throw new ArgumentNullException(nameof(request.Item));
            }
            if (string.IsNullOrEmpty(request.Item.NodeId))
            {
                throw new ArgumentNullException(nameof(request.Item.NodeId));
            }

            var(publisherId, endpoint) = await _publishers.FindPublisherEndpoint(
                endpointId);

            GetUserNamePassword(request.Header?.Elevation, out var user, out var password);
            var content = new PublishNodesRequestModel {
                EndpointUrl  = endpoint.Url,
                EndpointId   = endpointId,
                UseSecurity  = endpoint.SecurityMode != SecurityMode.None,
                SecurityMode = endpoint.SecurityMode == null ||
                               endpoint.SecurityMode == SecurityMode.Best ? null :
                               endpoint.SecurityMode.ToString(),
                SecurityProfileUri = endpoint.SecurityPolicy,
                Password           = password,
                UserName           = user,
                OpcNodes           = new List <PublisherNodeModel> {
                    new PublisherNodeModel {
                        Id                    = request.Item.NodeId,
                        DisplayName           = null,
                        OpcPublishingInterval = (int?)
                                                request.Item.PublishingInterval?.TotalMilliseconds,
                        OpcSamplingInterval = (int?)
                                              request.Item.SamplingInterval?.TotalMilliseconds
                    }
                }
            };

            var(errorInfo, _) = await CallMethodOnPublisherAsync(publisherId, "PublishNodes",
                                                                 JsonConvertEx.SerializeObject(content));

            return(new PublishStartResultModel {
                ErrorInfo = errorInfo
            });
        }
Ejemplo n.º 18
0
        /// <inheritdoc/>
        public Task HandleSampleAsync(MonitoredItemSampleModel sample)
        {
            // Set timestamp as source timestamp
            var properties = new Dictionary <string, string>()
            {
                [CommonProperties.EventSchemaType] =
                    MessageSchemaTypes.MonitoredItemMessageModelJson
            };

            return(_client.SendAsync(Encoding.UTF8.GetBytes(
                                         JsonConvertEx.SerializeObject(sample)), properties));
        }
        public async Task TestTestNoReturnInvocationNoReturnUsingMethodClient()
        {
            var harness = new ModuleHostHarness();
            await harness.RunTestAsync(GetControllers(), async (device, module, services) => {
                var hub = services.Resolve <IMethodClient>();

                var response = await hub.CallMethodAsync(device, module, "TestNoReturn_V1",
                                                         JsonConvertEx.SerializeObject(nameof(TestControllerV1.TestNoReturnAsync)));

                Assert.Null(response);
            });
        }
Ejemplo n.º 20
0
        /// <inheritdoc/>
        public void Log(string method, string file, int lineNumber,
                        LogLevel level, Exception exception, string message,
                        params object[] parameters)
        {
            var time = DateTimeOffset.UtcNow.ToString("u");

            message = $"[{level}][{_processId}][{time}][{method}] {message}";
            if (parameters != null && parameters.Length != 0)
            {
                message += $" ({JsonConvertEx.SerializeObject(parameters)})";
            }
            Trace.WriteLineIf(_loggingLevel <= level, message, level.ToString());
        }
        public async Task TestTestNoParametersInvocationNoParamUsingMethodClient()
        {
            var harness = new ModuleHostHarness();
            await harness.RunTestAsync(GetControllers(), async (device, module, services) => {
                var hub = services.Resolve <IMethodClient>();

                var response = await hub.CallMethodAsync(device, module, "TestNoParameters_V1",
                                                         JsonConvertEx.SerializeObject(null));

                var returned = JsonConvertEx.DeserializeObject <string>(response);
                Assert.Equal(nameof(TestControllerV1.TestNoParametersAsync), returned);
            });
        }
        /// <summary>
        /// Helper to invoke service
        /// </summary>
        /// <param name="service"></param>
        /// <param name="supervisorId"></param>
        /// <param name="payload"></param>
        /// <returns></returns>
        private async Task CallServiceOnSupervisor(string service, string supervisorId,
                                                   object payload)
        {
            var sw       = Stopwatch.StartNew();
            var deviceId = SupervisorModelEx.ParseDeviceId(supervisorId,
                                                           out var moduleId);
            var result = await _client.CallMethodAsync(deviceId, moduleId, service,
                                                       JsonConvertEx.SerializeObject(payload));

            _logger.Debug("Calling supervisor service '{service}' on " +
                          "{deviceId}/{moduleId} took {elapsed} ms.", service, deviceId,
                          moduleId, sw.ElapsedMilliseconds);
        }
        public void TestTest2InvocationNonChunkedFailsWithLargeBuffer()
        {
            var router   = GetRouter();
            var expected = new byte[96 * 1024];

            r.NextBytes(expected);
            var response = router.InvokeMethodAsync(new MethodRequest(
                                                        "Test2_V1", Encoding.UTF8.GetBytes(
                                                            JsonConvertEx.SerializeObject(expected)))).Result;

            Assert.Equal((int)HttpStatusCode.RequestEntityTooLarge,
                         response.Status);
        }
        public async Task TestTestNoParametersAndNoReturnInvocationNoParamAndNoReturnUsingMethodClient()
        {
            var harness    = new ModuleHostHarness();
            var controller = new TestControllerV1();
            await harness.RunTestAsync(controller.YieldReturn(), async (device, module, services) => {
                var hub = services.Resolve <IMethodClient>();

                var response = await hub.CallMethodAsync(device, module, "TestNoParametersAndNoReturn_V1",
                                                         JsonConvertEx.SerializeObject(null));

                Assert.Null(response);
                Assert.True(controller._noparamcalled);
            });
        }
        public void TestTest2InvocationNonChunked(int size)
        {
            var router   = GetRouter();
            var expected = new byte[size];

            r.NextBytes(expected);
            var response = router.InvokeMethodAsync(new MethodRequest(
                                                        "Test2_V1", Encoding.UTF8.GetBytes(
                                                            JsonConvertEx.SerializeObject(expected)))).Result;
            var returned = JsonConvertEx.DeserializeObject <byte[]>(
                response.ResultAsJson);

            Assert.Equal(expected, returned);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Test connectivity by listing and ensuring no exception happens.
        /// </summary>
        /// <returns></returns>
        private async Task <ServiceResultModel> TestConnectivityAsync(IPublisherClient server)
        {
            try {
                var test = JsonConvertEx.SerializeObject(new GetNodesRequestModel {
                    EndpointUrl = "opc.tcp://test"
                });
                var(errorInfo, result) = await server.CallMethodAsync(
                    "GetConfiguredNodesOnEndpoint", test, null);

                return(errorInfo);
            }
            catch {
                return(null);
            }
        }
Ejemplo n.º 27
0
 /// <inheritdoc/>
 protected override void WriteLine(string preamble, string message,
                                   Exception exception, object[] parameters)
 {
     message = $"{preamble} {message}";
     if (parameters != null && parameters.Length != 0)
     {
         message += $" ({JsonConvertEx.SerializeObject(parameters)})";
     }
     if (exception != null)
     {
         message += "\r\n";
         message += JsonConvertEx.SerializeObject(exception);
     }
     Console.WriteLine(message);
 }
        public async Task TestTestNoReturnInvocationNoReturn()
        {
            var harness = new ModuleHostHarness();
            await harness.RunTestAsync(GetControllers(), async (device, module, services) => {
                var hub = services.Resolve <IIoTHubTwinServices>();

                var response = await hub.CallMethodAsync(device, module, new MethodParameterModel {
                    Name        = "TestNoReturn_V1",
                    JsonPayload = JsonConvertEx.SerializeObject(nameof(TestControllerV1.TestNoReturnAsync))
                });

                Assert.Null(response.JsonPayload);
                Assert.Equal(200, response.Status);
            });
        }
Ejemplo n.º 29
0
        /// <summary>
        /// helper to invoke service
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="R"></typeparam>
        /// <param name="service"></param>
        /// <param name="endpointId"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        private async Task <R> CallServiceOnTwin <T, R>(string service,
                                                        string endpointId, T request)
        {
            if (string.IsNullOrEmpty(endpointId))
            {
                throw new ArgumentNullException(nameof(endpointId));
            }
            var sw     = Stopwatch.StartNew();
            var result = await _client.CallMethodAsync(endpointId, null, service,
                                                       JsonConvertEx.SerializeObject(request));

            _logger.Debug("Twin call '{service}' took {elapsed} ms)!",
                          service, sw.ElapsedMilliseconds);
            return(JsonConvertEx.DeserializeObject <R>(result));
        }
        public void TestTest2InvocationV2NonChunked()
        {
            var router = GetRouter();
            var buffer = new byte[1049];

            r.NextBytes(buffer);
            var response = router.InvokeMethodAsync(new MethodRequest(
                                                        "Test2_v2", Encoding.UTF8.GetBytes(
                                                            JsonConvertEx.SerializeObject(buffer)))).Result;

            Assert.Equal(400, response.Status);
            var ex = JsonConvertEx.DeserializeObject <ArgumentNullException>(
                response.ResultAsJson);

            Assert.Equal("request", ex.ParamName);
        }