예제 #1
0
        private void Channel_OnOpen(object sender, ChannelOpenEventArgs e)
        {
            try
            {
                session.IsAuthenticated = Channel.IsAuthenticated;
                if (session.IsAuthenticated)
                {
                    IdentityDecoder decoder = new IdentityDecoder(session.Config.IdentityClaimType, context,
                                                                  session.Config.Indexes);
                    session.Identity = decoder.Id;
                    session.Indexes  = decoder.Indexes;

                    UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity,
                                                                 session.Config.IdentityClaimType, Channel.TypeId, "MQTT", "Granted", DateTime.UtcNow);
                    userAuditor?.WriteAuditRecordAsync(record).Ignore();
                }

                adapter            = new OrleansAdapter(session.Identity, Channel.TypeId, "MQTT", graphManager, logger);
                adapter.OnObserve += Adapter_OnObserve;
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"MQTT adapter Channel_OnOpen error on channel '{Channel.Id}'.").GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }
        }
예제 #2
0
        private void Adapter_OnObserve(object sender, ObserveMessageEventArgs e)
        {
            MessageAuditRecord record = null;
            int      length           = 0;
            DateTime sendTime         = DateTime.UtcNow;

            try
            {
                byte[] message = ProtocolTransition.ConvertToMqtt(session, e.Message);
                Send(message).LogExceptions();

                MqttMessage mm = MqttMessage.DecodeMessage(message);

                length = mm.Payload.Length;
                record = new MessageAuditRecord(e.Message.MessageId, session.Identity, Channel.TypeId, "MQTT", length,
                                                MessageDirectionType.Out, true, sendTime);
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0} - MQTT adapter observe error on channel '{1}' with '{2}'",
                                           DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), Channel.Id, ex.Message);
                logger?.LogErrorAsync(ex, $"MQTT adapter observe error on channel '{Channel.Id}'.").GetAwaiter();
                record = new MessageAuditRecord(e.Message.MessageId, session.Identity, Channel.TypeId, "MQTT", length,
                                                MessageDirectionType.Out, true, sendTime, msg);
            }
            finally
            {
                if (e.Message.Audit)
                {
                    messageAuditor?.WriteAuditRecordAsync(record).Ignore();
                }
            }
        }
예제 #3
0
        private void Channel_OnOpen(object sender, ChannelOpenEventArgs e)
        {
            session.IsAuthenticated = Channel.IsAuthenticated;
            logger?.LogDebugAsync(
                $"CoAP protocol channel opening with session authenticated '{session.IsAuthenticated}'.").GetAwaiter();

            try
            {
                if (!Channel.IsAuthenticated && e.Message != null)
                {
                    CoapMessage msg     = CoapMessage.DecodeMessage(e.Message);
                    CoapUri     coapUri = new CoapUri(msg.ResourceUri.ToString());
                    session.IsAuthenticated = session.Authenticate(coapUri.TokenType, coapUri.SecurityToken);
                    logger?.LogDebugAsync(
                        $"CoAP protocol channel opening session authenticated '{session.IsAuthenticated}' by authenticator.")
                    .GetAwaiter();
                }

                if (session.IsAuthenticated)
                {
                    IdentityDecoder decoder = new IdentityDecoder(session.Config.IdentityClaimType, context,
                                                                  session.Config.Indexes);
                    session.Identity = decoder.Id;
                    session.Indexes  = decoder.Indexes;
                    logger?.LogDebugAsync($"CoAP protocol channel opening with session identity '{session.Identity}'.")
                    .GetAwaiter();

                    UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity,
                                                                 session.Config.IdentityClaimType, Channel.TypeId, "COAP", "Granted", DateTime.UtcNow);
                    userAuditor?.WriteAuditRecordAsync(record).Ignore();
                }
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"CoAP adapter opening channel '{Channel.Id}'.").GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }

            if (!session.IsAuthenticated && e.Message != null)
            {
                logger?.LogWarningAsync("CoAP adpater closing due to unauthenticated user.");
                Channel.CloseAsync().Ignore();
            }
            else
            {
                dispatcher = new CoapRequestDispatcher(session, Channel, config, graphManager, logger);
            }
        }
예제 #4
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord record = null;

            byte[]       payload = null;
            EventMessage msg     = null;

            loadQueue.Enqueue(message);

            try
            {
                while (!loadQueue.IsEmpty)
                {
                    bool isdequeued = loadQueue.TryDequeue(out msg);
                    if (!isdequeued)
                    {
                        continue;
                    }

                    payload = GetPayload(msg);
                    if (payload == null)
                    {
                        await logger?.LogWarningAsync(
                            $"Subscription '{metadata.SubscriptionUriString}' message not written to queue sink because message is null.");

                        return;
                    }

                    await storage.EnqueueAsync(queue, payload, ttl);

                    if (message.Audit)
                    {
                        record = new MessageAuditRecord(msg.MessageId,
                                                        uri.Query.Length > 0 ? uri.ToString().Replace(uri.Query, "") : uri.ToString(),
                                                        "AzureQueue", "AzureQueue", payload.Length, MessageDirectionType.Out, true,
                                                        DateTime.UtcNow);
                    }
                }
            }
            catch (Exception ex)
            {
                await logger?.LogErrorAsync(ex,
                                            $"Subscription '{metadata.SubscriptionUriString}' message not written to queue sink.");

                record = new MessageAuditRecord(msg.MessageId,
                                                uri.Query.Length > 0 ? uri.ToString().Replace(uri.Query, "") : uri.ToString(), "AzureQueue",
                                                "AzureQueue", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
                throw;
            }
            finally
            {
                if (record != null && msg.Audit)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
예제 #5
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord record = null;

            byte[] payload = null;

            try
            {
                byte[] msg = GetPayload(message);
                queue.Enqueue(msg);

                while (!queue.IsEmpty)
                {
                    arrayIndex = arrayIndex.RangeIncrement(0, clientCount - 1);
                    queue.TryDequeue(out payload);


                    if (payload == null)
                    {
                        Trace.TraceWarning("Subscription {0} could not write to event hub sink because payload was either null or unknown protocol type.");
                        return;
                    }

                    EventData data = new EventData(payload);
                    data.Properties.Add("Content-Type", message.ContentType);

                    if (String.IsNullOrEmpty(partitionId))
                    {
                        await storageArray[arrayIndex].SendAsync(data);
                    }
                    else
                    {
                        await senderArray[arrayIndex].SendAsync(data);
                    }

                    if (message.Audit)
                    {
                        record = new MessageAuditRecord(message.MessageId, String.Format("sb://{0}/{1}", uri.Authority, hubName), "EventHub", "EventHub", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                    }
                }
            }
            catch (Exception ex)
            {
                record = new MessageAuditRecord(message.MessageId, String.Format("sb://{0}", uri.Authority, hubName), "EventHub", "EventHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
                throw;
            }
            finally
            {
                if (message.Audit && record != null)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
예제 #6
0
        private async Task Send(byte[] message, ObserveMessageEventArgs e)
        {
            AuditRecord record = null;

            try
            {
                await channel.SendAsync(message);

                record = new MessageAuditRecord(e.Message.MessageId, session.Identity, this.channel.TypeId, "COAP", e.Message.Message.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
            }
            catch (Exception ex)
            {
                record = new MessageAuditRecord(e.Message.MessageId, session.Identity, this.channel.TypeId, "COAP", e.Message.Message.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
            }
            finally
            {
                if (e.Message.Audit)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
예제 #7
0
        private async Task PublishAsync(string identity, EventMessage message, List <KeyValuePair <string, string> > indexes = null)
        {
            EventMetadata metadata = await GraphManager.GetPiSystemMetadataAsync(message.ResourceUri);

            if (await adapter.CanPublishAsync(metadata, Channel.IsEncrypted))
            {
                await adapter.PublishAsync(message, indexes);
            }
            else
            {
                if (metadata.Audit)
                {
                    await messageAuditor?.WriteAuditRecordAsync(new MessageAuditRecord("XXXXXXXXXXXX", identity, this.Channel.TypeId, "REST", message.Message.Length, MessageDirectionType.In, false, DateTime.UtcNow, "Not authorized, missing resource metadata, or channel encryption requirements"));
                }
            }
        }
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord record = null;

            byte[]       payload = null;
            EventMessage msg     = null;

            loadQueue.Enqueue(message);

            try
            {
                while (!loadQueue.IsEmpty)
                {
                    bool isdequeued = loadQueue.TryDequeue(out msg);
                    if (isdequeued)
                    {
                        payload = GetPayload(msg);
                        if (payload == null)
                        {
                            Trace.TraceWarning("Subscription {0} could not write to queue storage sink because payload was either null or unknown protocol type.");
                            return;
                        }

                        await storage.EnqueueAsync(queue, payload, ttl);

                        if (message.Audit)
                        {
                            record = new MessageAuditRecord(msg.MessageId, uri.Query.Length > 0 ? uri.ToString().Replace(uri.Query, "") : uri.ToString(), "AzureQueue", "AzureQueue", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                record = new MessageAuditRecord(msg.MessageId, uri.Query.Length > 0 ? uri.ToString().Replace(uri.Query, "") : uri.ToString(), "AzureQueue", "AzureQueue", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
                throw;
            }
            finally
            {
                if (record != null && msg.Audit)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
예제 #9
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord record = null;

            HttpClient client = new HttpClient();

            try
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
                HttpContent content = new StringContent(Encoding.UTF8.GetString(message.Message), Encoding.UTF8,
                                                        "application/json");
                HttpResponseMessage response = await client.PostAsync(uri, content);

                if (response.IsSuccessStatusCode)
                {
                    byte[] outMessage = await response.Content.ReadAsByteArrayAsync();

                    EventMessage output = new EventMessage("application/json", outputPiSystem, message.Protocol,
                                                           outMessage, DateTime.UtcNow, message.Audit);
                    RaiseOnResponse(new EventSinkResponseArgs(output));
                    record = new MessageAuditRecord(message.MessageId, $"ai://{uri.Authority}", "MachineLearning",
                                                    "MachineLearning", message.Message.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                }
                else
                {
                    record = new MessageAuditRecord(message.MessageId, $"ai://{uri.Authority}", "MachineLearning",
                                                    "MachineLearning", message.Message.Length, MessageDirectionType.Out, false, DateTime.UtcNow);
                }
            }
            catch (Exception ex)
            {
                await logger?.LogErrorAsync(ex,
                                            $"Subscription {metadata.SubscriptionUriString} machine learning sink.");

                record = new MessageAuditRecord(message.MessageId, $"ai://{uri.Authority}", "MachineLearning",
                                                "MachineLearning", message.Message.Length, MessageDirectionType.Out, false, DateTime.UtcNow);
            }
            finally
            {
                if (record != null && message.Audit)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
예제 #10
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord record = null;

            byte[] payload = null;

            try
            {
                byte[] msg = GetPayload(message);
                queue.Enqueue(msg);

                while (!queue.IsEmpty)
                {
                    arrayIndex = arrayIndex.RangeIncrement(0, clientCount - 1);
                    queue.TryDequeue(out payload);

                    if (payload == null)
                    {
                        await logger?.LogWarningAsync(
                            $"Subscription '{metadata.SubscriptionUriString}' message not written to event hub sink because message is null.");

                        return;
                    }

                    EventData data = new EventData(payload);
                    data.Properties.Add("Content-Type", message.ContentType);

                    if (string.IsNullOrEmpty(partitionId))
                    {
                        await storageArray[arrayIndex].SendAsync(data);
                    }
                    else
                    {
                        await senderArray[arrayIndex].SendAsync(data);
                    }

                    if (message.Audit && record != null)
                    {
                        record = new MessageAuditRecord(message.MessageId,
                                                        $"sb://{uri.Authority}/{hubName}", "EventHub", "EventHub",
                                                        payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                    }
                }
            }
            catch (Exception ex)
            {
                await logger?.LogErrorAsync(ex,
                                            $"Subscription '{metadata.SubscriptionUriString}' message not written to event grid hub sink.");

                record = new MessageAuditRecord(message.MessageId, string.Format("sb://{0}", uri.Authority, hubName),
                                                "EventHub", "EventHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow,
                                                ex.Message);
                throw;
            }
            finally
            {
                if (message.Audit && record != null)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
예제 #11
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord    record  = null;
            HttpWebRequest request = null;

            byte[] payload = null;
            try
            {
                payload = GetPayload(message);
                if (payload == null)
                {
                    Trace.TraceWarning("Subscription {0} could not write to web service sink because payload was either null or unknown protocol type.");
                    return;
                }

                try
                {
                    request             = HttpWebRequest.Create(address) as HttpWebRequest;
                    request.ContentType = message.ContentType;
                    request.Method      = "POST";

                    SetSecurityToken(request);

                    request.ContentLength = payload.Length;
                    Stream stream = await request.GetRequestStreamAsync();

                    await stream.WriteAsync(payload, 0, payload.Length);
                }
                catch (Exception ex)
                {
                    Trace.TraceError("REST event sink subscription {0} could set request; error {1} ", metadata.SubscriptionUriString, ex.Message);
                    record = new MessageAuditRecord(message.MessageId, address, "WebService", "HTTP", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
                }

                try
                {
                    using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
                    {
                        if (response.StatusCode == HttpStatusCode.Accepted || response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NoContent)
                        {
                            Trace.TraceInformation("Rest request is success.");
                            record = new MessageAuditRecord(message.MessageId, address, "WebService", "HTTP", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                        }
                        else
                        {
                            Trace.TraceInformation("Rest request returned an expected status code.");
                            record = new MessageAuditRecord(message.MessageId, address, "WebService", "HTTP", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, String.Format("Rest request returned an expected status code {0}", response.StatusCode));
                        }
                    }
                }
                catch (WebException we)
                {
                    string faultMessage = String.Format("subscription '{0}' with status code '{1}' and error message '{2}'", metadata.SubscriptionUriString, we.Status.ToString(), we.Message);
                    Trace.TraceError(faultMessage);
                    record = new MessageAuditRecord(message.MessageId, address, "WebService", "HTTP", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, we.Message);
                }
            }
            catch (Exception ex)
            {
                record = new MessageAuditRecord(message.MessageId, address, "WebService", "HTTP", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
            }
            finally
            {
                if (message.Audit && record != null)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
예제 #12
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord record = null;

            byte[] payload = null;

            try
            {
                payload = GetPayload(message);
                if (payload == null)
                {
                    await logger?.LogWarningAsync(
                        $"Subscription '{metadata.SubscriptionUriString}' message not written to iot hub sink because message is null.");

                    return;
                }

                if (serviceClient != null)
                {
                    if (!string.IsNullOrEmpty(methodName))
                    {
                        if (message.ContentType == "application/json")
                        {
                            CloudToDeviceMethod method = new CloudToDeviceMethod(methodName);
                            method.SetPayloadJson(Encoding.UTF8.GetString(payload));
                            await serviceClient.InvokeDeviceMethodAsync(deviceId, method);

                            record = new MessageAuditRecord(message.MessageId,
                                                            $"iothub://{uri.Authority}", "IoTHub", "IoTHub", payload.Length,
                                                            MessageDirectionType.Out, true, DateTime.UtcNow);
                        }
                        else
                        {
                            await logger?.LogWarningAsync(
                                $"Subscription '{metadata.SubscriptionUriString}' cannot send IoTHub direct method sink because content-type is not JSON.");

                            record = new MessageAuditRecord(message.MessageId,
                                                            string.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length,
                                                            MessageDirectionType.Out, false, DateTime.UtcNow,
                                                            string.Format(
                                                                "Cannot send IoTHub device {0} direct message because content-type is not JSON.",
                                                                deviceId));
                        }
                    }
                    else
                    {
                        Message serviceMessage = new Message(payload)
                        {
                            ContentType = message.ContentType,
                            MessageId   = message.MessageId
                        };

                        if (!string.IsNullOrEmpty(propertyName))
                        {
                            serviceMessage.Properties.Add(propertyName, propertyValue);
                        }

                        await serviceClient.SendAsync(deviceId, serviceMessage);

                        record = new MessageAuditRecord(message.MessageId, string.Format("iothub://{0}", uri.Authority),
                                                        "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                    }
                }
                else if (deviceClient != null)
                {
                    Microsoft.Azure.Devices.Client.Message msg = new Microsoft.Azure.Devices.Client.Message(payload)
                    {
                        ContentType = message.ContentType,
                        MessageId   = message.MessageId
                    };

                    if (!string.IsNullOrEmpty(propertyName))
                    {
                        msg.Properties.Add(propertyName, propertyValue);
                    }

                    await deviceClient.SendEventAsync(msg);

                    record = new MessageAuditRecord(message.MessageId, $"iothub://{uri.Authority}",
                                                    "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                }
                else
                {
                    await logger?.LogWarningAsync(
                        $"Subscription '{metadata.SubscriptionUriString}' IoTHub sink has neither service or device client.");

                    record = new MessageAuditRecord(message.MessageId, $"iothub://{uri.Authority}",
                                                    "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow,
                                                    "IoTHub subscription has neither service or device client");
                }
            }
            catch (Exception ex)
            {
                await logger?.LogErrorAsync(ex,
                                            $"Subscription '{metadata.SubscriptionUriString}' message not written to IoTHub sink.");

                record = new MessageAuditRecord(message.MessageId, $"iothub://{uri.Authority}",
                                                "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
            }
            finally
            {
                if (record != null && message.Audit)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
예제 #13
0
        private void Channel_OnOpen(object sender, ChannelOpenEventArgs e)
        {
            if (!Channel.IsAuthenticated)  //requires channel authentication
            {
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, new SecurityException("Not authenticated.")));
                Channel.CloseAsync().Ignore();
                return;
            }

            if (e.Message.Method != HttpMethod.Post && e.Message.Method != HttpMethod.Get)
            {
                Channel.CloseAsync().Ignore();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, new SecurityException("Rest protocol adapter requires GET or POST only.")));
            }

            MessageUri      uri     = new MessageUri(e.Message);
            IdentityDecoder decoder = new IdentityDecoder(config.ClientIdentityNameClaimType, context, config.GetClientIndexes());

            identity = decoder.Id;

            adapter            = new OrleansAdapter(decoder.Id, "HTTP", "REST");
            adapter.OnObserve += Adapter_OnObserve;
            HttpRequestMessage request = (HttpRequestMessage)e.Message;

            AuditRecord record = new UserAuditRecord(Channel.Id, identity, config.ClientIdentityNameClaimType, Channel.TypeId, String.Format("REST-{0}", request.Method.ToString()), "Granted", DateTime.UtcNow);

            userAuditor?.WriteAuditRecordAsync(record).Ignore();

            if (request.Method == HttpMethod.Get)
            {
                foreach (var item in uri.Subscriptions)
                {
                    Task t = Task.Factory.StartNew(async() =>
                    {
                        await SubscribeAsync(item, decoder.Id, decoder.Indexes);
                    });

                    t.LogExceptions();
                }
            }

            if (request.Method == HttpMethod.Post)
            {
                byte[] buffer = request.Content.ReadAsByteArrayAsync().Result;
                Task   t      = Task.Factory.StartNew(async() =>
                {
                    EventMetadata metadata = await GraphManager.GetPiSystemMetadataAsync(uri.Resource);
                    EventMessage message   = new EventMessage(uri.ContentType, uri.Resource, ProtocolType.REST, buffer, DateTime.UtcNow, metadata.Audit);

                    if (!string.IsNullOrEmpty(uri.CacheKey))
                    {
                        message.CacheKey = uri.CacheKey;
                    }

                    List <KeyValuePair <string, string> > indexList = uri.Indexes == null ? null : new List <KeyValuePair <string, string> >(uri.Indexes);

                    await PublishAsync(decoder.Id, message, indexList);
                    await Channel.CloseAsync();
                });

                t.LogExceptions();
            }
        }
예제 #14
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord    record  = null;
            HttpWebRequest request = null;

            byte[] payload = null;
            try
            {
                payload = GetPayload(message);
                if (payload == null)
                {
                    await logger.LogWarningAsync($"Rest request '{metadata.SubscriptionUriString}' null payload.");

                    return;
                }

                try
                {
                    request             = WebRequest.Create(address) as HttpWebRequest;
                    request.ContentType = message.ContentType;
                    request.Method      = "POST";

                    SetSecurityToken(request);

                    request.ContentLength = payload.Length;
                    Stream stream = await request.GetRequestStreamAsync();

                    await stream.WriteAsync(payload, 0, payload.Length);
                }
                catch (Exception ex)
                {
                    Trace.TraceError("REST event sink subscription {0} could set request; error {1} ",
                                     metadata.SubscriptionUriString, ex.Message);
                    record = new MessageAuditRecord(message.MessageId, address, "WebService", "HTTP", payload.Length,
                                                    MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
                }

                try
                {
                    using HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;

                    if (response.StatusCode == HttpStatusCode.Accepted || response.StatusCode == HttpStatusCode.OK ||
                        response.StatusCode == HttpStatusCode.NoContent)
                    {
                        await logger.LogInformationAsync($"Rest request success {response.StatusCode}");

                        record = new MessageAuditRecord(message.MessageId, address, "WebService", "HTTP",
                                                        payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                    }
                    else
                    {
                        await logger.LogWarningAsync($"Rest request warning {response.StatusCode}");

                        record = new MessageAuditRecord(message.MessageId, address, "WebService", "HTTP",
                                                        payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow,
                                                        string.Format("Rest request returned an expected status code {0}", response.StatusCode));
                    }
                }
                catch (WebException we)
                {
                    string faultMessage =
                        $"subscription '{metadata.SubscriptionUriString}' with status code '{we.Status}' and error message '{we.Message}'";
                    await logger.LogErrorAsync(we, $"Rest request success.");

                    record = new MessageAuditRecord(message.MessageId, address, "WebService", "HTTP", payload.Length,
                                                    MessageDirectionType.Out, false, DateTime.UtcNow, we.Message);
                }
            }
            catch (Exception ex)
            {
                await logger.LogErrorAsync(ex, $"Rest request success.");

                record = new MessageAuditRecord(message.MessageId, address, "WebService", "HTTP", payload.Length,
                                                MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
            }
            finally
            {
                if (message.Audit && record != null)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
예제 #15
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord record = null;

            byte[] payload = null;

            try
            {
                payload = GetPayload(message);
                if (payload == null)
                {
                    Trace.TraceWarning("Subscription {0} could not write to iot hub sink because payload was either null or unknown protocol type.");
                    return;
                }

                if (serviceClient != null)                 //send message to device
                {
                    if (!String.IsNullOrEmpty(methodName)) //direct method to device
                    {
                        if (message.ContentType == "application/json")
                        {
                            CloudToDeviceMethod method = new CloudToDeviceMethod(methodName);
                            method.SetPayloadJson(Encoding.UTF8.GetString(payload));
                            await serviceClient.InvokeDeviceMethodAsync(deviceId, method);

                            record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                        }
                        else
                        {
                            Trace.TraceWarning("Cannot send IoTHub device {0} direct message because content-type is not JSON.", deviceId);
                            record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, String.Format("Cannot send IoTHub device {0} direct message because content-type is not JSON.", deviceId));
                        }
                    }
                    else //command to device
                    {
                        Microsoft.Azure.Devices.Message serviceMessage = new Microsoft.Azure.Devices.Message(payload);
                        serviceMessage.ContentType = message.ContentType;
                        serviceMessage.MessageId   = message.MessageId;

                        if (!String.IsNullOrEmpty(propertyName))
                        {
                            serviceMessage.Properties.Add(propertyName, propertyValue);
                        }

                        await serviceClient.SendAsync(deviceId, serviceMessage);

                        record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                    }
                }
                else if (deviceClient != null) //this subscription is a device and will send to IoTHub
                {
                    Microsoft.Azure.Devices.Client.Message msg = new Microsoft.Azure.Devices.Client.Message(payload);
                    msg.ContentType = message.ContentType;
                    msg.MessageId   = message.MessageId;
                    if (!String.IsNullOrEmpty(propertyName))
                    {
                        msg.Properties.Add(propertyName, propertyValue);
                    }
                    await deviceClient.SendEventAsync(msg);

                    record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                }
                else
                {
                    Trace.TraceWarning("IoTHub subscription has neither Service or Device client");
                    record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, "IoTHub subscription has neither service or device client");
                }
            }
            catch (Exception ex)
            {
                record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
            }
            finally
            {
                if (record != null && message.Audit)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
예제 #16
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord record = null;

            byte[] payload = null;
            queue.Enqueue(message);
            try
            {
                while (!queue.IsEmpty)
                {
                    arrayIndex = arrayIndex.RangeIncrement(0, clientCount - 1);
                    bool isdequeued = queue.TryDequeue(out EventMessage msg);

                    if (!isdequeued)
                    {
                        continue;
                    }

                    payload = GetPayload(message);
                    if (payload == null)
                    {
                        await logger?.LogWarningAsync(
                            $"Subscription '{metadata.SubscriptionUriString}' message not written to cosmos db sink because message is null.");

                        continue;
                    }

                    await using MemoryStream stream = new MemoryStream(payload)
                                {
                                    Position = 0
                                };
                    if (message.ContentType.Contains("json"))
                    {
                        await storageArray[arrayIndex].CreateDocumentAsync(collection.SelfLink,
                                                                           JsonSerializable.LoadFrom <Document>(stream));
                    }
                    else
                    {
                        dynamic documentWithAttachment = new {
                            Id        = Guid.NewGuid().ToString(),
                            Timestamp = DateTime.UtcNow
                        };

                        Document doc = await storageArray[arrayIndex]
                                       .CreateDocumentAsync(collection.SelfLink, documentWithAttachment);
                        string slug = GetSlug(documentWithAttachment.Id, message.ContentType);
                        await  storageArray[arrayIndex].CreateAttachmentAsync(doc.AttachmentsLink, stream,
                                                                              new MediaOptions {
                            ContentType = message.ContentType, Slug = slug
                        });
                    }

                    if (message.Audit)
                    {
                        record = new MessageAuditRecord(message.MessageId,
                                                        uri.Query.Length > 0 ? uri.ToString().Replace(uri.Query, "") : uri.ToString(),
                                                        "CosmosDB", "CosmoDB", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                    }
                }
            }
            catch (Exception ex)
            {
                await logger?.LogErrorAsync(ex,
                                            $"Subscription '{metadata.SubscriptionUriString}' message not written to cosmos db sink.");

                record = new MessageAuditRecord(message.MessageId,
                                                uri.Query.Length > 0 ? uri.ToString().Replace(uri.Query, "") : uri.ToString(), "CosmosDB",
                                                "CosmosDB", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
            }
            finally
            {
                if (record != null && message.Audit)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }