public void DoesNotSendTransmissionForUnsupportedCodes()
        {
            IList<Transmission> enqueuedTransmissions = new List<Transmission>();
            var transmitter = new StubTransmitter
            {
                OnEnqueue = t => { enqueuedTransmissions.Add(t); }
            };

            var policy = new PartialSuccessTransmissionPolicy();
            policy.Initialize(transmitter);

            var items = new List<ITelemetry> { new EventTelemetry(), new EventTelemetry() };
            Transmission transmission = new Transmission(new Uri("http://uri"), items, "type", "encoding");

            string response = this.GetBackendResponse(
                itemsReceived: 50,
                itemsAccepted: 45,
                errorCodes: new[] { "400", "402", "502", "409", "417" });

            var wrapper = new HttpWebResponseWrapper
            {
                StatusCode = 206,
                Content = response
            };

            transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(transmission, null, wrapper));

            Assert.Equal(0, policy.ConsecutiveErrors);
            Assert.Equal(0, enqueuedTransmissions.Count);
        }
        public void IfIndexMoreThanNumberOfItemsInTransmissionIgnoreError()
        {
            IList<Transmission> enqueuedTransmissions = new List<Transmission>();
            var transmitter = new StubTransmitter
            {
                OnEnqueue = t => { enqueuedTransmissions.Add(t); }
            };

            var policy = new PartialSuccessTransmissionPolicy();
            policy.Initialize(transmitter);

            var items = new List<ITelemetry> { new EventTelemetry() };
            Transmission transmission = new Transmission(new Uri("http://uri"), items, "type", "encoding");

            // Index is 0-based
            string response = this.GetBackendResponse(
                itemsReceived: 2,
                itemsAccepted: 1,
                errorCodes: new[] { "408" },
                indexStartWith: 1);

            var wrapper = new HttpWebResponseWrapper
            {
                StatusCode = 206,
                Content = response
            };

            transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(transmission, null, wrapper));

            Assert.Equal(0, policy.ConsecutiveErrors);
            Assert.Equal(0, enqueuedTransmissions.Count);
        }
        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));
            }
        }
        private static StubPlatformFile CreateTransmissionFile(Uri endpointAddress = null, byte[] content = null)
        {
            endpointAddress = endpointAddress ?? new Uri("http://address");
            content = content ?? new byte[1];

            var transmission = new Transmission(endpointAddress, content, string.Empty, string.Empty);

            var fileStream = new MemoryStream();
            transmission.Save(fileStream);
            fileStream.Seek(0, SeekOrigin.Begin);

            return CreateFile("TestFile" + TransmissionStorage.TransmissionFileExtension, fileStream);
        }
 /// <summary>
 /// Saves the transmission to the specified <paramref name="stream"/>.
 /// </summary>
 internal static async Task SaveAsync(Transmission transmission, Stream stream)
 {
     var writer = new StreamWriter(stream);
     try
     {
         await writer.WriteLineAsync(transmission.EndpointAddress.ToString()).ConfigureAwait(false);
         await writer.WriteLineAsync(Transmission.ContentTypeHeader + ":" + transmission.ContentType).ConfigureAwait(false);
         await writer.WriteLineAsync(Transmission.ContentEncodingHeader + ":" + transmission.ContentEncoding).ConfigureAwait(false);
         await writer.WriteLineAsync(string.Empty).ConfigureAwait(false);
         await writer.WriteAsync(Convert.ToBase64String(transmission.Content)).ConfigureAwait(false);
     }
     finally
     {
         writer.Flush();
     }
 }
        public virtual void Serialize(IEnumerable<ITelemetry> items)
        {
            if (items == null)
            {
                throw new ArgumentNullException("items");
            }

            if (!items.Any())
            {
                throw new ArgumentException("One or more telemetry item is expected", "items");
            }

            byte[] content = JsonSerializer.Serialize(items);
            string encoding = JsonSerializer.CompressionType;
            var transmission = new Transmission(this.endpointAddress, content, "application/x-json-stream", encoding);
            this.transmitter.Enqueue(transmission);
        }
 public void SetsTimeoutTo100SecondsByDefaultToMatchHttpWebRequest()
 {
     var transmission = new Transmission(new Uri("http://address"), new byte[1], "content/type", "content/encoding");
     Assert.Equal(TimeSpan.FromSeconds(100), transmission.Timeout);
 }
        public void IfResponseIsBadJsonWeDoNotIncreaseErrorCount()
        {
            IList<Transmission> enqueuedTransmissions = new List<Transmission>();
            var transmitter = new StubTransmitter
            {
                OnEnqueue = t => { enqueuedTransmissions.Add(t); }
            };

            var policy = new PartialSuccessTransmissionPolicy();
            policy.Initialize(transmitter);

            var items = new List<ITelemetry> { new EventTelemetry(), new EventTelemetry() };
            Transmission transmission = new Transmission(new Uri("http://uri"), items, "type", "encoding");

            string response = "[,]";

            var wrapper = new HttpWebResponseWrapper
            {
                StatusCode = 206,
                Content = response
            };

            transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(transmission, null, wrapper));

            Assert.Equal(0, policy.ConsecutiveErrors);
            Assert.Equal(0, enqueuedTransmissions.Count);
        }
        internal override async Task EnqueueAsync(Transmission transmission)
        {
            try
            {   
                if (transmission == null || this.StorageFolder == null)
                {
                    return;
                }

                // Initial storage size calculation. 
                await this.EnsureSizeIsCalculatedAsync().ConfigureAwait(false);

                if ((ulong)this.storageSize >= this.CapacityInBytes || this.storageCountFiles >= this.MaxFiles)
                {
                    // if max storage capacity has reached, drop the transmission (but log every 100 lost transmissions). 
                    if (this.transmissionsDropped++ % 100 == 0)
                    {
                        CoreEventSource.Log.LogVerbose("Total transmissions dropped: " + this.transmissionsDropped);
                    }

                    return;
                }

                // Writes content to a temporaty file and only then rename to avoid the Peek from reading the file before it is being written.
                // Creates the temp file name
                string tempFileName = Guid.NewGuid().ToString("N");                

                // Creates the temp file (doesn't save any content. Just creates the file)
                IStorageFile temporaryFile = await this.StorageFolder.CreateFileAsync(tempFileName + ".tmp").AsTask().ConfigureAwait(false);

                // Now that the file got created we can increase the files count
                Interlocked.Increment(ref this.storageCountFiles);

                // Saves transmission to the temp file
                await SaveTransmissionToFileAsync(transmission, temporaryFile).ConfigureAwait(false);

                // Now that the file is written increase storage size. 
                long temporaryFileSize = await this.GetSizeAsync(temporaryFile).ConfigureAwait(false);
                Interlocked.Add(ref this.storageSize, temporaryFileSize);

                // Creates a new file name
                string now = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
                string newFileName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}.trn", now, tempFileName);

                // Renames the file
                await temporaryFile.RenameAsync(newFileName, NameCollisionOption.FailIfExists).AsTask().ConfigureAwait(false);
            }
            catch (Exception e)
            {
                CoreEventSource.Log.LogVerbose(string.Format(CultureInfo.InvariantCulture, "EnqueueAsync: Exception: {0}", e));
            }
        }
            public void SetsTimeoutTo100SecondsByDefaultToMatchHttpWebRequest()
            {
                var transmission = new Transmission(testUri, new byte[1], "content/type", "content/encoding");

                Assert.AreEqual(TimeSpan.FromSeconds(100), transmission.Timeout);
            }
            public void SetsEndpointAddressPropertyToSpecifiedValue()
            {
                var transmission = new Transmission(testUri, new byte[1], "content/type", "content/encoding");

                Assert.AreEqual(testUri, transmission.EndpointAddress);
            }
 public void SetsEndpointAddressPropertyToSpecifiedValue()
 {
     var expectedAddress = new Uri("expected://uri");
     var transmission    = new Transmission(expectedAddress, new byte[1], "content/type", "content/encoding");
 }
        /// <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);
        }
 public TransmissionProcessedEventArgs(Transmission transmission, Exception exception = null)
 {
     this.transmission = transmission;
     this.exception = exception;
 }
 private static long SaveTransmissionToFile(Transmission transmission, IPlatformFile file)
 {
     using (Stream stream = file.Open())
     {
         transmission.Save(stream);
         return stream.Length;
     }
 }
        /// <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);
            }
        }
        private string ParsePartialSuccessResponse(Transmission initialTransmission, TransmissionProcessedEventArgs args)
        {
            BackendResponse backendResponse;
            string responseContent = args.Response.Content;
            try
            {
                backendResponse = this.serializer.Deserialize<BackendResponse>(responseContent);
            }
            catch (ArgumentException exp)
            {
                TelemetryChannelEventSource.Log.BreezeResponseWasNotParsedWarning(exp.Message, responseContent);
                this.ConsecutiveErrors = 0;
                return null;
            }
            catch (InvalidOperationException exp)
            {
                TelemetryChannelEventSource.Log.BreezeResponseWasNotParsedWarning(exp.Message, responseContent);
                this.ConsecutiveErrors = 0;
                return null;
            }

            string newTransmissions = null;

            if (backendResponse != null && backendResponse.ItemsAccepted != backendResponse.ItemsReceived)
            {
                string[] items = JsonSerializer
                    .Deserialize(initialTransmission.Content)
                    .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var error in backendResponse.Errors)
                {
                    if (error != null)
                    {
                        if (error.Index >= items.Length || error.Index < 0)
                        {
                            TelemetryChannelEventSource.Log.UnexpectedBreezeResponseWarning(items.Length, error.Index);
                            continue;
                        }

                        TelemetryChannelEventSource.Log.ItemRejectedByEndpointWarning(error.Message);

                        if (error.StatusCode == ResponseStatusCodes.RequestTimeout ||
                            error.StatusCode == ResponseStatusCodes.ServiceUnavailable ||
                            error.StatusCode == ResponseStatusCodes.InternalServerError ||
                            error.StatusCode == ResponseStatusCodes.ResponseCodeTooManyRequests ||
                            error.StatusCode == ResponseStatusCodes.ResponseCodeTooManyRequestsOverExtendedTime)
                        {
                            if (string.IsNullOrEmpty(newTransmissions))
                            {
                                newTransmissions = items[error.Index];
                            }
                            else
                            {
                                newTransmissions += Environment.NewLine + items[error.Index];
                            }
                        }
                    }
                }
            }

            return newTransmissions;
        }
        private void HandleTransmissionSentEvent(object sender, TransmissionProcessedEventArgs args)
        {
            if (args.Response != null && args.Response.StatusCode == ResponseStatusCodes.PartialSuccess)
            {
                string newTransmissions = this.ParsePartialSuccessResponse(args.Transmission, args);

                if (!string.IsNullOrEmpty(newTransmissions))
                {
                    this.ConsecutiveErrors++;
                    this.DelayFutureProcessing(args.Response);

                    byte[] data = JsonSerializer.ConvertToByteArray(newTransmissions);
                    Transmission newTransmission = new Transmission(
                        args.Transmission.EndpointAddress,
                        data,
                        args.Transmission.ContentType,
                        args.Transmission.ContentEncoding,
                        args.Transmission.Timeout);

                    this.Transmitter.Enqueue(newTransmission);
                }
            }
        }
 public void SetsTimeoutToSpecifiedValue()
 {
     var expectedValue = TimeSpan.FromSeconds(42);
     var transmission = new Transmission(new Uri("http://address"), new byte[1], "content/type", "content/encoding", expectedValue);
     Assert.Equal(expectedValue, transmission.Timeout);
 }
        internal virtual void Enqueue(Transmission transmission)
        {
            if (transmission == null)
            {
                return;
            }

            TelemetryChannelEventSource.Log.TransmitterEnqueue(transmission.Id);

            if (!this.arePoliciesApplied)
            {
                this.ApplyPolicies();
            }

            Func<Transmission> transmissionGetter = () => transmission;

            if (this.Sender.Enqueue(transmissionGetter))
            {
                return;
            }

            TelemetryChannelEventSource.Log.TransmitterSenderSkipped(transmission.Id);

            if (this.Buffer.Enqueue(transmissionGetter))
            {
                return;
            }

            TelemetryChannelEventSource.Log.TransmitterBufferSkipped(transmission.Id);

            if (!this.Storage.Enqueue(transmissionGetter))
            {
                TelemetryChannelEventSource.Log.TransmitterStorageSkipped(transmission.Id);
            }
        }
 public TransmissionProcessedEventArgs(Transmission transmission, Exception exception = null, HttpWebResponseWrapper response = null)
 {
     this.Transmission = transmission;
     this.Exception = exception;
     this.Response = response;
 }
        /// <summary>
        /// Persist the in-memory telemetry items.
        /// </summary>
        internal void Flush()
        {
            IEnumerable<ITelemetry> telemetryItems = this.telemetryBuffer.Dequeue();

            if (telemetryItems != null && telemetryItems.Any())
            {
                byte[] data = JsonSerializer.Serialize(telemetryItems);
                var transmission = new Transmission(
                    this.EndpointAddress,
                    data,
                    "application/x-json-stream",
                    JsonSerializer.CompressionType);

                this.storage.EnqueueAsync(transmission).ConfigureAwait(false).GetAwaiter().GetResult();
            }
        }
        /// <summary>
        /// Splits the Transmission object into two pieces using a method
        /// to determine the length of the first piece based off of the length of the transmission.
        /// </summary>
        /// <returns>
        /// A tuple with the first item being a Transmission object with n ITelemetry objects
        /// and the second item being a Transmission object with the remaining ITelemetry objects.
        /// </returns>
        public virtual Tuple <Transmission, Transmission> Split(Func <int, int> calculateLength)
        {
            Transmission transmissionA = this;
            Transmission transmissionB = null;

            // We can be more efficient if we have a copy of the telemetry items still
            if (this.TelemetryItems != null)
            {
                // We don't need to deserialize, we have a copy of each telemetry item
                int numItems = calculateLength(this.TelemetryItems.Count);
                if (numItems != this.TelemetryItems.Count)
                {
                    List <ITelemetry> itemsA = new List <ITelemetry>();
                    List <ITelemetry> itemsB = new List <ITelemetry>();
                    var i = 0;
                    foreach (var item in this.TelemetryItems)
                    {
                        if (i < numItems)
                        {
                            itemsA.Add(item);
                        }
                        else
                        {
                            itemsB.Add(item);
                        }

                        i++;
                    }

                    transmissionA = new Transmission(
                        this.EndpointAddress,
                        itemsA);
                    transmissionB = new Transmission(
                        this.EndpointAddress,
                        itemsB);
                }
            }
            else if (this.ContentType == JsonSerializer.ContentType)
            {
                // We have to decode the payload in order to split
                bool     compress     = this.ContentEncoding == JsonSerializer.CompressionType;
                string[] payloadItems = JsonSerializer
                                        .Deserialize(this.Content, compress)
                                        .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                int numItems = calculateLength(payloadItems.Length);

                if (numItems != payloadItems.Length)
                {
                    string itemsA = string.Empty;
                    string itemsB = string.Empty;

                    for (int i = 0; i < payloadItems.Length; i++)
                    {
                        if (i < numItems)
                        {
                            if (!string.IsNullOrEmpty(itemsA))
                            {
                                itemsA += Environment.NewLine;
                            }

                            itemsA += payloadItems[i];
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(itemsB))
                            {
                                itemsB += Environment.NewLine;
                            }

                            itemsB += payloadItems[i];
                        }
                    }

                    transmissionA = new Transmission(
                        this.EndpointAddress,
                        JsonSerializer.ConvertToByteArray(itemsA, compress),
                        this.ContentType,
                        this.ContentEncoding);
                    transmissionB = new Transmission(
                        this.EndpointAddress,
                        JsonSerializer.ConvertToByteArray(itemsB, compress),
                        this.ContentType,
                        this.ContentEncoding);
                }
            }
            else
            {
                // We can't deserialize it!
                // We can say it's of length 1 at the very least
                int numItems = calculateLength(1);

                if (numItems == 0)
                {
                    transmissionA = null;
                    transmissionB = this;
                }
            }

            return(Tuple.Create(transmissionA, transmissionB));
        }
        private static Transmission CreateTransmission(ITelemetry telemetry)
        {
            byte[] data = JsonSerializer.Serialize(telemetry);
            Transmission transmission = new Transmission(
                                new Uri(@"http://some.url"),
                                data,
                                "application/x-json-stream",
                                JsonSerializer.CompressionType);

            return transmission;
        }
예제 #25
0
 internal abstract Task EnqueueAsync(Transmission transmission);
예제 #26
0
        internal override async Task EnqueueAsync(Transmission transmission)
        {   
            try
            {
                if (this.StorageFolder == null)
                {
                    return;
                }

                if (transmission == null)
                {
                    CoreEventSource.Log.LogVerbose("transmission is null. EnqueueAsync is skipped");
                    return;
                }

                if (this.IsStorageLimitsReached())
                {
                    // if max storage capacity has reached, drop the transmission (but log every 100 lost transmissions). 
                    if (Interlocked.Increment(ref this.transmissionsDropped) % 100 == 0)
                    {
                        CoreEventSource.Log.LogVerbose("Total transmissions dropped: " + this.transmissionsDropped);
                    }

                    return;
                }

                // Write content to a temporaty file and only then rename to avoid the Peek method from reading the file before it is being written.
                // Creates the temp file name
                string tempFileName = Guid.NewGuid().ToString("N");
                string tempFullFilePath = Path.Combine(this.StorageFolder.FullName, tempFileName + ".tmp");

                // Saves tranmission to file
                await SaveTransmissionToFileAsync(transmission, tempFullFilePath).ConfigureAwait(false);

                // Creates a new file name
                string now = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
                string newFileName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}.trn", now, tempFileName);
                string newFillFilePath = Path.Combine(this.StorageFolder.FullName, newFileName);

                // Renames the file
                File.Move(tempFullFilePath, newFillFilePath);
            }
            catch (Exception e)
            {
                CoreEventSource.Log.LogVerbose(string.Format(CultureInfo.InvariantCulture, "EnqueueAsync: Exception: {0}", e));
            }
        }
            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();
                }
            }
        public void NewTransmissionCreatedByIndexesFromResponse()
        {
            IList<Transmission> enqueuedTransmissions = new List<Transmission>();
            var transmitter = new StubTransmitter
            {
                OnEnqueue = t => { enqueuedTransmissions.Add(t); }
            };

            var policy = new PartialSuccessTransmissionPolicy();
            policy.Initialize(transmitter);

            var items = new List<ITelemetry>
                {
                    new EventTelemetry("1"),
                    new EventTelemetry("2"),
                    new EventTelemetry("3"),
                };
            Transmission transmission = new Transmission(new Uri("http://uri"), items, "type", "encoding");

            string response = this.GetBackendResponse(
                itemsReceived: 3,
                itemsAccepted: 1,
                errorCodes: new[] { "439", "439" });

            var wrapper = new HttpWebResponseWrapper
            {
                StatusCode = 206,
                Content = response
            };

            transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(transmission, null, wrapper));

            string[] newItems = JsonSerializer
                .Deserialize(enqueuedTransmissions[0].Content)
                .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            Assert.Equal(2, newItems.Length);
            Assert.True(newItems[0].Contains("\"name\":\"1\""));
            Assert.True(newItems[1].Contains("\"name\":\"2\""));
        }
 public void SetsEndpointAddressPropertyToSpecifiedValue()
 {
     var expectedAddress = new Uri("expected://uri");
     var transmission = new Transmission(expectedAddress, new byte[1], "content/type", "content/encoding");
 }
        public void IfItemIsRejectedOnlyThisItemIsUploadedBack()
        {
            IList<Transmission> enqueuedTransmissions = new List<Transmission>();
            var transmitter = new StubTransmitter
            {
                OnEnqueue = t => { enqueuedTransmissions.Add(t); }
            };

            var policy = new PartialSuccessTransmissionPolicy();
            policy.Initialize(transmitter);

            var items = new List<ITelemetry> { new EventTelemetry(), new EventTelemetry() };
            Transmission transmission = new Transmission(new Uri("http://uri"), items, "type", "encoding");

            string response = this.GetBackendResponse(
                itemsReceived: 2,
                itemsAccepted: 1,
                errorCodes: new[] { "429" });

            var wrapper = new HttpWebResponseWrapper
            {
                StatusCode = 206,
                Content = response
            };

            transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(transmission, null, wrapper));

            Assert.Equal(1, enqueuedTransmissions.Count);
        }
 public void SetsContentPropertyToSpecifiedValue()
 {
     var expectedContent = new byte[42];
     var transmission = new Transmission(new Uri("http://address"), expectedContent, "content/type", "content/encoding");
     Assert.Same(expectedContent, transmission.Content);
 }
 public void SetsContentTypePropertyToSpecifiedValue()
 {
     string expectedContentType = "TestContentType123";
     var transmission = new Transmission(new Uri("http://address"), new byte[1], expectedContentType, "content/encoding");
     Assert.Same(expectedContentType, transmission.ContentType);
 }
예제 #33
0
 private static async Task SaveTransmissionToFileAsync(Transmission transmission, string fileFullName)
 {
     try
     {
         using (Stream stream = File.OpenWrite(fileFullName))
         {
             await StorageTransmission.SaveAsync(transmission, stream).ConfigureAwait(false);
         }
     }
     catch (UnauthorizedAccessException)
     {
         string message = string.Format("Failed to save transmission to file. UnauthorizedAccessException. File full path: {0}", fileFullName);
         CoreEventSource.Log.LogVerbose(message);
         throw;
     }
 }
 public void SetContentEncodingPropertyToSpecifiedValue()
 {
     string expectedContentEncoding = "gzip";
     var transmission = new Transmission(new Uri("http://address"), new byte[1], "any/content", expectedContentEncoding);
     Assert.Same(expectedContentEncoding, transmission.ContentEncoding);
 }
 internal override void Enqueue(Transmission transmission)
 {
     this.OnEnqueue(transmission);
 }
        public void IfNumberOfRecievedItemsEqualsToNumberOfAcceptedErrorsListIsIgnored()
        {
            var transmitter = new StubTransmitter();

            var policy = new PartialSuccessTransmissionPolicy();
            policy.Initialize(transmitter);

            var items = new List<ITelemetry> { new EventTelemetry(), new EventTelemetry() };
            Transmission transmission = new Transmission(new Uri("http://uri"), items, "type", "encoding");

            string response = this.GetBackendResponse(
                itemsReceived: 2,
                itemsAccepted: 2,
                errorCodes: new[] { "408", "408" });

            var wrapper = new HttpWebResponseWrapper
            {
                StatusCode = 206,
                Content = response
            };

            transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(transmission, null, wrapper));

            Assert.Equal(0, policy.ConsecutiveErrors);
        }