public void TestEmptyGeometryCollection()
        {
            var coll = StreamExtensions.CreateBytes(4326, (byte)0x01, (byte)0x04,
                                                    0,                    //vertices
                                                    0,                    //figures
                                                    1, -1, -1, (byte)0x07 //shapes
                                                    );

            var g = SqlGeometry.Parse("GEOMETRYCOLLECTION EMPTY");

            g.STSrid = 4326;

            var serialized = g.Serialize().Value;

            CollectionAssert.AreEqual(coll, serialized);
        }
Esempio n. 2
0
        public void TestGeometryCollectionWithEmpty()
        {
            var coll = StreamExtensions.CreateBytes(4326, (byte)0x01, (byte)0x04,
                                                    1, 4d, 6d,                                                //vertices
                                                    1, (byte)0x01, 0,                                         //figures
                                                    3, -1, 0, (byte)0x07, 0, 0, (byte)0x00, 0, -1, (byte)0x01 //shapes
                                                    );

            var g = SqlGeometry.Parse("GEOMETRYCOLLECTION(POINT(4 6), POINT EMPTY)");

            g.STSrid = 4326;

            var serialized = g.Serialize().Value;

            CollectionAssert.AreEqual(coll, serialized);
        }
        public void TestCopyToAsync3_PreCanceled()
        {
            // declaring these makes it clear we are testing the correct overload
            Stream stream      = new MemoryStream();
            Stream destination = new MemoryStream();
            int    bufferSize  = 81920;

            CancellationTokenSource cts = new CancellationTokenSource();

            cts.Cancel();
            CancellationToken cancellationToken = cts.Token;

            Task task = StreamExtensions.CopyToAsync(stream, destination, bufferSize, cancellationToken);

            Assert.AreEqual(TaskStatus.Canceled, task.Status);
        }
        public void TestCopyToAsync3_NullDestination()
        {
            // declaring these makes it clear we are testing the correct overload
            Stream            stream            = new MemoryStream();
            Stream            destination       = null;
            int               bufferSize        = 81920;
            CancellationToken cancellationToken = CancellationToken.None;

            bool hasException = false;

            CompletedTask.Default.Then(_ => StreamExtensions.CopyToAsync(stream, destination, bufferSize, cancellationToken))
            .Catch <ArgumentNullException>((task, e) => hasException = true)
            .Wait();

            Assert.IsTrue(hasException);
        }
Esempio n. 5
0
        public void TestEmptyGeometryCollection()
        {
            var coll = StreamExtensions.CreateBytes(4326, (byte)0x01, (byte)0x04,
                                                    0,                    //vertices
                                                    0,                    //figures
                                                    1, -1, -1, (byte)0x07 //shapes
                                                    );
            var g = Microsoft.SqlServer.Types.SqlGeometry.Deserialize(new System.Data.SqlTypes.SqlBytes(coll));

            Assert.IsFalse(g.IsNull);
            Assert.AreEqual("GeometryCollection", g.STGeometryType().Value);
            Assert.AreEqual(4326, g.STSrid.Value);
            Assert.IsTrue(g.STX.IsNull);
            Assert.IsTrue(g.STY.IsNull);
            Assert.AreEqual(0, g.STNumGeometries());
        }
Esempio n. 6
0
        public async Task AsyncUnaryCall_UnknownCompressMetadataSentWithRequest_ThrowsError()
        {
            // Arrange
            HttpRequestMessage?httpRequestMessage = null;
            HelloRequest?      helloRequest       = null;

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                httpRequestMessage = request;

                var requestStream = await request.Content.ReadAsStreamAsync();

                helloRequest = await StreamExtensions.ReadMessageAsync(
                    requestStream,
                    NullLogger.Instance,
                    ClientTestHelpers.ServiceMethod.RequestMarshaller.ContextualDeserializer,
                    "gzip",
                    maximumMessageSize: null,
                    GrpcProtocolConstants.DefaultCompressionProviders,
                    singleMessage: true,
                    CancellationToken.None);

                HelloReply reply = new HelloReply
                {
                    Message = "Hello world"
                };

                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();

                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            var compressionMetadata = CreateClientCompressionMetadata("not-supported");
            var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(headers: compressionMetadata), new HelloRequest
            {
                Name = "Hello"
            });

            // Assert
            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => call.ResponseAsync).DefaultTimeout();

            Assert.AreEqual(StatusCode.Internal, ex.StatusCode);
            Assert.AreEqual("Error starting gRPC call. InvalidOperationException: Could not find compression provider for 'not-supported'.", ex.Status.Detail);
            Assert.AreEqual("Could not find compression provider for 'not-supported'.", ex.Status.DebugException.Message);
        }
        public async Task AsyncUnaryCall_CompressedResponseWithUnknownEncoding_ErrorThrown()
        {
            // Arrange
            HttpRequestMessage?httpRequestMessage = null;
            HelloRequest?      helloRequest       = null;

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                httpRequestMessage = request;

                var requestStream = await request.Content !.ReadAsStreamAsync().DefaultTimeout();

                helloRequest = await StreamExtensions.ReadMessageAsync(
                    requestStream,
                    new DefaultDeserializationContext(),
                    NullLogger.Instance,
                    ClientTestHelpers.ServiceMethod.RequestMarshaller.ContextualDeserializer,
                    "gzip",
                    maximumMessageSize: null,
                    GrpcProtocolConstants.DefaultCompressionProviders,
                    singleMessage: true,
                    CancellationToken.None);

                HelloReply reply = new HelloReply
                {
                    Message = "Hello world"
                };

                var compressionProvider = new GzipCompressionProvider(System.IO.Compression.CompressionLevel.Fastest);
                var streamContent       = await ClientTestHelpers.CreateResponseContent(reply, compressionProvider).DefaultTimeout();

                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent, grpcEncoding: "not-supported"));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest
            {
                Name = "Hello"
            });

            // Assert
            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => call.ResponseAsync).DefaultTimeout();

            Assert.AreEqual(StatusCode.Unimplemented, ex.StatusCode);
            Assert.AreEqual("Unsupported grpc-encoding value 'not-supported'. Supported encodings: identity, gzip", ex.Status.Detail);
        }
        public async Task AsyncUnaryCall_CompressedResponse_ResponseMessageDecompressed()
        {
            // Arrange
            HttpRequestMessage?httpRequestMessage = null;
            HelloRequest?      helloRequest       = null;

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                httpRequestMessage = request;

                var requestStream = await request.Content !.ReadAsStreamAsync().DefaultTimeout();

                helloRequest = await StreamExtensions.ReadMessageAsync(
                    requestStream,
                    new DefaultDeserializationContext(),
                    NullLogger.Instance,
                    ClientTestHelpers.ServiceMethod.RequestMarshaller.ContextualDeserializer,
                    "gzip",
                    maximumMessageSize: null,
                    GrpcProtocolConstants.DefaultCompressionProviders,
                    singleMessage: true,
                    CancellationToken.None);

                HelloReply reply = new HelloReply
                {
                    Message = "Hello world"
                };

                var compressionProvider = new GzipCompressionProvider(System.IO.Compression.CompressionLevel.Fastest);
                var streamContent       = await ClientTestHelpers.CreateResponseContent(reply, compressionProvider).DefaultTimeout();

                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent, grpcEncoding: "gzip"));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest
            {
                Name = "Hello"
            });

            // Assert
            var response = await call.ResponseAsync;

            Assert.IsNotNull(response);
            Assert.AreEqual("Hello world", response.Message);
        }
Esempio n. 9
0
        public static Solution CreateNew(string directory, string name)
        {
            string text     = StreamExtensions.ReadAllText(Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Solution), "Solution.txt"));
            string filename = FubuCore.StringExtensions.AppendPath(directory, new string[]
            {
                name
            });

            if (Path.GetExtension(filename) != ".sln")
            {
                filename += ".sln";
            }
            return(new Solution(filename, text)
            {
                Version = Solution.DefaultVersion
            });
        }
Esempio n. 10
0
        public void TestWriteAsync1_NullBuffer()
        {
            // declaring these makes it clear we are testing the correct overload
            Stream stream = new MemoryStream();

            byte[] buffer = null;
            int    offset = 0;
            int    count  = 81920;

            bool hasException = false;

            CompletedTask.Default.Then(_ => StreamExtensions.WriteAsync(stream, buffer, offset, count))
            .Catch <ArgumentNullException>((task, e) => hasException = true)
            .Wait();

            Assert.IsTrue(hasException);
        }
        public void TestEmptyPoint()
        {
            var  d          = double.NaN;
            var  bits       = BitConverter.DoubleToInt64Bits(d);
            bool isFinite   = (bits & 0x7FFFFFFFFFFFFFFF) < 0x7FF0000000000000;
            var  emptyPoint = StreamExtensions.CreateBytes(0, (byte)0x01, (byte)0x04, 0, 0, 1, -1, -1, (byte)0x01);
            var  g          = Microsoft.SqlServer.Types.SqlGeometry.Deserialize(new System.Data.SqlTypes.SqlBytes(emptyPoint));

            Assert.IsFalse(g.IsNull);
            Assert.AreEqual("Point", g.STGeometryType().Value);
            Assert.AreEqual(0, g.STSrid.Value);
            Assert.IsTrue(g.STX.IsNull);
            Assert.IsTrue(g.STY.IsNull);
            Assert.IsTrue(g.M.IsNull);
            Assert.IsTrue(g.Z.IsNull);
            Assert.AreEqual(0, g.STNumGeometries().Value);
        }
        public void TestCurvePolygon()
        {
            //TODO: Curve support not complete
            var coll = StreamExtensions.CreateBytes(4326, (byte)0x02, (byte)0x24,
                                                    5, 0d, 0d, 2d, 0d, 2d, 2d, 0d, 1d, 0d, 0d, //vertices
                                                    1, (byte)0x03, 0,                          //figures
                                                    1, -1, 0, (byte)0x10,                      //shapes
                                                    3, (byte)0x02, (byte)0x00, (byte)0x03      //Segments
                                                    );

            var g = Microsoft.SqlServer.Types.SqlGeometry.Deserialize(new System.Data.SqlTypes.SqlBytes(coll));

            Assert.IsFalse(g.IsNull);
            Assert.AreEqual("CURVEPOLYGON", g.STGeometryType().Value);
            Assert.AreEqual(4326, g.STSrid.Value);
            //TODO More asserts here
        }
Esempio n. 13
0
 public void TestArrayEquals()
 {
     Assert.True(StreamExtensions.Equal(null, null));
     Assert.False(StreamExtensions.Equal(new byte[0], null));
     Assert.False(StreamExtensions.Equal(null, new byte[0]));
     Assert.False(StreamExtensions.Equal(new byte[0], new byte[1]));
     Assert.False(StreamExtensions.Equal(new byte[2] {
         0, 1
     }, new byte[2] {
         0, 2
     }));
     Assert.True(StreamExtensions.Equal(new byte[2] {
         64, 128
     }, new byte[2] {
         64, 128
     }));
 }
Esempio n. 14
0
        public static List <System.IO.MemoryStream> splitMOVPacket(System.IO.MemoryStream buf, AvcCBox avcC)
        {
            List <System.IO.MemoryStream> result = new List <System.IO.MemoryStream>();
            int nls = avcC.getNalLengthSize();

            System.IO.MemoryStream dup = buf.duplicate();
            while (dup.remaining() >= nls)
            {
                int len = readLen(dup, nls);
                if (len == 0)
                {
                    break;
                }
                result.Add(StreamExtensions.read(dup, len));
            }
            return(result);
        }
        private void ReadLoop()
        {
            if (!Reading)
                return;

            var _buffer = new byte[1024];
            var _signal = new EventSignal<CallbackDetail<int>>();

            _signal.Finished += (sender, e) =>
            {
                if (e.Result.IsFaulted)
                {
                    Exception exception = e.Result.Exception.GetBaseException();

                    if (!HttpBasedTransport.IsRequestAborted(exception))
                    {
                        if (!(exception is IOException))
                            m_connection.OnError(exception);
                        StopReading(true);
                    }
                    return;
                }

                int _read = e.Result.Result;

                if (_read > 0)
                    // Put chunks in the buffer
                    m_buffer.Add(_buffer, _read);

                if (_read == 0)
                {
                    // Stop any reading we're doing
                    StopReading(true);
                    return;
                }

                // Keep reading the next set of data
                ReadLoop();

                if (_read <= _buffer.Length)
                    // If we read less than we wanted or if we filled the buffer, process it
                    ProcessBuffer();
            };
            StreamExtensions.ReadAsync(_signal, m_stream, _buffer);
        }
Esempio n. 16
0
        /// <summary>
        /// Reads PE headers from the current location in the stream.
        /// </summary>
        /// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param>
        /// <param name="size">Size of the PE image.</param>
        /// <param name="isLoadedImage">True if the PE image has been loaded into memory by the OS loader.</param>
        /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception>
        /// <exception cref="IOException">Error reading from the stream.</exception>
        /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception>
        public PEHeaders(Stream peStream, int size, bool isLoadedImage)
        {
            if (peStream == null)
            {
                throw new ArgumentNullException(nameof(peStream));
            }

            if (!peStream.CanRead || !peStream.CanSeek)
            {
                throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream));
            }

            _isLoadedImage = isLoadedImage;

            int actualSize = StreamExtensions.GetAndValidateSize(peStream, size, nameof(peStream));
            var reader     = new PEBinaryReader(peStream, actualSize);

            bool isCoffOnly;

            SkipDosHeader(ref reader, out isCoffOnly);

            _coffHeaderStartOffset = reader.CurrentOffset;
            _coffHeader            = new CoffHeader(ref reader);

            if (!isCoffOnly)
            {
                _peHeaderStartOffset = reader.CurrentOffset;
                _peHeader            = new PEHeader(ref reader);
            }

            _sectionHeaders = this.ReadSectionHeaders(ref reader);

            if (!isCoffOnly)
            {
                int offset;
                if (TryCalculateCorHeaderOffset(actualSize, out offset))
                {
                    _corHeaderStartOffset = offset;
                    reader.Seek(offset);
                    _corHeader = new CorHeader(ref reader);
                }
            }

            CalculateMetadataLocation(actualSize, out _metadataStartOffset, out _metadataSize);
        }
Esempio n. 17
0
        public MediaFileStream(Uri source, System.IO.Stream stream, DateTime?quantifier = null, int size = 8192, bool shouldDelete = true)
            : base(GetCurrentWorkingDirectory().Directory.ToString() + (quantifier.HasValue ? quantifier.Value.ToFileTimeUtc() : DateTime.UtcNow.ToFileTimeUtc()).ToString(), System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite)
        {
            m_Source = source;

            FileInfo = new System.IO.FileInfo(Name);

            Buffering = true;

            StreamExtensions.ITransactionResult result = StreamExtensions.BeginCopyTo(stream, this, size, WriteAt);

            //Race, the transaction might have already finished on small files...
            if (result.IsCompleted)
            {
                IStreamCopyTransactionResultCompleted(this, result);
            }
            else
            {
                result.TransactionCompleted += IStreamCopyTransactionResultCompleted;
            }

            if (shouldDelete)
            {
                AfterClose = new Action(DeleteFromFileInfoIfExists);
            }

            //SetEndOfFile
            //SetLength(result.ExpectedLength);

            //Done by WriteAt
            ////result.TransactionWrite += (s, e) =>
            ////{
            ////    m_Position += e.LastRead;

            ////    m_Length = e.Total;

            ////};

            //Wait for the end of the transaction or the root to be valid
            //Buffering && Root == null
            while (result.IsTransactionDone == false && Root == null)
            {
                result.AsyncWaitHandle.WaitOne(0);
            }
        }
Esempio n. 18
0
        public void ContentEqualsReturnNegativeResult4()
        {
            // Arrange
            string first  = @"two";
            string second = @"two
NUGET: END LICENSE TEXT
SADKLFJ;LDSAJKFDSAFDSAFDAS
DSALK;FJL;KDSAJFL;KDSJAFL;KDSA
FSDAKLJF;LKDSAJFLK;DSAJFASD
DSALKJFLK;DSAJFDSA
              ----SDALFJ;LDSAKJFLK;DJSAL;FKJDSLAK;FDSA";

            // Act
            bool equal = StreamExtensions.ContentEquals(first.AsStream(), second.AsStream());

            // Assert
            Assert.False(equal);
        }
Esempio n. 19
0
        public void ContentEqualsReturnNegativeResult3()
        {
            // Arrange
            string first  = @"two";
            string second = @"two
******** nuget: begin license text
SADKLFJ;LDSAJKFDSAFDSAFDAS
DSALK;FJL;KDSAJFL;KDSJAFL;KDSA
FSDAKLJF;LKDSAJFLK;DSAJFASD
DSALKJFLK;DSAJFDSA
              ----SDALFJ;LDSAKJFLK;DJSAL;FKJDSLAK;FDSA";

            // Act
            bool equal = StreamExtensions.ContentEquals(first.AsStream(), second.AsStream());

            // Assert
            Assert.True(equal);
        }
Esempio n. 20
0
        public override void Save(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            long offset = _stream.Position;

            try
            {
                StreamExtensions.CopyStream(_stream, stream);
            }
            finally
            {
                _stream.Position = offset;
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Reads the file into memory
        /// </summary>
        /// <param name="physicalPath"></param>
        MemCachedFile(string physicalPath)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            this.path = physicalPath;
            using (System.IO.FileStream fs = new FileStream(physicalPath, FileMode.Open, FileAccess.Read))
            {
                this.data = StreamExtensions.CopyToBytes(fs);
            }

            sw.Stop();
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Trace.Write("MemCachedFile loaded file into memory in " + sw.ElapsedMilliseconds + "ms");
            }
        }
Esempio n. 22
0
        public void TestWriteAsync2_PreCanceled()
        {
            // declaring these makes it clear we are testing the correct overload
            Stream stream = new MemoryStream();

            byte[] buffer = new byte[81920];
            int    offset = 0;
            int    count  = 0;

            CancellationTokenSource cts = new CancellationTokenSource();

            cts.Cancel();
            CancellationToken cancellationToken = cts.Token;

            Task task = StreamExtensions.WriteAsync(stream, buffer, offset, count, cancellationToken);

            Assert.AreEqual(TaskStatus.Canceled, task.Status);
        }
Esempio n. 23
0
        public void TestWriteAsync2_NullStream()
        {
            // declaring these makes it clear we are testing the correct overload
            Stream stream = null;

            byte[]            buffer            = new byte[81920];
            int               offset            = 0;
            int               count             = Buffer.ByteLength(buffer);
            CancellationToken cancellationToken = CancellationToken.None;

            bool hasException = false;

            CompletedTask.Default.Then(_ => StreamExtensions.WriteAsync(stream, buffer, offset, count, cancellationToken))
            .Catch <ArgumentNullException>((task, e) => hasException = true)
            .Wait();

            Assert.IsTrue(hasException);
        }
        public void AsStringAsyncEargelyThrowsWhenEncodingIsNull()
        {
            using (var ms = new MemoryStream(100))
            {
                // xUnit demands that I use an async check, which is exacly what I don't do in order to have
                // eager checking, so I did the check manually
                try
                {
                    _ = StreamExtensions.AsStringAsync(ms, null);

                    throw new Exception("The method didn't eargely threw.");
                }
                catch (Exception e)
                {
                    Assert.IsType <ArgumentNullException>(e);
                }
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Execute a web request against foreign resource and copy the target response to the local outgoing response steam
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            WebRequest proxy = WebRequest.Create(TargetUri);

            if (CookiesToPassOn != null)
            {
                proxy.Headers.Add("Cookie", CookiesToPassOn.ToCookieCollectionKeyValueString());
            }

            using (WebResponse proxyResponse = proxy.GetResponse())
            {
                context.HttpContext.Response.ContentType = proxyResponse.ContentType;
                using (Stream proxyResponseStream = proxyResponse.GetResponseStream())
                {
                    StreamExtensions.CopyStream(proxyResponseStream, context.HttpContext.Response.OutputStream);
                }
            }
        }
Esempio n. 26
0
        public void Process(System.Web.HttpContext current, IResponseArgs e)
        {
            var modDate = e.HasModifiedDate ? e.GetModifiedDateUTC() : DateTime.MinValue;
            var key     = e.RequestKey + "|" + modDate.Ticks.ToString(NumberFormatInfo.InvariantInfo);

            CacheEntry entry;

            byte[] data;

            //Ensure cache is loaded
            if (!loaded)
            {
                Load();
            }

            if (!TryGetData(key, out data, out entry))
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                //Cache miss - process request, outside of lock
                MemoryStream ms = new MemoryStream(4096);
                e.ResizeImageToStream(ms);
                data = StreamExtensions.CopyToBytes(ms, true);
                sw.Stop();
                //Save to cache
                entry = PutData(key, data, sw.ElapsedMilliseconds);
            }

            ((ResponseArgs)e).ResizeImageToStream = delegate(Stream s) {
                s.Write(data, 0, data.Length);
            };

            current.RemapHandler(new NoCacheHandler(e));

            if (cache.changes_since_cleanse > ChangeThreshold)
            {
                CleanseAndFlush();
            }
            else if (cache.changes_since_cleanse > 0 && DateTime.UtcNow.Subtract(lastFlush) > new TimeSpan(0, 0, 30))
            {
                Flush();
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Decrypts the specified data using a derived key and the specified IV
        /// </summary>
        /// <param name="data"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public byte[] Decrypt(byte[] data, byte[] iv)
        {
            if (iv.Length != BlockSizeInBytes)
            {
                throw new ArgumentOutOfRangeException("The specified IV is invalid - an " + BlockSizeInBytes + " byte array is required.");
            }

            var rm = GetAlgorithm();

            try {
                using (var decrypt = rm.CreateDecryptor(GetKey(), iv))
                    using (var ms = new MemoryStream(data, 0, data.Length, false, true))
                        using (var s = new CryptoStream(ms, decrypt, CryptoStreamMode.Read)) {
                            return(StreamExtensions.CopyToBytes(s));
                        }
            } finally {
                rm.Clear();
            }
        }
Esempio n. 28
0
        /// <summary>
        /// 一个工厂方法,用于实例化各个具体的PdfFile实例
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static PdfFile Create(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (stream is MemoryStream)
            {
                return(new PdfMemoryStreamFile((MemoryStream)stream));
            }
            else if (stream is FileStream)
            {
                return(new PdfFileStreamFile((FileStream)stream));
            }
            else
            {
                return(new PdfBufferFile(StreamExtensions.ToByteArray(stream)));
            }
        }
Esempio n. 29
0
        public void ContentEqualsReturnPositiveResult4()
        {
            // Arrange
            string first  = @"this is awesome.
holiday season is over.";
            string second = @"******** NUGET: BEGIN LICENSE TEXT
SADKLFJ;LDSAJKFDSAFDSAFDAS
DSALK;FJL;KDSAJFL;KDSJAFL;KDSA
FSDAKLJF;LKDSAJFLK;DSAJFASD
DSALKJFLK;DSAJFDSA
              NUGET: end License Text ----SDALFJ;LDSAKJFLK;DJSAL;FKJDSLAK;FDSA
this is awesome.
holiday season is over.";

            // Act
            bool equal = StreamExtensions.ContentEquals(first.AsStream(), second.AsStream());

            // Assert
            Assert.True(equal);
        }
        public void TestGetResponseAsync1()
        {
            WebRequest request = WebRequest.CreateHttp("http://httpbin.org/get");

            request.Method = "GET";

            MemoryStream outputStream = new MemoryStream();

            Task testTask =
                WebRequestExtensions.GetResponseAsync(request)
                .Then(task => StreamExtensions.CopyToAsync(task.Result.GetResponseStream(), outputStream));

            testTask.Wait();
            Assert.AreEqual(TaskStatus.RanToCompletion, testTask.Status);
            Console.Error.WriteLine(Encoding.UTF8.GetString(outputStream.GetBuffer()));

            GetData getData = JsonConvert.DeserializeObject <GetData>(Encoding.UTF8.GetString(outputStream.GetBuffer()));

            Assert.AreEqual(request.RequestUri.OriginalString, getData.url);
        }