Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
Beispiel #1
1
        public virtual IDisposable Draw(DrawingContext drawingContext, Rect targetItemRect, int level)
        {
            //Default is to draw the image bits into the context:

            //Do not dispose of the memory stream here, because System.Media.Windows uses
            // retained mode rendering where the commands get batched to execute later.
            MemoryStream imageStream = new MemoryStream(this.ImageData);
            try
            {
                TransformedBitmap shrunkImage = ResizePng(imageStream, targetItemRect.Size);

                //DrawingContext.DrawImage will scale an image to fill the size, so modify
                // our target rect to be exactly the correct image position on the tile.
                Rect targetImageRect = new Rect(targetItemRect.X, targetItemRect.Y,
                    shrunkImage.PixelWidth, shrunkImage.PixelHeight);
                drawingContext.DrawImage(shrunkImage, targetImageRect);

                return imageStream; //Return our stream so it can be disposed later.
            }
            catch
            {
                if (null != imageStream)
                {
                    imageStream.Dispose();
                }
                throw;
            }
        }
Beispiel #2
0
        /// <exception cref="InvalidImageException">
        /// ストリームから読みだされる画像データが不正な場合にスローされる
        /// </exception>
        protected MemoryImage(MemoryStream stream)
        {
            try
            {
                this.Image = Image.FromStream(stream);
            }
            catch (ArgumentException e)
            {
                stream.Dispose();
                throw new InvalidImageException("Invalid image", e);
            }
            catch (OutOfMemoryException e)
            {
                // GDI+ がサポートしない画像形式で OutOfMemoryException がスローされる場合があるらしい
                stream.Dispose();
                throw new InvalidImageException("Invalid image?", e);
            }
            catch (ExternalException e)
            {
                // 「GDI+ で汎用エラーが発生しました」という大雑把な例外がスローされる場合があるらしい
                stream.Dispose();
                throw new InvalidImageException("Invalid image?", e);
            }
            catch (Exception)
            {
                stream.Dispose();
                throw;
            }

            this.Stream = stream;
        }
Beispiel #3
0
        public async Task SendPacket(IPacket packet, Stream netStream)
        {
            var ms = new MemoryStream();
            var bw = new BinaryWriter(ms);

            if (packet is IAutoSerializePacket)
                (packet as IAutoSerializePacket).AutoSerialize(bw);
            else
            {
                bw.Write(packet.ID);
                packet.SerializePacket(bw);
            }

            bw.Flush();

            // Copy ms -> redirect writer to new ms -> prepend packet size prefix -> append packet paylod
            FinalizePacket(ref bw);
            ms.Dispose(); // Dispose of expired ms, writer's basestream is created in FinalizePacket
            ms = bw.BaseStream as MemoryStream;
            // this here failed? ye wait a moment
            await netStream.WriteAsync(ms.ToArray(), 0, (int)ms.Length);

            if (OnPacketSent != null)
                OnPacketSent(null, new PacketEventArgs(null, packet, (int)ms.Length));

            ms.Dispose();
            bw.Dispose();

        }
        public async Task<Stream> GetFileAsync(string folderName, string fileName)
        {
            if (String.IsNullOrWhiteSpace(folderName))
            {
                throw new ArgumentNullException("folderName");
            }

            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            ICloudBlobContainer container = await GetContainer(folderName);

            var blob = container.GetBlobReference(fileName);

            var stream = new MemoryStream();
            try
            {
                await blob.DownloadToStreamAsync(stream);
            }
            catch (StorageException ex)
            {
                stream.Dispose();

                if (ex.RequestInformation.ExtendedErrorInformation.ErrorCode == BlobErrorCodeStrings.BlobNotFound)
                {
                    return null;
                }

                throw;
            }
            catch (TestableStorageClientException ex)
            {
                // This is for unit test only, because we can't construct an 
                // StorageException object with the required ErrorCode
                stream.Dispose();

                if (ex.ErrorCode == BlobErrorCodeStrings.BlobNotFound)
                {
                    return null;
                }

                throw;
            }

            stream.Position = 0;
            return stream;
        }
        public void SingleLineSummary()
        {
            // Given
            string code = @"
                namespace Foo
                {
                    /// <summary>This is a summary.</summary>
                    class Green
                    {
                    }

                    /// <summary>This is another summary.</summary>
                    struct Red
                    {
                    }
                }
            ";
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(code));
            IDocument document = Substitute.For<IDocument>();
            document.GetStream().Returns(stream);
            IExecutionContext context = Substitute.For<IExecutionContext>();
            context.InputFolder.Returns(Environment.CurrentDirectory);
            context.GetNewDocument(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<IEnumerable<MetadataItem>>())
                .Returns(x => new TestDocument((IEnumerable<MetadataItem>)x[2]));
            IModule module = new AnalyzeCSharp();

            // When
            List<IDocument> results = module.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

            // Then
            Assert.AreEqual("This is a summary.", GetResult(results, "Green")["Summary"]);
            Assert.AreEqual("This is another summary.", GetResult(results, "Red")["Summary"]);
            stream.Dispose();
        }
 public override byte[] CreateImage(out string validataCode)
 {
     Bitmap bitmap;
     string formatString = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
     GetRandom(formatString, this.ValidataCodeLength, out validataCode);
     MemoryStream stream = new MemoryStream();
     AnimatedGifEncoder encoder = new AnimatedGifEncoder();
     encoder.Start();
     encoder.SetDelay(1);
     encoder.SetRepeat(0);
     for (int i = 0; i < 3; i++)
     {
         this.SplitCode(validataCode);
         this.ImageBmp(out bitmap, validataCode);
         bitmap.Save(stream, ImageFormat.Png);
         encoder.AddFrame(Image.FromStream(stream));
         stream = new MemoryStream();
         bitmap.Dispose();
     }
     encoder.OutPut(ref stream);
     bitmap = null;
     stream.Close();
     stream.Dispose();
     return stream.GetBuffer();
 }
Beispiel #7
0
		///<summary>Encrypts signature text and returns a base 64 string so that it can go directly into the database.</summary>
		public static string Encrypt(string str,byte[] key){
			//No need to check RemotingRole; no call to db.
			if(str==""){
				return "";
			}
			byte[] ecryptBytes=Encoding.UTF8.GetBytes(str);
			MemoryStream ms=new MemoryStream();
			CryptoStream cs=null;
			Aes aes=new AesManaged();
			aes.Key=key;
			aes.IV=new byte[16];
			ICryptoTransform encryptor=aes.CreateEncryptor(aes.Key,aes.IV);
			cs=new CryptoStream(ms,encryptor,CryptoStreamMode.Write);
			cs.Write(ecryptBytes,0,ecryptBytes.Length);
			cs.FlushFinalBlock();
			byte[] encryptedBytes=new byte[ms.Length];
			ms.Position=0;
			ms.Read(encryptedBytes,0,(int)ms.Length);
			cs.Dispose();
			ms.Dispose();
			if(aes!=null) {
				aes.Clear();
			}
			return Convert.ToBase64String(encryptedBytes);			
		}
        public void TplDownloadMultipleBlobsTest()
        {
            MemoryStream blobData1 = new MemoryStream(GetRandomBuffer(2 * 1024));
            MemoryStream blobData2 = new MemoryStream(GetRandomBuffer(2 * 1024));
            MemoryStream downloaded1 = new MemoryStream();
            MemoryStream downloaded2 = new MemoryStream();

            CloudPageBlob blob1 = this.testContainer.GetPageBlobReference("blob1");
            CloudPageBlob blob2 = this.testContainer.GetPageBlobReference("blob2");


            Task[] uploadTasks = new Task[]
                                     {
                                         blob1.UploadFromStreamAsync(blobData1),
                                         blob2.UploadFromStreamAsync(blobData2)
                                     };
            Task.WaitAll(uploadTasks);

            Task[] downloadTasks = new Task[]
                                       {
                                           blob1.DownloadToStreamAsync(downloaded1),
                                           blob2.DownloadToStreamAsync(downloaded2)
                                       };
            Task.WaitAll(downloadTasks);
            
            TestHelper.AssertStreamsAreEqual(blobData1, downloaded1);
            TestHelper.AssertStreamsAreEqual(blobData2, downloaded2);

            blobData1.Dispose();
            blobData2.Dispose();
            downloaded1.Dispose();
            downloaded2.Dispose();
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override Image ProcessBitmap()
        {
            if (Opetion == null) throw new ImageException("Opetion is null");
            if (TextFont == null) TextFont = new Font("SimSun", 20);
            MemoryStream sourcestream = new MemoryStream(SourceImgBuffter);

            var sourceImg = Image.FromStream(sourcestream);

            var trageSize = Opetion == null ? null : Opetion.TragetSize;
            Image tmpimg = trageSize != null ? new Bitmap(trageSize.Value.Width, trageSize.Value.Height) : new Bitmap(sourceImg.Width, sourceImg.Height);
            Graphics gType = CreateGraphics(tmpimg, sourceImg);
            var attributes = GetOpacity(Opetion.Opacity);
            var sizef = gType.MeasureString(Text, TextFont, sourceImg.Width, StringFormat.GenericDefault);
            var waterImg = new Bitmap((int)sizef.Width, (int)sizef.Height);
            var waterRectangle = GetWaterRectangle(sourceImg, waterImg);
            var tmpwatrer = CreateFillImage(waterImg);
            try
            {
                gType.DrawImage(tmpwatrer, waterRectangle, 0, 0, tmpwatrer.Width, tmpwatrer.Height, GraphicsUnit.Pixel, attributes);
                return tmpimg;
            }
            finally
            {
                sourcestream.Dispose();
                tmpwatrer.Dispose();
                sourceImg.Dispose();
            }
        }
Beispiel #10
0
        public void ReadFromStreamWithDefaultColumnsShouldHandleFirstRowAsRowData()
        {
            DataTableBuilder builder = new DataTableBuilder();
            var stream = new MemoryStream();
            var sw = new StreamWriter(stream);
            var rows = new[] { "first,row,is,data", "second,row,is,johnny", "second,row,was,laura", };
            foreach (var row in rows)
            {
                sw.WriteLine(row);
            }

            sw.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            try
            {
                var lazy = builder.ReadLazy(stream, rows[0].Split(','));
                Assert.Equal(rows[0].Split(','), lazy.ColumnNames);
                var rowEnumerator = rows.Skip(0).GetEnumerator();
                rowEnumerator.MoveNext();
                var rowCount = 0;
                foreach (var row in lazy.Rows)
                {
                    Assert.Equal(rowEnumerator.Current, string.Join(",", row.Values));
                    rowEnumerator.MoveNext();
                    rowCount++;
                }

                Assert.Equal(rows.Length, rowCount);
            }
            finally
            {
                sw.Dispose();
                stream.Dispose();
            }
        }
 public void ProcessEMF(byte[] emf)
 {
     try
     {
         _ms = new MemoryStream(emf);
         _mf = new Metafile(_ms);
         _bm = new Bitmap(1, 1);
         g = Graphics.FromImage(_bm);
         //XScale = Width / _mf.Width;
         //YScale = Height/ _mf.Height;
         m_delegate = new Graphics.EnumerateMetafileProc(MetafileCallback);
         g.EnumerateMetafile(_mf, new Point(0, 0), m_delegate);
     }
     finally
     {
         if (g != null)
             g.Dispose();
         if (_bm != null)
             _bm.Dispose();
         if (_ms != null)
         {
             _ms.Close();
             _ms.Dispose();
         }
     }
 }
Beispiel #12
0
        public Texture2D ConvertToTexture(Bitmap bitmap)
        {
            Texture2D texture;
            if (bitmap == null)
            {
                return null;
            }

            // MemoryStream to store the bitmap data.
            MemoryStream ms = new MemoryStream();
            // Save image to MemoryStream
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

            //Go to the beginning of the memory stream.
            ms.Seek(0, SeekOrigin.Begin);

            //Fill the texture.
            texture = Texture2D.FromStream(graphicsDevice, ms);

            ms.Close();
            ms.Dispose();
            ms = null;

            return texture;
        }
        public static byte[] CreateThumbnail(byte[] imageByte, bool maintainAspectRatio, int desiredWidth, int desiredHeight)
        {
            byte[] byteArray = new byte[0];
            Bitmap bmp;
            try
            {
                MemoryStream memStream = new MemoryStream(imageByte);
                System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);

                if (maintainAspectRatio)
                {
                    AspectRatio aspectRatio = new AspectRatio();
                    aspectRatio.WidthAndHeight(img.Width, img.Height, desiredWidth, desiredHeight);
                    bmp = new Bitmap(img, aspectRatio.Width, aspectRatio.Height);
                }
                else
                {
                    bmp = new Bitmap(img, desiredWidth, desiredHeight);
                }
                byteArray = ToByteArray(bmp, ImageFormat.Jpeg);
                memStream.Dispose();
            }
            catch (Exception ex)
            {

            }
            return byteArray;
        }
        public Stream FetchData(String url)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            if (httpWebResponse.StatusCode != HttpStatusCode.OK)
            {
                throw new BNetResponseFailedException();
            }

            using (var responseStream = httpWebResponse.GetResponseStream())
            {
                // Get the response an try to detect if server returned an object indicating a failure
                // Note: Do not use "using" statement, as we want the stream not to be closed to be used outside !
                var memoryStream = new MemoryStream();
                responseStream.CopyTo(memoryStream);
                memoryStream.Position = 0;

                // if json object is returned, test if it is an error message
                if (httpWebResponse.ContentType.Contains("application/json"))
                {
                    var failureObject = GetFailedObjectFromJSonStream(memoryStream);

                    if (failureObject.IsFailureObject())
                    {
                        memoryStream.Dispose();
                        throw new BNetFailureObjectReturnedException(failureObject);
                    }

                    memoryStream.Position = 0;
                }

                return memoryStream;
            }
        }
        public async Task StreamWriteAsyncTest()
        {
            byte[] buffer = GetRandomBuffer(1 * 1024 * 1024);
            MemoryStream stream1 = new MemoryStream(buffer);
            MemoryStream stream2 = new MemoryStream();

            OperationContext tempOperationContext = new OperationContext();
            RESTCommand<NullType> cmd = new RESTCommand<NullType>(TestBase.StorageCredentials, null);
            ExecutionState<NullType> tempExecutionState = new ExecutionState<NullType>(cmd, null, tempOperationContext);

            // Test basic write
            await stream1.WriteToAsync(stream2, null, null, false, tempExecutionState, null, CancellationToken.None);
            stream1.Position = 0;

            TestHelper.AssertStreamsAreEqual(stream1, stream2);

            stream2.Dispose();
            stream2 = new MemoryStream();

            await TestHelper.ExpectedExceptionAsync<ArgumentException>(
                async () => await stream1.WriteToAsync(stream2, 1024, 1024, false, tempExecutionState, null, CancellationToken.None),
                "Parameters copyLength and maxLength cannot be passed simultaneously.");

            stream1.Dispose();
            stream2.Dispose();
        }
Beispiel #16
0
 public Task<byte[]> ReadAsBufferAsync()
 {
     var tcs = new TaskCompletionSource<byte[]>();
     try {
         Stream stream = new MemoryStream();
         this.SerializeToStreamAsync(stream).ContinueWith(copyTask => {
             try {
                 if (copyTask.IsFaulted) {
                     stream.Dispose();
                     tcs.SetException(copyTask.Exception.GetBaseException());
                 }
                 else {
                     if (copyTask.IsCanceled) {
                         stream.Dispose();
                         tcs.SetCanceled();
                     }
                     else {
                         stream.Seek(0, SeekOrigin.Begin);
                         var buff = new byte[stream.Length];
                         Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buff, 0, buff.Length, null).ContinueWith(readTask => tcs.SetResult(buff));
                     }
                 }
             }
             catch (Exception ex) {
                 stream.Dispose();
                 tcs.SetException(ex);
             }
         });
     }
     catch (Exception ex) {
         tcs.SetException(ex);
     }
     return tcs.Task;
 }
        private static async Task <IHttpContent> GetCompressedContent(IHttpContent originalContent)
        {
            var ms = new System.IO.MemoryStream();

            try
            {
                await CompressOriginalContentStream(originalContent, ms).ConfigureAwait(false);

                ms.Seek(0, System.IO.SeekOrigin.Begin);

                var compressedContent = new Windows.Web.Http.HttpStreamContent(ms.AsInputStream());
                originalContent.CopyHeadersTo(compressedContent);
                compressedContent.Headers.ContentEncoding.Clear();
                compressedContent.Headers.ContentEncoding.Add(new Windows.Web.Http.Headers.HttpContentCodingHeaderValue("gzip"));
                compressedContent.Headers.ContentLength = (ulong)ms.Length;

                originalContent.Dispose();

                return(compressedContent);
            }
            catch
            {
                ms?.Dispose();
                throw;
            }
        }
Beispiel #18
0
		private void WriteTagContainer(TagContainer tagContainer)
		{
			Stream dataStream = null;
			Stream tagStream = null;
			try
			{
				dataStream = new MemoryStream(m_AudioData);
				tagStream = new MemoryStream(64000);

				// Write the content to a byte stream.
				m_Controller.Write(tagContainer, dataStream, tagStream);
			}
			finally
			{
				if (dataStream != null)
				{
					dataStream.Close();
					dataStream.Dispose();
				}

				if (tagStream != null)
				{
					tagStream.Close();
					tagStream.Dispose();
				}
			}
		}
Beispiel #19
0
        public void ExcerptAlternateQuerySelector()
        {
            // Given
            string input = @"<html>
                    <head>
                        <title>Foobar</title>
                    </head>
                    <body>
                        <h1>Title</h1>
                        <p>This is some Foobar text</p>
                        <div>This is some other text</div>
                    </body>
                </html>";
            IDocument document = Substitute.For<IDocument>();
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(input));
            document.GetStream().Returns(stream);
            Excerpt excerpt = new Excerpt("div");

            // When
            excerpt.Execute(new[] { document }, null).ToList();  // Make sure to materialize the result list

            // Then
            document.Received(1).Clone(Arg.Any<IEnumerable<KeyValuePair<string, object>>>());
            document.Received().Clone(Arg.Is<IEnumerable<KeyValuePair<string, object>>>(x => x.SequenceEqual(new[]
            {
                new KeyValuePair<string, object>("Excerpt", "<div>This is some other text</div>")
            })));
            stream.Dispose();
        }
        public void FullNameDoesNotContainFullHierarchy()
        {
            // Given
            string code = @"
                namespace Foo
                {
                }

                namespace Foo.Bar
                {
                }
            ";
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(code));
            IDocument document = Substitute.For<IDocument>();
            document.GetStream().Returns(stream);
            IExecutionContext context = Substitute.For<IExecutionContext>();
            context.GetNewDocument(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<IEnumerable<KeyValuePair<string, object>>>())
                .Returns(x => new TestDocument((IEnumerable<KeyValuePair<string, object>>)x[2]));
            IModule module = new AnalyzeCSharp();

            // When
            List<IDocument> results = module.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

            // Then
            CollectionAssert.AreEquivalent(new[] { string.Empty, "Foo", "Bar" }, results.Select(x => x["FullName"]));
            stream.Dispose();
        }
        public void CloseResource2()
        {
            var stream = new MemoryStream();
            stream.Dispose();

            this.fs.Close();
        }
		public void GetVsNew()
		{
			var manager = new MemoryStreamManager(memoryBlockSize);

			var results = LoadTest.ExecuteCompare
				(
					"Get",
					index =>
					{
						var stream = manager.Get();

						manager.Put(stream);
					},
					"New",
					index =>
					{
						var stream = new MemoryStream(memoryBlockSize);

						stream.Dispose();
					},
					iterationCount
				);

			Trace.Write(results.ToString());
		}
Beispiel #23
0
        public void AddFile(DeduplicatorState state, FileInfo sourceFile, string destinationPath)
        {
            if (state.DestinationToFileHash.ContainsKey(destinationPath))
            {
                // File has already been added.
                return;
            }

            // Read the source file.
            var memory = new MemoryStream();
            using (var stream = new BufferedStream(new FileStream(sourceFile.FullName, FileMode.Open, FileAccess.Read, FileShare.None), 1200000))
            {
                stream.CopyTo(memory);
            }

            // Hash the memory stream.
            var sha1 = new SHA1Managed();
            memory.Seek(0, SeekOrigin.Begin);
            var hashBytes = sha1.ComputeHash(memory);
            var hashString = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
            memory.Seek(0, SeekOrigin.Begin);

            // Add to the file hash -> source map if not already present.
            if (!state.FileHashToSource.ContainsKey(hashString))
            {
                state.FileHashToSource.Add(hashString, memory);
            }
            else
            {
                memory.Dispose();
            }

            state.DestinationToFileHash.Add(destinationPath, hashString);
        }
		public void ParallelNewVsGet()
		{
			var manager = new MemoryStreamManager(memoryBlockSize);

			var newResults = LoadTest.ExecuteParallelAsync
				(
					"new",
					index =>
					{
						var stream = new MemoryStream(memoryBlockSize);

						stream.Dispose();
					},
					iterationCount,
					4096
				).Result;

			Trace.Write(newResults.ToString());

			var cacheResults = LoadTest.ExecuteParallelAsync
				(
					"get",
					index =>
					{
						var stream = manager.Get();

						manager.Put(stream);
					},
					iterationCount,
					4096
				).Result;

			Trace.Write(cacheResults.ToString());
		}
Beispiel #25
0
 /// <summary>
 /// Creates an image object from bytes.
 /// </summary>
 /// <param name="stream">Stream of bytes</param>
 public Image(MemoryStream stream) {
     if (stream == null || stream.Length == 0)
         throw new Errors.NullImageError();
     _bitmap = (Bitmap)Bitmap.FromStream(stream, false, false);
     stream.Dispose();
     COMDisposable.Subscribe(this, typeof(ComInterfaces._Image));
 }
Beispiel #26
0
            public void GeneratingMetadataFromStringTemplateSetsContent()
            {
                // Given
                IDocument document = Substitute.For<IDocument>();
                MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(string.Empty));
                document.GetStream().Returns(stream);
                IModule generateContent = new GenerateMeta("Foo", @"[rs:4;,\s]{<noun>}").WithSeed(1000);
                IExecutionContext context = Substitute.For<IExecutionContext>();
                object result;
                context.TryConvert(new object(), out result)
                    .ReturnsForAnyArgs(x =>
                    {
                        x[1] = x[0];
                        return true;
                    });

                // When
                generateContent.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<IEnumerable<KeyValuePair<string, object>>>());
                context.Received().GetDocument(Arg.Is(document), Arg.Is<IEnumerable<KeyValuePair<string, object>>>(
                    x => x.SequenceEqual(new[] { new KeyValuePair<string, object>("Foo", "nectarine, gambler, marijuana, chickadee") })));
                stream.Dispose();
            }
        public void ShouldMoveRoversCorrectly()
        {
            Stream stream = null;
            try
            {
                stream = new MemoryStream();
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    stream = null;
                    writer.WriteLine("5 5");
                    writer.WriteLine("1 2 N");
                    writer.WriteLine("LMLMLMLMM");
                    writer.WriteLine("3 3 E");
                    writer.WriteLine("MMRMMRMRRM");
                    writer.Flush();

                    writer.BaseStream.Position = 0;

                    var controller = new RoverController(writer.BaseStream);

                    var result = controller.RoverPositions();

                    result.ShouldEqual("1 3 N\r\n5 1 E\r\n");
                }
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
        }
Beispiel #28
0
        public static void InputStreamClosed()
        {
            var ms2 = new MemoryStream();
            ms2.Dispose();

            Assert.Throws<ArgumentException>(() => new StreamReader(ms2, false));
        }
        public async Task WritesMessage()
        {
            MemoryStream outputStream = new MemoryStream();

            MessageWriter messageWriter = 
                new MessageWriter(
                    outputStream,
                    this.messageSerializer);

            // Write the message and then roll back the stream to be read
            // TODO: This will need to be redone!
            await messageWriter.WriteMessage(Message.Event("testEvent", null));
            outputStream.Seek(0, SeekOrigin.Begin);

            string expectedHeaderString =
                string.Format(
                    Constants.ContentLengthFormatString,
                    ExpectedMessageByteCount);

            byte[] buffer = new byte[128];
            await outputStream.ReadAsync(buffer, 0, expectedHeaderString.Length);

            Assert.Equal(
                expectedHeaderString,
                Encoding.ASCII.GetString(buffer, 0, expectedHeaderString.Length));

            // Read the message
            await outputStream.ReadAsync(buffer, 0, ExpectedMessageByteCount);

            Assert.Equal(
                TestEventString,
                Encoding.UTF8.GetString(buffer, 0, ExpectedMessageByteCount));

            outputStream.Dispose();
        }
 private BitmapImage BitmapImageFromBytes(byte[] bytes)
 {
     BitmapImage image = null;
     MemoryStream stream = null;
     try
     {
         stream = new MemoryStream(bytes);
         stream.Seek(0, SeekOrigin.Begin);
         System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
         image = new BitmapImage();
         image.BeginInit();
         MemoryStream ms = new MemoryStream();
         img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
         ms.Seek(0, SeekOrigin.Begin);
         image.StreamSource = ms;
         image.StreamSource.Seek(0, SeekOrigin.Begin);
         image.EndInit();
     }
     catch (Exception)
     {
         throw;
     }
     finally
     {
         stream.Close();
         stream.Dispose();
     }
     return image;
 }
Beispiel #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XlsxInput"/> class.
        /// </summary>
        private XlsxInput(string[] workSheetNames)
        {
            var stream = new NativeIO.MemoryStream();

            try
            {
                using (var excel = new ExcelPackage(stream))
                {
                    #region destroy stream
                    stream = null;
                    #endregion

                    #region add worksheet

                    int i = 0;
                    foreach (var workSheetName in workSheetNames)
                    {
                        var worksheet = excel.Workbook.Worksheets.Add(string.IsNullOrEmpty(workSheetName) ? $"Sheet{i}" : workSheetName);
                        worksheet.View.ShowGridLines = true;
                        i++;
                    }

                    #endregion

                    #region create input
                    Input = (byte[])excel.GetAsByteArray().Clone();
                    #endregion
                }
            }
            finally
            {
                stream?.Dispose();
            }

            AutoUpdateChanges             = true;
            DeletePhysicalFilesAfterMerge = true;
        }
Beispiel #32
0
 /// <summary>
 /// Serializes current  object into an XML document
 /// </summary>
 /// <returns>string XML value</returns>
 public static string Serialize <T>(T xml, bool isThrowException = false)
 {
     System.IO.StreamReader streamReader = null;
     System.IO.MemoryStream memoryStream = null;
     try
     {
         XmlSerializer serializer = new XmlSerializer(typeof(T));
         memoryStream = new System.IO.MemoryStream();
         serializer.Serialize(memoryStream, xml);
         memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
         streamReader = new System.IO.StreamReader(memoryStream);
         return(streamReader.ReadToEnd());
     }
     catch (Exception ex)
     {
         if (isThrowException)
         {
             throw ex;
         }
         else
         {
             return(null);
         }
     }
     finally
     {
         if ((streamReader != null))
         {
             streamReader.Dispose();
         }
         if ((memoryStream != null))
         {
             memoryStream.Dispose();
         }
     }
 }
 /// <summary>
 /// Serializes current NewDataSet object into an XML document
 /// </summary>
 /// <returns>string XML value</returns>
 public virtual string Serialize()
 {
     System.IO.StreamReader streamReader = null;
     System.IO.MemoryStream memoryStream = null;
     try
     {
         memoryStream = new System.IO.MemoryStream();
         Serializer.Serialize(memoryStream, this);
         memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
         streamReader = new System.IO.StreamReader(memoryStream);
         return(streamReader.ReadToEnd());
     }
     finally
     {
         if ((streamReader != null))
         {
             streamReader.Dispose();
         }
         if ((memoryStream != null))
         {
             memoryStream.Dispose();
         }
     }
 }
Beispiel #34
0
        /// <summary>
        /// 获取返回包装对象子类(6种Response对象中的一种)
        /// </summary>
        /// <returns></returns>
        public ESPDataBase GetSubResponse(RequestBase request)
        {
            RequestType requestType = request.ESP_Header.ESP_Protocol;
            ESPDataBase resp        = null;

            System.IO.MemoryStream ms = ESP_TransferData.AsMemoryStream();
            switch (requestType)
            {
            case RequestType.PageV21:
                resp = new PageV21Response(Context);
                break;

            case RequestType.Mixed:
                resp = new MixedResponse(Context);
                break;

            case RequestType.Page:
                resp = new PageResponse(Context);
                break;

            case RequestType.Resource:
                ResourceRequest resReq = request as ResourceRequest;
                if (!resReq.IsPackageReqeust())
                {
                    resp = new ResourcePartialResponse(Context);
                }
                else
                {
                    resp = new ResourceResponse(Context);
                }
                break;

            case RequestType.Application:
                ApplicationRequest appReq = request as ApplicationRequest;
                if (!appReq.IsPackageReqeust())
                {
                    resp = new ApplicationResponse(Context);
                }
                else
                {
                    resp = new ApplicationPartialResponse(Context);
                }
                break;

            case RequestType.UpdateCenter:
                resp = new GatewayUpdateResponse(Context);
                break;

            case RequestType.SynServerAddress:
                resp = new SynServerAddressResponse(Context);
                break;

            default:
                break;
            }

            SpecUtil.BindFromNetworkStream(resp, ms, ms.Position, false, 0);
            resp.ContentRange[0] = 0;
            resp.ContentRange[1] = ESP_TransferData.LongLength - 1;
            ms.Close();
            ms.Dispose();

            return(resp);
        }
Beispiel #35
0
    private void GetMap2(HttpContext context)
    {
        HttpRequest  req  = context.Request;
        HttpResponse resp = context.Response;

        string docName    = req.QueryString["mapDoc"];
        string mapName    = req.QueryString["mapName"];
        string strwidth   = req.QueryString["width"];
        string metadataId = req.QueryString["metadataid"];
        string classpath  = req.QueryString["classpath"];

        string strlevel = req.QueryString["level"];
        string strrow   = req.QueryString["row"];
        string strcol   = req.QueryString["col"];

        if (strlevel == null || strcol == null || strrow == null)
        {
            //
            string strbox    = req.QueryString["box"];
            string strheight = req.QueryString["height"];
            strwidth = req.QueryString["width"];
            if (strbox != null)
            {
                string[] tmp    = strbox.Split(',');
                double   xmin   = Double.Parse(tmp[0]);
                double   ymin   = Double.Parse(tmp[1]);
                double   xmax   = Double.Parse(tmp[2]);
                double   ymax   = Double.Parse(tmp[3]);
                int      h      = Int32.Parse(strheight);
                int      w      = Int32.Parse(strwidth);
                string   dcs    = GetDCS();
                Bitmap   bitmap = null;
                if (docName != null && mapName != null)
                {
                    bitmap = MapHelper.GetMapByBox(dcs, docName, mapName, xmin, xmax, ymin, ymax, w, h, 256, "Png");
                }
                if (classpath == null)
                {
                    classpath = req.Form["classpath"];
                }
                if (classpath != null && metadataId != null)
                {
                    bitmap = MapHelper.GetMetadataMapByBox(dcs, metadataId, classpath, xmin, xmax, ymin, ymax, w, h, 256, "Png");
                }
                resp.StatusCode  = 200;
                resp.ContentType = "image/jpeg";
                resp.Buffer      = true;
                bitmap.Save(resp.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
            }
            return;
        }

        if (strwidth == null)
        {
            strwidth = "256";
        }

        strwidth = "256";

        int level = int.Parse(strlevel);
        int row   = int.Parse(strrow);
        int col   = int.Parse(strcol);
        int size  = int.Parse(strwidth);

        //获取dws的URL
        string soapaddr = GetDCS();
        string path     = null;

        if ((mapName == null || docName == null) && metadataId != null)
        {
            if (classpath == null)
            {
                classpath = req.Form["classpath"];
            }
            if (classpath != null)
            {
                path = MapHelper.GetMetadataMap(soapaddr, metadataId, classpath, level, row, col, 256, "png");//  .GetMap(soapaddr, docName, mapName, level, row, col, size, "png");
            }
        }
        else
        {
            //path = MapHelper.GetMap(soapaddr, docName, mapName, level, row, col, size, "png");
            DWS.dwService dws = new DWS.dwService();
            dws.Url = soapaddr;
            DWS.MapQuery query = new DWS.MapQuery();
            query.format    = "png";
            query.classPath = "";
            query.mapDoc    = docName;

            query.col     = col;
            query.row     = row;
            query.level   = (short)level;
            query.useTile = true;
            query.width   = 256;
            query.height  = 256;
            if (mapName == "NULL")
            {
                query.version = 1;
                query.mapName = "";
                query.useTile = true;
            }

            //开始绘制
            DWS.MapInfo mi = dws.getMap(query);
            //绘制成功
            if (mi.isSuccess && mi.image != null)
            {
                resp.Clear();
                resp.ClearHeaders();
                resp.ClearContent();
                resp.ContentType = "image/jpeg";
                resp.Buffer      = true;
                resp.StatusCode  = 200;
                System.IO.MemoryStream ms = new System.IO.MemoryStream(mi.image);
                Bitmap fullimage          = new Bitmap(ms);
                fullimage.Save(resp.OutputStream, System.Drawing.Imaging.ImageFormat.Png); //展现图片
                ms.Dispose();
                return;
            }
        }

        //resp.Clear();
        //resp.ClearHeaders();
        //resp.ClearContent();

        //if (path == null)
        //{
        //    //
        //    resp.StatusCode = 404;
        //}
        //else if (path == "empty")
        //{
        //    //
        //    resp.StatusCode = 204;
        //}
        //else
        //{
        //    resp.StatusCode = 200;
        //    resp.WriteFile(path);
        //}
        //long count = 0;
        //string openStr = docName + "|" + mapName;
        //try
        //{
        //    if (dataDic.ContainsKey(openStr))
        //    {
        //        dataDic.TryGetValue(openStr, out count);
        //        count++;
        //    }
        //    dataDic[openStr] = count;
        //}
        //catch (Exception countEx)
        //{
        //    dataDic = new System.Collections.Generic.Dictionary<string, long>();
        //    dataDic.Add(openStr, count);
        //}

        //string time = DateTime.Now.ToString();
        //string respHead = "本次连接状态:" + resp.StatusCode + " " + resp.StatusDescription;
        //string remoteIp = req.UserHostAddress;
        //string requestData = "请求数据:" + openStr + "\r\n本次服务器开机该数据访问计数:" + count + "\r\n分块编码:" + strlevel + "级 " + strrow + "行 " + strcol + "列";
        //string info = time + "\r\n远程用户:" + remoteIp + "\r\n" + requestData + "\r\n" + respHead;
        //try
        //{
        //    MapLog.WriteLine(info + "\r\n");
        //}
        //catch (Exception)
        //{

        //}
    }
        protected void ExportButton_Click(object sender, EventArgs e)
        {
            ProductSearchInfo productSearch = new ProductSearchInfo();
            OrderSearchInfo   orderSearch   = new OrderSearchInfo();

            productSearch.IsSale     = (int)BoolType.True;
            productSearch.Name       = ShopCommon.ConvertToT <string>(Name.Text);
            productSearch.ClassId    = ShopCommon.ConvertToT <string>(ClassID.Text);
            productSearch.BrandId    = ShopCommon.ConvertToT <int>(BrandID.Text);
            orderSearch.StartAddDate = ShopCommon.ConvertToT <DateTime>(StartAddDate.Text);
            orderSearch.EndAddDate   = ShopCommon.SearchEndDate(ShopCommon.ConvertToT <DateTime>(EndAddDate.Text));
            orderSearch.UserName     = ShopCommon.ConvertToT <string>(UserName.Text);
            orderSearch.OrderNumber  = ShopCommon.ConvertToT <string>(OrderNumber.Text);
            var data = OrderDetailBLL.StatisticsSaleDetail(1, 1000, orderSearch, productSearch, ref Count);

            NPOI.HSSF.UserModel.HSSFWorkbook book  = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet         sheet = book.CreateSheet("Sheet1");
            sheet.DefaultColumnWidth = 18;
            sheet.CreateFreezePane(0, 1, 0, 1);

            NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
            row.Height = 20 * 20;
            row.CreateCell(0).SetCellValue("时间");
            row.CreateCell(1).SetCellValue("单号");
            row.CreateCell(2).SetCellValue("商品名称");
            row.CreateCell(3).SetCellValue("数量");
            row.CreateCell(4).SetCellValue("金额");
            row.CreateCell(5).SetCellValue("用户名");

            //设置表头格式
            var headFont = book.CreateFont();

            headFont.Boldweight         = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
            headFont.FontHeightInPoints = 10;
            var headStyle = book.CreateCellStyle();

            headStyle.SetFont(headFont);
            headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            headStyle.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderRight       = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderTop         = NPOI.SS.UserModel.BorderStyle.Thin;
            foreach (var cell in row.Cells)
            {
                cell.CellStyle = headStyle;
            }

            foreach (DataRow dr in data.Rows)
            {
                NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(data.Rows.IndexOf(dr) + 1);
                dataRow.CreateCell(0).SetCellValue(Convert.ToString(dr["AddDate"]));
                dataRow.CreateCell(1).SetCellValue(Convert.ToString(dr["OrderNumber"]));
                dataRow.CreateCell(2).SetCellValue(Convert.ToString(dr["Name"]));
                dataRow.CreateCell(3).SetCellValue(Convert.ToString(dr["BuyCount"]));
                dataRow.CreateCell(4).SetCellValue(Convert.ToString(dr["Money"]));
                dataRow.CreateCell(5).SetCellValue(Convert.ToString(dr["UserName"]));

                var style = book.CreateCellStyle();
                style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
                foreach (var cell in dataRow.Cells)
                {
                    cell.CellStyle = style;
                }
            }

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            Response.BinaryWrite(ms.ToArray());
            book = null;
            ms.Close();
            ms.Dispose();
            Response.End();
        }
Beispiel #37
0
        public virtual void ProcessRequest(HttpContext context)
        {
            #region path structure

            var width          = 0;
            var height         = 0;
            var square         = 0;
            var keepRatio      = false;
            var imageid        = context.Request.QueryString["imageid"];
            var imageExtension = context.Request.QueryString["extension"];
            var microsite      = context.Request.QueryString["micrositeid"];
            var rootFolder     = ConfigurationManager.AppSettings["BarCodeDir"];

            try
            {
                if (!string.IsNullOrWhiteSpace(context.Request.QueryString["w"]))
                {
                    width = Convert.ToInt32(context.Request.QueryString["w"]);
                }

                if (!string.IsNullOrWhiteSpace(context.Request.QueryString["h"]))
                {
                    height = Convert.ToInt32(context.Request.QueryString["h"]);
                }

                if (!string.IsNullOrWhiteSpace(context.Request.QueryString["r"]))
                {
                    keepRatio = true;
                }

                if (!string.IsNullOrWhiteSpace(context.Request.QueryString["s"]))
                {
                    square = Convert.ToInt32(context.Request.QueryString["s"]);
                }

                if (width > 2000)
                {
                    width = 0;
                }
                if (height > 2000)
                {
                    height = 0;
                }
                if (square > 2000)
                {
                    square = 0;
                }
            }
            catch
            {
                //ignore
            }

            var findPath = string.Format("~{0}{1}/{2}", rootFolder, microsite, imageid + "." + imageExtension);

            var fi = new FileInfo(context.Server.MapPath(findPath));

            #endregion

            #region response type (hidden cause its rubbish and i want to redo later)

            if (imageExtension.Equals("jpg", StringComparison.CurrentCultureIgnoreCase))
            {
                context.Response.ContentType = "image/jpeg";
            }
            else if (imageExtension.Equals("png", StringComparison.CurrentCultureIgnoreCase))
            {
                context.Response.ContentType = "image/png";
            }
            else if (imageExtension.Equals("gif", StringComparison.CurrentCultureIgnoreCase))
            {
                context.Response.ContentType = "image/gif";
            }

            #endregion

            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetMaxAge(new TimeSpan(7, 0, 0, 0));

            context.Response.BufferOutput = false;

            if (!fi.Exists)
            {
                //get it!
                if (imageid != null)
                {
                    var image     = ImageDbService.RetrieveImageOnThefly(imageid);
                    var stream    = new System.IO.MemoryStream(image.Data);
                    var newstream = new MemoryStream();

                    try
                    {
                        //save locally
                        var di = Directory.CreateDirectory(fi.DirectoryName);

                        System.Drawing.Image i    = System.Drawing.Image.FromStream(stream);
                        System.Drawing.Image newi = null;
                        if (width > 0 && height > 0 && (width != i.Width || height != i.Height))
                        {
                            if (keepRatio)
                            {
                                newi = ImageService.ScaleImageToFixedSize(i, new System.Drawing.Size(width, height));
                            }
                            else
                            {
                                newi = ImageService.ResizeImage(i, new System.Drawing.Size(width, height));
                            }

                            newi.Save(newstream, i.RawFormat);
                        }
                        else if (width > 0 && width != i.Width)
                        {
                            newi = ImageService.ScaleImageToWidth(i, width);
                            newi.Save(newstream, i.RawFormat);
                        }
                        else if (height > 0 && height != i.Height)
                        {
                            newi = ImageService.ScaleImageToHeight(i, height);
                            newi.Save(newstream, i.RawFormat);
                        }
                        else if (square > 0)
                        {
                            if (i.Width >= i.Height)
                            {
                                newi = ImageService.ScaleImageToHeight(i, square);
                            }
                            else
                            {
                                newi = ImageService.ScaleImageToWidth(i, square);
                            }

                            int cx = (newi.Width / 2) - (square / 2);
                            int cy = (newi.Height / 2) - (square / 2);
                            newi = ImageService.CropImage(newi, cx, cy, square, square);
                            newi.Save(newstream, i.RawFormat);
                        }
                        else
                        {
                            newi      = i;
                            newstream = stream;
                        }

                        newi.Save(fi.FullName, i.RawFormat);
                        newi.Dispose();
                        i.Dispose();
                    }
                    catch
                    {
                        //ignore
                    }

                    if (newstream != null)
                    {
                        newstream.Position = 0;
                        const int buffersize = 1024 * 16;
                        byte[]    buffer     = new byte[buffersize];

                        int count = newstream.Read(buffer, 0, buffersize);
                        while (count > 0)
                        {
                            context.Response.OutputStream.Write(buffer, 0, count);
                            count = newstream.Read(buffer, 0, buffersize);
                        }

                        newstream.Close();
                        newstream.Dispose();
                    }

                    stream.Close();
                    stream.Dispose();
                }
            }
            else
            {
                //send it !
                context.Response.WriteFile(context.Server.MapPath(findPath));
            }

            context.Response.End();
        }
        public void DownlodExcel()
        {
            SaveFileDialog sflg = new SaveFileDialog();

            sflg.Filter   = "Excel(*.xls)|*.xls|Excel(*.xlsx)|*.xlsx";
            sflg.FileName = "采购单细节导入模板表.xls";
            if (sflg.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            NPOI.SS.UserModel.IWorkbook book = null;
            if (sflg.FilterIndex == 1)
            {
                book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            }

            NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("采购细节表");

            // 添加表头
            NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);

            NPOI.SS.UserModel.ICell cell = row.CreateCell(0);
            cell.SetCellType(NPOI.SS.UserModel.CellType.String);
            cell.SetCellValue("品名");

            #region 医疗器械(这里不用)
            //if ((int)this.toolStripComboBox1.ComboBox.SelectedValue == (int)PurchaseDrugTypes.医疗器械)
            //{
            //    cell = row.CreateCell(1);
            //    cell.SetCellType(NPOI.SS.UserModel.CellType.STRING);
            //    cell.SetCellValue("型号");

            //    cell = row.CreateCell(2);
            //    cell.SetCellType(NPOI.SS.UserModel.CellType.STRING);
            //    cell.SetCellValue("规格");

            //    cell = row.CreateCell(3);
            //    cell.SetCellType(NPOI.SS.UserModel.CellType.STRING);
            //    cell.SetCellValue("单位");

            //    cell = row.CreateCell(4);
            //    cell.SetCellType(NPOI.SS.UserModel.CellType.STRING);
            //    cell.SetCellValue("生产厂家");

            //    cell = row.CreateCell(5);
            //    cell.SetCellType(NPOI.SS.UserModel.CellType.NUMERIC);
            //    cell.SetCellValue("数量");

            //    cell = row.CreateCell(6);
            //    cell.SetCellType(NPOI.SS.UserModel.CellType.NUMERIC);
            //    cell.SetCellValue("单价");

            //    cell = row.CreateCell(7);
            //    cell.SetCellType(NPOI.SS.UserModel.CellType.NUMERIC);
            //    cell.SetCellValue("税率(%)");
            //}
            //else
            #endregion
            {
                cell = row.CreateCell(1);
                cell.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell.SetCellValue("剂型");

                cell = row.CreateCell(2);
                cell.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell.SetCellValue("规格");

                cell = row.CreateCell(3);
                cell.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell.SetCellValue("单位");

                cell = row.CreateCell(4);
                cell.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell.SetCellValue("生产厂家");

                cell = row.CreateCell(5);
                cell.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell.SetCellValue("产地");

                cell = row.CreateCell(6);
                cell.SetCellType(NPOI.SS.UserModel.CellType.Numeric);
                cell.SetCellValue("数量");

                cell = row.CreateCell(7);
                cell.SetCellType(NPOI.SS.UserModel.CellType.Numeric);
                cell.SetCellValue("单价");

                cell = row.CreateCell(8);
                cell.SetCellType(NPOI.SS.UserModel.CellType.Numeric);
                cell.SetCellValue("税率(%)");
            }

            // 写入
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            book = null;

            using (FileStream fs = new FileStream(sflg.FileName, FileMode.Create, FileAccess.Write))
            {
                byte[] data = ms.ToArray();
                fs.Write(data, 0, data.Length);
                fs.Flush();
            }

            ms.Close();
            ms.Dispose();
        }
Beispiel #39
0
        /// <summary>
        /// 将DataTable数据导入到excel中
        /// </summary>
        /// <param name="data">要导入的数据</param>
        /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
        /// <param name="sheetName">要导入的excel的sheet的名称</param>
        /// <returns>导入数据行数(包含列名那一行)</returns>
        public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
        {
            int    i     = 0;
            int    j     = 0;
            int    count = 0;
            ISheet sheet = null;

            fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            if (fileName.IndexOf(".xlsx") > 0) // 2007版本
            {
                workbook = new XSSFWorkbook();
            }
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
            {
                workbook = new HSSFWorkbook();
            }

            try
            {
                if (workbook != null)
                {
                    sheet = workbook.CreateSheet(sheetName);
                }
                else
                {
                    return(-1);
                }

                if (isColumnWritten == true) //写入DataTable的列名
                {
                    IRow row = sheet.CreateRow(0);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }

                for (i = 0; i < data.Rows.Count; ++i)
                {
                    IRow row = sheet.CreateRow(count);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                    }
                    ++count;
                }
                workbook.Write(fs); //写入到excel

                #region excel下载
                // 写入到客户端
                MemoryStream ms = new System.IO.MemoryStream();
                workbook.Write(ms);
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                HttpContext.Current.Response.Charset     = "UTF8";
                //根据不同的浏览器设置对应的文件名
                string attachFilename = "";
                {
                    string enCodeFilename = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
                    string userAgent      = HttpContext.Current.Request.Browser.Browser;
                    userAgent = userAgent.ToLower();
                    //IE浏览器
                    if (userAgent.IndexOf("ie") != -1 || userAgent.IndexOf("mozilla") != -1)
                    {
                        attachFilename = @"filename=" + enCodeFilename;
                    }
                    //Opera浏览器只能采用filename*
                    else if (userAgent.IndexOf("opera") != -1)
                    {
                        attachFilename = @"filename*=UTF-8''" + enCodeFilename;
                    }
                    //FireFox浏览器
                    else if (userAgent.IndexOf("firefox") != -1)
                    {
                        attachFilename = @"filename*=" + enCodeFilename;
                    }
                    //遨游
                    else if (userAgent.IndexOf("chrome") != -1)
                    {
                        attachFilename = @"filename=" + enCodeFilename;
                    }
                    else
                    {
                        attachFilename = @"filename=" + enCodeFilename;
                    }
                }
                HttpContext.Current.Response.AddHeader("Content-Disposition",
                                                       string.Format("attachment;{0}.xls", attachFilename));
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                HttpContext.Current.Response.End();
                workbook = null;
                ms.Close();
                ms.Dispose();
                #endregion

                return(count);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return(-1);
            }
        }
Beispiel #40
0
        protected void ExportButton_Click(object sender, EventArgs e)
        {
            UserSearchInfo userSearch = new UserSearchInfo();

            userSearch.UserName = ShopCommon.ConvertToT <string>(UserName.Text);
            userSearch.Sex      = ShopCommon.ConvertToT <int>(Sex.Text);
            DateTime startDate       = ShopCommon.ConvertToT <DateTime>(StartDate.Text);
            DateTime endDate         = ShopCommon.SearchEndDate(ShopCommon.ConvertToT <DateTime>(EndDate.Text));
            string   userConsumeType = ShopCommon.ConvertToT <string>(UserConsumeType.Text);

            userConsumeType = (userConsumeType == string.Empty) ? "OrderCount" : userConsumeType;
            var data = UserBLL.StatisticsUserConsume(1, 1000, userSearch, ref Count, userConsumeType, startDate, endDate);

            NPOI.HSSF.UserModel.HSSFWorkbook book  = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet         sheet = book.CreateSheet("Sheet1");
            sheet.DefaultColumnWidth = 18;
            sheet.CreateFreezePane(0, 1, 0, 1);

            NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
            row.Height = 20 * 20;
            row.CreateCell(0).SetCellValue("用户");
            row.CreateCell(1).SetCellValue("性别");
            row.CreateCell(2).SetCellValue("订单次数");
            row.CreateCell(3).SetCellValue("订单金额");

            //设置表头格式
            var headFont = book.CreateFont();

            headFont.Boldweight         = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
            headFont.FontHeightInPoints = 10;
            var headStyle = book.CreateCellStyle();

            headStyle.SetFont(headFont);
            headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            headStyle.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderRight       = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderTop         = NPOI.SS.UserModel.BorderStyle.Thin;
            foreach (var cell in row.Cells)
            {
                cell.CellStyle = headStyle;
            }

            foreach (DataRow dr in data.Rows)
            {
                NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(data.Rows.IndexOf(dr) + 1);
                dataRow.CreateCell(0).SetCellValue(Convert.ToString(dr["UserName"]));
                dataRow.CreateCell(1).SetCellValue(EnumHelper.ReadEnumChineseName <SexType>(Convert.ToInt32(dr["Sex"])));
                dataRow.CreateCell(2).SetCellValue(Convert.ToString(dr["OrderCount"]));
                dataRow.CreateCell(3).SetCellValue(Convert.ToString(dr["OrderMoney"]));

                var style = book.CreateCellStyle();
                style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
                foreach (var cell in dataRow.Cells)
                {
                    cell.CellStyle = style;
                }
            }

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            Response.BinaryWrite(ms.ToArray());
            book = null;
            ms.Close();
            ms.Dispose();
            Response.End();
        }
Beispiel #41
0
        /// <summary>
        /// Datatable生成Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="colsWidth">列宽</param>
        /// <returns></returns>
        public byte[] GenerateExcelTwoSheet(System.Data.DataTable dt1, System.Data.DataTable dt2, int[] colsWidth1 = null, int[] colsWidth2 = null)
        {
            HSSFWorkbook book   = new HSSFWorkbook();
            ISheet       sheet1 = book.CreateSheet("Data1");
            ISheet       sheet2 = book.CreateSheet("Data2");

            //设置列宽
            if (colsWidth1 != null)
            {
                for (int i = 0; i < colsWidth1.Length; i++)
                {
                    sheet1.SetColumnWidth(i, colsWidth1[i] * 256);
                }
            }
            else
            {
                for (int i = 0; i < dt1.Columns.Count; i++)
                {
                    sheet1.SetColumnWidth(i, 20 * 256);
                }
            }

            //列头
            IRow row = sheet1.CreateRow(0);

            row.Height = 600;
            ICellStyle titleStyle1 = book.CreateCellStyle();

            titleStyle1.Alignment           = HorizontalAlignment.Center;
            titleStyle1.VerticalAlignment   = VerticalAlignment.Center;
            titleStyle1.FillBackgroundColor = HSSFColor.LightBlue.Index;
            titleStyle1.WrapText            = true;
            IFont titleFont1 = book.CreateFont();

            titleFont1.Boldweight = (short)FontBoldWeight.Bold;
            titleStyle1.SetFont(titleFont1);
            titleStyle1.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle1.BottomBorderColor = HSSFColor.Black.Index;
            titleStyle1.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Dotted;
            titleStyle1.LeftBorderColor   = HSSFColor.Black.Index;
            titleStyle1.BorderRight       = NPOI.SS.UserModel.BorderStyle.Dotted;
            titleStyle1.RightBorderColor  = HSSFColor.Black.Index;
            titleStyle1.BorderTop         = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle1.TopBorderColor    = HSSFColor.Black.Index;
            for (int i = 0; i < dt1.Columns.Count; i++)
            {
                row.CreateCell(i).CellStyle = titleStyle1;
                row.GetCell(i).SetCellValue(dt1.Columns[i].ColumnName);
            }
            sheet1.CreateFreezePane(0, 1, 0, 1);
            //数据
            ICellStyle dataStyle1 = book.CreateCellStyle();

            dataStyle1.Alignment = HorizontalAlignment.Center;
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                IRow row2 = sheet1.CreateRow(i + 1);
                for (int j = 0; j < dt1.Columns.Count; j++)
                {
                    row2.CreateCell(j).SetCellValue(dt1.Rows[i][j].ToString());
                    row2.GetCell(j).CellStyle = dataStyle1;
                }
            }



            if (colsWidth2 != null)
            {
                for (int i = 0; i < colsWidth2.Length; i++)
                {
                    sheet2.SetColumnWidth(i, colsWidth2[i] * 256);
                }
            }
            else
            {
                for (int i = 0; i < dt2.Columns.Count; i++)
                {
                    sheet2.SetColumnWidth(i, 20 * 256);
                }
            }

            //列头
            IRow row3 = sheet2.CreateRow(0);

            row3.Height = 600;
            ICellStyle titleStyle = book.CreateCellStyle();

            titleStyle.Alignment           = HorizontalAlignment.Center;
            titleStyle.VerticalAlignment   = VerticalAlignment.Center;
            titleStyle.FillBackgroundColor = HSSFColor.LightBlue.Index;
            titleStyle.WrapText            = true;
            IFont titleFont = book.CreateFont();

            titleFont.Boldweight = (short)FontBoldWeight.Bold;
            titleStyle.SetFont(titleFont);
            titleStyle.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle.BottomBorderColor = HSSFColor.Black.Index;
            titleStyle.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Dotted;
            titleStyle.LeftBorderColor   = HSSFColor.Black.Index;
            titleStyle.BorderRight       = NPOI.SS.UserModel.BorderStyle.Dotted;
            titleStyle.RightBorderColor  = HSSFColor.Black.Index;
            titleStyle.BorderTop         = NPOI.SS.UserModel.BorderStyle.Thin;
            titleStyle.TopBorderColor    = HSSFColor.Black.Index;
            for (int i = 0; i < dt2.Columns.Count; i++)
            {
                row3.CreateCell(i).CellStyle = titleStyle;
                row3.GetCell(i).SetCellValue(dt2.Columns[i].ColumnName);
            }
            sheet2.CreateFreezePane(0, 1, 0, 1);
            //数据
            ICellStyle dataStyle = book.CreateCellStyle();

            dataStyle.Alignment = HorizontalAlignment.Center;
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                IRow row2 = sheet2.CreateRow(i + 1);
                for (int j = 0; j < dt2.Columns.Count; j++)
                {
                    row2.CreateCell(j).SetCellValue(dt2.Rows[i][j].ToString());
                    row2.GetCell(j).CellStyle = dataStyle;
                }
            }

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);

            book = null;
            ms.Close();
            ms.Dispose();
            return(ms.ToArray());
        }
Beispiel #42
0
        /// <summary>
        /// Write a set of input files to a torrent XZ archive (assuming the same output archive name)
        /// </summary>
        /// <param name="inputFiles">Input files to be moved</param>
        /// <param name="outDir">Output directory to build to</param>
        /// <param name="rom">DatItem representing the new information</param>
        /// <param name="date">True if the date from the DAT should be used if available, false otherwise (default)</param>
        /// <param name="romba">True if files should be output in Romba depot folders, false otherwise</param>
        /// <returns>True if the archive was written properly, false otherwise</returns>
        public override bool Write(List <string> inputFiles, string outDir, List <Rom> roms, bool date = false, bool romba = false)
        {
            bool   success  = false;
            string tempFile = Path.Combine(outDir, "tmp" + Guid.NewGuid().ToString());

            // If either list of roms is null or empty, return
            if (inputFiles == null || roms == null || inputFiles.Count == 0 || roms.Count == 0)
            {
                return(success);
            }

            // If the number of inputs is less than the number of available roms, return
            if (inputFiles.Count < roms.Count)
            {
                return(success);
            }

            // If one of the files doesn't exist, return
            foreach (string file in inputFiles)
            {
                if (!File.Exists(file))
                {
                    return(success);
                }
            }

            // Get the output archive name from the first rebuild rom
            string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".xz") ? "" : ".xz"));

            // Set internal variables
            SevenZipBase.SetLibraryPath("7za.dll");
            SevenZipExtractor  oldZipFile;
            SevenZipCompressor zipFile;

            try
            {
                // If the full output path doesn't exist, create it
                if (!Directory.Exists(Path.GetDirectoryName(archiveFileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(archiveFileName));
                }

                // If the archive doesn't exist, create it and put the single file
                if (!File.Exists(archiveFileName))
                {
                    zipFile = new SevenZipCompressor()
                    {
                        ArchiveFormat    = OutArchiveFormat.XZ,
                        CompressionLevel = CompressionLevel.Normal,
                    };

                    // Map all inputs to index
                    Dictionary <string, int> inputIndexMap = new Dictionary <string, int>();
                    for (int i = 0; i < inputFiles.Count; i++)
                    {
                        inputIndexMap.Add(roms[i].Name.Replace('\\', '/'), i);
                    }

                    // Sort the keys in TZIP order
                    List <string> keys = inputIndexMap.Keys.ToList();
                    keys.Sort(ZipFile.TorrentZipStringCompare);

                    // Create the temp directory
                    string tempPath = Path.Combine(outDir, Guid.NewGuid().ToString());
                    if (!Directory.Exists(tempPath))
                    {
                        Directory.CreateDirectory(tempPath);
                    }

                    // Now add all of the files in order
                    foreach (string key in keys)
                    {
                        string newkey = Path.Combine(tempPath, key);

                        File.Move(inputFiles[inputIndexMap[key]], newkey);
                        zipFile.CompressFiles(tempFile, newkey);
                        File.Move(newkey, inputFiles[inputIndexMap[key]]);

                        // After the first file, make sure we're in append mode
                        zipFile.CompressionMode = CompressionMode.Append;
                    }

                    Utilities.CleanDirectory(tempPath);
                    Utilities.TryDeleteDirectory(tempPath);
                }

                // Otherwise, sort the input files and write out in the correct order
                else
                {
                    // Open the old archive for reading
                    using (oldZipFile = new SevenZipExtractor(archiveFileName))
                    {
                        // Map all inputs to index
                        Dictionary <string, int> inputIndexMap = new Dictionary <string, int>();
                        for (int i = 0; i < inputFiles.Count; i++)
                        {
                            // If the old one contains the new file, then just skip out
                            if (oldZipFile.ArchiveFileNames.Contains(roms[i].Name.Replace('\\', '/')))
                            {
                                continue;
                            }

                            inputIndexMap.Add(roms[i].Name.Replace('\\', '/'), -(i + 1));
                        }

                        // Then add all of the old entries to it too
                        for (int i = 0; i < oldZipFile.FilesCount; i++)
                        {
                            inputIndexMap.Add(oldZipFile.ArchiveFileNames[i], i);
                        }

                        // If the number of entries is the same as the old archive, skip out
                        if (inputIndexMap.Keys.Count <= oldZipFile.FilesCount)
                        {
                            success = true;
                            return(success);
                        }

                        // Otherwise, process the old zipfile
                        zipFile = new SevenZipCompressor()
                        {
                            ArchiveFormat    = OutArchiveFormat.XZ,
                            CompressionLevel = CompressionLevel.Normal,
                        };

                        // Get the order for the entries with the new file
                        List <string> keys = inputIndexMap.Keys.ToList();
                        keys.Sort(ZipFile.TorrentZipStringCompare);

                        // Copy over all files to the new archive
                        foreach (string key in keys)
                        {
                            // Get the index mapped to the key
                            int index = inputIndexMap[key];

                            // If we have the input file, add it now
                            if (index < 0)
                            {
                                FileStream inputStream = Utilities.TryOpenRead(inputFiles[-index - 1]);

                                // Create a stream dictionary
                                Dictionary <string, Stream> dict = new Dictionary <string, Stream>();
                                dict.Add(key, inputStream);

                                // Now add the stream
                                zipFile.CompressStreamDictionary(dict, tempFile);
                            }

                            // Otherwise, copy the file from the old archive
                            else
                            {
                                Stream oldZipFileEntryStream = new MemoryStream();
                                oldZipFile.ExtractFile(index, oldZipFileEntryStream);
                                oldZipFileEntryStream.Seek(0, SeekOrigin.Begin);

                                // Create a stream dictionary
                                Dictionary <string, Stream> dict = new Dictionary <string, Stream>();
                                dict.Add(oldZipFile.ArchiveFileNames[index], oldZipFileEntryStream);

                                // Now add the stream
                                zipFile.CompressStreamDictionary(dict, tempFile);
                                oldZipFileEntryStream.Dispose();
                            }

                            // After the first file, make sure we're in append mode
                            zipFile.CompressionMode = CompressionMode.Append;
                        }
                    }
                }

                success = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                success = false;
            }

            // If the old file exists, delete it and replace
            if (File.Exists(archiveFileName))
            {
                Utilities.TryDeleteFile(archiveFileName);
            }
            File.Move(tempFile, archiveFileName);

            // Now make the file T7Z
            // TODO: Add ACTUAL T7Z compatible code

            BinaryWriter bw = new BinaryWriter(Utilities.TryOpenReadWrite(archiveFileName));

            bw.Seek(0, SeekOrigin.Begin);
            bw.Write(Constants.Torrent7ZipHeader);
            bw.Seek(0, SeekOrigin.End);

            using (oldZipFile = new SevenZipExtractor(Utilities.TryOpenReadWrite(archiveFileName)))
            {
                // Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4)
                byte[] tempsig = Constants.Torrent7ZipSignature;
                if (oldZipFile.FilesCount > 1)
                {
                    tempsig[16] = 0x2;
                }
                else
                {
                    tempsig[16] = 0;
                }

                bw.Write(tempsig);
                bw.Flush();
                bw.Dispose();
            }

            return(true);
        }
        public static void downloadFromDrive(string filename, string fileId, string savePath, string mimeType, frmMain parentForm)
        {
            frmMain parent    = parentForm;
            long    totalSize = 100000;

            parent.updateStatusBar(0, "Downloading...");
            try
            {
                if (Path.HasExtension(filename))
                {
                    var request = driveService.Files.Get(fileId);

                    var stream = new System.IO.MemoryStream();
                    System.Diagnostics.Debug.WriteLine(fileId);
                    // Add a handler which will be notified on progress changes.
                    // It will notify on each chunk download and when the
                    // download is completed or failed.
                    request.MediaDownloader.ProgressChanged +=
                        (IDownloadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case DownloadStatus.Downloading:
                        {
                            System.Diagnostics.Debug.WriteLine(progress.BytesDownloaded);

                            parent.updateStatusBar((progress.BytesDownloaded * 100) / totalSize, "Downloading...");
                            break;
                        }

                        case DownloadStatus.Completed:
                        {
                            parent.updateStatusBar(100, "Download complete.");
                            System.Diagnostics.Debug.WriteLine("Download complete.");
                            break;
                        }

                        case DownloadStatus.Failed:
                        {
                            parent.updateStatusBar(0, "Download failed.");
                            System.Diagnostics.Debug.WriteLine("Download failed.");
                            MessageBox.Show("File failed to download!!!", "Download Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                        }
                        }
                    };
                    request.Download(stream);
                    convertMemoryStreamToFileStream(stream, savePath + @"\" + @filename);
                    stream.Dispose();
                }
                else
                {
                    string extension = "", converter = "";
                    foreach (MimeTypeConvert obj in MimeConverter.mimeList())
                    {
                        if (mimeType == obj.mimeType)
                        {
                            extension = obj.extension;
                            converter = obj.converterType;
                        }
                    }
                    System.Diagnostics.Debug.WriteLine("{0} {1} {2}", fileId, extension, mimeType);
                    var request = driveService.Files.Export(fileId, converter);
                    var stream  = new System.IO.MemoryStream();
                    // Add a handler which will be notified on progress changes.
                    // It will notify on each chunk download and when the
                    // download is completed or failed.
                    request.MediaDownloader.ProgressChanged +=
                        (IDownloadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case DownloadStatus.Downloading:
                        {
                            Console.WriteLine(progress.BytesDownloaded);
                            break;
                        }

                        case DownloadStatus.Completed:
                        {
                            parent.updateStatusBar(100, "Download Complete!");
                            Console.WriteLine("Download complete.");
                            break;
                        }

                        case DownloadStatus.Failed:
                        {
                            parent.updateStatusBar(0, "Download failed.");
                            Console.WriteLine("Download failed.");
                            MessageBox.Show("File failed to download!!!", "Download Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                        }
                        }
                    };
                    request.Download(stream);
                    convertMemoryStreamToFileStream(stream, savePath + @"\" + @filename + extension);
                    stream.Dispose();
                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Download From Drive Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Download From Drive.\n");
            }
        }
Beispiel #44
0
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (0 > e.RowIndex)
            {
                return;
            }
            Hzexe.QQMusic.Model.SongItem si = (dataGridView1.Rows[e.RowIndex].DataBoundItem as TableModel).SongItem;
            var col = dataGridView1.Columns[e.ColumnIndex];

            Action <EnumFileType, SongItem> fun = new Action <EnumFileType, SongItem>((ext, obj) =>
            {
                var att = ext.GetFileType();

                string musicfilename            = $"{obj.title}-{obj.singer[0].name}.{att.Suffix}";
                saveFileDialog1.CheckPathExists = true;
                saveFileDialog1.CheckFileExists = false;
                saveFileDialog1.DefaultExt      = att.Suffix;
                saveFileDialog1.OverwritePrompt = true;
                saveFileDialog1.ValidateNames   = true;
                saveFileDialog1.Tag             = new { si = obj, ft = ext };
                saveFileDialog1.Filter          = $"{att.Suffix}(*.{att.Suffix})|*.{att.Suffix}";
                saveFileDialog1.FileName        = musicfilename;
                saveFileDialog1.ShowDialog();
            });

            if ("Ape" == col.DataPropertyName)
            {
                fun(EnumFileType.Ape, si);
            }
            else if ("Flac" == col.DataPropertyName)
            {
                fun(EnumFileType.Flac, si);
            }
            else if ("Mp3_320k" == col.DataPropertyName)
            {
                fun(EnumFileType.Mp3_320k, si);
            }
            else if ("Mp3_128k" == col.DataPropertyName)
            {
                fun(EnumFileType.Mp3_128k, si);
            }
            else if ("M4a" == col.DataPropertyName)
            {
                fun(EnumFileType.M4a, si);
            }
            else if ("Play" == col.DataPropertyName)
            {
                EnumFileType type         = si.file.GetAvailableFileType();//取当前歌曲可用的类型
                EnumFileType downloadType = 0;
                downloadType |= (type & EnumFileType.Ape);
                if (downloadType == 0)
                {
                    downloadType |= (type & EnumFileType.Flac);
                }
                if (downloadType == 0)
                {
                    downloadType |= (type & EnumFileType.Mp3_320k);
                }
                if (downloadType == 0)
                {
                    downloadType |= (type & EnumFileType.Mp3_128k);
                }
                if (downloadType == 0)
                {
                    downloadType |= (type & EnumFileType.M4a);
                }



                string url = api.GetDownloadSongUrl(si, downloadType);
                mediaPlayer.SetMedia(new Uri(url));

                Task.Run(async() =>
                {
                    //尝试载歌词
                    var ms = new System.IO.MemoryStream();
                    if (await api.downloadLyricAsync(si, ms))
                    {
                        ms.Position = 0;
                        lrc         = Lrc.InitLrc(ms);
                    }
                    else
                    {
                        lrc = null;
                    }
                    ms.Dispose();
                    mediaPlayer.Play();
                });
            }
        }
Beispiel #45
0
        /// <summary>
        /// 导出问卷数据
        /// </summary>
        /// <param name="list"></param>
        public string CreateExcel()
        {
            list = (from r in _db.tbl_record
                    join emp in _db.tbl_employeeMK on new { EId = r.eId.Value } equals new { EId = emp.eId }
                    join ans in
                    (
                        (from a in _db.tbl_answer
                         group a by new
            {
                a.rId
            } into g
                         select new
            {
                arid = g.Key.rId.Value,
                answer1 = g.Max(p => (p.qId == 1 ? p.aContent : null)),
                answer2 = g.Max(p => (p.qId == 2 ? p.aContent : null)),
                answer3 = g.Max(p => (p.qId == 3 ? p.aContent : null)),
                answer4 = g.Max(p => (p.qId == 4 ? p.aContent : null)),
                answer5 = g.Max(p => (p.qId == 5 ? p.aContent : null)),
                answer6 = g.Max(p => (p.qId == 6 ? p.aContent : null)),
                answer7 = g.Max(p => (p.qId == 7 ? p.aContent : null)),
                answer8 = g.Max(p => (p.qId == 8 ? p.aContent : null)),
                answer9 = g.Max(p => (p.qId == 9 ? p.aContent : null)),
                answer10 = g.Max(p => (p.qId == 10 ? p.aContent : null)),
                answer11 = g.Max(p => (p.qId == 11 ? p.aContent : null)),
                answer12 = g.Max(p => (p.qId == 12 ? p.aContent : null))
            }))on new { RId = r.rId } equals new { RId = ans.arid }
                    orderby
                    r.rId
                    select new RecordModel
            {
                AnswerId = r.rId,
                AnswerName = emp.eName,
                AnswerNumber = emp.eNumber,
                AnswerPhone = emp.ePhone,
                AnswerDuration = r.rDuration.Value,
                AnswerTime = r.rEndtime.Value,
                AnswerAnswer1 = ans.answer1,
                AnswerAnswer2 = ans.answer2,
                AnswerAnswer3 = ans.answer3,
                AnswerAnswer4 = ans.answer4,
                AnswerAnswer5 = ans.answer5,
                AnswerAnswer6 = ans.answer6,
                AnswerAnswer7 = ans.answer7,
                AnswerAnswer8 = ans.answer8,
                AnswerAnswer9 = ans.answer9,
                AnswerAnswer10 = ans.answer10,
                AnswerAnswer11 = ans.answer11,
                AnswerAnswer12 = ans.answer12,
            }
                    ).ToList();

            if (list != null && list.Count > 0)  //
            {
                try
                {
                    NPOI.HSSF.UserModel.HSSFWorkbook book  = new NPOI.HSSF.UserModel.HSSFWorkbook();
                    NPOI.SS.UserModel.ISheet         sheet = book.CreateSheet("问卷数据下载");
                    //
                    NPOI.SS.UserModel.IRow rowHeader = sheet.CreateRow(0);
                    sheet.SetColumnWidth(0, 12 * 256);
                    sheet.SetColumnWidth(1, 10 * 256);
                    sheet.SetColumnWidth(2, 15 * 256);
                    sheet.SetColumnWidth(3, 18 * 256);
                    sheet.SetColumnWidth(4, 20 * 256);
                    sheet.SetColumnWidth(5, 25 * 256);
                    ICellStyle      style       = book.CreateCellStyle();
                    HSSFColor       color       = new HSSFColor.BLACK();
                    FillPatternType fillPattern = FillPatternType.SOLID_FOREGROUND;//灰色背景
                    HSSFColor       backGround  = new HSSFColor.GREY_25_PERCENT();
                    IFont           font        = ExportData.GetFontStyle(book, "宋体", color, 11);
                    //设置单元格的样式:水平对齐居中
                    style = ExportData.GetCellStyle(book, font, fillPattern, backGround, HorizontalAlignment.CENTER, VerticalAlignment.CENTER);


                    ICell cell1 = rowHeader.CreateCell(0);
                    cell1.SetCellValue("姓名");
                    //将新的样式赋给单元格
                    cell1.CellStyle = style;

                    ICell cell2 = rowHeader.CreateCell(1);
                    cell2.SetCellValue("编号");
                    cell2.CellStyle = style;

                    ICell cell3 = rowHeader.CreateCell(2);
                    cell3.SetCellValue("手机号码");
                    cell3.CellStyle = style;

                    ICell cell4 = rowHeader.CreateCell(3);
                    cell4.SetCellValue("第1题");
                    cell4.CellStyle = style;

                    ICell cell5 = rowHeader.CreateCell(4);
                    cell5.SetCellValue("第2题");
                    cell5.CellStyle = style;

                    ICell cell6 = rowHeader.CreateCell(5);
                    cell6.SetCellValue("第3题");
                    cell6.CellStyle = style;

                    ICell cell7 = rowHeader.CreateCell(6);
                    cell7.SetCellValue("第4题");
                    cell7.CellStyle = style;

                    ICell cell8 = rowHeader.CreateCell(7);
                    cell8.SetCellValue("第5题");
                    cell8.CellStyle = style;

                    ICell cell9 = rowHeader.CreateCell(8);
                    cell9.SetCellValue("第6题");
                    cell9.CellStyle = style;

                    ICell cell10 = rowHeader.CreateCell(9);
                    cell10.SetCellValue("第7题");
                    cell10.CellStyle = style;
                    ICell cell11 = rowHeader.CreateCell(10);
                    cell11.SetCellValue("第8题");
                    cell11.CellStyle = style;

                    ICell cell12 = rowHeader.CreateCell(11);
                    cell12.SetCellValue("第9题");
                    cell12.CellStyle = style;

                    ICell cell13 = rowHeader.CreateCell(12);
                    cell13.SetCellValue("第10题");
                    cell13.CellStyle = style;

                    ICell cell14 = rowHeader.CreateCell(13);
                    cell14.SetCellValue("第11题");
                    cell14.CellStyle = style;

                    ICell cell15 = rowHeader.CreateCell(14);
                    cell15.SetCellValue("第12题");
                    cell15.CellStyle = style;

                    ICellStyle cellStyle = book.CreateCellStyle();
                    cellStyle.Alignment         = HorizontalAlignment.CENTER;
                    cellStyle.VerticalAlignment = VerticalAlignment.CENTER;
                    IFont rowfont = book.CreateFont();
                    rowfont.FontName           = "宋体";
                    rowfont.FontHeightInPoints = (short)11;
                    rowfont.Color = color.GetIndex();
                    cellStyle.SetFont(rowfont);
                    //
                    NPOI.SS.UserModel.IRow row = null;
                    for (int i = 0; i < list.Count; i++)
                    {
                        RecordModel model = list[i];
                        row = sheet.CreateRow(i + 1);
                        ICell rowcell1 = row.CreateCell(0);
                        rowcell1.SetCellValue(model.AnswerName);
                        rowcell1.CellStyle = cellStyle;
                        ICell rowcell2 = row.CreateCell(1);
                        rowcell2.SetCellValue(model.AnswerNumber);
                        rowcell2.CellStyle = cellStyle;

                        ICell rowcell3 = row.CreateCell(2);
                        rowcell3.SetCellValue(model.AnswerPhone);
                        rowcell3.CellStyle = cellStyle;

                        ICell rowcell4 = row.CreateCell(3);
                        rowcell4.SetCellValue(model.AnswerAnswer1);
                        rowcell4.CellStyle = cellStyle;

                        ICell rowcell5 = row.CreateCell(4);
                        rowcell5.SetCellValue(model.AnswerAnswer2);
                        rowcell5.CellStyle = cellStyle;

                        ICell rowcell6 = row.CreateCell(5);
                        rowcell6.SetCellValue(model.AnswerAnswer3);
                        rowcell6.CellStyle = cellStyle;


                        ICell rowcell7 = row.CreateCell(6);
                        rowcell7.SetCellValue(model.AnswerAnswer4);
                        rowcell7.CellStyle = cellStyle;

                        ICell rowcell8 = row.CreateCell(7);
                        rowcell8.SetCellValue(model.AnswerAnswer5);
                        rowcell8.CellStyle = cellStyle;

                        ICell rowcell9 = row.CreateCell(8);
                        rowcell9.SetCellValue(model.AnswerAnswer6);
                        rowcell9.CellStyle = cellStyle;

                        ICell rowcell10 = row.CreateCell(9);
                        rowcell10.SetCellValue(model.AnswerAnswer7);
                        rowcell10.CellStyle = cellStyle;

                        ICell rowcell11 = row.CreateCell(10);
                        rowcell11.SetCellValue(model.AnswerAnswer8);
                        rowcell11.CellStyle = cellStyle;
                        ICell rowcell12 = row.CreateCell(11);
                        rowcell12.SetCellValue(model.AnswerAnswer9);
                        rowcell12.CellStyle = cellStyle;
                        ICell rowcell13 = row.CreateCell(12);
                        rowcell13.SetCellValue(model.AnswerAnswer10);
                        rowcell13.CellStyle = cellStyle;
                        ICell rowcell14 = row.CreateCell(13);
                        rowcell14.SetCellValue(model.AnswerAnswer11);
                        rowcell14.CellStyle = cellStyle;

                        ICell rowcell15 = row.CreateCell(14);
                        rowcell15.SetCellValue(model.AnswerAnswer12);
                        rowcell15.CellStyle = cellStyle;
                    }
                    //
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        book.Write(ms);

                        //string path = @"C:\Users\DNS\Desktop\导出参会人";
                        //string path = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\数据导出Excel";
                        // path = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\数据导出Excel";
                        string        path     = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Data\\";
                        DirectoryInfo excelDir = new DirectoryInfo(path);
                        //如果路径不存在就创建
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        string fileName = "mk_q" + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                        //string strDate = DateTime.Now.ToString("yyyy-MM-dd-HH ");

                        path = excelDir.FullName + fileName;
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                        using (Stream localFile = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            //ms.ToArray()转换为字节数组就是想要的图片源字节
                            localFile.Write(ms.ToArray(), 0, (int)ms.Length);
                        }
                        book = null;
                        ms.Close();
                        ms.Dispose();
                        //
                        string webAddress = System.Configuration.ConfigurationManager.AppSettings["mkDataPath"].ToString();

                        return(webAddress + fileName);
                    }
                }
                catch (Exception)
                {
                    //Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('导出格式错误');</script>");
                    return("Error1");
                }
            }
            else
            {
                return("Error2");
            }
        }
Beispiel #46
0
        // Pass in the device you want to connect to!
        public Form_Wacom_STU(String _message, Uri _url, WebBrowser _WebBrowser, Wacom_STU_Manager _STU, wgssSTU.IUsbDevice usbDevice)
        {
            WebBrowser = _WebBrowser;
            urlapp     = _url;
            STU        = _STU;
            Text       = _message;

            // This is a DPI aware application, so ensure you understand how .NET client coordinates work.
            // Testing using a Windows installation set to a high DPI is recommended to understand how
            // values get scaled or not.

            this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
            this.AutoScaleMode       = System.Windows.Forms.AutoScaleMode.Dpi;

            InitializeComponent();

            m_penData = new List <wgssSTU.IPenData>();

            m_tablet = new wgssSTU.Tablet();
            wgssSTU.ProtocolHelper protocolHelper = new wgssSTU.ProtocolHelper();

            // A more sophisticated applications should cycle for a few times as the connection may only be
            // temporarily unavailable for a second or so.
            // For example, if a background process such as Wacom STU Display
            // is running, this periodically updates a slideshow of images to the device.

            wgssSTU.IErrorCode ec = m_tablet.usbConnect(usbDevice, true);
            if (ec.value == 0)
            {
                m_capability  = m_tablet.getCapability();
                m_information = m_tablet.getInformation();
            }
            else
            {
                throw new Exception(ec.message);
            }

            this.SuspendLayout();
            this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
            this.AutoScaleMode       = System.Windows.Forms.AutoScaleMode.Dpi;

            // Set the size of the client window to be actual size,
            // based on the reported DPI of the monitor.

            Size clientSize = new Size((int)(m_capability.tabletMaxX / 2540F * 96F), (int)(m_capability.tabletMaxY / 2540F * 96F));

            this.ClientSize = clientSize;
            this.ResumeLayout();

            m_btns = new Button[3];
            if (usbDevice.idProduct != 0x00a2)
            {
                // Place the buttons across the bottom of the screen.

                int w2 = m_capability.screenWidth / 3;
                int w3 = m_capability.screenWidth / 3;
                int w1 = m_capability.screenWidth - w2 - w3;
                int y  = m_capability.screenHeight * 6 / 7;
                int h  = m_capability.screenHeight - y;

                m_btns[0].Bounds = new Rectangle(0, y, w1, h);
                m_btns[1].Bounds = new Rectangle(w1, y, w2, h);
                m_btns[2].Bounds = new Rectangle(w1 + w2, y, w3, h);
            }
            else
            {
                // The STU-300 is very shallow, so it is better to utilise
                // the buttons to the side of the display instead.

                int x = m_capability.screenWidth * 3 / 4;
                int w = m_capability.screenWidth - x;

                int h2 = m_capability.screenHeight / 3;
                int h3 = m_capability.screenHeight / 3;
                int h1 = m_capability.screenHeight - h2 - h3;

                m_btns[0].Bounds = new Rectangle(x, 0, w, h1);
                m_btns[1].Bounds = new Rectangle(x, h1, w, h2);
                m_btns[2].Bounds = new Rectangle(x, h1 + h2, w, h3);
            }
            m_btns[0].Text  = "OK";
            m_btns[1].Text  = "Clear";
            m_btns[2].Text  = "Cancel";
            m_btns[0].Click = new EventHandler(btnOk_Click);
            m_btns[1].Click = new EventHandler(btnClear_Click);
            m_btns[2].Click = new EventHandler(btnCancel_Click);


            // Disable color if the STU-520 bulk driver isn't installed.
            // This isn't necessary, but uploading colour images with out the driver
            // is very slow.

            // Calculate the encodingMode that will be used to update the image

            ushort idP = m_tablet.getProductId();

            wgssSTU.encodingFlag encodingFlag = (wgssSTU.encodingFlag)protocolHelper.simulateEncodingFlag(idP, 0);
            bool useColor = false;

            if ((encodingFlag & (wgssSTU.encodingFlag.EncodingFlag_16bit | wgssSTU.encodingFlag.EncodingFlag_24bit)) != 0)
            {
                if (m_tablet.supportsWrite())
                {
                    useColor = true;
                }
            }
            if ((encodingFlag & wgssSTU.encodingFlag.EncodingFlag_24bit) != 0)
            {
                m_encodingMode = m_tablet.supportsWrite() ? wgssSTU.encodingMode.EncodingMode_24bit_Bulk : wgssSTU.encodingMode.EncodingMode_24bit;
            }
            else if ((encodingFlag & wgssSTU.encodingFlag.EncodingFlag_16bit) != 0)
            {
                m_encodingMode = m_tablet.supportsWrite() ? wgssSTU.encodingMode.EncodingMode_16bit_Bulk : wgssSTU.encodingMode.EncodingMode_16bit;
            }
            else
            {
                // assumes 1bit is available
                m_encodingMode = wgssSTU.encodingMode.EncodingMode_1bit;
            }



            // Size the bitmap to the size of the LCD screen.
            // This application uses the same bitmap for both the screen and client (window).
            // However, at high DPI, this bitmap will be stretch and it would be better to
            // create individual bitmaps for screen and client at native resolutions.
            m_bitmap = new Bitmap(m_capability.screenWidth, m_capability.screenHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            {
                Graphics gfx = Graphics.FromImage(m_bitmap);
                gfx.Clear(Color.White);

                // Uses pixels for units as DPI won't be accurate for tablet LCD.
                Font         font = new Font(FontFamily.GenericSansSerif, m_btns[0].Bounds.Height / 2F, GraphicsUnit.Pixel);
                StringFormat sf   = new StringFormat();
                sf.Alignment     = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;

                if (useColor)
                {
                    gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
                }
                else
                {
                    // Anti-aliasing should be turned off for monochrome devices.
                    gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
                }

                // Draw the buttons
                for (int i = 0; i < m_btns.Length; ++i)
                {
                    if (useColor)
                    {
                        gfx.FillRectangle(Brushes.LightGray, m_btns[i].Bounds);
                    }
                    gfx.DrawRectangle(Pens.Black, m_btns[i].Bounds);
                    gfx.DrawString(m_btns[i].Text, font, Brushes.Black, m_btns[i].Bounds, sf);
                }

                gfx.Dispose();
                font.Dispose();

                // Finally, use this bitmap for the window background.
                this.BackgroundImage       = m_bitmap;
                this.BackgroundImageLayout = ImageLayout.Stretch;
            }

            // Now the bitmap has been created, it needs to be converted to device-native
            // format.
            {
                // Unfortunately it is not possible for the native COM component to
                // understand .NET bitmaps. We have therefore convert the .NET bitmap
                // into a memory blob that will be understood by COM.

                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                m_bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                m_bitmapData   = (byte[])protocolHelper.resizeAndFlatten(stream.ToArray(), 0, 0, (uint)m_bitmap.Width, (uint)m_bitmap.Height, m_capability.screenWidth, m_capability.screenHeight, (byte)m_encodingMode, wgssSTU.Scale.Scale_Fit, 0, 0);
                protocolHelper = null;
                stream.Dispose();
            }

            // If you wish to further optimize image transfer, you can compress the image using
            // the Zlib algorithm.

            bool useZlibCompression = false;

            if (!useColor && useZlibCompression)
            {
                // m_bitmapData = compress_using_zlib(m_bitmapData); // insert compression here!
                m_encodingMode |= wgssSTU.encodingMode.EncodingMode_Zlib;
            }

            // Calculate the size and cache the inking pen.

            SizeF s          = this.AutoScaleDimensions;
            float inkWidthMM = 0.7F;

            m_penInk          = new Pen(Color.DarkBlue, inkWidthMM / 25.4F * ((s.Width + s.Height) / 2F));
            m_penInk.StartCap = m_penInk.EndCap = System.Drawing.Drawing2D.LineCap.Round;
            m_penInk.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;


            // Add the delagate that receives pen data.
            m_tablet.onPenData            += new wgssSTU.ITabletEvents2_onPenDataEventHandler(onPenData);
            m_tablet.onGetReportException += new wgssSTU.ITabletEvents2_onGetReportExceptionEventHandler(onGetReportException);


            // Initialize the screen
            clearScreen();

            // Enable the pen data on the screen (if not already)
            m_tablet.setInkingMode(0x01);
        }
        /// <summary>
        /// 獲得postdata的串
        /// </summary>
        /// <returns></returns>
        private object GetPostDataData(HttpParameter hp, ResponseObject hd)
        {
            if (hp.ContentType.ToLower().IndexOf("/json") > 0)
            {
                return(hp.PostData.ToJSONString());
            }
            else if (hp.ContentType == "multipart/form-data")
            {
                /*
                 * multipart/form-data的请求内容格式如下
                 * Content-Type: multipart/form-data; boundary=AaB03x
                 *
                 * --boundary
                 * Content-Disposition: form-data; name="submit-name"
                 *
                 * Larry
                 * --boundary
                 * Content-Disposition: form-data; name="file"; filename="file1.dat"
                 * Content-Type: application/octet-stream
                 *
                 * ... contents of file1.dat ...
                 * --boundary--
                 * */

                var boundary     = String.Format("----------{0:N}", Guid.NewGuid());
                var _contenttype = hp.ContentType + ";boundary=" + boundary;

                Stream formDataStream = new System.IO.MemoryStream();

                foreach (var k in hp.PostData.Keys)
                {
                    var item = hp.PostData.GetValue(k);
                    if (item is FrameDLRObject)
                    {
                        dynamic dobj = item;
                        if (ComFunc.nvl(dobj.contenttype) == "application/octet-stream")
                        {
                            var name            = ComFunc.nvl(dobj.name);
                            var filename        = ComFunc.nvl(dobj.filename);
                            var filecontenttype = ComFunc.nvl(dobj.filecontenttype);
                            var filecontent     = (byte[])dobj.formitem;

                            // Add just the first part of this param, since we will write the file data directly to the Stream
                            string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
                                                          boundary,
                                                          name,
                                                          filename,
                                                          filecontenttype != "" ? filecontenttype : "application/octet-stream");

                            formDataStream.Write(hp.ContentEncoding.GetBytes(header), 0, hp.ContentEncoding.GetByteCount(header));

                            // Write the file data directly to the Stream, rather than serializing it to a string.
                            formDataStream.Write(filecontent, 0, filecontent.Length);
                        }
                        else
                        {
                            var name     = ComFunc.nvl(dobj.name);
                            var formitem = ComFunc.nvl(dobj.formitem);
                            // Add just the first part of this param, since we will write the file data directly to the Stream
                            string header = string.Format("--{0}\r\nContent-Disposition: form-data; name={1}\r\n\r\n",
                                                          boundary,
                                                          name);

                            formDataStream.Write(hp.ContentEncoding.GetBytes(header), 0, hp.ContentEncoding.GetByteCount(header));
                            var bytes = Encoding.UTF8.GetBytes(formitem);
                            // Write the file data directly to the Stream, rather than serializing it to a string.
                            formDataStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                }


                // Add the end of the request.  Start with a newline
                string footer = "\r\n--" + boundary + "--\r\n";
                formDataStream.Write(hp.ContentEncoding.GetBytes(footer), 0, hp.ContentEncoding.GetByteCount(footer));

                // Dump the Stream into a byte[]
                formDataStream.Position = 0;
                byte[] formData = new byte[formDataStream.Length];
                formDataStream.Read(formData, 0, formData.Length);
                formDataStream.Dispose();

                return(formData);
            }//以put的方式发送文件内容
            else if (hp.ContentType.ToLower().StartsWith("put/"))
            {
                if (hp.PostData.Keys.Count > 0)
                {
                    var item = hp.PostData.GetValue(hp.PostData.Keys[0]);
                    if (item is FrameDLRObject)
                    {
                        dynamic dobj = item;
                        //只处理第一笔资料
                        //var name = ComFunc.nvl(dobj.name);
                        //var filename = ComFunc.nvl(dobj.filename);
                        //var filecontenttype = ComFunc.nvl(dobj.filecontenttype);
                        var filecontent = (byte[])dobj.formitem;

                        return(filecontent);
                    }
                    else if (item is byte[])
                    {
                        return((byte[])item);
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            else if (hp.ContentType.ToLower().IndexOf("/xml") > 0)
            {
                return(hp.PostData.ToXml());
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                foreach (string s in hp.PostData.Keys)
                {
                    sb.AppendFormat("&{0}={1}", s, hp.PostData.GetValue(s));
                }
                return(sb.Length > 0 ? sb.ToString().Substring(1) : "");
            }
        }
Beispiel #48
0
        private void SavePic(BitmapSource bitmap)
        {
            TestingData.ProfilePhoto = new BitmapImage();

            JpegBitmapEncoder encoder = new JpegBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.QualityLevel = 100;

            //HACK
            TestingData.SubjectCode = "11";

            var PICTURE_FILENAME = string.Format("{0}.jpg", TestingData.sheet._id);
            //var PICTURE_FILENAME = "";
            string serverPath = @"C:\PCTest\pic\";
            var    picPath    = System.IO.Path.Combine(serverPath, PICTURE_FILENAME);

            if (!Directory.Exists(serverPath))
            {
                Directory.CreateDirectory(serverPath);
            }

            using (var fstream = new System.IO.FileStream(picPath, FileMode.Create))
            {
                encoder.Save(fstream);
                fstream.Flush();
                fstream.Close();
                fstream.Dispose();

                webcam.Stop();
                _isCameraOn = false;
            }

            var profileBitmap = BitmapFromSource(bitmap);

            ProfilePhoto = profileBitmap;


            TestingData.ProfilePhoto = new BitmapImage();
            Uri uri = new Uri(picPath, UriKind.RelativeOrAbsolute);

            TestingData.ProfilePhoto.BeginInit();
            TestingData.ProfilePhoto.UriSource   = uri;
            TestingData.ProfilePhoto.CacheOption = BitmapCacheOption.OnLoad;
            TestingData.ProfilePhoto.EndInit();

            //save image to server
            byte[] bit = new byte[0];

            using (var stream = new System.IO.MemoryStream())
            {
                JpegBitmapEncoder encoder2 = new JpegBitmapEncoder();
                encoder2.Frames.Add(BitmapFrame.Create(bitmap));
                encoder2.QualityLevel = 100;
                encoder2.Save(stream);
                bit = stream.ToArray();

                OnsiteServices svc = new OnsiteServices();

                PicRequest picre = new PicRequest
                {
                    FileName = PICTURE_FILENAME,
                    bytes    = bit
                };
                svc.SavePic(picre);

                stream.Flush();
                stream.Close();
                stream.Dispose();
            }
        }
        /// <summary>
        /// 生成读取直接节点数据信息的内容
        /// </summary>
        /// <param name="slot">PLC所在的槽号</param>
        /// <param name="cips">cip指令内容</param>
        /// <returns>最终的指令值</returns>
        public static byte[] PackCommandSpecificData(byte slot, params byte[][] cips)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream( );
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x01);       // 超时
            ms.WriteByte(0x00);
            ms.WriteByte(0x02);       // 项数
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);       // 连接的地址项
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);       // 长度
            ms.WriteByte(0x00);
            ms.WriteByte(0xB2);       // 连接的项数
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);       // 后面数据包的长度,等全部生成后在赋值
            ms.WriteByte(0x00);

            ms.WriteByte(0x52);       // 服务
            ms.WriteByte(0x02);       // 请求路径大小
            ms.WriteByte(0x20);       // 请求路径
            ms.WriteByte(0x06);
            ms.WriteByte(0x24);
            ms.WriteByte(0x01);
            ms.WriteByte(0x0A);       // 超时时间
            ms.WriteByte(0xF0);
            ms.WriteByte(0x00);       // CIP指令长度
            ms.WriteByte(0x00);

            int count = 0;

            if (cips.Length == 1)
            {
                ms.Write(cips[0], 0, cips[0].Length);
                count += cips[0].Length;
            }
            else
            {
                ms.WriteByte(0x0A);     // 固定
                ms.WriteByte(0x02);
                ms.WriteByte(0x20);
                ms.WriteByte(0x02);
                ms.WriteByte(0x24);
                ms.WriteByte(0x01);
                count += 8;

                ms.Write(BitConverter.GetBytes((ushort)cips.Length), 0, 2);      // 写入项数
                ushort offect = (ushort)(0x02 + 2 * cips.Length);
                count += 2 * cips.Length;

                for (int i = 0; i < cips.Length; i++)
                {
                    ms.Write(BitConverter.GetBytes(offect), 0, 2);
                    offect = (ushort)(offect + cips[i].Length);
                }

                for (int i = 0; i < cips.Length; i++)
                {
                    ms.Write(cips[i], 0, cips[i].Length);
                    count += cips[i].Length;
                }
            }
            ms.WriteByte(0x01);       // Path Size
            ms.WriteByte(0x00);
            ms.WriteByte(0x01);       // port
            ms.WriteByte(slot);

            byte[] data = ms.ToArray( );
            ms.Dispose( );
            BitConverter.GetBytes((short)count).CopyTo(data, 24);
            data[14] = BitConverter.GetBytes((short)(data.Length - 16))[0];
            data[15] = BitConverter.GetBytes((short)(data.Length - 16))[1];
            return(data);
        }
Beispiel #50
0
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="savepath">导出文件完整路径(包括文件名)</param>
        /// <param name="dt">数据源</param>
        /// <param name="widths">列宽集合</param>
        public static void ExportExcel(string savePath, DataTable dt, string title, List <int> widths = null)
        {
            IWorkbook book = null;

            book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            ISheet sheet = book.CreateSheet("数据清单");

            var headerIndex = 0;

            if (title.Length > 0)
            {
                //第1行添加标题
                sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Rows[0].ItemArray.Length - 1));
                headerIndex = 1;
            }
            //设置行高   Height的单位是1/20个点。例:设置高度为30个点
            IRow row = sheet.CreateRow(0);

            row.Height = 30 * 20;


            ICell titleCell = row.CreateCell(0);

            titleCell.SetCellValue(title);
            titleCell.CellStyle.Alignment         = HorizontalAlignment.Left;
            titleCell.CellStyle.VerticalAlignment = VerticalAlignment.Center;
            IFont titleFont = book.CreateFont();

            titleFont.FontHeightInPoints = 11;
            titleCell.CellStyle.SetFont(titleFont);

            if (widths != null)
            {
                //设置列宽
                for (int i = 0; i < widths.Count; i++)
                {
                    sheet.SetColumnWidth(i, widths[i] * 256); //列宽单位为 1/256个字符
                }
            }

            int index = 0;

            // 添加表头
            row = sheet.CreateRow(headerIndex);
            foreach (DataColumn item in dt.Columns)
            {
                ICell cell = row.CreateCell(index);
                cell.SetCellType(CellType.String);
                cell.SetCellValue(item.Caption);
                index++;
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                index = 0;
                row   = sheet.CreateRow(i + headerIndex + 1); // 添加数据  从第3行开始
                foreach (DataColumn item in dt.Columns)
                {
                    ICell cell = row.CreateCell(index);
                    cell.SetCellType(CellType.String);
                    cell.SetCellValue(dt.Rows[i][item.ColumnName].ToString());
                    index++;
                }
            }

            // 写入
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            book = null;

            using (FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write))
            {
                byte[] data = ms.ToArray();
                fs.Write(data, 0, data.Length);
                fs.Flush();
            }
            ms.Close();
            ms.Dispose();
        }
Beispiel #51
0
        //Fonction: Envoie de l'image
        public bool Envoi_image(System.Drawing.Image image)
        {
            Program.LogFich.Info("[Wacom_STU] Envoi_image() - Envoie des données");
            bool b = true;

            MemoryStream mstImage = new MemoryStream();

            image.Save(mstImage, System.Drawing.Imaging.ImageFormat.Jpeg);

            byte[] data = mstImage.GetBuffer();
            mstImage.Dispose();
            //StringBuilder dataSB = new StringBuilder();
            //IntPtr dataPtr = Marshal.AllocHGlobal(data.Length);

            /*
             * for (int i = 0; i < data.Length; ++i)
             * {
             *  data[i] = Marshal.ReadByte(dataPtr, i);
             *  dataSB.Append(data[i]);
             * }
             */

            try
            {
                Uri url = new Uri(urlapp.ToString() + "devices/TOPAZ_SIGPLUS.asp");

                //StringBuilder sb = new StringBuilder();
                //sb.Append("type_peripherique=").Append(HttpUtility.UrlEncode("TOPAZ_SIGPLUS", Encoding.ASCII));
                //sb.Append("&machine=").Append(HttpUtility.UrlEncode(Functions.getHost(), Encoding.ASCII));
                //sb.Append("data=").Append(HttpUtility.UrlEncode(data.ToString(), Encoding.ASCII));
                //sb.Append("&datalen=").Append(HttpUtility.UrlEncode(data.Length.ToString(), Encoding.ASCII));

                string boundary = DateTime.Now.Ticks.ToString("x");

                MemoryStream memStream = new System.IO.MemoryStream();

                byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                string headerTemplate = "Content-Disposition: form-data; name=\"signature\"; filename=\"signature.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";
                byte[] headerbytes    = System.Text.Encoding.ASCII.GetBytes(headerTemplate);

                memStream.Write(boundarybytes, 0, boundarybytes.Length);
                memStream.Write(headerbytes, 0, headerbytes.Length);
                memStream.Write(data, 0, data.Length);
                memStream.Write(boundarybytes, 0, boundarybytes.Length);

                memStream.Position = 0;
                byte[] postBytes = memStream.GetBuffer();
                memStream.Dispose();

                string s = System.Text.Encoding.ASCII.GetString(postBytes);

                StringBuilder adr = new StringBuilder();
                adr.Append(url.ToString());
                adr.Append(this.WebBrowser.Url.Query);
                Uri adresse = new Uri(adr.ToString());
                WebBrowser.Navigate(adresse, "", postBytes, "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n" + "Content-Length: " + postBytes.Length + "\r\n" + "\r\n");

                Program.LogFich.Info("[Wacom_STU] Envoi_image() - Envoie termine - Trame envoyee = " + postBytes.ToString());
            }
            catch (Exception e)
            {
                b = false;

                Program.LogFich.Error("[Wacom_STU] Envoi_image() - Erreur d'envoie = " + e.ToString());
            }
            return(b);
        }
Beispiel #52
0
        protected virtual void Export()
        {
            if (this.bTabControl1.SelectedIndex == 0)
            {
                //this.bsprData.Export(false);

                string file     = "";
                bool   bProtect = this.bsprData.ActiveSheet.Protect;

                this.bsprData.ActiveSheet.Protect = false;

                SaveFileDialog openDlg = new SaveFileDialog();
                openDlg.Filter          = "Excel Files (*.xls)|*.xls";
                openDlg.FileName        = "";
                openDlg.DefaultExt      = ".xls";
                openDlg.CheckFileExists = false;
                openDlg.CheckPathExists = true;

                DialogResult res = openDlg.ShowDialog();

                if (res != DialogResult.OK)
                {
                    return;
                }

                file = openDlg.FileName;

                FarPoint.Win.Spread.SheetView spread_Sheet1 = new FarPoint.Win.Spread.SheetView();
                spread_Sheet1.SheetName = "_ExcelExportSheet";

                FarPoint.Win.Spread.FpSpread spread = new FarPoint.Win.Spread.FpSpread();

                spread.Sheets.Add(spread_Sheet1);
                spread_Sheet1.Visible = true;
                spread.ActiveSheet    = spread_Sheet1;

                byte[] buffer = null;
                System.IO.MemoryStream stream = null;
                this.bsprData.SetFilterVisible(false);

                try
                {
                    stream = new System.IO.MemoryStream();
                    this.bsprData.Save(stream, false);
                    buffer = stream.ToArray();
                    stream.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                        stream = null;
                    }
                }

                stream = new System.IO.MemoryStream(buffer);
                spread.Open(stream);

                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }

                for (int i = spread.ActiveSheet.Columns.Count - 1; i >= 0; i--)
                {
                    if (!spread.ActiveSheet.Columns[i].Visible)
                    {
                        spread.ActiveSheet.Columns[i].Remove();
                    }
                }

                spread.SaveExcel(file, FarPoint.Win.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly);
                this.bsprData.ActiveSheet.Protect = bProtect;

                string strMessage = "It was saved successfully. Do you open saved file?";

                DialogResult result = MessageBox.Show(strMessage, "Open", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Classes\Applications\EXCEL.EXE");

                    if (key == null)
                    {
                        MSGHandler.DisplayMessage(MSGType.Error, "SPC_INFO_NEED_MS_OFFICE", null, null);
                    }
                    else
                    {
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo.FileName = file;
                        process.Start();
                    }
                }
            }
            else
            {
                string file     = "";
                bool   bProtect = this.bsprRawData.ActiveSheet.Protect;

                this.bsprRawData.ActiveSheet.Protect = false;

                SaveFileDialog openDlg = new SaveFileDialog();
                openDlg.Filter          = "Excel Files (*.xls)|*.xls";
                openDlg.FileName        = "";
                openDlg.DefaultExt      = ".xls";
                openDlg.CheckFileExists = false;
                openDlg.CheckPathExists = true;

                DialogResult res = openDlg.ShowDialog();

                if (res != DialogResult.OK)
                {
                    return;
                }

                file = openDlg.FileName;

                FarPoint.Win.Spread.SheetView spread_Sheet1 = new FarPoint.Win.Spread.SheetView();
                spread_Sheet1.SheetName = "_ExcelExportSheet";

                FarPoint.Win.Spread.FpSpread spread = new FarPoint.Win.Spread.FpSpread();

                spread.Sheets.Add(spread_Sheet1);
                spread_Sheet1.Visible = true;
                spread.ActiveSheet    = spread_Sheet1;

                byte[] buffer = null;
                System.IO.MemoryStream stream = null;
                this.bsprRawData.SetFilterVisible(false);

                try
                {
                    stream = new System.IO.MemoryStream();
                    this.bsprRawData.Save(stream, false);
                    buffer = stream.ToArray();
                    stream.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                        stream = null;
                    }
                }

                stream = new System.IO.MemoryStream(buffer);
                spread.Open(stream);

                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }

                for (int i = spread.ActiveSheet.Columns.Count - 1; i >= 0; i--)
                {
                    if (!spread.ActiveSheet.Columns[i].Visible)
                    {
                        spread.ActiveSheet.Columns[i].Remove();
                    }
                }

                spread.SaveExcel(file, FarPoint.Win.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly);
                this.bsprRawData.ActiveSheet.Protect = bProtect;

                string strMessage = "It was saved successfully. Do you open saved file?";

                DialogResult result = MessageBox.Show(strMessage, "Open", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Classes\Applications\EXCEL.EXE");

                    if (key == null)
                    {
                        MSGHandler.DisplayMessage(MSGType.Error, "SPC_INFO_NEED_MS_OFFICE", null, null);
                    }
                    else
                    {
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo.FileName = file;
                        process.Start();
                    }
                }
            }
        }
Beispiel #53
0
        protected void ExportButton_Click(object sender, EventArgs e)
        {
            ProductSearchInfo productSearch = new ProductSearchInfo();

            productSearch.IsSale  = (int)BoolType.True;
            productSearch.Name    = ShopCommon.ConvertToT <string>(Name.Text);
            productSearch.ClassId = ShopCommon.ConvertToT <string>(ClassID.Text);
            productSearch.BrandId = ShopCommon.ConvertToT <int>(BrandID.Text);

            var dataProduct = ProductBLL.SearchList(1, 1000, productSearch, ref Count);
            var dataStatis  = StatisticsSaleStop(dataProduct);

            NPOI.HSSF.UserModel.HSSFWorkbook book  = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet         sheet = book.CreateSheet("Sheet1");
            sheet.DefaultColumnWidth = 18;
            sheet.CreateFreezePane(0, 2, 0, 2);

            NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
            row.Height = 20 * 20;
            row.CreateCell(0).SetCellValue("商品名称");
            row.CreateCell(1).SetCellValue("最近一次销售");
            row.CreateCell(2).SetCellValue("");
            row.CreateCell(3).SetCellValue("");
            row.CreateCell(4).SetCellValue("滞销天数");

            NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(1);
            row2.Height = 20 * 20;
            row2.CreateCell(0).SetCellValue("");
            row2.CreateCell(1).SetCellValue("订单号");
            row2.CreateCell(2).SetCellValue("销售数量");
            row2.CreateCell(3).SetCellValue("日期");
            row2.CreateCell(4).SetCellValue("");

            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 1, 0, 0));
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 1, 4, 4));
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 1, 3));

            //设置表头格式
            var headFont = book.CreateFont();

            headFont.Boldweight         = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
            headFont.FontHeightInPoints = 10;
            var headStyle = book.CreateCellStyle();

            headStyle.SetFont(headFont);
            headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            headStyle.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            headStyle.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderRight       = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderTop         = NPOI.SS.UserModel.BorderStyle.Thin;
            foreach (var cell in row.Cells)
            {
                cell.CellStyle = headStyle;
            }
            foreach (var cell in row2.Cells)
            {
                cell.CellStyle = headStyle;
            }

            foreach (var product in dataProduct)
            {
                DataRow dr = ReadSaleStop(product.Id, dataStatis);

                NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(dataProduct.IndexOf(product) + 2);
                dataRow.CreateCell(0).SetCellValue(product.Name);
                if (dr != null)
                {
                    dataRow.CreateCell(1).SetCellValue(Convert.ToString(dr["OrderNumber"]));
                    dataRow.CreateCell(2).SetCellValue(Convert.ToString(dr["BuyCount"]));
                    dataRow.CreateCell(3).SetCellValue(Convert.ToString(dr["AddDate"]));
                    dataRow.CreateCell(4).SetCellValue(Convert.ToString((DateTime.Now.Date - Convert.ToDateTime(dr["AddDate"]).Date).Days));
                }
                else
                {
                    dataRow.CreateCell(1).SetCellValue("");
                    dataRow.CreateCell(2).SetCellValue("");
                    dataRow.CreateCell(3).SetCellValue("");
                    dataRow.CreateCell(4).SetCellValue("");
                }

                var style = book.CreateCellStyle();
                style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
                foreach (var cell in dataRow.Cells)
                {
                    cell.CellStyle = style;
                }
            }

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            Response.BinaryWrite(ms.ToArray());
            book = null;
            ms.Close();
            ms.Dispose();
            Response.End();
        }
Beispiel #54
-1
        public void Test_ReadLine()
        {
            const string raw = "line1\r\nline2\nline3";
            var stream = new MemoryStream(Encoding.ASCII.GetBytes(raw));

            var line = stream.ReadLine();
            Assert.AreEqual("line1", line);
            Assert.AreEqual(7, stream.Position);

            line = stream.ReadLine();
            Assert.AreEqual("line2", line);
            Assert.AreEqual(13, stream.Position);

            line = stream.ReadLine();
            Assert.AreEqual("line3", line);
            Assert.AreEqual(18, stream.Position);

            stream.Seek(2, SeekOrigin.Begin);
            line = stream.ReadLine();
            Assert.AreEqual("ne1", line);
            Assert.AreEqual(7, stream.Position);

            stream.Seek(9, SeekOrigin.Begin);
            line = stream.ReadLine();
            Assert.AreEqual("ne2", line);
            Assert.AreEqual(13, stream.Position);

            stream.Dispose();
        }