public async Task SendAsyncUsesEmptyContentTypeIfNoneSpecifiedInConstructor()
            {
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        // VALIDATE
                        Assert.IsNull(req.Content.Headers.ContentType);

                        return(Task.FromResult <HttpResponseMessage>(new HttpResponseMessage()));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    var items = new List <ITelemetry> {
                        new EventTelemetry(), new EventTelemetry()
                    };

                    // Instantiate Transmission with the mock HttpClient
                    var transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty, "ContentEncoding");

                    HttpWebResponseWrapper result = await transmission.SendAsync();
                }
            }
Beispiel #2
0
            public async Task TestTransmissionStatusEventHandlerWithUnKnownFailureTransmission()
            {
                // ARRANGE
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        throw new Exception("test");
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    // Instantiate Transmission with the mock HttpClient
                    Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty, string.Empty);
                    transmission.Timeout = TimeSpan.Zero;

                    // VALIDATE
                    transmission.TransmissionStatusEvent += delegate(object sender, TransmissionStatusEventArgs args)
                    {
                        Assert.AreEqual(999, args.Response.StatusCode);
                    };

                    // ACT
                    try
                    {
                        HttpWebResponseWrapper result = await transmission.SendAsync();
                    }
                    catch (Exception ex)
                    {
                        Assert.AreEqual("test", ex.Message);
                    }
                }
            }
            public async Task SendAsyncHandlesTimeout()
            {
                int clientTimeoutInMillisecs = 1;

                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        // Intentionally delay for atleast client timeout.
                        // By this time, client's cancellation token would definitely expire.
                        Task.Delay(100 * clientTimeoutInMillisecs).Wait();
                        // This simulates actual timeout
                        cancellationToken.ThrowIfCancellationRequested();
                        return(Task.FromResult <HttpResponseMessage>(new HttpResponseMessage()));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    // Instantiate Transmission with the mock HttpClient and Timeout to be just 1 msec to force Timeout.
                    Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty,
                                                                 string.Empty, TimeSpan.FromMilliseconds(clientTimeoutInMillisecs));

                    // ACT
                    HttpWebResponseWrapper result = await transmission.SendAsync();

                    // VALIDATE
                    Assert.IsNotNull(result);
                    Assert.AreEqual((int)HttpStatusCode.RequestTimeout, result.StatusCode);
                    Assert.IsNull(result.Content, "Content is not to be read except in partial response (206) status.");
                }
            }
            public async Task SendAsyncHandleResponseForPartialContentResponse()
            {
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        HttpResponseMessage response = new HttpResponseMessage();
                        response.StatusCode         = HttpStatusCode.PartialContent;
                        response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(5));
                        return(Task.FromResult <HttpResponseMessage>(response));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    // Instantiate Transmission with the mock HttpClient
                    Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty, string.Empty);

                    // ACT
                    HttpWebResponseWrapper result = await transmission.SendAsync();

                    // VALIDATE
                    Assert.AreEqual(206, result.StatusCode);
                    Assert.AreEqual("5", result.RetryAfterHeader);
                    Assert.IsNull(result.Content);
                }
            }
            public async Task SendAsyncUsesSpecifiedContentTypeAndEncoding()
            {
                var expectedContentType     = "content/type";
                var expectedContentEncoding = "contentEncoding";
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        // VALIDATE
                        Assert.AreEqual(expectedContentType, req.Content.Headers.ContentType.MediaType);
                        Assert.AreEqual(expectedContentEncoding, req.Content.Headers.ContentEncoding.FirstOrDefault());

                        return(Task.FromResult <HttpResponseMessage>(new HttpResponseMessage()));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    var items = new List <ITelemetry> {
                        new EventTelemetry(), new EventTelemetry()
                    };

                    // Instantiate Transmission with the mock HttpClient
                    var transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, expectedContentType, expectedContentEncoding);

                    HttpWebResponseWrapper result = await transmission.SendAsync();
                }
            }
            public async Task SendAsyncReturnsCorrectHttpResponseWrapperWithRetryHeaderWhenNoExceptionOccur()
            {
                // HttpClient.SendAsync throws HttpRequestException only on the following scenarios:
                // "The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout."
                // For every other case, a response is returned, and we expect Transmission.SendAsync to properly return HttpWebResponseWrapper.

                // ARRANGE
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        HttpResponseMessage response = new HttpResponseMessage();
                        response.StatusCode         = HttpStatusCode.ServiceUnavailable;
                        response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(5));
                        return(Task.FromResult <HttpResponseMessage>(response));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    // Instantiate Transmission with the mock HttpClient
                    Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty, string.Empty);

                    // ACT
                    HttpWebResponseWrapper result = await transmission.SendAsync();

                    // VALIDATE
                    Assert.IsNotNull(result);
                    Assert.AreEqual(503, result.StatusCode);
                    Assert.AreEqual("5", result.RetryAfterHeader);
                    Assert.IsNull(result.Content, "Content is not to be read except in partial response (206) status.");
                }
            }
Beispiel #7
0
            public async Task SendAsyncHandlesTimeout()
            {
                int clientTimeoutInMillisecs = 1;

                //ARRANGE
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = async(req, cancellationToken) =>
                    {
                        await Task.Delay(clientTimeoutInMillisecs + 10); // this ensures client timeout is hit.

                        return(await Task.FromResult <HttpResponseMessage>(new HttpResponseMessage()));
                    }
                };

                using (var fakeHttpClient = new HttpClient())
                {
                    // Instantiate Transmission with the mock HttpClient and Timeout to be just 1 msec to force Timeout.
                    Transmission transmission = new Transmission(new Uri("http://uri"), new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty,
                                                                 string.Empty, TimeSpan.FromMilliseconds(clientTimeoutInMillisecs));

                    // ACT
                    HttpWebResponseWrapper result = await transmission.SendAsync();

                    // VALIDATE
                    Assert.IsNotNull(result);
                    Assert.AreEqual((int)HttpStatusCode.RequestTimeout, result.StatusCode);
                    Assert.IsNull(result.Content, "Content is not to be read except in partial response (206) status.");
                }
            }
            public async Task SendAsyncUsesPostMethodToSpecifiedHttpEndpoint()
            {
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        // VALIDATE
                        Assert.AreEqual(testUri, req.RequestUri);
                        Assert.AreEqual(HttpMethod.Post, req.Method);
                        return(Task.FromResult <HttpResponseMessage>(new HttpResponseMessage()));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    var items = new List <ITelemetry> {
                        new EventTelemetry(), new EventTelemetry()
                    };

                    // Instantiate Transmission with the mock HttpClient
                    Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty, string.Empty);
                    // transmission.Timeout = TimeSpan.FromMilliseconds(1);

                    HttpWebResponseWrapper result = await transmission.SendAsync();
                }
            }
            public async Task TestTransmissionStatusEventHandlerWithSuccessTransmission()
            {
                // ARRANGE
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        return(Task.FromResult <HttpResponseMessage>(new HttpResponseMessage()));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    // Instantiate Transmission with the mock HttpClient
                    Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty, string.Empty);

                    // VALIDATE
                    transmission.TransmissionStatusEvent += delegate(object sender, TransmissionStatusEventArgs args)
                    {
                        Assert.IsTrue(sender is Transmission);
                        Assert.AreEqual((int)HttpStatusCode.OK, args.Response.StatusCode);
                        Assert.AreNotEqual(0, args.ResponseDurationInMs);
                    };

                    // ACT
                    HttpWebResponseWrapper result = await transmission.SendAsync();
                }
            }
            public async Task TestTransmissionStatusEventHandlerWithKnownFailureTransmission()
            {
                // ARRANGE
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        return(Task.FromResult <HttpResponseMessage>(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    // Instantiate Transmission with the mock HttpClient
                    Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty, string.Empty);
                    transmission.Timeout = TimeSpan.Zero;

                    // VALIDATE
                    transmission.TransmissionStatusEvent += delegate(object sender, TransmissionStatusEventArgs args)
                    {
                        Assert.AreEqual((int)HttpStatusCode.RequestTimeout, args.Response.StatusCode);
                        Assert.AreEqual(0, args.ResponseDurationInMs);
                    };

                    // ACT
                    HttpWebResponseWrapper result = await transmission.SendAsync();
                }
            }
            public async Task SendAsyncSendsContentPassedInConstructor()
            {
                var expectedContent = new byte[] { 1, 2, 3, 4, 5 };
                var handler         = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = async(req, cancellationToken) =>
                    {
                        HttpResponseMessage response = new HttpResponseMessage();
                        byte[] actualContent         = await req.Content.ReadAsByteArrayAsync();

                        AssertEx.AreEqual(expectedContent, actualContent);
                        return(await Task.FromResult <HttpResponseMessage>(response));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    // Instantiate Transmission with the mock HttpClient
                    Transmission transmission = new Transmission(testUri, expectedContent, fakeHttpClient, string.Empty, string.Empty);

                    // ACT
                    HttpWebResponseWrapper result = await transmission.SendAsync();
                }
            }
            public async Task ThrowsInvalidOperationExceptionWhenTransmissionIsAlreadySending()
            {
                Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, new HttpClient(), string.Empty, string.Empty); FieldInfo isSendingField = typeof(Transmission).GetField("isSending", BindingFlags.NonPublic | BindingFlags.Instance);

                isSendingField.SetValue(transmission, 1);
                await AssertEx.ThrowsAsync <InvalidOperationException>(() => transmission.SendAsync());
            }
Beispiel #13
0
        /// <summary>
        /// Serializes a list of telemetry items and sends them.
        /// </summary>
        private async Task Send(IEnumerable <ITelemetry> telemetryItems)
        {
            if (telemetryItems == null || !telemetryItems.Any())
            {
                CoreEventSource.Log.LogVerbose("No Telemetry Items passed to Enqueue");
                return;
            }

            byte[] data         = JsonSerializer.Serialize(telemetryItems);
            var    transmission = new Transmission(this.endpointAddress, data, "application/x-json-stream", JsonSerializer.CompressionType);

            await transmission.SendAsync().ConfigureAwait(false);
        }
Beispiel #14
0
        /// <summary>
        /// Sending the item to the endpoint immediately without persistence.
        /// </summary>
        /// <param name="item">Telemetry item.</param>
        /// <param name="endpointAddress">Server endpoint address.</param>
        internal void SendForDeveloperMode(ITelemetry item, string endpointAddress)
        {
            try
            {
                byte[] data         = JsonSerializer.Serialize(item);
                var    transmission = new Transmission(new Uri(endpointAddress), data, "application/x-json-stream", JsonSerializer.CompressionType);

                transmission.SendAsync().ConfigureAwait(false).GetAwaiter().GetResult();
            }
            catch (Exception exception)
            {
                CoreEventSource.Log.LogVerbose("Failed sending event in developer mode Exception:" + exception);
            }
        }
            public async Task SendAsyncLogsIngestionReponseTimeOnFailureEventCounter()
            {
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        Thread.Sleep(TimeSpan.FromMilliseconds(30));
                        HttpResponseMessage response = new HttpResponseMessage();
                        response.StatusCode = HttpStatusCode.ServiceUnavailable;
                        return(Task.FromResult <HttpResponseMessage>(response));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    // Instantiate Transmission with the mock HttpClient
                    Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty, string.Empty);

                    using (var listener = new EventCounterListener())
                    {
                        for (int i = 0; i < 5; i++)
                        {
                            HttpWebResponseWrapper result = await transmission.SendAsync();
                        }
                        //Sleep for few seconds as the event counter is sampled on a second basis
                        Thread.Sleep(TimeSpan.FromSeconds(3));

                        // VERIFY
                        // We validate by checking SDK traces.
                        var allTraces = listener.EventsReceived.ToList();
                        var traces    = allTraces.Where(item => item.EventName == "EventCounters").ToList();
                        Assert.IsTrue(traces?.Count >= 1);
                        var payload = (IDictionary <string, object>)traces[0].Payload[0];
                        Assert.AreEqual("IngestionEndpoint-ResponseTimeMsec", payload["Name"].ToString());
                        Assert.IsTrue((int)payload["Count"] >= 5);
                        // Mean should be more than 30 ms, as we introduced a delay of 30ms in SendAsync.
#if NETCOREAPP2_1
                        Assert.IsTrue((float)payload["Mean"] >= 30);
#endif

#if NETCOREAPP3_1
                        Assert.IsTrue((double)payload["Mean"] >= 30);
#endif
                    }
                }
            }
Beispiel #16
0
        /// <summary>
        /// Serializes a list of telemetry items and sends them.
        /// </summary>
        private Task Send(IEnumerable <ITelemetry> telemetryItems, TimeSpan timeout)
        {
            if (telemetryItems == null || !telemetryItems.Any())
            {
                CoreEventSource.Log.LogVerbose("No Telemetry Items passed to Enqueue");
#if NET40
                return(TaskEx.FromResult <object>(null));
#else
                return(Task.FromResult <object>(null));
#endif
            }

            byte[] data         = JsonSerializer.Serialize(telemetryItems);
            var    transmission = new Transmission(this.endpointAddress, data, JsonSerializer.ContentType, JsonSerializer.CompressionType, timeout);

            return(transmission.SendAsync());
        }
        /// <summary>
        /// Serializes a list of telemetry items and sends them.
        /// </summary>
        private Task Send(IEnumerable <ITelemetry> telemetryItems, TimeSpan timeout)
        {
            byte[] data = null;

            if (telemetryItems != null)
            {
                data = JsonSerializer.Serialize(telemetryItems);
            }

            if (data == null || data.Length == 0)
            {
                CoreEventSource.Log.LogVerbose("No Telemetry Items passed to Enqueue");
                return(Task.FromResult <object>(null));
            }

            var transmission = new Transmission(this.endpointAddress, data, JsonSerializer.ContentType, JsonSerializer.CompressionType, timeout);

            return(transmission.SendAsync());
        }
            public async Task SendAsyncHandlesTimeout()
            {
                int clientTimeoutInMillisecs = 1;

                using (var fakeHttpClient = new HttpClient())
                {                    
                    // Instantiate Transmission with the mock HttpClient and Timeout to be just 1 msec to force Timeout.
                    Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty, 
                        string.Empty, TimeSpan.FromMilliseconds(clientTimeoutInMillisecs));

                    // ACT
                    HttpWebResponseWrapper result = await transmission.SendAsync();
                    
                    // VALIDATE
                    Assert.IsNotNull(result);
                    Assert.AreEqual((int) HttpStatusCode.RequestTimeout, result.StatusCode);
                    Assert.IsNull(result.Content, "Content is not to be read except in partial response (206) status.");
                }
            }
            public async Task SendAsyncPropogatesHttpRequestException()
            {
                //ARRANGE
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        throw new HttpRequestException();
                    }
                };

                using (var fakeHttpClient = new HttpClient())
                {
                    // Instantiate Transmission with the mock HttpClient and Timeout to be just 1 msec to force Timeout.
                    Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty,
                                                                 string.Empty);

                    // ACT & VALIDATE
                    await AssertEx.ThrowsAsync <HttpRequestException>(() => transmission.SendAsync());
                }
            }
            public async Task TestTransmissionStatusEventHandlerFails()
            {
                // ARRANGE
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        return(Task.FromResult <HttpResponseMessage>(new HttpResponseMessage()));
                    }
                };

                using (var listener = new TestEventListener())
                {
                    listener.EnableEvents(CoreEventSource.Log, EventLevel.LogAlways,
                                          (EventKeywords)AllKeywords);

                    using (var fakeHttpClient = new HttpClient(handler))
                    {
                        // Instantiate Transmission with the mock HttpClient
                        Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty, string.Empty);

                        // VALIDATE
                        transmission.TransmissionStatusEvent += delegate(object sender, TransmissionStatusEventArgs args)
                        {
                            throw new Exception("test");
                        };

                        // ACT
                        HttpWebResponseWrapper result = await transmission.SendAsync();
                    }

                    // Assert:
                    var allTraces = listener.Messages.ToList();
                    var traces    = allTraces.Where(item => item.EventId == 71).ToList();
                    Assert.AreEqual(1, traces.Count);
                }
            }
            public async Task SendAsyncLogsIngestionReponseTimeAndStatusCode()
            {
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        return(Task.FromResult <HttpResponseMessage>(new HttpResponseMessage()));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    // Instantiate Transmission with the mock HttpClient
                    Transmission transmission = new Transmission(testUri, new byte[] { 1, 2, 3, 4, 5 }, fakeHttpClient, string.Empty, string.Empty);

                    using (var listener = new TestEventListener())
                    {
                        var eventCounterArguments = new Dictionary <string, string>
                        {
                            { "EventCounterIntervalSec", "1" }
                        };

                        listener.EnableEvents(CoreEventSource.Log, EventLevel.LogAlways, (EventKeywords)AllKeywords, eventCounterArguments);

                        HttpWebResponseWrapper result = await transmission.SendAsync();

                        // VERIFY
                        // We validate by checking SDK traces.
                        var allTraces = listener.Messages.ToList();
                        // Event 67 is logged after response from Ingestion Service.
                        var traces = allTraces.Where(item => item.EventId == 67).ToList();
                        Assert.AreEqual(1, traces.Count);
                    }
                }
            }
            public async Task TestTransmissionStatusEventWithEventsFromMultipleIKey()
            {
                // ARRANGE
                // Raw response from backend for partial response
                var ingestionResponse = "{" +
                                        "\r\n  \"itemsReceived\": 5,\r\n  \"itemsAccepted\": 2,\r\n  " +
                                        "\"errors\": [\r\n    {\r\n      " +
                                        "\"index\": 0,\r\n      \"statusCode\": 400,\r\n      \"message\": \"Error 1\"\r\n    },\r\n    {\r\n      " +
                                        "\"index\": 2,\r\n      \"statusCode\": 503,\r\n      \"message\": \"Error 2\"\r\n    },\r\n    {\r\n      " +
                                        "\"index\": 3,\r\n      \"statusCode\": 500,\r\n      \"message\": \"Error 3\"\r\n    }\r\n  ]\r\n}";

                // Fake HttpClient will respond back with partial content
                var handler = new HandlerForFakeHttpClient
                {
                    InnerHandler = new HttpClientHandler(),
                    OnSendAsync  = (req, cancellationToken) =>
                    {
                        return(Task.FromResult <HttpResponseMessage>(new HttpResponseMessage {
                            StatusCode = HttpStatusCode.PartialContent, Content = new StringContent(ingestionResponse)
                        }));
                    }
                };

                using (var fakeHttpClient = new HttpClient(handler))
                {
                    // Create a list of telemetry which could send information to different instrumentation keys
                    var telemetryItems = new List <ITelemetry>();

                    EventTelemetry eventTelemetry1 = new EventTelemetry("Event1");
                    eventTelemetry1.Context.InstrumentationKey = "IKEY_1";
                    telemetryItems.Add(eventTelemetry1);

                    EventTelemetry eventTelemetry2 = new EventTelemetry("Event2");
                    eventTelemetry2.Context.InstrumentationKey = "IKEY_2";
                    telemetryItems.Add(eventTelemetry2);

                    EventTelemetry eventTelemetry3 = new EventTelemetry("Event3");
                    eventTelemetry3.Context.InstrumentationKey = "IKEY_3";
                    telemetryItems.Add(eventTelemetry3);

                    EventTelemetry eventTelemetry4 = new EventTelemetry("Event3");
                    eventTelemetry4.Context.InstrumentationKey = "IKEY_2";
                    telemetryItems.Add(eventTelemetry4);

                    EventTelemetry eventTelemetry5 = new EventTelemetry("Event5");
                    eventTelemetry5.Context.InstrumentationKey = "IKEY_1";
                    telemetryItems.Add(eventTelemetry5);

                    // Serialize the telemetry items before passing to transmission
                    var serializedData = JsonSerializer.Serialize(telemetryItems, true);

                    // Instantiate Transmission with the mock HttpClient
                    Transmission transmission = new Transmission(testUri, serializedData, fakeHttpClient, string.Empty, string.Empty);

                    // VALIDATE
                    transmission.TransmissionStatusEvent += delegate(object sender, TransmissionStatusEventArgs args)
                    {
                        var sendertransmission = sender as Transmission;
                        // convert raw JSON response to Backendresponse object
                        BackendResponse backendResponse = GetBackendResponse(args.Response.Content);

                        // Deserialize telemetry items to identify which items has failed
                        string[] items = JsonSerializer
                                         .Deserialize(sendertransmission.Content)
                                         .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                        string[] failedItems = new string[3];
                        int      i           = 0;

                        // Create a list of failed items
                        foreach (var error in backendResponse.Errors)
                        {
                            failedItems[i++] = items[error.Index];
                        }

                        Assert.AreEqual((int)HttpStatusCode.PartialContent, args.Response.StatusCode);
                        Assert.AreEqual(5, backendResponse.ItemsReceived);
                        Assert.AreEqual(2, backendResponse.ItemsAccepted);

                        //IKEY_1
                        int totalItemsForIkey  = items.Where(x => x.Contains("IKEY_1")).Count();
                        int failedItemsForIkey = failedItems.Where(x => x.Contains("IKEY_1")).Count();
                        Assert.AreEqual(2, totalItemsForIkey);
                        Assert.AreEqual(1, failedItemsForIkey);

                        //IKEY_2
                        totalItemsForIkey  = items.Where(x => x.Contains("IKEY_2")).Count();
                        failedItemsForIkey = failedItems.Where(x => x.Contains("IKEY_2")).Count();
                        Assert.AreEqual(2, totalItemsForIkey);
                        Assert.AreEqual(1, failedItemsForIkey);

                        //IKEY_3
                        totalItemsForIkey  = items.Where(x => x.Contains("IKEY_3")).Count();
                        failedItemsForIkey = failedItems.Where(x => x.Contains("IKEY_3")).Count();
                        Assert.AreEqual(1, totalItemsForIkey);
                        Assert.AreEqual(1, failedItemsForIkey);
                    };

                    // ACT
                    HttpWebResponseWrapper result = await transmission.SendAsync();
                }
            }
        private async Task StartSending(Transmission transmission)
        {
            Exception exception = null;
            try
            {
                TelemetryChannelEventSource.Log.TransmissionSendStarted(transmission.Id);
                await transmission.SendAsync().ConfigureAwait(false);                
            }
            catch (Exception e)
            {
                exception = e;
            }
            finally
            {
                int currentCapacity = Interlocked.Decrement(ref this.transmissionCount);
                if (exception == null)
                {
                    TelemetryChannelEventSource.Log.TransmissionSentSuccessfully(transmission.Id, currentCapacity);
                }
                else
                {
                    TelemetryChannelEventSource.Log.TransmissionSendingFailedWarning(transmission.Id, exception.ToString());
                }

                this.OnTransmissionSent(new TransmissionProcessedEventArgs(transmission, exception));
            }
        }
        /// <summary>
        /// Sending the item to the endpoint immediately without persistence.
        /// </summary>
        /// <param name="item">Telemetry item.</param>
        /// <param name="endpointAddress">Server endpoint address.</param>
        internal void SendForDeveloperMode(ITelemetry item, string endpointAddress)
        {
            try
            {
                byte[] data = JsonSerializer.Serialize(item);
                var transmission = new Transmission(new Uri(endpointAddress), data, "application/x-json-stream", JsonSerializer.CompressionType);

                transmission.SendAsync().ConfigureAwait(false).GetAwaiter().GetResult();
            }
            catch (Exception exception)
            {
                CoreEventSource.Log.LogVerbose("Failed sending event in developer mode Exception:" + exception);
            }
        }
        /// <summary>
        /// Serializes a list of telemetry items and sends them.
        /// </summary>
        private async Task Send(IEnumerable<ITelemetry> telemetryItems)
        {
            if (telemetryItems == null || !telemetryItems.Any())
            {
                CoreEventSource.Log.LogVerbose("No Telemetry Items passed to Enqueue");
                return;
            }

            byte[] data = JsonSerializer.Serialize(telemetryItems);
            var transmission = new Transmission(this.endpointAddress, data, "application/x-json-stream", JsonSerializer.CompressionType);

            await transmission.SendAsync().ConfigureAwait(false);
        }