Exemplo n.º 1
0
            public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
            {
                var stream = new DummyStream();

                Streams.Add(new ContentStream(headers, stream));
                return(stream);
            }
        public void ResponseSizeTask_updates_minimum()
        {
            var fixture    = new Fixture();
            var fakeMetric = fixture.Build <ResponseSizeTask.ResponseSize>().With(x => x.MinimumSize, 200).Create();

            var storage = new ApplicationStorageMock();

            storage.Set(nameof(ResponseSizeTask), fakeMetric);

            var context = Substitute.For <IMetricTaskContext>();

            context.ApplicationStorage.Returns(storage);

            var dummyStream = new DummyStream();

            dummyStream.SetLength(100);
            context.HttpContext.Response.Filter.Returns(dummyStream);

            var task = new ResponseSizeTask(context);

            //Act
            task.EndRequest();

            //Assert
            storage.Get <ResponseSizeTask.ResponseSize>(nameof(ResponseSizeTask)).MinimumSize.Should().Be(100);
        }
        public void ResponseSizeTask_correctly_calculates_average()
        {
            var storage = new ApplicationStorageMock();

            var context = Substitute.For <IMetricTaskContext>();

            context.ApplicationStorage.Returns(storage);

            var dummyStream = new DummyStream();

            context.HttpContext.Response.Filter.Returns(dummyStream);

            var fixture  = new Fixture();
            var requests = fixture.CreateMany <long>().ToList();

            var task = new ResponseSizeTask(context);

            //Act
            foreach (var r in requests)
            {
                dummyStream.SetLength(r);
                task.EndRequest();
            }

            //Assert
            var correctAvg    = requests.Sum() / (double)requests.Count;
            var assertAverage = storage.Get <ResponseSizeTask.ResponseSize>(nameof(ResponseSizeTask)).AverageSize;

            assertAverage.Should().Be(correctAvg);
        }
Exemplo n.º 4
0
    public static int Main(string[] args)
    {
        var stream = new DummyStream();
        var buffer = new byte[stream.Length];
        int read   = stream.ReadAsync(buffer, 0, buffer.Length).GetAwaiter().GetResult();

        return(read + buffer[0]);
    }
Exemplo n.º 5
0
        public void Should_post_large_files([Values(Host.Owin, Host.IISExpress)] Host host)
        {
            var stopwatch = new Stopwatch();
            var stream1   = new DummyStream(100.MB());
            var stream2   = new DummyStream(200.MB());

            var stream1Length = stream1.Length;
            var stream2Length = stream2.Length;

            stopwatch.Start();

            var result = Http.ForHost(host).PostMultipartForm <List <MultipartTestHandler
                                                                     .InputBodyModel> >($"{BaseUrl}LargeStreams", x => x
                                                                                        //.InputBodyModel>>("webapi/multipart", x => x
                                                                                        .AddStreamFormData("somefile", stream1, "filename.txt", MimeTypes.TextHtml)
                                                                                        .AddStreamFormData("anotherfile", stream2, "filename.png", MimeTypes.ImagePng));

            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);

            result.Status.ShouldEqual(HttpStatusCode.OK);

            result.Data.Count.ShouldEqual(2);

            var file = result.Data.First();

            Console.WriteLine($"Checksum: {file.Data}");
            Console.WriteLine($"Length: {file.Length}");

            file.Name.ShouldEqual("somefile");
            file.Filename.ShouldEqual("filename.txt");
            file.Data.ShouldEqual(stream1.Checksum.ToString());
            file.ContentType.ShouldEqual(MimeTypes.TextHtml);
            file.Encoding.ShouldBeEmpty();
            file.Length.ShouldEqual(stream1Length);

            file = result.Data.Second();

            Console.WriteLine($"Checksum: {file.Data}");
            Console.WriteLine($"Length: {file.Length}");

            file.Name.ShouldEqual("anotherfile");
            file.Filename.ShouldEqual("filename.png");
            file.Data.ShouldEqual(stream2.Checksum.ToString());
            file.ContentType.ShouldEqual(MimeTypes.ImagePng);
            file.Encoding.ShouldBeEmpty();
            file.Length.ShouldEqual(stream2Length);
        }
Exemplo n.º 6
0
        public List <InputBodyModel> PostLargeStreams(IEnumerable <InputStream> files)
        {
            return(files.Select(x =>
            {
                var stream = new DummyStream();
                x.Data.CopyTo(stream);

                return new InputBodyModel
                {
                    Name = x.Name,
                    Filename = x.Filename,
                    ContentType = x.ContentType,
                    Encoding = x.Encoding.ToList(),
                    Length = stream.Length,
                    Data = stream.Checksum.ToString()
                };
            }).ToList());
        }
        public void ResponseSizeTask_creates_response_size()
        {
            var storage = new ApplicationStorageMock();
            var context = Substitute.For <IMetricTaskContext>();

            context.ApplicationStorage.Returns(storage);

            var dummyStream = new DummyStream();

            dummyStream.SetLength(100);
            context.HttpContext.Response.Filter.Returns(dummyStream);

            var task = new ResponseSizeTask(context);

            //Act
            task.EndRequest();

            //Assert
            storage.Get <ResponseSizeTask.ResponseSize>(nameof(ResponseSizeTask)).Should()
            .BeOfType <ResponseSizeTask.ResponseSize>();
        }
Exemplo n.º 8
0
 static IIntStream InputStream(IToken token)
     {
     IIntStream result = null;
     //
     if (token is Antlr.Runtime.CommonToken)
         {
         Antlr.Runtime.CommonToken common = (Antlr.Runtime.CommonToken)token;
         result = common.InputStream;
         }
     //
     if (null == result)
         result = new DummyStream();
     //
     return result;
     }
Exemplo n.º 9
0
 public ContentStream(HttpContentHeaders headers, DummyStream stream)
 {
     Headers = headers;
     Stream  = stream;
 }
        public void Encrypt_File()
        {
            byte[] bytesToEncrypt = new byte[] { 1, 2, 3, 4, 5, 6 };
            byte[] expectedEncryptedBytes = new byte[] { 2, 4, 6, 8, 10, 12 };
            byte[] hashedPasswordBytes = new byte[] {
                                                        1, 2, 3, 4, 5, 6, 7, 8,
                                                        1, 2, 3, 4, 5, 6, 7, 7,
                                                        1, 2, 3, 4, 5, 6, 7, 6,
                                                        1, 2, 3, 4, 5, 6, 7, 5,
                                                        1, 2, 3, 4, 5, 6, 7, 4,
                                                        1, 2, 3, 4, 5, 6, 7, 3,
                                                        1, 2, 3, 4, 5, 6, 7, 2,
                                                        1, 2, 3, 4, 5, 6, 7, 1,
                                                    };
            string inputFilePath = "TestInputFilePath";
            string outputFilePath = "TestOutputFilePath";
            string password = "******";
            System.Func<byte, byte> transformMethod = (a) =>
            {
                if(a >= 127)
                    return System.Byte.MaxValue;
                return (byte)(a * 2);
            };

            DummyStream streamToEncrypt = new DummyStream(bytesToEncrypt);
            DummyStream outputStream = new DummyStream();

            Mock<IHashAlgorithm> hashMock = new Mock<IHashAlgorithm>();
            Mock<IAESAlgorithm> aesMock = new Mock<IAESAlgorithm>();
            Mock<IFile> fileMock = new Mock<IFile>();
            DummyEncryptor transform = new DummyEncryptor(transformMethod, 16);

            hashMock.Setup(a => a.ComputeHash(It.IsAny<byte[]>())).Returns(hashedPasswordBytes);
            aesMock.Setup(a => a.CreateEncryptor(It.IsAny<byte[]>(), It.IsAny<byte[]>())).Returns(transform);
            fileMock.Setup(a => a.Exists(inputFilePath)).Returns(true);
            fileMock.Setup(a => a.Exists(outputFilePath)).Returns(false);
            fileMock.Setup(a => a.OpenRead(inputFilePath)).Returns(streamToEncrypt);
            fileMock.Setup(a => a.OpenWrite(outputFilePath)).Returns(outputStream);

            EncryptorImplementation encryptor = new EncryptorImplementation(aesMock.Object, hashMock.Object, fileMock.Object);

            encryptor.Encrypt(inputFilePath, outputFilePath, password);

            outputStream.Position = 0;
            CollectionAssert.AreEqual(expectedEncryptedBytes, outputStream.ToArray());
        }
Exemplo n.º 11
0
        private void ReadBody(MailReader reader, MailProperties partProps, String separator)
        {
            string contentType = partProps.GetKeyPrincipal("Content-Type");

            bool isTextPlain  = (string.Compare(contentType, "text/plain", true) == 0);
            bool isTextHtml   = (string.Compare(contentType, "text/html", true) == 0);
            bool isAttachment = (!isTextPlain && !isTextHtml) || AttachmentContentDisposition(partProps);

            string oldSeparator = reader.GetSeparator();

            reader.SetSeparator(separator);
            reader.SetTextPlain(isTextPlain);
            GXLogging.Debug(log, "isAttachment:" + isAttachment + " isTextHTML:" + isTextHtml + " istextplain:" + isTextPlain);
            MimeDecoder decoder = GetDecoder(partProps.GetField("Content-Transfer-Encoding"));

            if (isAttachment)
            {
                string outname = string.Empty;
                try
                {
                    Stream output;
                    if (this.DownloadAttachments)
                    {
                        string cid = GetAttachmentContentId(partProps);

                        string fileName = qpDecoder.DecodeHeader(RemoveQuotes(partProps.GetKeyProperty("Content-Disposition", "filename")));
                        if (string.IsNullOrEmpty(fileName))
                        {
                            fileName = RemoveQuotes(partProps.GetKeyProperty("Content-Type", "name"));
                        }

                        bool inlineAttachment = partProps.GetKeyPrincipal("Content-Disposition").StartsWith("inline");
                        if (inlineAttachment && !string.IsNullOrEmpty(cid))
                        {
                            fileName         = String.Format("{0}_{1}", cid, fileName);
                            outname          = GetFileName(attachmentsPath, fileName, contentType);
                            this.messageHtml = this.messageHtml.Replace("cid:" + cid, outname);
                        }
                        else
                        {
                            outname = GetFileName(attachmentsPath, fileName, contentType);
                        }

                        attachments += outname + ";";

                        if (!Directory.Exists(attachmentsPath))
                        {
                            Directory.CreateDirectory(attachmentsPath);
                        }
                        output = new FileStream(attachmentsPath + outname, FileMode.Create);
                    }
                    else
                    {
                        output = new DummyStream();
                    }
                    try
                    {
                        decoder.DecodeFile(reader, output, runner);
                    }
                    catch (Exception e)
                    {
                        GXLogging.Error(log, "ReadBody error", e);
                        throw e;
                    }
                    finally
                    {
                        output.Close();
                    }
                }
                catch (DirectoryNotFoundException dex)
                {
                    GXLogging.Error(log, "Error with attachments, attachment path:" + attachmentsPath + outname, dex);
                    throw new CouldNotSaveAttachmentException(dex);
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                    }
                    GXLogging.Error(log, "Error with attachments, attachment path:" + attachmentsPath + outname, ex);
                    throw new InvalidAttachmentException(ex);
                }
            }
            else
            {
                try
                {
                    TextWriter output = new StringWriter();
                    try
                    {
                        decoder.DecodeText(reader, output, runner);
                        if (isTextPlain)
                        {
                            messageText.Append(((StringWriter)output).GetStringBuilder().ToString());
                        }
                        else if (isTextHtml)
                        {
                            messageHtml.Append(((StringWriter)output).GetStringBuilder().ToString());
                        }
                    }
                    catch (Exception e)
                    {
                        GXLogging.Error(log, "ReadBody error", e);
                        throw e;
                    }
                    finally
                    {
                        output.Close();
                    }
                }
                catch (Exception ex1)
                {
                    if (ex1.InnerException != null)
                    {
                        ex1 = ex1.InnerException;
                    }
                    GXLogging.Error(log, "ReadBody error", ex1);
                    throw new InvalidMessageException(ex1);
                }
            }
            reader.SetSeparator(oldSeparator);
        }