public void TestExtractArchiveTarGzCreateContainer()
        {
            CloudFilesProvider provider = (CloudFilesProvider)Bootstrapper.CreateObjectStorageProvider();
            string containerName = TestContainerPrefix + Path.GetRandomFileName();
            string sourceFileName = "DarkKnightRises.jpg";
            byte[] content = File.ReadAllBytes("DarkKnightRises.jpg");
            using (MemoryStream outputStream = new MemoryStream())
            {
                using (GZipOutputStream gzoStream = new GZipOutputStream(outputStream))
                {
                    gzoStream.IsStreamOwner = false;
                    gzoStream.SetLevel(9);
                    using (TarOutputStream tarOutputStream = new TarOutputStream(gzoStream))
                    {
                        tarOutputStream.IsStreamOwner = false;
                        TarEntry entry = TarEntry.CreateTarEntry(containerName + '/' + sourceFileName);
                        entry.Size = content.Length;
                        tarOutputStream.PutNextEntry(entry);
                        tarOutputStream.Write(content, 0, content.Length);
                        tarOutputStream.CloseEntry();
                        tarOutputStream.Close();
                    }
                }

                outputStream.Flush();
                outputStream.Position = 0;
                ExtractArchiveResponse response = provider.ExtractArchive(outputStream, "", ArchiveFormat.TarGz);
                Assert.IsNotNull(response);
                Assert.AreEqual(1, response.CreatedFiles);
                Assert.IsNotNull(response.Errors);
                Assert.AreEqual(0, response.Errors.Count);
            }

            using (MemoryStream downloadStream = new MemoryStream())
            {
                provider.GetObject(containerName, sourceFileName, downloadStream, verifyEtag: true);
                Assert.AreEqual(content.Length, GetContainerObjectSize(provider, containerName, sourceFileName));

                downloadStream.Position = 0;
                byte[] actualData = new byte[downloadStream.Length];
                downloadStream.Read(actualData, 0, actualData.Length);
                Assert.AreEqual(content.Length, actualData.Length);
                using (MD5 md5 = MD5.Create())
                {
                    byte[] contentMd5 = md5.ComputeHash(content);
                    byte[] actualMd5 = md5.ComputeHash(actualData);
                    Assert.AreEqual(BitConverter.ToString(contentMd5), BitConverter.ToString(actualMd5));
                }
            }

            /* Cleanup
             */
            provider.DeleteContainer(containerName, deleteObjects: true);
        }
示例#2
0
文件: Clone.cs 项目: ggeurts/nhive
        private static void realtester <U>(U extensible) where U : class, IExtensible <int>, new()
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
                new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.Stream stream = new System.IO.MemoryStream();
            formatter.Serialize(stream, extensible);
            stream.Flush();
            stream.Seek(0L, System.IO.SeekOrigin.Begin);
            object clone = formatter.Deserialize(stream);

            Assert.IsNotNull(clone);
            Assert.AreEqual(typeof(U), clone.GetType(),
                            String.Format("Wrong type '{0}' of clone of '{1}'", clone.GetType(), typeof(U)));
            U theClone = clone as U;

            Assert.IsTrue(theClone.Check(), "Clone does not pass Check()");
            if (typeof(ICollection <int>).IsAssignableFrom(typeof(U)))
            {
                Assert.IsTrue(EqualityComparer <U> .Default.Equals(extensible, theClone), "Clone has wrong contents");
            }
            else //merely extensible
            {
                Assert.IsTrue(IC.eq(theClone, extensible.ToArray()), "Clone has wrong contents");
            }
        }
示例#3
0
        public async Task <IActionResult> GetPay(int?id)
        {
            Pay pay = new Pay();

            var order = await _context.Orders
                        .Include(o => o.Car)
                        .Include(o => o.Driver)
                        .FirstOrDefaultAsync(m => m.OrderID == id);

            pay.Date  = order.OrderDate;
            pay.Model = order.Car.FullName;
            pay.Name  = order.Driver.FullName;
            pay.Price = (int)order.Price;

            System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(Pay));
            var stream = new System.IO.MemoryStream();

            xml.Serialize(stream, pay);
            stream.Flush();
            var data = stream.GetBuffer();

            stream.Close();
            string name = order.OrderDate.Date.Month.ToString() + " " + order.OrderDate.Date.Day.ToString() + "_" + order.OrderID;

            return(File(data, "application/xhtml+xml", name + ".xml"));
        }
示例#4
0
        private static void OtherWaysToGetReport()
        {
            string report = @"d:\bla.rdl";

            // string lalal = System.IO.File.ReadAllText(report);
            // byte[] foo = System.Text.Encoding.UTF8.GetBytes(lalal);
            // byte[] foo = System.IO.File.ReadAllBytes(report);

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {

                using (System.IO.FileStream file = new System.IO.FileStream(report, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    byte[] bytes = new byte[file.Length];
                    file.Read(bytes, 0, (int)file.Length);
                    ms.Write(bytes, 0, (int)file.Length);
                    ms.Flush();
                    ms.Position = 0;
                }

                using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("resource"))
                {
                    using (System.IO.TextReader reader = new System.IO.StreamReader(ms))
                    {
                        // rv.LocalReport.LoadReportDefinition(reader);
                    }
                }

                using (System.IO.TextReader reader = System.IO.File.OpenText(report))
                {
                    // rv.LocalReport.LoadReportDefinition(reader);
                }

            }
        }
示例#5
0
        private IEnumerable <VersionDescription> ParseResponse(WebHeaderCollection header, byte[] body)
        {
            switch (header.Get("Content-Encoding"))
            {
            case "gzip":
                using (var dst = new System.IO.MemoryStream())
                    using (var s = new System.IO.Compression.GZipStream(new System.IO.MemoryStream(body), System.IO.Compression.CompressionMode.Decompress)) {
                        s.CopyTo(dst);
                        dst.Flush();
                        body = dst.ToArray();
                    }
                break;

            case "deflate":
                using (var dst = new System.IO.MemoryStream())
                    using (var s = new System.IO.Compression.DeflateStream(new System.IO.MemoryStream(body), System.IO.Compression.CompressionMode.Decompress)) {
                        s.CopyTo(dst);
                        dst.Flush();
                        body = dst.ToArray();
                    }
                break;

            default:
                break;
            }
            return(ParseAppCast(System.Text.Encoding.UTF8.GetString(body)));
        }
示例#6
0
        private static System.Drawing.Imaging.EncoderParameters getOptiumQuarity(long size, System.Drawing.Bitmap bmp, System.Drawing.Imaging.ImageCodecInfo ici)
        {
            long quality = 100;

            //EncoderParameterオブジェクトを1つ格納できる
            //EncoderParametersクラスの新しいインスタンスを初期化
            //ここでは品質のみ指定するため1つだけ用意する
            System.Drawing.Imaging.EncoderParameters eps =
                new System.Drawing.Imaging.EncoderParameters(1);

            System.IO.MemoryStream sr = new System.IO.MemoryStream();
            do
            {
                sr.Flush();//Streamの中身をクリア
                sr = new System.IO.MemoryStream();

                //品質を指定
                System.Drawing.Imaging.EncoderParameter ep =
                    new System.Drawing.Imaging.EncoderParameter(
                        System.Drawing.Imaging.Encoder.Quality, (long)quality);

                //EncoderParametersにセットする
                eps.Param[0] = ep;

                //試しに保存する
                bmp.Save(sr, ici, eps);

                quality -= 5;
            } while (sr.Length > size);
            return(eps);
        }
示例#7
0
        private string TransformXML(string sXML, string XSLPath)
        {
            XmlDataDocument oXML = new XmlDataDocument();
            //XPathDocument oXSL = new XPathDocument(XSLPath);

            XslCompiledTransform oTransform = new XslCompiledTransform();
            XsltArgumentList     xslArg     = new XsltArgumentList();
            string sMessage;

            //oXML.Load(new XmlTextReader(sXML, XmlNodeType.Document, null));
            oXML.Load(sXML);
            XPathNavigator nav = oXML.CreateNavigator();

            oTransform.Load(XSLPath);

            try
            {
                System.IO.MemoryStream oText    = new System.IO.MemoryStream();
                XmlTextWriter          xmlWrite = new XmlTextWriter(oText, System.Text.Encoding.UTF8);
                oTransform.Transform(nav, xmlWrite);
                xmlWrite.Flush();
                oText.Flush();
                oText.Position = 1;
                System.IO.StreamReader sr = new System.IO.StreamReader(oText);
                sMessage = sr.ReadToEnd();
                oText.Close();
                return(sMessage);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#8
0
        private static void OtherWaysToGetReport()
        {
            string report = @"d:\bla.rdl";

            // string lalal = System.IO.File.ReadAllText(report);
            // byte[] foo = System.Text.Encoding.UTF8.GetBytes(lalal);
            // byte[] foo = System.IO.File.ReadAllBytes(report);

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                using (System.IO.FileStream file = new System.IO.FileStream(report, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    byte[] bytes = new byte[file.Length];
                    file.Read(bytes, 0, (int)file.Length);
                    ms.Write(bytes, 0, (int)file.Length);
                    ms.Flush();
                    ms.Position = 0;
                }


                using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("resource"))
                {
                    using (System.IO.TextReader reader = new System.IO.StreamReader(ms))
                    {
                        // rv.LocalReport.LoadReportDefinition(reader);
                    }
                }

                using (System.IO.TextReader reader = System.IO.File.OpenText(report))
                {
                    // rv.LocalReport.LoadReportDefinition(reader);
                }
            }
        }
        protected void storeData_Submit(object sender, StoreSubmitDataEventArgs e)
        {
            XmlNode xml = e.Xml;

            this.Response.Clear();

            this.Response.Charset         = "GB2312";
            this.Response.ContentType     = "application/vnd.ms-excel";
            this.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xls");
            XslCompiledTransform xtExcel = new XslCompiledTransform();

            xtExcel.Load(Server.MapPath("Excel.xsl"));
            string temp = "";

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

            xtExcel.Transform(xml, null, str);

            str.Flush();
            str.Position = 0;
            using (System.IO.StreamReader sr = new System.IO.StreamReader(str, System.Text.Encoding.GetEncoding("GB2312")))
            {
                temp = sr.ReadToEnd();
            };


            temp = temp.Replace("encoding=\"utf-8\"", "encoding=\"GB2312\"");


            this.Response.Write(temp);


            this.Response.End();
        }
示例#10
0
        public void testSerialization()
        {
            Scintilla.Configuration.Scintilla x1;
            x1                 = new Scintilla.Configuration.Scintilla();
            x1.globals         = new Scintilla.Configuration.Value[2];
            x1.globals[0]      = new Scintilla.Configuration.Value();
            x1.globals[1]      = new Scintilla.Configuration.Value();
            x1.globals[0].name = "myname";
            x1.globals[0].val  = "myval";
            x1.globals[1].name = "yourname";
            x1.globals[1].val  = "yourval";


            System.Xml.Serialization.XmlSerializer myDeSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Scintilla.Configuration.Scintilla));
            // To write to a file, create a StreamWriter object.
            System.IO.MemoryStream ms = new System.IO.MemoryStream(40000);

            System.IO.StreamWriter myWriter = new System.IO.StreamWriter(ms);
            myDeSerializer.Serialize(myWriter, x1);

            ms.Flush();
            string sq = System.Text.ASCIIEncoding.ASCII.GetString(ms.GetBuffer(), 0, (int)ms.Length);

            MessageBox.Show(sq);
        }
示例#11
0
        public void CopySelectedObjectsToClipboard()
        {
            System.Windows.Forms.DataObject dao = new System.Windows.Forms.DataObject();

            ArrayList objectList = new ArrayList();

            foreach (IHitTestObject o in this.m_SelectedObjects)
            {
                if (o.HittedObject is System.Runtime.Serialization.ISerializable)
                {
                    objectList.Add(o.HittedObject);
                }
            }

            dao.SetData("Altaxo.Graph.GraphObjectList", objectList);

            // Test code to test if the object list can be serialized
#if false
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binform = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                binform.Serialize(stream, objectList);

                stream.Flush();
                stream.Seek(0, System.IO.SeekOrigin.Begin);
                object obj = binform.Deserialize(stream);
                stream.Close();
                stream.Dispose();
            }
#endif

            // now copy the data object to the clipboard
            System.Windows.Forms.Clipboard.SetDataObject(dao, true);
        }
示例#12
0
        /// <summary>
        /// 绘制图像(等比例缩放)
        /// </summary>
        /// <param name="image"></param>
        /// <param name="rect"></param>
        public void DrawImage(System.Drawing.Image image, System.Drawing.Rectangle rect)
        {
            //缩放图像
            var rateW = 1.0F * rect.Width / image.Width;
            var rateH = 1.0F * rect.Height / image.Height;
            var rate  = rateW < rateH ? rateW : rateH;

            var ms  = new System.IO.MemoryStream();
            var img = new System.Drawing.Bitmap((int)(image.Width * rate), (int)(image.Height * rate));
            var g   = System.Drawing.Graphics.FromImage(img);

            g.DrawImage(image, new System.Drawing.Rectangle(0, 0, (int)(image.Width * rate), (int)(image.Height * rate)));
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            ms.Flush();

            var r    = Transform2(rect);
            var img2 = Image.GetInstance(ms.GetBuffer());

            img2.SetAbsolutePosition(r.Left, r.Top);

            Canvas.AddImage(img2);

            ms.Dispose();
            img.Dispose();
        }
示例#13
0
        } // End Sub Decompress

        public static byte[] DeflateDecompress(byte[] gzip)
        {
            byte[] baRetVal = null;
            using (System.IO.MemoryStream ByteStream = new System.IO.MemoryStream(gzip))
            {
                // Create a GZIP stream with decompression mode.
                // ... Then create a buffer and write into while reading from the GZIP stream.
                using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ByteStream
                                                                                                            , System.IO.Compression.CompressionMode.Decompress))
                {
                    const int size   = 4096;
                    byte[]    buffer = new byte[size];
                    using (System.IO.MemoryStream memstrm = new System.IO.MemoryStream())
                    {
                        int count = 0;
                        count = stream.Read(buffer, 0, size);
                        while (count > 0)
                        {
                            memstrm.Write(buffer, 0, count);
                            memstrm.Flush();
                            count = stream.Read(buffer, 0, size);
                        } // Whend

                        baRetVal = memstrm.ToArray();
                        memstrm.Close();
                    } // End Using memstrm

                    stream.Close();
                } // End Using System.IO.Compression.GZipStream stream

                ByteStream.Close();
            } // End Using System.IO.MemoryStream ByteStream

            return(baRetVal);
        } // End Sub Decompress
示例#14
0
        public static string FormatXmlDocument(string xml)
        {
            var xmlDocument = new System.Xml.XmlDocument();

            xmlDocument.LoadXml(xml);

            var stream = new System.IO.MemoryStream();
            var writer = new System.Xml.XmlTextWriter(stream, Encoding.Unicode);

            // indent setting
            writer.Formatting  = System.Xml.Formatting.Indented;
            writer.Indentation = 2;   // indent length
            writer.IndentChar  = ' '; // indent character

            // formatting write
            xmlDocument.WriteContentTo(writer);
            writer.Flush();
            stream.Flush();
            stream.Position = 0;

            // to string
            var    reader       = new System.IO.StreamReader(stream);
            string formattedXml = reader.ReadToEnd();

            return(formattedXml);
        }
示例#15
0
        private void BuildVcode1()
        {
            // 获取随机字符串
            string vcStr = this.NextString(this.MinChars, this.MaxChars).ToUpper();

            // 创建验证码图片生成器
            VcodeImageCreator vcImgCreator = new VcodeImageCreator();

            // 设置字符尺寸
            vcImgCreator.CharMinSize = this.CharMinSize;
            vcImgCreator.CharMaxSize = this.CharMaxSize;

            // 创建验证码图片
            Image vcImg = vcImgCreator.CreateImage(this.ImageWidth, this.ImageHeight, vcStr);

            // 保存验证码
            HttpContext.Current.Session["__validatecodeimage"] = vcStr;
            // 保存验证码图片
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                HttpContext.Current.Response.ContentType = "Image/PNG";
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.BufferOutput = true;
                vcImg.Save(ms, ImageFormat.Png);
                ms.Flush();
                HttpContext.Current.Response.BinaryWrite(ms.GetBuffer());
                HttpContext.Current.Response.End();
            }
        }
示例#16
0
        private void SaveSectorImage()
        {
            Bitmap.Config config = Bitmap.Config.Argb8888;

            Bitmap newBitmap = Bitmap.CreateBitmap(1000, 1000, config);
            int    cellSize  = 100;
            Canvas canvas    = new Canvas(newBitmap);
            Rect   destRect  = new Rect(0, 0, 1024, 1024);
            Bitmap bkgnd     = BitmapHelper.GetImageBitmapFromUrl(parent.pop.curSector.DefaultUrl);
            Rect   srcRect   = new Rect(0, 0, bkgnd.Width, bkgnd.Height);
            Paint  thePaint  = new Paint(PaintFlags.AntiAlias);

            canvas.DrawBitmap(bkgnd, srcRect, destRect, thePaint);
            SectorObj curSector = parent.pop.curSector;

            foreach (StructureObj curStructure in parent.pop.curSector.structures)
            {
                bkgnd    = BitmapHelper.GetImageBitmapFromUrl(curStructure.imageURL);
                srcRect  = new Rect(0, 0, bkgnd.Width, bkgnd.Height);
                destRect = new Rect(curStructure.xLoc * cellSize, curStructure.yLoc * cellSize,
                                    (curStructure.xLoc + curStructure.xSize) * cellSize,
                                    (curStructure.yLoc + curStructure.ySize) * cellSize);
                canvas.DrawBitmap(bkgnd, srcRect, destRect, thePaint);
            }
            // at this point, the bitmap should be drawn
            using (System.IO.MemoryStream photoStream = new System.IO.MemoryStream())
            {
                newBitmap.Compress(Bitmap.CompressFormat.Jpeg, 90, photoStream);
                photoStream.Flush();
                PhabrikServer.UploadImage(photoStream, "sector", (newURL) =>
                {
                    parent.UpdateSectorUrl(curSector, newURL);
                });
            }
        }
        static void Main(string[] args)
        {
            Container container = new Container();
            Container copy      = null;

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
                new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            // may be a formatter created elsewhere
            if (formatter.SurrogateSelector == null)
            {
                formatter.SurrogateSelector = new StopWatchSelector();
            }
            else
            {
                formatter.SurrogateSelector.ChainSelector(new StopWatchSelector());
            }

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) {
                formatter.Serialize(stream, container);

                stream.Flush();
                stream.Position = 0;

                copy = formatter.Deserialize(stream) as Container;
            }


            System.Diagnostics.Debug.WriteLine(
                "Reference Equals: " + (object.ReferenceEquals(container, copy)).ToString());

            System.Console.ReadKey();
        }
示例#18
0
        private void InsertImageIntoRange(ImageSource source, Excel.Worksheet currentSheet, Excel.Range range, int maxHeight = -1)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            var encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(source as System.Windows.Media.Imaging.BitmapSource));
            encoder.Save(ms);
            ms.Flush();

            System.Windows.Forms.Clipboard.SetDataObject(System.Drawing.Image.FromStream(ms), true);
            currentSheet.Paste(range);

            // Resize image to fit range
            Excel.Shape shape = (Excel.Shape)currentSheet.Shapes.Item(currentSheet.Shapes.Count);
            shape.LockAspectRatio = Office.MsoTriState.msoCTrue;

            if (maxHeight == -1)
            {
                shape.Height = (int)range.Height;
            }
            else
            {
                shape.Height = (int)((source.Height / (double)maxHeight) * range.Height);
            }

            shape.Line.Visible = Office.MsoTriState.msoTrue;
            ms.Close();
        }
示例#19
0
		private static void BinWriteDataSetToStream(System.IO.Stream stream, System.Data.DataSet ds)
		{
			//Version
			IO.StreamPersistence.Write(stream, c_BinaryVersion);

			//Schema byte[]
			byte[] bytesSchema;
			using (System.IO.MemoryStream schemaStream = new System.IO.MemoryStream())
			{
				ds.WriteXmlSchema(schemaStream);
				schemaStream.Flush();
				schemaStream.Seek(0, System.IO.SeekOrigin.Begin);
				bytesSchema = schemaStream.ToArray();
			}
			IO.StreamPersistence.Write(stream, bytesSchema);

			//Tables
			for (int iTable = 0; iTable < ds.Tables.Count; iTable++)
			{
				System.Data.DataTable table = ds.Tables[iTable];
				//Only the current Rows
				System.Data.DataRow[] rows = table.Select(null, null, System.Data.DataViewRowState.CurrentRows);
				IO.StreamPersistence.Write(stream, rows.Length);
				//Rows
				for (int r = 0; r < rows.Length; r++)
				{
					//Columns
					for (int c = 0; c < table.Columns.Count; c++)
						BinWriteFieldToStream(stream, rows[r][c], table.Columns[c].DataType);
				}
			}
		}
示例#20
0
        /// <summary>
        /// Creates an Image object containing a screen shot of a specific window
        /// </summary>
        /// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
        /// <returns></returns>

        // [DllImport("gdi32.dll")]
        // static extern IntPtr CreateDC(string lpszDriver, string lpszDevice, string lpszOutput, IntPtr lpInitData);


        public static Tuple <Bitmap, byte[]> CaptureWindowFromDevice(string deviceName, int x, int y, int width, int height)
        {
            IntPtr hdcSrc = GDI32.CreateDC(deviceName, null, null, IntPtr.Zero);

            // create a device context we can copy to
            IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
            // create a bitmap we can copy it to,
            // using GetDeviceCaps to get the width/height
            IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
            // select the bitmap object
            IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);

            // bitblt over
            GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, x, y, GDI32.SRCCOPY);
            // restore selection
            GDI32.SelectObject(hdcDest, hOld);
            // clean up
            GDI32.DeleteDC(hdcDest);
            GDI32.DeleteDC(hdcSrc);
            // get a .NET image object for it
            Bitmap img1 = Image.FromHbitmap(hBitmap);

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

            img1.Save(m, ImageFormat.Bmp);
            m.Flush();
            byte[] raw = m.ToArray();
            m.Close();

            // free up the Bitmap object
            GDI32.DeleteObject(hBitmap);
            return(new Tuple <Bitmap, byte[]>(img1, raw));
        }
示例#21
0
        public void CloseAndFlush()
        {
            var memStream = new System.IO.MemoryStream();

            memStream.Close();
            memStream.Flush();
        }
示例#22
0
        public void CloseAndFlush()
        {
            var memStream = new System.IO.MemoryStream();

            memStream.Close();
            memStream.Flush();
        }
示例#23
0
        private static void BinWriteDataSetToStream(System.IO.Stream stream, System.Data.DataSet ds)
        {
            //Version
            IO.StreamPersistence.Write(stream, c_BinaryVersion);

            //Schema byte[]
            byte[] bytesSchema;
            using (System.IO.MemoryStream schemaStream = new System.IO.MemoryStream())
            {
                ds.WriteXmlSchema(schemaStream);
                schemaStream.Flush();
                schemaStream.Seek(0, System.IO.SeekOrigin.Begin);
                bytesSchema = schemaStream.ToArray();
            }
            IO.StreamPersistence.Write(stream, bytesSchema);

            //Tables
            for (int iTable = 0; iTable < ds.Tables.Count; iTable++)
            {
                System.Data.DataTable table = ds.Tables[iTable];
                //Only the current Rows
                System.Data.DataRow[] rows = table.Select(null, null, System.Data.DataViewRowState.CurrentRows);
                IO.StreamPersistence.Write(stream, rows.Length);
                //Rows
                for (int r = 0; r < rows.Length; r++)
                {
                    //Columns
                    for (int c = 0; c < table.Columns.Count; c++)
                    {
                        BinWriteFieldToStream(stream, rows[r][c], table.Columns[c].DataType);
                    }
                }
            }
        }
示例#24
0
        public System.IO.MemoryStream GetPNGImage2(double width, double height, double actualWidth, double actualHeight, bool whiteBG = false)
        {
            double dpiX = (width / actualWidth) * 96d;
            double dpiY = (height / actualHeight) * 96d;

            RenderTargetBitmap bitmap = new RenderTargetBitmap((int)width, (int)height, dpiX, dpiY, PixelFormats.Default);

            if (whiteBG)
            {
                DrawingVisual backgroundVisual = new System.Windows.Media.DrawingVisual();
                using (var dc = backgroundVisual.RenderOpen())
                    dc.DrawRectangle(Brushes.White, null, new Rect(0, 0, actualWidth, actualHeight));
                bitmap.Render(backgroundVisual);
            }

            bitmap.Render(m_visual);
            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            System.IO.MemoryStream returnStream = new System.IO.MemoryStream();
            encoder.Save(returnStream);
            returnStream.Flush();
            m_visual.Offset = new Vector(0, 0);
            return(returnStream);
        }
示例#25
0
        /// <summary>
        /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file)
        /// </summary>
        /// <param name="ds">DataSet containing the data to be written to the Excel.</param>
        /// <param name="filename">The filename (without a path) to call the new Excel file.</param>
        /// <param name="Response">HttpResponse of the current page.</param>
        /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns>
        public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true))
            {
                WriteExcelFile(ds, document);
            }
            stream.Flush();
            stream.Position = 0;

            Response.ClearContent();
            Response.Clear();
            Response.Buffer  = true;
            Response.Charset = "";

            //  NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have
            //  manually added System.Web to this project's References.

            Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
            Response.AddHeader("content-disposition", "attachment; filename=" + filename);
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            byte[] data1 = new byte[stream.Length];
            stream.Read(data1, 0, data1.Length);
            stream.Close();
            Response.BinaryWrite(data1);
            Response.Flush();


            return(true);
        }
示例#26
0
        static byte[] DecompressFileLZMA(byte[] data)
        {
            if (null == data)
            {
                return(null);
            }

            var coder  = new SevenZip.Compression.LZMA.Decoder();
            var input  = new System.IO.MemoryStream(data);
            var output = new System.IO.MemoryStream();

            // Read the decoder properties
            byte[] properties = new byte[5];
            input.Read(properties, 0, 5);

            // Read in the decompress file size.
            byte[] fileLengthBytes = new byte[8];
            input.Read(fileLengthBytes, 0, 8);

            long fileLength = System.BitConverter.ToInt64(fileLengthBytes, 0);

            // Decompress the file.
            coder.SetDecoderProperties(properties);
            coder.Code(input, output, input.Length, fileLength, null);
            output.Flush();
            byte[] returnData = output.ToArray();
            output.Close();
            input.Close();
            return(returnData);
        }
        private String GetPrintXML(String xml)
        {
            if (String.IsNullOrEmpty(xml))
            {
                return(String.Empty);
            }

            /*try
             * {
             *  System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Parse(xml);
             *  return doc.ToString();
             * }
             * catch (Exception)
             * {
             *  return xml;
             * }*/

            String Result = String.Empty;

            using (System.IO.MemoryStream mStream = new System.IO.MemoryStream())
            {
                System.Xml.XmlTextWriter writer   = new System.Xml.XmlTextWriter(mStream, Encoding.UTF8);
                System.Xml.XmlDocument   document = new System.Xml.XmlDocument();

                try
                {
                    // Load the XmlDocument with the XML.
                    document.LoadXml(xml);

                    writer.Formatting = System.Xml.Formatting.Indented;

                    // Write the XML into a formatting XmlTextWriter
                    document.WriteContentTo(writer);
                    writer.Flush();
                    mStream.Flush();

                    // Have to rewind the MemoryStream in order to read
                    // its contents.
                    mStream.Position = 0;

                    // Read MemoryStream contents into a StreamReader.
                    System.IO.StreamReader sReader = new System.IO.StreamReader(mStream);

                    // Extract the text from the StreamReader.
                    String FormattedXML = sReader.ReadToEnd();

                    Result = FormattedXML;
                }
                catch (System.Xml.XmlException)
                {
                    return(xml);
                }
                finally
                {
                    writer.Close();
                }
            }
            return(Result);
        }
示例#28
0
 public void Flush()
 {
     this.InnerStream.Flush();
     if (null != _filtered)
     {
         _filtered.Flush();
     }
 }
 public static System.IO.MemoryStream parseStringToMemoryStream(string s)
 {
     byte[] byteArray = Encoding.UTF8.GetBytes(s);
     System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
     stream.Flush();
     stream.Position = 0;
     return(stream);
 }
示例#30
0
 private byte[] GetCsv()
 {
     System.IO.MemoryStream ms = _dataTableToCsvMapper.Map(_tableReader.GetDataTable());
     byte[] byteArray          = ms.ToArray();
     ms.Flush();
     ms.Close();
     return(byteArray);
 }
示例#31
0
 // POST api/values
 public void Post([FromBody]string value)
 {
     var s = new System.IO.MemoryStream();
       Request.Content.CopyToAsync(s);
       s.Flush();
       Console.WriteLine("payload:[{0}]", System.Text.Encoding.UTF8.GetString(s.ToArray()));
       Console.WriteLine(value);
 }
示例#32
0
        public static System.IO.MemoryStream ImageToStream(System.Drawing.Image image, System.Drawing.Imaging.ImageFormat format)
        {
            var str = new System.IO.MemoryStream();

            image.Save(str, format);
            str.Flush();
            str.Seek(0, System.IO.SeekOrigin.Begin);
            return(str);
        }
示例#33
0
 public static System.IO.Stream GenerateViaXSLT(System.Xml.Xsl.XslTransform xslTransform, System.Xml.XPath.XPathNavigator xNavMetaData, string outputType, ExtObject[] extObjects, params Param[] @params)
 {
     System.IO.MemoryStream stream;
     stream = new System.IO.MemoryStream();
     GenerateXSLTToStream(xslTransform, xNavMetaData, stream, outputType, extObjects, @params);
     stream.Flush();
     stream.Seek(0, System.IO.SeekOrigin.Begin);
     return(stream);
 }
示例#34
0
        public static Metafile GetMetafile(GraphDocument doc)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            Metafile mf = SaveAsMetafile(doc, stream, 300);

            stream.Flush();
            stream.Close();
            return(mf);
        }
示例#35
0
 public static System.IO.Stream GenerateViaXSLT(string xsltFileName, System.Xml.XmlDocument xmlMetaData, string outputType, ExtObject[] extObjects, params Param[] @params)
 {
     System.IO.MemoryStream stream;
     stream = new System.IO.MemoryStream();
     GenerateXSLTToStream(xsltFileName, xmlMetaData, stream, outputType, extObjects, @params);
     stream.Flush();
     stream.Seek(0, System.IO.SeekOrigin.Begin);
     return(stream);
 }
 public static SerializedObject DeSerialize(string messageBody)
 {
     byte[] bytes = Convert.FromBase64String(messageBody);
     System.IO.MemoryStream stream = new System.IO.MemoryStream();
     stream.Write(bytes, 0, bytes.Length);
     stream.Flush();
     stream.Position = 0;
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     object result = f.Deserialize(stream);
     return (SerializedObject)result;
 }
示例#37
0
        //// GET: api/Values
        //public IEnumerable<string> Get()
        //{
        //    return new string[] { "value1", "value2" };
        //}
        //// GET: api/Values/5
        //public string Get(int id)
        //{
        //    return "value";
        //}
        // POST: api/Values
        public string Post([FromBody]string value)
        {
            var enc = System.Text.Encoding.UTF8;

            using (var mem = new System.IO.MemoryStream())
            using (var gzip = new System.IO.Compression.GZipStream(mem, System.IO.Compression.CompressionMode.Compress, true))
            using (var text = new System.IO.StreamWriter(gzip, enc, 0, true))
            {
                text.Write(value);
                text.Flush();

                mem.Flush();
                mem.Seek(0, System.IO.SeekOrigin.Begin);

                return System.Convert.ToBase64String(mem.ToArray());

            }
        }
示例#38
0
        public System.IO.Stream WriteToStream(IPolicySetCache set, bool runtime)
        {
            using (System.IO.MemoryStream outputMemoryStream = new System.IO.MemoryStream())
            {
                using (ZipOutputStream zipOutputStream = new ZipOutputStream(outputMemoryStream))
                {
                    WriteToZipStream(zipOutputStream, set, runtime);

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

                    Crypto.Instance.WriteStreamToEncryptedStream(outputMemoryStream, returnStream, false);

                    returnStream.Flush();
                    returnStream.Position = 0;
                    
                    return returnStream;
                }
            }
        }
示例#39
0
        public static bool Attach(bool noAutoExit)
        {
            lock (_syncRoot) {
                NativeMethods.FileSafeHandle handle = null;
                bool isFirstInstance = false;
                try {
                    _mtxFirstInstance = new Mutex(true, MutexName, out isFirstInstance);
                    if (isFirstInstance == false) { //we need to contact previous instance.
                        _mtxFirstInstance = null;

                        byte[] buffer;
                        using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
                            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                            bf.Serialize(ms, new NewInstanceEventArgs(System.Environment.CommandLine, System.Environment.GetCommandLineArgs()));
                            ms.Flush();
                            buffer = ms.GetBuffer();
                        }

                        //open pipe
                        if (!NativeMethods.WaitNamedPipe(NamedPipeName, NativeMethods.NMPWAIT_USE_DEFAULT_WAIT)) { throw new System.InvalidOperationException(Resources.ExceptionWaitNamedPipeFailed); }
                        handle = NativeMethods.CreateFile(NamedPipeName, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 0, System.IntPtr.Zero, NativeMethods.OPEN_EXISTING, NativeMethods.FILE_ATTRIBUTE_NORMAL, System.IntPtr.Zero);
                        if (handle.IsInvalid) {
                            throw new System.InvalidOperationException(Resources.ExceptionCreateFileFailed);
                        }

                        //send bytes
                        uint written = 0;
                        NativeOverlapped overlapped = new NativeOverlapped();
                        if (!NativeMethods.WriteFile(handle, buffer, (uint)buffer.Length, ref written, ref overlapped)) {
                            throw new System.InvalidOperationException(Resources.ExceptionWriteFileFailed);
                        }
                        if (written != buffer.Length) { throw new System.InvalidOperationException(Resources.ExceptionWriteFileWroteUnexpectedNumberOfBytes); }

                    } else {  //there is no application already running.

                        _thread = new Thread(Run);
                        _thread.Name = "Medo.Application.SingleInstance.0";
                        _thread.IsBackground = true;
                        _thread.Start();

                    }

                } catch (System.Exception ex) {
                    System.Diagnostics.Trace.TraceWarning(ex.Message + "  {Medo.Application.SingleInstance}");

                } finally {
                    //if (handle != null && (!(handle.IsClosed || handle.IsInvalid))) {
                    //    handle.Close();
                    //}
                    if (handle != null) {
                        handle.Dispose();
                    }
                }

                if ((isFirstInstance == false) && (noAutoExit == false)) {
                    System.Diagnostics.Trace.TraceInformation("Exit(E_ABORT): Another instance is running.  {Medo.Application.SingleInstance}");
                    System.Environment.Exit(unchecked((int)0x80004004)); //E_ABORT(0x80004004)
                }

                return isFirstInstance;
            }
        }
示例#40
0
        /// <summary>
        /// �����󣩡�����ֻ�õ�cookie�� ���л�
        /// </summary>
        /// <param name="obj">����</param>
        /// <returns></returns>
        public static string SerializeObject(object obj)
        {
            System.Runtime.Serialization.IFormatter bf = new BinaryFormatter();

            string result = string.Empty;

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {

                bf.Serialize(ms, obj);

                byte[] byt = Encoding.UTF8.GetBytes(ms.ToString());//new byte[ms.length];Ҳ��

                byt = ms.ToArray();

                result = System.Convert.ToBase64String(byt);

                ms.Flush();

            }

            return result;
        }
示例#41
0
        public override XmlDocument ToAsciiArt(Bitmap bmp)
        {
            //�ŏI�I�Ȗ߂�l�p��XmlDocument�𐶐�
            var xml = new XmlDocument();

            //AA�p��String[]�^�̕���(aaString)��p�ӂ���B(_char��null�̏ꍇ�ɔ�������̕������p�ӂ����B)
            var aaChars = _chars == null ? "@#WBRQ0hexc!;:. " : _chars;
            var aaString = new string[aaChars.Length];
            for (int i = 0; i < aaString.Length; i++)
                //�󔒕����΍�Ƃ��Ď��O�ɋ󔒂�HTML�p�ɕϊ�����
                aaString[i] = //aaChars[i].ToString();
                    (aaChars[i].ToString() == " ") ? "&nbsp;" : aaChars[i].ToString();

            /*�����̎g��������w��B���邳�}�b�N�X�̍ۂɕs���
             * ���邽�߃}�b�N�X�͌ォ��蓮��256�Ǝw�肵���B*/
            List<int> AA_threshold = new List<int>();
            for (int i = 0; i < aaString.Length - 1; i++)
            {
                AA_threshold.Add((256 / aaString.Length) * (i + 1));
            }
            AA_threshold.Add(256);

            //XmlWriter�Ƃ���̐����p�Ƀ�������Ԃ�m��
            //XmlDocument�ł͑��x�ɓ�L�̂���XmlWriter�𗘗p����
            using (var memory = new System.IO.MemoryStream())
            {
                //�{�����p��Writer
                var xmlWriter = XmlTextWriter.Create(memory);
                try
                {
                    //<div id="aaArea">
                    xmlWriter.WriteStartDocument();
                    xmlWriter.WriteStartElement("AsciiArt");
                    xmlWriter.WriteAttributeString("id", "aaArea");
                    xmlWriter.WriteAttributeString("width", bmp.Width.ToString());
                    xmlWriter.WriteAttributeString("height", bmp.Height.ToString());

                    #region XML�����o��
                    //<![CDATA[ <�e�X�g> ]]>
                    for (int h = 0; h < bmp.Height; h++)
                    {
                        //�s�̊J�n�����
                        xmlWriter.WriteStartElement("line");
                        for (int w = 0; w < bmp.Width; w++)
                        {
                            Color pixel_source = bmp.GetPixel(w, h);
                            //���邳��Z�o
                            int Ave_color = 0;
                            Ave_color += int.Parse(pixel_source.R.ToString());
                            Ave_color += int.Parse(pixel_source.G.ToString());
                            Ave_color += int.Parse(pixel_source.B.ToString());
                            Ave_color = Ave_color / 3;

                            //�摜�̖��x�ɉ����ĕ�����I��
                            for (int i = 0; i < AA_threshold.Count; i++)
                                if (Ave_color < AA_threshold[i])
                                {
                                    xmlWriter.WriteString(aaString[i]);
                                    break;
                                }
                        }
                        //x�s�ڂ�<line>��‚���
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteString("\r\n");
                    }
                    #endregion

                    //</AsciiArt>
                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteEndDocument();

                    //�o�b�t�@��̂�̂���ׂď�������XmlDocument�֕ϊ�����
                    xmlWriter.Flush();
                    memory.Flush();
                    memory.Position = 0;

                    //xmlWriter�ō쐬����AA��xmlDocument�ɕϊ�
                    xml.Load(memory);
                }
                finally
                {
                    xmlWriter.Close();
                }
            }
            return xml;
        }
示例#42
0
        public void ActOnInMessage(IConMessage conMsg)
        {
            StrMessage message = (StrMessage)conMsg;
            #region INF
            if (message is INF)
            {
                INF inf = (INF)message;
                if (hub != null && inf.Type.Equals("I"))
                {
                    if (hub.RegMode < 0)
                        hub.RegMode = 0;
                    UpdateInf();
                    Info = inf.UserInfo;
                    if (hub != null && Info.Description == null)
                        Update(con, new FmdcEventArgs(Actions.Name, new Containers.HubName(Info.DisplayName)));
                    else if (hub != null)
                        Update(con, new FmdcEventArgs(Actions.Name, new Containers.HubName(Info.DisplayName, Info.Description)));
                }
                else if (trans != null && inf.Type.Equals("C"))
                {
                    string token = null;
                    // CINF IDE3VACJVAXNOQLGRFQS7D5HYH4A6GLZDO3LJ33HQ TO2718662518
                    if (trans.Me != null && trans.Me.ContainsKey("TO"))
                        token = trans.Me.Get("TO");
                    else if (inf.UserInfo.ContainsKey("TO"))
                        token = inf.UserInfo.Get("TO");

                    TransferRequest req = new TransferRequest(token, null, inf.UserInfo);
                    FmdcEventArgs eArgs = new FmdcEventArgs(0, req);
                    RequestTransfer(trans, eArgs);
                    req = eArgs.Data as TransferRequest;
                    if (!eArgs.Handled || req == null)
                    {
                        // Can't see user/connection on my allow list
                        trans.Disconnect("No match for Request");
                        return;
                    }
                    if (!((req.User.ContainsKey(UserInfo.CID) && inf.UserInfo.ContainsKey(UserInfo.CID)) && req.User.Get(UserInfo.CID).Equals(inf.UserInfo.Get(UserInfo.CID))))
                    {
                        // For some reason user is trying to tell us it is a diffrent user. We dont like that.
                        FmdcEventArgs e = new FmdcEventArgs((int)TransferErrors.USERID_MISMATCH);
                        Error(trans, e);
                        if (!e.Handled)
                        {
                            trans.Disconnect("User Id Mismatch");
                            return;
                        }
                    }
                    if (trans.Me == null)
                        trans.Me = req.Me;
                    trans.User = req.User;
                    info = trans.User;
                    trans.Share = req.Share;
                    trans.Source = req.Source;
                    download = req.Download;

                    con.Send(new INF(con, trans.Me));
                    if (download)
                    {
                        EnsureCurrentSegmentCancelation();
                        // Request new segment from user. IF we have found one. ELSE disconnect.
                        if (GetSegment(true))
                        {
                            OnDownload();
                        }
                        else
                            trans.Disconnect("All content downloaded");
                    }
                }
                else if (hub != null)
                {
                    User usr = null;
                    if ((usr = hub.GetUserById(inf.Id)) == null)
                    {
                        if (inf.UserInfo.Mode == ConnectionTypes.Unknown)
                        {
                            inf.UserInfo.Mode = ConnectionTypes.Passive;
                        }
                        Update(con, new FmdcEventArgs(Actions.UserOnline, inf.UserInfo));
                    }
                    else
                    {
                        usr.UserInfo = inf.UserInfo;
                        Update(con, new FmdcEventArgs(Actions.UserInfoChange, usr.UserInfo));
                    }
                    // This is so we update our own reg/op hub count.
                    if (string.Equals(hub.Me.ID,inf.Id))
                    {
                        // Should we be marked with key?
                        bool regmodeChanged = false;
                        if (hub.RegMode < 2)
                        {
                            if (((UserInfo.ACCOUNT_FLAG_OPERATOR & inf.UserInfo.Account) == UserInfo.ACCOUNT_FLAG_OPERATOR))
                            {
                                hub.RegMode = 2;
                                regmodeChanged = true;
                            }
                            else if (((UserInfo.ACCOUNT_FLAG_SUPERUSER & inf.UserInfo.Account) == UserInfo.ACCOUNT_FLAG_SUPERUSER))
                            {
                                hub.RegMode = 2;
                                regmodeChanged = true;
                            }
                            else if (((UserInfo.ACCOUNT_FLAG_HUBOWNER & inf.UserInfo.Account) == UserInfo.ACCOUNT_FLAG_HUBOWNER))
                            {
                                hub.RegMode = 2;
                                regmodeChanged = true;
                            }
                        }
                        // Should we be marked as reg?
                        if (hub.RegMode < 1)
                        {
                            if (((UserInfo.ACCOUNT_FLAG_REGISTERED & inf.UserInfo.Account) == UserInfo.ACCOUNT_FLAG_REGISTERED))
                            {
                                hub.RegMode = 1;
                                regmodeChanged = true;
                            }

                        }
                        if (regmodeChanged)
                            UpdateInf();

                        IsReady = true;
                    }
                }
            }
            #endregion
            #region MSG
            else if (message is MSG && hub != null)
            {
                MSG msg = (MSG)message;
                if (msg.PmGroup == null)
                {
                    MainMessage main = new MainMessage(msg.From, msg.Content);
                    Update(con, new FmdcEventArgs(Actions.MainMessage, main));
                }
                else
                {
                    PrivateMessage pm = new PrivateMessage(msg.To, msg.From, msg.Content, msg.PmGroup);
                    Update(con, new FmdcEventArgs(Actions.PrivateMessage, pm));
                }
            }
            #endregion
            #region SID
            else if (message is SID && hub != null)
            {
                SID sid = (SID)message;
                hub.Me.Set(UserInfo.SID, sid.Id);
            }
            #endregion
            #region STA
            else if (message is STA)
            {
                STA sta = (STA)message;
                if (hub != null)
                {
                    MainMessage main = new MainMessage(info.ID, sta.Content);
                    Update(con, new FmdcEventArgs(Actions.MainMessage, main));
                }
            }
            #endregion
            #region GPA
            else if (message is GPA)
            {
                GPA gpa = (GPA)message;
                this.gpaString = gpa.RandomData;
                if (trans != null)
                {
                    Update(con, new FmdcEventArgs(Actions.Password, null));
                }
                if (hub != null && hub.HubSetting.Password.Length == 0)
                {
                    Update(con, new FmdcEventArgs(Actions.Password, null));
                }
                else
                    hub.Send(new PAS(hub, gpa.RandomData, hub.HubSetting.Password));
            }
            #endregion
            #region QUI
            else if (message is QUI && hub != null)
            {
                QUI qui = (QUI)message;
                User usr = null;
                if ((usr = hub.GetUserById(qui.Id)) != null)
                {
                    Update(con, new FmdcEventArgs(Actions.UserOffline, usr.UserInfo));
                    if (usr.ID == hub.Me.ID)
                    {
                        // TODO : Banning and redirect handling
                        hub.Disconnect();
                        // Redirect
                        if (!string.IsNullOrEmpty(qui.Address))
                            Update(con, new FmdcEventArgs(Actions.Redirect, new RedirectInfo(qui.Address, qui.Message, qui.DisconnectedBy)));
                        // Banned
                        else
                        {
                            if (qui.Time != -1)
                                // Sets reconnect attempt to infinite
                                hub.KeepAliveInterval = 0;
                            else
                                hub.KeepAliveInterval = qui.Time;
                            Update(con, new FmdcEventArgs(Actions.Banned, new BannedInfo(qui.Time, qui.Message, qui.DisconnectedBy)));
                        }
                    }
                }
            }
            #endregion
            #region SUP
            else if (message is SUP)
            {
                if (trans != null && !hasSentSUP)
                {
                    con.Send(new SUP(con));
                }
                supports = (SUP)message;
                // TODO : We should really care about what hub support.
                if (!supports.BASE && !supports.TIGR)
                {
                    // We will just simply disconnect if hub doesnt support this right now
                    con.Disconnect("Connection doesnt support BASE or BAS0");
                }
            #if !COMPACT_FRAMEWORK
                // Encrypted transfers
                if (supports.ADCS)
                {
                    if (
                        (hub != null && hub.Me.ContainsKey(UserInfo.SECURE)) ||
                        (trans != null && trans.Me.ContainsKey(UserInfo.SECURE))
                        )
                    {
                        con.SecureProtocol = SecureProtocols.TLS;
                    }
                }
            #endif
            }
            #endregion
            #region RES
            else if (message is RES)
            {
                RES res = (RES)message;
                SearchResultInfo srinfo = new SearchResultInfo(res.Info, res.Id, res.Token);
                if (hub != null)
                    Update(con, new FmdcEventArgs(Actions.SearchResult, srinfo));
            }
            #endregion
            #region SCH
            else if (message is SCH)
            {
                SCH sch = (SCH)message;
                UserInfo usr = null;
                if (hub != null)
                {
                    User u = hub.GetUserById(sch.Id);
                    if (u != null)
                        usr = u.UserInfo;
                }
                else if (trans != null)
                    usr = trans.User;

                SendRES(sch.Info, usr);
            }
            #endregion
            #region CTM
            else if (message is CTM && hub != null)
            {
                CTM ctm = (CTM)message;

                // We really hate buggy hubsofts. Only reason we will get this message is because hubsoft dont know diffrent between E and D messages.
                if (ctm.Id == hub.Me.ID)
                    return;

                User usr = null;
                string addr = null;

                // Do we support same protocol?
                double version = 0.0;
                if (ctm.Protocol != null && (ctm.Protocol.StartsWith("ADC/") || ctm.Protocol.StartsWith("ADCS/")))
                {
                    try
                    {
                        version = double.Parse(ctm.Protocol.Substring( ctm.Protocol.IndexOf("/") +1), CultureInfo.GetCultureInfo("en-GB").NumberFormat);
                    }
                    catch { }
                }
                if (version > 1.0)
                {
                    hub.Send(new STA(hub, ctm.Id, hub.Me.ID, "241", "Protocol is not supported. I only support ADC 1.0/ADCS 0.10 and prior", "TO" + ctm.Token + " PR" + ctm.Protocol));
                    return;
                }

                if ((usr = hub.GetUserById(ctm.Id)) != null && usr.UserInfo.ContainsKey(UserInfo.IP))
                {
                    addr = usr.UserInfo.Get(UserInfo.IP);
                    Transfer trans = new Transfer(addr, ctm.Port);
                    trans.Share = hub.Share;
                    // We are doing this because we want to filter out PID and so on.
                    User me = hub.GetUserById(hub.Me.ID);
                    trans.Me = new UserInfo(me.UserInfo);
                    trans.Protocol = new AdcProtocol(trans);
            #if !COMPACT_FRAMEWORK
                    if (ctm.Secure)
                        trans.SecureProtocol = SecureProtocols.TLS;
            #endif

                    // Support for prior versions of adc then 1.0
                    string token = ctm.Token;
                    if (version < 1.0 && ctm.Token.StartsWith("TO"))
                        token = ctm.Token.Substring(2);
                    trans.Me.Set("TO", token);

                    Update(con, new FmdcEventArgs(Actions.TransferRequest, new TransferRequest(token, hub, usr.UserInfo,false)));
                    Update(con, new FmdcEventArgs(Actions.TransferStarted, trans));
                }
            }
            #endregion
            #region RCM
            else if (message is RCM && hub != null)
            {
                RCM rcm = (RCM)message;

                // We really hate buggy hubsofts. Only reason we will get this message is because hubsoft dont know diffrent between E and D messages.
                if (rcm.Id == hub.Me.ID)
                    return;

               if (hub.Me.Mode != FlowLib.Enums.ConnectionTypes.Passive && hub.Share != null)
                {
                    User usr = null;
                    if ((usr = hub.GetUserById(rcm.Id)) != null)
                    {
                        // Do we support same protocol?
                        double version = 0.0;
                        if (rcm.Protocol != null && (rcm.Protocol.StartsWith("ADC/") || rcm.Protocol.StartsWith("ADCS/")))
                        {
                            try
                            {
                                version = double.Parse(rcm.Protocol.Substring(rcm.Protocol.IndexOf("/") + 1), CultureInfo.GetCultureInfo("en-GB").NumberFormat);
                            }
                            catch { }
                            if (version <= 1.0)
                            {
                                // Support for prior versions of adc then 1.0
                                string token = rcm.Token;
                                if (version < 1.0 && rcm.Token.StartsWith("TO"))
                                    token = rcm.Token.Substring(2);

                                Update(con, new FmdcEventArgs(Actions.TransferRequest, new TransferRequest(token, hub, usr.UserInfo, false)));

                                if (rcm.Secure && hub.Me.ContainsKey(UserInfo.SECURE))
                                    hub.Send(new CTM(hub, rcm.Id, rcm.IDTwo, rcm.Protocol, int.Parse(0 + hub.Me.Get(UserInfo.SECURE)), token));
                                else
                                    hub.Send(new CTM(hub, rcm.Id, rcm.IDTwo, rcm.Protocol, hub.Share.Port, token));
                            }
                            else
                            {
                                hub.Send(new STA(hub, rcm.Id, hub.Me.ID, "241", "Protocol is not supported. I only support ADC 1.0 and prior", "TO" + rcm.Token + " PR" + rcm.Protocol));
                                return;
                            }
                        }
                    }
                }
                else
                {
                    // TODO : we should probably return a STA message.
                }
            }
            #endregion
            #region GFI
            else if (message is GFI && this.trans != null)
            {
                GFI gfi = (GFI)message;
                if (gfi.Identifier != null)
                {
                    trans.Content = new ContentInfo();
                    switch (gfi.ContentType)
                    {
                        case "file":        // Requesting file
                            // This is because we have support for old DC++ client and mods like (DCDM who has ASCII encoding)
                            if (gfi.Identifier.Equals("files.xml.bz2"))
                            {
                                trans.Content.Set(ContentInfo.FILELIST, Utils.FileLists.BaseFilelist.XMLBZ);
                                trans.Content.Set(ContentInfo.VIRTUAL, System.Text.Encoding.UTF8.WebName + gfi.Identifier);
                            }
                            else if (gfi.Identifier.StartsWith("TTH/"))
                            {
                                trans.Content.Set(ContentInfo.TTH, gfi.Identifier.Substring(4));
                            }
                            else
                            {
                                trans.Content.Set(ContentInfo.VIRTUAL, gfi.Identifier);
                            }
                            break;
                        case "list":        // TODO : We dont care about what subdirectoy user whats list for
                            trans.Content.Set(ContentInfo.FILELIST, Utils.FileLists.BaseFilelist.XML);
                            trans.Content.Set(ContentInfo.VIRTUAL, System.Text.Encoding.UTF8.WebName + "files.xml");
                            break;
                        default:            // We are not supporting type. Disconnect
                            con.Send(new STA(con, "251", "Type not known:" + gfi.ContentType, null));
                            con.Disconnect();
                            return;
                    }
                    SearchInfo si = new SearchInfo();
                    if (trans.Content.ContainsKey(ContentInfo.TTH))
                        si.Set(SearchInfo.TYPE, trans.Content.Get(ContentInfo.TTH));
                    si.Set(SearchInfo.SEARCH, trans.Content.Get(ContentInfo.VIRTUAL));
                    SendRES(si, trans.User);
                }
            }
            #endregion
            #region GET
            else if (message is GET && this.trans != null)
            {
                GET get = (GET)message;
                // If we are supposed to download and other client tries to download. Disconnect.
                if (trans != null && this.download)
                {
                    trans.Disconnect();
                    return;
                }
                bool firstTime = true;

                if (get.Identifier != null)
                {
                    trans.Content = new ContentInfo();
                    switch (get.ContentType)
                    {
                        case "file":        // Requesting file
                            // This is because we have support for old DC++ client and mods like (DCDM who has ASCII encoding)
                            if (get.Identifier.Equals("files.xml.bz2"))
                            {
                                trans.Content.Set(ContentInfo.FILELIST, Utils.FileLists.BaseFilelist.XMLBZ);
                                trans.Content.Set(ContentInfo.VIRTUAL, System.Text.Encoding.UTF8.WebName + get.Identifier);
                            }
                            else if (get.Identifier.StartsWith("TTH/"))
                            {
                                trans.Content.Set(ContentInfo.TTH, get.Identifier.Substring(4));
                            }
                            else
                            {
                                trans.Content.Set(ContentInfo.VIRTUAL, get.Identifier);
                            }
                            break;
                        case "list":        // TODO : We dont care about what subdirectoy user whats list for
                            trans.Content.Set(ContentInfo.FILELIST, Utils.FileLists.BaseFilelist.XML);
                            trans.Content.Set(ContentInfo.VIRTUAL, System.Text.Encoding.UTF8.WebName + "files.xml");
                            break;
                        case "tthl":
                            // TTH/DQSGG2MYKKLXX4N2P7TBPKSC5HVBO3ISYZPLMWA
                            if (get.Identifier.StartsWith("TTH/"))
                            {
                                trans.Content.Set(ContentInfo.TTH, get.Identifier.Substring(4));

                                ContentInfo tmp = trans.Content;
                                if (con.Share != null && con.Share.ContainsContent(ref tmp) && tmp.ContainsKey(ContentInfo.TTHL))
                                {
                                    byte[] bytes = Utils.Convert.Base32.Decode(tmp.Get(ContentInfo.TTHL));
            #if !COMPACT_FRAMEWORK
                                    trans.CurrentSegment = new SegmentInfo(-1, 0, bytes.LongLength);
            #else
                                    trans.CurrentSegment = new SegmentInfo(-1, 0, bytes.Length);
            #endif

                                    con.Send(new SND(trans, get.ContentType, get.Identifier, new SegmentInfo(-1, trans.CurrentSegment.Start, trans.CurrentSegment.Length)));
                                    // Send content to user
                                    System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
                                    ms.Flush();
                                    bytes = ms.ToArray();
                                    con.Send(new BinaryMessage(con, bytes, bytes.Length));
                                    System.Console.WriteLine("TTH Leaves:" + FlowLib.Utils.Convert.Base32.Encode(bytes));
                                    firstTime = true;
                                }
                            }
                            if (!firstTime)
                            {
                                // We should not get here if file is in share.
                                con.Send(new STA(con, "251", "File not available", null));
                                con.Disconnect();
                            }
                            return;
                        default:            // We are not supporting type. Disconnect
                            con.Send(new STA(con, "251", "Type not known:" + get.ContentType, null));
                            con.Disconnect();
                            return;
                    }
                    trans.CurrentSegment = get.SegmentInfo;
                    byte[] bytesToSend = null;
                    try
                    {
                        // TODO : ZLib compression here doesnt work as we want. It takes much memory and much cpu
                        //Util.Compression.ZLib zlib = null;
                        //if (adcget.ZL1)
                        //    zlib = new Fmdc.Util.Compression.ZLib();
                        while (connectionStatus != TcpConnection.Disconnected && (bytesToSend = GetContent(System.Text.Encoding.UTF8, trans.CurrentSegment.Position, trans.CurrentSegment.Length - trans.CurrentSegment.Position)) != null)
                        {
                            if (firstTime)
                            {
                                con.Send(new SND(trans, get.ContentType, get.Identifier, new SegmentInfo(-1, get.SegmentInfo.Start, trans.CurrentSegment.Length)));
                                firstTime = false;
                            }

                            trans.CurrentSegment.Position += bytesToSend.Length;
                            // We want to compress content with ZLib
                            //if (zlib != null)
                            //{
                            //    zlib.Compress2(bytesToSend);
                            //    bytesToSend = zlib.Read();
                            //}
                            con.Send(new BinaryMessage(trans, bytesToSend, bytesToSend.Length));
                            bytesToSend = null;

                        }

                        // If we compressing data with zlib. We need to send ending bytes too.
                        //if (zlib != null && connectionStatus != Connection.Disconnected)
                        //    trans.Send(new ConMessage(trans, zlib.close()));
                    }
                    catch (System.Exception e) { System.Console.WriteLine("ERROR:" + e); }
                }
                trans.CurrentSegment = new SegmentInfo(-1);
                trans.Content = null;
                if (firstTime)
                {
                    // We should not get here if file is in share.
                    con.Send(new STA(con, "251", "File not available", null));
                    con.Disconnect();
                }
            }
            #endregion
            #region SND
            else if (message is SND)
            {
                SND snd = (SND)message;
                if (!trans.Content.Get(ContentInfo.REQUEST).Equals(snd.Identifier))
                {
                    trans.Disconnect("I want my bytes..");
                    return;
                }
                if (trans.DownloadItem.ContentInfo.Size == -1)
                {
                    trans.DownloadItem.ContentInfo.Size = snd.SegmentInfo.Length;
                    trans.DownloadItem.SegmentSize = snd.SegmentInfo.Length;
                    EnsureCurrentSegmentCancelation();
                    GetSegment(false);
                }
                else if (trans.CurrentSegment != null && trans.CurrentSegment.Length != snd.SegmentInfo.Length)
                {
                    trans.Disconnect("Why would i want to get a diffrent length of bytes then i asked for?");
                    return;
                }
                this.IsRawData = true;
                trans.ShouldBlockOnSend = true;
            }
            #endregion
        }
示例#43
0
 internal static byte[] Serialize(object obj)
 {
     if (obj==null)
     {
         throw new ArgumentException("Parameter is invalid.", "obj", null);
     }
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         bf.Serialize(ms, obj);
         ms.Seek(0, System.IO.SeekOrigin.Begin);
         byte[] result = ms.ToArray();
         ms.Flush();
         return result;
     }
 }
 /// <summary>
 /// Serializes the data and writes it to the file.
 /// </summary>
 /// <param name="data">The data to serialize.</param>
 /// <param name="offset">The position in the file to start.</param>
 /// <param name="length">The buffer size in bytes.</param>
 public void WriteSerialize(object data, int offset, int length)
 {
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter
         = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     byte[] binaryData = new byte[length];
     System.IO.MemoryStream ms = new System.IO.MemoryStream(binaryData,0,length,true,true);
     formatter.Serialize(ms,data);
     ms.Flush();
     ms.Close();
     WriteBytes(binaryData,offset);
 }
示例#45
0
 public static Metafile GetMetafile(GraphDocument doc)
 {
   System.IO.MemoryStream stream = new System.IO.MemoryStream();
   Metafile mf = SaveAsMetafile(doc, stream,300);
   stream.Flush();
   stream.Close();
   return mf;
 }
示例#46
0
        // GET /api/music/5
        public HttpResponseMessage Get(Guid id, string play)
        {
            string musicPath = HttpContext.Current.Server.MapPath("~/Content/Music") + "\\" + id.ToString() + ".mp3";
            if (System.IO.File.Exists(musicPath))
            {
                HttpResponseMessage result = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
                System.IO.FileStream stream = new System.IO.FileStream(musicPath, System.IO.FileMode.Open);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();

                ms.SetLength(stream.Length);
                stream.Read(ms.GetBuffer(), 0, (int)stream.Length);
                ms.Flush();
                stream.Close();
                stream.Dispose();
                result.Content = new StreamContent(ms);
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("audio/mpeg");
                return result;
            }
            else
            {
                return new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);
            }
        }
        public void TestExtractArchiveTarBz2()
        {
            CloudFilesProvider provider = (CloudFilesProvider)Bootstrapper.CreateObjectStorageProvider();
            string containerName = TestContainerPrefix + Path.GetRandomFileName();
            string sourceFileName = "DarkKnightRises.jpg";
            byte[] content = File.ReadAllBytes("DarkKnightRises.jpg");
            using (MemoryStream outputStream = new MemoryStream())
            {
                using (BZip2OutputStream bz2Stream = new BZip2OutputStream(outputStream))
                {
                    bz2Stream.IsStreamOwner = false;
                    using (TarArchive archive = TarArchive.CreateOutputTarArchive(bz2Stream))
                    {
                        archive.IsStreamOwner = false;
                        archive.RootPath = Path.GetDirectoryName(Path.GetFullPath(sourceFileName)).Replace('\\', '/');
                        TarEntry entry = TarEntry.CreateEntryFromFile(sourceFileName);
                        archive.WriteEntry(entry, true);
                        archive.Close();
                    }
                }

                outputStream.Flush();
                outputStream.Position = 0;
                ExtractArchiveResponse response = provider.ExtractArchive(outputStream, containerName, ArchiveFormat.TarBz2);
                Assert.IsNotNull(response);
                Assert.AreEqual(1, response.CreatedFiles);
                Assert.IsNotNull(response.Errors);
                Assert.AreEqual(0, response.Errors.Count);
            }

            using (MemoryStream downloadStream = new MemoryStream())
            {
                provider.GetObject(containerName, sourceFileName, downloadStream, verifyEtag: true);
                Assert.AreEqual(content.Length, GetContainerObjectSize(provider, containerName, sourceFileName));

                downloadStream.Position = 0;
                byte[] actualData = new byte[downloadStream.Length];
                downloadStream.Read(actualData, 0, actualData.Length);
                Assert.AreEqual(content.Length, actualData.Length);
                using (MD5 md5 = MD5.Create())
                {
                    byte[] contentMd5 = md5.ComputeHash(content);
                    byte[] actualMd5 = md5.ComputeHash(actualData);
                    Assert.AreEqual(BitConverter.ToString(contentMd5), BitConverter.ToString(actualMd5));
                }
            }

            /* Cleanup
             */
            provider.DeleteContainer(containerName, deleteObjects: true);
        }
示例#48
0
 public static byte[] ImageToBuffer(Image Image, System.Drawing.Imaging.ImageFormat imageFormat)
 {
     if (Image == null) { return null; }
     byte[] data = null;
     using (System.IO.MemoryStream oMemoryStream = new System.IO.MemoryStream())
     {
         //建立副本
         using (Bitmap oBitmap = new Bitmap(Image))
         {
             //儲存圖片到 MemoryStream 物件,並且指定儲存影像之格式
             oBitmap.Save(oMemoryStream, imageFormat);
             //設定資料流位置
             oMemoryStream.Position = 0;
             //設定 buffer 長度
             data = new byte[oMemoryStream.Length];
             //將資料寫入 buffer
             oMemoryStream.Read(data, 0, Convert.ToInt32(oMemoryStream.Length));
             //將所有緩衝區的資料寫入資料流
             oMemoryStream.Flush();
         }
     }
     return data;
 }
        /// <summary>
        /// Creates a SoapFaultDetail message based upon the type of exception specified.
        /// </summary>
        /// <param name="ex">An exception containing information that is to be added to the SoapFaultDetail message.</param>
        /// <returns>The SoapFaultDetail message.</returns>
        public static XmlDocument CreateSoapFaultDetailMsg(System.Exception ex)
        {
            // Create the message
            SoapFaultDetail msg = new SoapFaultDetail();
            msg.Internal = new SoapFaultDetailInternal();
            msg.Internal.Workflow = new SoapFaultDetailInternalWorkflow();

            // Set the Message, Exception Number and any other specific information
            BusinessProcessException bpex = ex as BusinessProcessException;
            DacSqlException dex = ex as DacSqlException;
            if (bpex != null)
            {
                // A workflow engine business process exception
                HandleBpException(bpex, ref msg);
            }
            else if (dex != null)
            {
                // A workflow engine data access component (DAC) exception
                HandleDacException(dex, ref msg);
            }
            else
            {
                // Handle it as a generic System.Exception
                HandleSystemException(ex, ref msg);
            }

            // Category
            switch (GetExceptionCategory(ex))
            {
                case WorkflowExceptionCategory.Error:
                    msg.Category = SoapFaultDetailCategory.Error;
                    break;
                case WorkflowExceptionCategory.Warning:
                    msg.Category = SoapFaultDetailCategory.Warning;
                    break;
            }

            // Exception Case Number
            msg.ExceptionCaseNumber = Framework.ExceptionManagement.ExceptionCaseNumber.Generate();

            // Exception Code
            msg.ExceptionCode = GetExceptionCode(ex);

            // Internal - Subsystem
            msg.Internal.Subsystem = Framework.Subsystem.WorkflowEngine.ToString();

            // Internal - Source
            msg.Internal.Source = ex.Source;

            // Internal - Stack Trace
            msg.Internal.StackTrace = ex.StackTrace.Trim();

            // Internal - Workflow - Workflow Server
            msg.Internal.Workflow.WorkflowServer = System.Environment.MachineName;

            // Internal - Workflow - Orchestration Name
            // Note: We are trying to get information about the orchestration in which the error occurred.
            //       However, if there is a messaging error (e.g. a message could not be delivered to a
            //       SOAP web service, the error will occur in an assembly in the BizTalk Engine, thus the
            //       top-level stack frame will be the BizTalk Engine and not the orchestration.
            //       Also, if there is an error in a component that is called from an Expression shape, the
            //       top-level stack frame will be the component and not the orchestration.
            //       Variable 'sf' will be null if the exception occurred outside of Orchestration
            StackFrame sf = Framework.ExceptionManagement.ExceptionManager.GetStackFrameByNamespace(ex, ".Orchestrations");
            if (sf == null)
            {
                msg.Internal.Workflow.OrchestrationName = "";
            }
            else
            {
                msg.Internal.Workflow.OrchestrationName = sf.GetMethod().DeclaringType.FullName;
            }

            // Serialise the class into Xml and return it as an Xml document
            XmlDocument msgXml = new XmlDocument();
            XmlSerializer serializer = new XmlSerializer(typeof(SoapFaultDetail));
            using (System.IO.MemoryStream writer = new System.IO.MemoryStream())
            {
                serializer.Serialize(writer, msg);
                writer.Flush();
                writer.Position = 0;
                msgXml.Load(writer);
            }
            return msgXml;
        }
示例#50
0
        internal static byte[] Deflate(byte[] source_byte, System.IO.Compression.CompressionMode type_deflate)
        {
            byte[] dest_byte = null;

            using (System.IO.MemoryStream dest_mem = new System.IO.MemoryStream())
            {
                using (System.IO.MemoryStream source_mem = new System.IO.MemoryStream(source_byte))
                {
                    if (source_mem.CanSeek)
                    {
                        source_mem.Seek(0, System.IO.SeekOrigin.Begin);
                    }

                    if (type_deflate == System.IO.Compression.CompressionMode.Compress)
                    {
                        using (System.IO.Compression.DeflateStream deflate = new System.IO.Compression.DeflateStream(dest_mem, type_deflate))
                        {
                            source_mem.CopyTo(deflate);
                            deflate.Flush();
                        }
                    }
                    else
                    {
                        using (System.IO.Compression.DeflateStream deflate = new System.IO.Compression.DeflateStream(source_mem, type_deflate))
                        {
                            deflate.CopyTo(dest_mem);
                            deflate.Flush();
                        }
                    }

                    source_mem.Flush();
                }
                if (dest_mem.CanSeek)
                {
                    dest_mem.Seek(0, System.IO.SeekOrigin.Begin);
                }
                dest_byte = dest_mem.ToArray();
                dest_mem.Flush();
            }

            return dest_byte;
        }
示例#51
0
        public static System.Windows.Media.Imaging.BitmapImage GetImage(string fileId)
        {
            if (string.IsNullOrWhiteSpace(fileId))
            {
                if (_olaf == null)
                {
                    _olaf = GetImage(Olaf);
                }

                return _olaf;
            }

            using (var db = new PetoeterDb(PetoeterDb.FileName))
            {
                var file = db.FileStorage.FindById(fileId);

                if (file == null)
                {
                    if (fileId == Olaf)
                    {
                        SaveFile(Olaf, @"olaf.png");
                    }

                    return null;
                }

                using(var reader = file.OpenRead())
                {
                    System.IO.MemoryStream mem = new System.IO.MemoryStream();
                    mem.SetLength(file.Length);

                    reader.Read(mem.GetBuffer(), 0, (int)file.Length);
                    mem.Flush();

                    System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage();

                    image.BeginInit();
                    image.StreamSource = mem;
                    image.EndInit();

                    image.Freeze();

                    return image;
                }
            }
        }
 protected void ExportarButton_Click(object sender, EventArgs e)
 {
     System.Collections.Generic.List<CedForecastWebEntidades.Proyectado> lista;
     CedForecastWebEntidades.Proyectado Proyectado = new CedForecastWebEntidades.Proyectado();
     Proyectado.IdTipoPlanilla = "Proyectado";
     Proyectado.IdCuenta = CuentaDropDownList.SelectedValue.Trim();
     CedForecastWebEntidades.Cliente cliente = new CedForecastWebEntidades.Cliente();
     cliente.Id = ClienteDropDownList.SelectedValue.ToString().Trim();
     Proyectado.Cliente = cliente;
     CedForecastWebRN.Periodo.ValidarPeriodoYYYYMM(PeriodoTextBox.Text);
     Proyectado.IdPeriodo = PeriodoTextBox.Text;
     lista = CedForecastWebRN.Proyectado.Lista(Proyectado, (CedForecastWebEntidades.Sesion)Session["Sesion"]);
     string archivo = "Id.Vendedor; Id.Cliente; Nombre Cliente; Id.Artículo; Nombre Artículo; ";
     int colFijas = 4;
     for (int i = 1; i <= 12; i++)
     {
         archivo += TextoCantidadHeader(i, PeriodoTextBox.Text) + "; ";
     }
     archivo += "Total " + PeriodoTextBox.Text + "; ";
     archivo += "Total " + Convert.ToDateTime("01" + PeriodoTextBox.Text.Substring(4,2) + "/" + PeriodoTextBox.Text.Substring(0,4)).AddYears(1).Year.ToString() + "; ";
     archivo += "Total " + Convert.ToDateTime("01" + PeriodoTextBox.Text.Substring(4,2) + "/" + PeriodoTextBox.Text.Substring(0,4)).AddYears(2).Year.ToString() + "; ";
     archivo += "\r\n";
     FileHelperEngine fhe = new FileHelperEngine(typeof(CedForecastWebEntidades.Proyectado));
     archivo += fhe.WriteString(lista);
     byte[] a = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(archivo);
     System.IO.MemoryStream m = new System.IO.MemoryStream(a);
     Byte[] byteArray = m.ToArray();
     m.Flush();
     m.Close();
     Response.Clear();
     Response.AddHeader("Content-Disposition", "attachment; filename=Proyectado.csv");
     Response.ContentType = "application/octet-stream";
     Response.BinaryWrite(byteArray);
     Response.End();
 }
 protected void ExportarDinamicaButton1_Click(object sender, EventArgs e)
 {
     System.Collections.Generic.List<CedForecastWebEntidades.Forecast> lista;
     CedForecastWebEntidades.Forecast Forecast = new CedForecastWebEntidades.Forecast();
     Forecast.IdTipoPlanilla = "RollingForecast";
     Forecast.IdCuenta = CuentaDropDownList.SelectedValue.Trim();
     CedForecastWebEntidades.Cliente cliente = new CedForecastWebEntidades.Cliente();
     cliente.Id = ClienteDropDownList.SelectedValue.ToString().Trim();
     Forecast.Cliente = cliente;
     CedForecastWebRN.Periodo.ValidarPeriodoYYYYMM(PeriodoTextBox.Text);
     Forecast.IdPeriodo = PeriodoTextBox.Text;
     lista = CedForecastWebRN.Forecast.Lista(Forecast, (CedForecastWebEntidades.Sesion)Session["Sesion"]);
     string archivo = "Id.Cliente; Nombre Cliente; Familia Artículo; Id.Artículo; Nombre Artículo; Periodo; Volumen";
     archivo += "\r\n";
     FileHelperEngine fhe = new FileHelperEngine(typeof(CedForecastWebEntidades.Forecast));
     archivo += fhe.WriteString(lista);
     byte[] a = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(archivo);
     System.IO.MemoryStream m = new System.IO.MemoryStream(a);
     Byte[] byteArray = m.ToArray();
     m.Flush();
     m.Close();
     Response.Clear();
     Response.AddHeader("Content-Disposition", "attachment; filename=RollingForecastDinamico.csv");
     Response.ContentType = "application/octet-stream";
     Response.BinaryWrite(byteArray);
     Response.End();
 }
示例#54
0
 internal static object DeSerialize(byte[] obj)
 {
     if (obj == null || obj.Length<=0)
     {
         throw new ArgumentException("Parameter is invalid.", "obj", null);
     }
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream(obj))
     {
         System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         ms.Seek(0, System.IO.SeekOrigin.Begin);
         object result = bf.Deserialize(ms);
         ms.Flush();
         return result;
     }
 }
示例#55
0
			/// <summary>
			/// 将本对象序列化
			/// </summary>
			/// <returns></returns>
			public string Serialize()
			{
				System.IO.MemoryStream ms = new System.IO.MemoryStream();
				System.Xml.Serialization.XmlSerializer bf = new System.Xml.Serialization.XmlSerializer(typeof(Config));
				bf.Serialize(ms, this);
				ms.Flush();

				string msg = System.Text.Encoding.Default.GetString(ms.ToArray());
				ms.Close();

				return msg;
			}
 private string ComputeHash(XDocument doc, DateTime timestamp)
 {
     using (var stream = new System.IO.MemoryStream())
     using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
     using (var w = new System.IO.BinaryWriter(stream))
     {
         w.Write(timestamp.ToBinary());
         w.Flush();
         doc.Save(stream, SaveOptions.OmitDuplicateNamespaces);
         stream.Flush();
         var hash = md5.ComputeHash(stream.GetBuffer());
         string hex = BitConverter.ToString(hash);
         return hex.Replace("-", string.Empty);
     }
 }
示例#57
0
        private void mnuProcess_Mail_Click(object sender, EventArgs e)
        {
            string sBody =
                "Hello Yolanda  Xie,\r\n" +
                "\r\n" +
                "Thank you for purchasing Naurtech software. Here are the registration keys for your software licenses. Please note that both the License ID and Registration keys are case sensitive. You can find instructions to manually register your license at:\r\n" +
                "http://www.naurtech.com/wiki/wiki.php?n=Main.TrainingVideoManualRegistration\r\n" +
                "\r\n" +
                "     Order Number:     15109\r\n" +
                "     Order Date:       4/10/2014\r\n" +
                "     Your PO Number:   PO93504\r\n" +
                "     End Customer:     Honeywell\r\n" +
                "     Product:          [NAU-1504] CETerm for Windows CE 6.0 / 5.0 / CE .NET\r\n" +
                "     Quantity:         46\r\n" +
                "\r\n" +
                "     Qty Ordered...............: 46\r\n" +
                "     Qty Shipped To Date.......: 46\r\n" +
                "\r\n" +
                "     Qty Shipped in this email.: 46\r\n" +
                "\r\n" +
                "\r\n" +
                "**** Registration Keys for Version 5.7 ***** \r\n" +
                "\r\n" +
                "\r\n" +
                "Version 5.1 and above support AUTOMATED LICENSE REGISTRATION. Please use the attached license file. This prevents you from having to type each key to register your copy of the software. Please refer to support wiki article http://www.naurtech.com/wiki/wiki.php?n=Main.AutoRegistration\r\n" +
                "";

            string testFile = utils.helpers.getAppPath() + "LicenseXMLFileSample.xml";
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            //read file into memorystream
            using (System.IO.FileStream file = new System.IO.FileStream(testFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                byte[] bytes = new byte[file.Length];
                file.Read(bytes, 0, (int)file.Length);
                ms.Write(bytes, 0, (int)file.Length);
                ms.Flush();
            }

            Attachement[] atts = new Attachement[] { new Attachement(ms, "test.xml") };
            MailMessage msg = new MailMessage("E841719", sBody, "License Keys - Order: 15476: [NAU-1504] CETerm for Windows CE 6.0 / 5.0 / CE .NET", atts, DateTime.Now);

            this.Cursor = Cursors.WaitCursor;
            this.Enabled = false;
            Application.DoEvents();
            int i = _licenseMail.processMail(msg);
            this.Enabled = true;
            this.Cursor = Cursors.Default;
            Application.DoEvents();

            //setLblStatus("Updated data. Use refresh";
            doRefresh();
        }
示例#58
0
 private bool loadXml(string filename)
 {
     if (!System.IO.File.Exists(filename))
     {
         MessageBox.Show(filename + " does not exist, please select a file");
         return false;
     }
     string xmlstr = System.IO.File.ReadAllText(filename);
     // Encode in UTF-8 byte array
     byte[] encodedString = Encoding.UTF8.GetBytes(xmlstr);
     // Put the byte array into a stream and rewind
     System.IO.MemoryStream ms = new System.IO.MemoryStream(encodedString);
     ms.Flush();
     ms.Position = 0;
     _xml.Load(ms);
     return true;
 }
示例#59
0
        public void Convert()
        {
            //System.Web.HttpContext.Current.Response.Write("hello");
            string vstExcep;
            this._stNmRpt = this._stNmRpt.Replace(".rpt", "");
            this._stNmRpt = this._stNmRpt.Replace(".RPT", "");
            try
            {
                    //System.Web.HttpContext.Current.Response.Write(_stNmRpt);
                System.IO.MemoryStream vioMemor = new System.IO.MemoryStream();
                CrystalDecisions.CrystalReports.Engine.ReportDocument vrpRepor = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

                string vstRepor = System.Web.HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"].ToString() + "report\\"+this._stNmRpt + ".rpt";
                                //System.Web.HttpContext.Current.Response.Write(vstRepor);
                vrpRepor.Load(vstRepor);
                if (_dsDatas == null) { return; }
                vrpRepor.Database.Tables[0].SetDataSource(this._dsDatas.Tables[0]);
                vrpRepor.Refresh();
                //vioMemor = (System.IO.MemoryStream)vrpRepor.ExportToStream(CrystalDecisions.Shared.ExportFormatType.Excel);
                vioMemor = (System.IO.MemoryStream)vrpRepor.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                vrpRepor.Close();
                try
                {
                    System.Web.HttpContext.Current.Response.Buffer = false;
                    System.Web.HttpContext.Current.Response.ClearContent();
                    System.Web.HttpContext.Current.Response.ClearHeaders();
                    System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
                    System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + this._stNmRpt.Replace("\\", "") + ".pdf");
                    System.Web.HttpContext.Current.Response.BinaryWrite(vioMemor.ToArray());
                    System.Web.HttpContext.Current.Response.Buffer = true;
                }
                catch (System.Exception vsqExcep) { vstExcep = vsqExcep.Message; }
                finally
                {
                    if (vioMemor != null) { vioMemor.Flush(); vioMemor = null; }
                    else { vioMemor = null; }
                    if (vrpRepor != null) vrpRepor = null;
                }
            }
            catch (System.Exception vsqExcep) { vstExcep = vsqExcep.Message; }
        }
    public void CopySelectedObjectsToClipboard()
    {
      System.Windows.Forms.DataObject dao = new System.Windows.Forms.DataObject();

      ArrayList objectList = new ArrayList();

      foreach (IHitTestObject o in this.m_SelectedObjects)
      {
        if (o.HittedObject is System.Runtime.Serialization.ISerializable)
        {
          objectList.Add(o.HittedObject);
        }
      }

      dao.SetData("Altaxo.Graph.GraphObjectList", objectList);

      // Test code to test if the object list can be serialized
#if false
      {
      System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binform = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        System.IO.MemoryStream stream = new System.IO.MemoryStream();
        binform.Serialize(stream, objectList);

        stream.Flush();
        stream.Seek(0, System.IO.SeekOrigin.Begin);
        object obj = binform.Deserialize(stream);
        stream.Close();
        stream.Dispose();
      }
#endif

      // now copy the data object to the clipboard
      System.Windows.Forms.Clipboard.SetDataObject(dao, true);
    }