Flush() public method

public Flush ( ) : void
return void
Exemplo n.º 1
0
        public void With_WebSocket_CanReadSmallFrame()
        {
            var handshake = GenerateSimpleHandshake();
            using (var ms = new MemoryStream())
            using (WebSocket ws = new WebSocketRfc6455(ms, new WebSocketListenerOptions() { PingTimeout = Timeout.InfiniteTimeSpan }, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2), handshake.Request,handshake.Response, handshake.NegotiatedMessageExtensions))
            {
                ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);

                var reader = ws.ReadMessageAsync(CancellationToken.None).Result;
                Assert.IsNotNull(reader);
                using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true))
                {
                    String s = sr.ReadToEnd();
                    Assert.AreEqual("Hi", s);
                }

                ms.Seek(0, SeekOrigin.Begin);
                ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);

                reader = ws.ReadMessageAsync(CancellationToken.None).Result;
                Assert.IsNotNull(reader);
                using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true))
                {
                    String s = sr.ReadToEndAsync().Result;
                    Assert.AreEqual("Hi", s);
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Downloads data from a url.
        /// </summary>
        /// <param name="url">Url to retrieve the data.</param>
        /// <returns>Byte array of data from the url.</returns>
        public static byte[] DownloadData(this string url)
        {
            WebRequest webRequest = WebRequest.Create(url);

            using (WebResponse webResponse = webRequest.GetResponse())
            {
                using (Stream stream = webResponse.GetResponseStream())
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        byte[] buffer = new byte[1024];

                        while (true)
                        {
                            int bytesRead = stream.Read(buffer, 0, buffer.Length);

                            if (bytesRead == 0)
                            {
                                break;
                            }
                            else
                            {
                                memoryStream.Write(buffer, 0, bytesRead);
                            }
                        }

                        memoryStream.Flush();

                        return memoryStream.ToArray();
                    }
                }
            }
        }
        public override byte[] Encode(byte[] bytes)
        {
            using (var inputstr = new MemoryStream(bytes))
            using (var outputstr = new MemoryStream())
            {
                // http://stackoverflow.com/questions/9050260/what-does-a-zlib-header-look-like
                // http://stackoverflow.com/questions/18450297/is-it-possible-to-use-the-net-deflatestream-for-pdf-creation
                // https://web.archive.org/web/20130905215303/http://connect.microsoft.com/VisualStudio/feedback/details/97064/deflatestream-throws-exception-when-inflating-pdf-streams

//#if IONIC
                using (var dstream = new Ionic.Zlib.ZlibStream(outputstr, Ionic.Zlib.CompressionMode.Compress))
                {
                    dstream.FlushMode = Ionic.Zlib.FlushType.Finish;
//#elif NET40
//                using (var dstream = new System.IO.Compression.DeflateStream(outputstr, System.IO.Compression.CompressionMode.Compress))
//                {
//                    // Zlib magic header (Default Compression):
//                    outputstr.WriteByte(0x78);
//                    outputstr.WriteByte(0x9C);
//#else //NET45+
//                using (var dstream = new System.IO.Compression.DeflateStream(outputstr, System.IO.Compression.CompressionLevel.Optimal))
//                {
//                    // Zlib magic header (Best Compression):
//                    outputstr.WriteByte(0x78);
//                    outputstr.WriteByte(0xDA);
//#endif
                    inputstr.CopyTo(dstream);
                    inputstr.Flush();
                }
                return outputstr.ToArray();
            }
        }
        public override bool Execute()
        {
            Log.LogMessage( MessageImportance.Low, "Packing M-Files Application." );

            // Make sure the collections are never null.
            References = References ?? new ITaskItem[ 0 ];
            SourceFiles = SourceFiles ?? new ITaskItem[ 0 ];
            DefaultEnvironments = DefaultEnvironments ?? new string[ 0 ];

            // Create the application package contents.
            var references = References.Select( item => new Reference( item ) ).ToList();
            var files = SourceFiles.Select( item => new PackageFile( item ) ).ToList();

            var appDef = CreateApplicationDefinition( references, files );
            var outputZip = CreatePackage( references, files );

            // Serialize the application definition file.
            var stream = new MemoryStream();
            var serializer = new XmlSerializer( typeof( ApplicationDefinition ) );
            serializer.Serialize( stream, appDef );
            stream.Flush();
            stream.Position = 0;
            outputZip.AddEntry( "appdef.xml", stream );

            // Save the zip.
            outputZip.Save();

            return true;
        }
        /// <summary>
        /// Loads the report and binds the data for the selected report
        /// </summary>
        protected void btnCreateReport_Click(object sender, EventArgs e)
        {
            getReportName();

            //Gets the location of the RDLC file to load
            m_rdlcPath = HttpContext.Current.Request.MapPath(".") + "\\" + "Reports" + "\\" + m_reportName + ".rdlc";

            //creates the ReportDataSource and populates it based on the selected values
            ReportDataSource rds = getDatasource();

            //Resets the ReportViewer, adds the new datasource, and changes the name of the report
            ReportViewer1.Reset();
            ReportViewer1.LocalReport.DataSources.Add(rds);
            ReportViewer1.LocalReport.DisplayName = "reportDatasource";

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(m_rdlcPath);
            using (MemoryStream xmlStream = new MemoryStream())
            {
                xmldoc.Save(xmlStream);
                xmlStream.Flush();
                xmlStream.Position = 0;
                ReportViewer1.LocalReport.LoadReportDefinition(xmlStream);
            }

            //binds the data to the reportviewer and refreshes the display
            ReportViewer1.DataBind();
            ReportViewer1.LocalReport.Refresh();
            ReportViewer1.Visible = true;
        }
Exemplo n.º 6
0
 public static void SaveJPG100(this Bitmap image, MemoryStream stream)
 {
     stream.Flush();
     EncoderParameters encoderParameters = new EncoderParameters(1);
     encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 75L);
     image.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
 }
Exemplo n.º 7
0
        private void ParseCurrentBuffer()
        {
            try
            {
                var ms = new MemoryStream();
                var sw = new StreamWriter(ms);
                var str = TextBox1.Text;
                sw.Write(str);
                sw.Flush();
                ms.Flush();
                ms.Position = 0;
                try
                {
                    var content = XamlReader.Load(ms);
                    if (content != null)
                    {
                        cc.Children.Clear();
                        cc.Children.Add((UIElement) content);
                    }
                    TextBox1.Foreground = Brushes.Black;
                    ErrorText.Text = "";
                }

                catch (XamlParseException xpe)
                {
                    TextBox1.Foreground = Brushes.Red;
                    TextBox1.TextWrapping = TextWrapping.Wrap;
                    ErrorText.Text = xpe.Message;
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }
Exemplo n.º 8
0
        public XmlDocument ToXML()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                // xmlns:georss="http://www.georss.org/georss"
                // xmlns:gml="http://www.opengis.net/gml"
                //xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
                //xmlns:kml="http://www.opengis.net/kml/2.2"
                //xmlns:dc="http://purl.org/dc/elements/1.1/"
                var ns = new XmlSerializerNamespaces();
                ns.Add("georss", "http://www.georss.org/georss");
                ns.Add("gml", "http://www.opengis.net/gml");
                ns.Add("geo", "http://www.w3.org/2003/01/geo/wgs84_pos#");
                ns.Add("kml", "http://www.opengis.net/kml/2.2");
                ns.Add("dc", "http://purl.org/dc/elements/1.1/");

                XmlSerializer s = new XmlSerializer(this.GetType());
                Console.WriteLine("Testing for type: {0}", this.GetType());
                s.Serialize(XmlWriter.Create(stream), this, ns);
                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                //object o = s.Deserialize(XmlReader.Create(stream));
                //Console.WriteLine("  Deserialized type: {0}", o.GetType());
                XmlDocument xml = new XmlDocument();
                xml.Load(stream);
                Console.Write(xml.InnerXml);
                return xml;
            }

            //var serializer = new XmlSerializer(this.GetType());
            //serializer.Serialize(new StreamWriter("test.xml"), this);
        }
Exemplo n.º 9
0
        protected override void OnPreRender(EventArgs e)
        {
            if (!this.ReadOnlyMode && !UseBrowseTemplate)
            {
                string jsonData;

                using (var s = new MemoryStream())
                {
                    var workData = ContentType.GetContentTypes()
                        .Select(n => new ContentTypeItem {value = n.Name, label = n.DisplayName, path = n.Path, icon = n.Icon})
                        .OrderBy(n => n.label);

                    var serializer = new DataContractJsonSerializer(typeof (ContentTypeItem[]));
                    serializer.WriteObject(s, workData.ToArray());
                    s.Flush();
                    s.Position = 0;
                    using (var sr = new StreamReader(s))
                    {
                        jsonData = sr.ReadToEnd();
                    }
                }

                // init control happens in prerender to handle postbacks (eg. pressing 'inherit from ctd' button)
                var contentTypes = _contentTypes ?? GetContentTypesFromControl();
                InitControl(contentTypes);
                var inherit = contentTypes == null || contentTypes.Count() == 0 ? 0 : 1;

                UITools.RegisterStartupScript("initdropboxautocomplete", string.Format("SN.ACT.init({0},{1})", jsonData, inherit), this.Page);
            }

            base.OnPreRender(e);
        }
Exemplo n.º 10
0
        public static String XMLPrint(this String xml){
            if (string.IsNullOrEmpty(xml))
                return xml;
            String result = "";

            var mStream = new MemoryStream();
            var writer = new XmlTextWriter(mStream, Encoding.Unicode);
            var document = new XmlDocument();

            try{
                document.LoadXml(xml);
                writer.Formatting = Formatting.Indented;
                document.WriteContentTo(writer);
                writer.Flush();
                mStream.Flush();
                mStream.Position = 0;
                var sReader = new StreamReader(mStream);
                String formattedXML = sReader.ReadToEnd();

                result = formattedXML;
            }
            catch (XmlException){
            }

            mStream.Close();
            writer.Close();

            return result;
        }
Exemplo n.º 11
0
        public void TestRoundTripElementSerialisation()
        {
            // Use a BinaryFormatter or SoapFormatter.
            IFormatter formatter = new BinaryFormatter();
            //IFormatter formatter = new SoapFormatter();

            // Create an instance of the type and serialize it.
            var elementId = new SerializableId
            {
                IntID = 42,
                StringID = "{BE507CAC-7F23-43D6-A2B4-13F6AF09046F}"
            };

            //Serialise to a test memory stream
            var m = new MemoryStream();
            formatter.Serialize(m, elementId);
            m.Flush();

            //Reset the stream
            m.Seek(0, SeekOrigin.Begin);

            //Readback
            var readback = (SerializableId)formatter.Deserialize(m);

            Assert.IsTrue(readback.IntID == 42);
            Assert.IsTrue(readback.StringID.Equals("{BE507CAC-7F23-43D6-A2B4-13F6AF09046F}"));
        }
Exemplo n.º 12
0
        public void ProcessAction(Object eventObject)
        {
            lock (blacklistLock)
            {
                if(blacklist.Contains(eventObject))
                {
                    blacklist.Remove(eventObject);
                    return;
                }
            }

            var memoryStream = new MemoryStream();
            var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress);
            var writer = new StreamWriter(gzipStream);

            serializer.Serialize(writer, eventObject);

            writer.Flush();
            gzipStream.Flush();
            memoryStream.Flush();

            writer.Close();
            gzipStream.Close();
            memoryStream.Close();

            var obj = new EventObject { MessageType = eventObject.GetType().AssemblyQualifiedName, MessageBody = memoryStream.ToArray(), SessionId = sessionId };

            eventRepository.Save(obj);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Attempt to get the list of character types.
        /// </summary>
        public bool GetCharacterTypes()
        {
            omaeSoapClient objService = _objOmaeHelper.GetOmaeService();

            try
            {
                MemoryStream objStream = new MemoryStream();
                XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8);

                objService.GetCharacterTypes().WriteTo(objWriter);
                // Flush the output.
                objWriter.Flush();
                objStream.Flush();

                XmlDocument objXmlDocument = _objOmaeHelper.XmlDocumentFromStream(objStream);

                // Close everything now that we're done.
                objWriter.Close();
                objStream.Close();

                // Stuff all of the items into a ListItem List.
                foreach (XmlNode objNode in objXmlDocument.SelectNodes("/types/type"))
                {
                    ListItem objItem = new ListItem();
                    objItem.Value = objNode["id"].InnerText;
                    objItem.Name = objNode["name"].InnerText;
                    _lstCharacterTypes.Add(objItem);
                }

                // Add an item for Official NPCs.
                ListItem objNPC = new ListItem();
                objNPC.Value = "4";
                objNPC.Name = "Official NPC Packs";
                _lstCharacterTypes.Add(objNPC);

                // Add an item for Custom Data.
                ListItem objData = new ListItem();
                objData.Value = "data";
                objData.Name = "Data";
                _lstCharacterTypes.Add(objData);

                // Add an item for Character Sheets.
                ListItem objSheets = new ListItem();
                objSheets.Value = "sheets";
                objSheets.Name = "Character Sheets";
                _lstCharacterTypes.Add(objSheets);

                cboCharacterTypes.Items.Clear();
                cboCharacterTypes.DataSource = _lstCharacterTypes;
                cboCharacterTypes.ValueMember = "Value";
                cboCharacterTypes.DisplayMember = "Name";
            }
            catch (EndpointNotFoundException)
            {
                MessageBox.Show(NO_CONNECTION_MESSAGE, NO_CONNECTION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            objService.Close();

            return false;
        }
Exemplo n.º 14
0
        public void AddAttachmentPlaceHolder(string actualPath, string placeholderPath)
        {
            var placeholderDocument = new XmlDocument();

			placeholderDocument.CreateXmlDeclaration("1.0", "utf-16", "yes");

            XmlNode rootNode = placeholderDocument.CreateNode(XmlNodeType.Element, "ManagedAttachment", string.Empty);
            XmlNode actualPathNode = placeholderDocument.CreateNode(XmlNodeType.Element, "ActualPath", string.Empty);
            XmlNode placeholderNode = placeholderDocument.CreateNode(XmlNodeType.Element, "PlaceholderPath",
                                                                     string.Empty);

            actualPathNode.InnerText = actualPath;
            placeholderNode.InnerText = placeholderPath;

            rootNode.AppendChild(actualPathNode);
            rootNode.AppendChild(placeholderNode);

            placeholderDocument.AppendChild(rootNode);

            using (var ms = new MemoryStream())
            {
                ms.Position = 0;
                placeholderDocument.Save(ms);
                ms.Flush();

                ms.Position = 0;
                var sr = new StreamReader(ms);
                string xml = sr.ReadToEnd();

                string filecontents = LargeAttachmentHelper.FileTag + xml;
				File.WriteAllText(placeholderPath, filecontents, Encoding.Unicode);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Encrypts a string
        /// </summary>
        /// <param name="key">The key that will be used to encrypt the data</param>
        /// <param name="data">The string you wish to encrypt</param>
        /// <returns>Encrypted data</returns>
        public static string Encrypt(string key, string data)
        {
            string result = string.Empty;

            if (!string.IsNullOrEmpty(data))
            {
                byte[] m_Key = new byte[8];
                byte[] m_IV = new byte[8];

                InitKey(key, ref m_Key, ref m_IV);

                DESCryptoServiceProvider csprov = new DESCryptoServiceProvider();
                MemoryStream memstream = new MemoryStream();
                CryptoStream crstream = new CryptoStream(memstream, csprov.CreateEncryptor(m_Key, m_IV), CryptoStreamMode.Write);
                StreamWriter sw = new StreamWriter(crstream);

                sw.Write(data);
                sw.Flush();
                crstream.FlushFinalBlock();
                memstream.Flush();

                result = Convert.ToBase64String(memstream.GetBuffer(), 0, Convert.ToInt32(memstream.Length));

                sw.Close();
                crstream.Close();
                memstream.Close();
            }

            return result;
        }
Exemplo n.º 16
0
        public static Stream GetStream(Stream fileStream)
        {
            Stream objFileStream = null;
            try
            {
                GZipStream gzip = new GZipStream(fileStream, CompressionMode.Decompress);

                MemoryStream memStream = new MemoryStream();

                byte[] bytes = new byte[1024];
                int bytesRead = -1;
                while (bytesRead != 0)
                {
                    bytesRead = gzip.Read(bytes, 0, 1024);
                    memStream.Write(bytes, 0, bytesRead);
                    memStream.Flush();
                }
                memStream.Position = 0;
                objFileStream = memStream;

                gzip.Close();
                gzip.Dispose();

                fileStream.Dispose();
            }
            catch (Exception)
            {
                fileStream.Position = 0;
                objFileStream = fileStream;
            }
            return objFileStream;
        }
Exemplo n.º 17
0
        private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset, long ExpectedLength)
        {
            bool result = true;
            long startLength = ms.Position;
            long nextbyte = startLength % 256;

            byte[] byteBuffer = new byte[BufferLength];
            for (int i = Offset; i < (Offset + BytesToWrite); i++)
            {
                byteBuffer[i] = (byte)nextbyte;

                // Reset if wraps past 255
                if (++nextbyte > 255)
                    nextbyte = 0;
            }

            ms.Write(byteBuffer, Offset, BytesToWrite);
            ms.Flush();
            if (ExpectedLength < ms.Length)
            {
                result = false;
                Log.Exception("Expeceted final length of " + ExpectedLength + " bytes, but got " + ms.Length + " bytes");
            }
            return result;
        }
		public void DocumentIsUpToDate()
		{
			var fullpath = Path.GetFullPath(@"..\..\..\RulesList.xml");
			var docText = File.ReadAllText(fullpath);
			var children =
				_rules.OrderBy(_ => _.ID)
					.Select(
						rule =>
						new XElement(
							"rule",
							new XElement("id", rule.ID),
							new XElement("title", rule.Title),
							new XElement("suggestion", rule.Suggestion)))
					.Cast<object>()
					.ToArray();
			var rules = new XElement("rules", children);
			var doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), rules);
			var currentText = string.Empty;
			using (var ms = new MemoryStream())
			{
				doc.Save(ms);
				ms.Flush();
				ms.Position = 0;
				using (var reader = new StreamReader(ms))
				{
					currentText = reader.ReadToEnd();
				}
			}

			Assert.AreEqual(docText, currentText);
		}
Exemplo n.º 19
0
        public void Print()
        {
            if (RunAsUser)
            {
                MemoryStream stdin = new MemoryStream();
                MemoryStream stdout = new MemoryStream();
                MemoryStream stderr = new MemoryStream();

                try
                {
                    Serialize(stdin, this);
                    stdin.Flush();
                    stdin.Position = 0;

                    int retcode = WindowsIdentityStore.RunProcessAsUser(UserName, stdin, stdout, stderr, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Assembly.GetExecutingAssembly().Location, new string[] { "-print" });

                    if (retcode != 0)
                    {
                        stderr.Position = 0;
                        Logger.Log(LogLevel.Info, "Error printing file:\n{0}", System.Text.Encoding.ASCII.GetString(stderr.ToArray()));
                        throw new AggregateException((Exception)Deserialize(stderr));
                    }
                }
                finally
                {
                    stdin.Dispose();
                    stdout.Dispose();
                    stderr.Dispose();
                }
            }
            else
            {
                Run();
            }
        }
Exemplo n.º 20
0
        public static string ConvertToXml(string pXmlString)
        {
            string Result = "";
            MemoryStream mStream = null;
            XmlTextWriter writer = null;
            XmlDocument document = new XmlDocument();;

            try
            {
                document.LoadXml(pXmlString);
                mStream = new MemoryStream();
                writer = new XmlTextWriter(mStream, Encoding.Unicode);
                writer.Formatting = Formatting.Indented;

                document.WriteContentTo(writer);
                writer.Flush();
                mStream.Flush();
                mStream.Position = 0;

                StreamReader sReader = new StreamReader(mStream);
                String FormattedXML = sReader.ReadToEnd();
                Result = FormattedXML;
            }
            catch { }

            if (mStream != null)
                mStream.Close();
            if (writer != null)
                writer.Close();

            return Result;
        }
Exemplo n.º 21
0
 private static Stream Serialize(Message message)
 {
     MemoryStream stream = new MemoryStream();
     Serializer.Serialize(message, stream);
     stream.Flush();
     return stream;
 }
Exemplo n.º 22
0
        /// <summary>
        /// Gets the bytes from the Web using the specified uri.
        /// </summary>
        /// <param name="uri">File Web location.</param>
        /// <param name="onProgress">Function executed when progress changes. Return true to cancel the operation, false to continue.</param>
        /// <returns>Encoded image or undefined output in case if the operation is canceled.</returns>
        public static byte[] GetBytes(this Uri uri, Func<float, bool> onProgress = null)
        {
            byte[] output = null;
            var request = (HttpWebRequest)WebRequest.Create(uri.AbsoluteUri);

            using (WebResponse response = request.GetResponse())
            using (Stream source = response.GetResponseStream())
            using(MemoryStream target = new MemoryStream())
            {
                int bytes, copiedBytes = 0;
                var buffer = new byte[1024];
                while ((bytes = source.Read(buffer, 0, buffer.Length)) > 0)
                {
                    target.Write(buffer, 0, bytes);
                    copiedBytes += bytes;

                    if (onProgress != null)
                    {
                        bool shouldCancel = onProgress((float)copiedBytes / response.ContentLength);
                        if (shouldCancel)
                            break;
                    }
                }

                target.Flush();
                output = target.ToArray();
            }

            return output;
        }
Exemplo n.º 23
0
        public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (item == null)
            {
                writer.WriteNull();
                return;
            }

            var formatter = new BinaryFormatter();
            byte[] bytes;
            using (var memoryStream = new MemoryStream())
            {
                formatter.Serialize(memoryStream, item);
                memoryStream.Flush();
                bytes = memoryStream.ToArray();
            }
            
            writer.Write(bytes.Length);
            writer.Write(bytes);
        }
Exemplo n.º 24
0
        public RecordedVideoFrame(ColorImageFrame colorFrame)
        {
            if (colorFrame != null)
            {
                byte[] bits = new byte[colorFrame.PixelDataLength];
                colorFrame.CopyPixelDataTo(bits);

                int BytesPerPixel = colorFrame.BytesPerPixel;
                int Width = colorFrame.Width;
                int Height = colorFrame.Height;

                var bmp = new WriteableBitmap(Width, Height, 96, 96, PixelFormats.Bgr32, null);
                bmp.WritePixels(new System.Windows.Int32Rect(0, 0, Width, Height), bits, Width * BytesPerPixel, 0);
                JpegBitmapEncoder jpeg = new JpegBitmapEncoder();
                jpeg.Frames.Add(BitmapFrame.Create(bmp));
                var SaveStream = new MemoryStream();
                jpeg.Save(SaveStream);
                SaveStream.Flush();
                JpegData = SaveStream.ToArray();
            }
            else
            {
                return;
            }
        }
Exemplo n.º 25
0
        public static void SendMessage(IntPtr hWnd, string message)
        {
            BinaryFormatter b = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            b.Serialize(stream, message);
            stream.Flush();

            // Now move the data into a pointer so we can send
            // it using WM_COPYDATA:
            // Get the length of the data:
            int dataSize = (int)stream.Length;
            if (dataSize > 0)
            {
                byte[] data = new byte[dataSize];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, dataSize);
                IntPtr ptrData = Marshal.AllocCoTaskMem(dataSize);
                Marshal.Copy(data, 0, ptrData, dataSize);

                COPYDATASTRUCT cds = new COPYDATASTRUCT();
                cds.cbData = dataSize;
                cds.dwData = IntPtr.Zero;
                cds.lpData = ptrData;
                int res = SendMessage(hWnd, WM_COPYDATA, 0, ref cds);

                // Clear up the data:
                Marshal.FreeCoTaskMem(ptrData);
            }

            stream.Close();
        }
Exemplo n.º 26
0
 public void SetCookieDomain(string cookiename, object cookievalue, int hour)
 {
     try
     {
         System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         string result = string.Empty;
         //将字符串进行base64编码,解决中文问题。然后进行序列化化,将shopcart保存至cookie
         using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
         {
             bf.Serialize(ms, cookievalue);
             byte[] byt = new byte[ms.Length];
             byt    = ms.ToArray();
             result = System.Convert.ToBase64String(byt);
             ms.Flush();
         }
         HttpCookie hc = new HttpCookie(cookiename);
         hc.Value    = result;
         hc.HttpOnly = false;
         if (hour != 0)
         {
             hc.Expires = DateTime.Now.AddHours(hour);  //设置过期时间
         }
         else
         {
             hc.Expires = DateTime.MaxValue;
         }
         hc.Domain = CFun.GetAppStr("webDomain");
         HttpContext.Current.Response.Cookies.Add(hc);
     }
     catch
     {
     }
 }
Exemplo n.º 27
0
        /// <summary>
        /// Do Encry for plainString.
        /// </summary>
        /// <param name="plainString">Plain string.</param>
        /// <returns>Encrypted string as base64.</returns>
        public string Encrypt(string plainString)
        {
            // Create the file streams to handle the input and output files.
            MemoryStream fout = new MemoryStream(200);
            fout.SetLength(0);

            // Create variables to help with read and write.
            byte[] bin = System.Text.Encoding.Unicode.GetBytes(plainString);
            DES des = new DESCryptoServiceProvider();

            // des.KeySize=64;
            CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
            encStream.Write(bin, 0, bin.Length);
            encStream.FlushFinalBlock();

            fout.Flush();
            fout.Seek(0, SeekOrigin.Begin);

            // read all string
            byte[] bout = new byte[fout.Length];
            fout.Read(bout, 0, bout.Length);
            encStream.Close();
            fout.Close();

            return Convert.ToBase64String(bout, 0, bout.Length);
        }
Exemplo n.º 28
0
    public static Program ReResolveInMem(Program p, bool doTypecheck = true)
    {
        Program output;

        using (var writer = new System.IO.MemoryStream())
        {
            var st = new System.IO.StreamWriter(writer);
            var tt = new TokenTextWriter(st);
            p.Emit(tt);
            writer.Flush();
            st.Flush();

            writer.Seek(0, System.IO.SeekOrigin.Begin);
            var s = ParserHelper.Fill(writer, new List <string>());

            var v = Parser.Parse(s, "ReResolveInMem", out output);
            if (ResolveProgram(output, "ReResolveInMem"))
            {
                throw new InvalidProg("Cannot resolve " + "ReResolveInMem");
            }
            if (doTypecheck && TypecheckProgram(output, "ReResolveInMem"))
            {
                throw new InvalidProg("Cannot typecheck " + "ReResolveInMem");
            }
        }
        return(output);
    }
Exemplo n.º 29
0
        public override IDocument Render(IDictionary<string, object> context)
        {
            Debug.Assert(context != null);
            Debug.Assert(this.engine != null);

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            //执行主要内容的渲染过程
            using (var inStream = new MemoryStream(base.GetBuffer(), false))
            using (var reader = new StreamReader(inStream, Encoding.UTF8))
            using (var ws = new MemoryStream())
            using (var writer = new StreamWriter(ws))
            {
                //执行渲染
                this.engine.Evaluate(context, reader, writer);
                writer.Flush();
                ws.Flush();
                var resultDoc = new ExcelMLTemplate();
                resultDoc.PutBuffer(ws.ToArray());
                return resultDoc;
            }
        }
        public static String FormatXml(String value)
        {
            using (var mStream = new MemoryStream())
            {
                using (var writer = new XmlTextWriter(mStream, Encoding.Unicode) { Formatting = System.Xml.Formatting.Indented})
                {
                    var document = new XmlDocument();
                    try
                    {
                        document.LoadXml(value);

                        document.WriteContentTo(writer);
                        writer.Flush();
                        mStream.Flush();

                        mStream.Position = 0;
                        var sReader = new StreamReader(mStream);

                        return sReader.ReadToEnd();
                    }
                    catch (XmlException)
                    {
                    }
                }
            }
            return value;
        }
Exemplo n.º 31
0
        public bool PutImageToCache(MemoryStream tile, MapType type, Point pos, int zoom)
        {
            FileStream fs = null;
            try
            {
                string fileName = GetFilename(type, pos, zoom, true);
                fs = new FileStream(fileName, FileMode.Create);
                tile.WriteTo(fs);
                tile.Flush();
                fs.Close();
                fs.Dispose();
                tile.Seek(0, SeekOrigin.Begin);

                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error in FilePureImageCache.PutImageToCache:\r\n" + ex.ToString());
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                return false;
            }
        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            if (!request.IsEmpty)
            {
                XmlReader bodyReader = request.GetReaderAtBodyContents().ReadSubtree();

                MemoryStream stream = new MemoryStream();
                XmlWriter writer = XmlWriter.Create(stream);

                if (transform == null)
                {
                    transform = new XslCompiledTransform(true);
                    var reader = XmlReader.Create(new StringReader(Properties.Resources.XmlCleaner));
                    transform.Load(reader);
                }
                transform.Transform(bodyReader, writer);

                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                bodyReader = XmlReader.Create(stream);

                Message changedMessage = Message.CreateMessage(request.Version, null, bodyReader);
                changedMessage.Headers.CopyHeadersFrom(request.Headers);
                changedMessage.Properties.CopyProperties(request.Properties);
                request = changedMessage;
            }

            return null;
        }
Exemplo n.º 33
0
 byte[] packData(object v)
 {
     MsgPack.MessagePackObject mpobj  = convertToMsgPackObject(v);
     System.IO.MemoryStream    stream = new System.IO.MemoryStream();
     MsgPack.Packer            packer = MsgPack.Packer.Create(stream);
     mpobj.PackToMessage(packer, null);
     stream.Flush();
     return(stream.GetBuffer());
 }
Exemplo n.º 34
0
 public static T Clone <T>(T obj)
 {
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
     serializer.WriteObject(ms, obj);
     ms.Flush();
     ms = new System.IO.MemoryStream(ms.ToArray());
     return((T)serializer.ReadObject(ms));
 }
Exemplo n.º 35
0
        public static string Beautify(System.Xml.XmlDocument doc)
        {
            string strRetValue = null;

            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            // enc = new System.Text.UTF8Encoding(false);

            System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
            xmlWriterSettings.Encoding            = enc;
            xmlWriterSettings.Indent              = true;
            xmlWriterSettings.IndentChars         = "    ";
            xmlWriterSettings.NewLineChars        = "\r\n";
            xmlWriterSettings.NewLineOnAttributes = true;
            xmlWriterSettings.NewLineHandling     = System.Xml.NewLineHandling.Replace;
            //xmlWriterSettings.OmitXmlDeclaration = true;
            xmlWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Document;


            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(ms, xmlWriterSettings))
                {
                    doc.Save(writer);
                    writer.Flush();
                    ms.Flush();

                    writer.Close();
                } // End Using writer

                ms.Position = 0;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(ms, enc))
                {
                    // Extract the text from the StreamReader.
                    strRetValue = sr.ReadToEnd();

                    sr.Close();
                } // End Using sr

                ms.Close();
            } // End Using ms


            /*
             * System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Always yields UTF-16, no matter the set encoding
             * using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings))
             * {
             *  doc.Save(writer);
             *  writer.Close();
             * } // End Using writer
             * strRetValue = sb.ToString();
             * sb.Length = 0;
             * sb = null;
             */

            xmlWriterSettings = null;
            return(strRetValue);
        } // End Function Beautify
Exemplo n.º 36
0
        //---------------------------------------------------------------------------------------------
        /// <summary>
        /// This method creates a Plan Quality Metric report for the specified plansum.
        /// </summary>
        /// <param name="patient">loaded patient</param>
        /// <param name="ss">structure set to use while generating Plan Quality Metrics</param>
        /// <param name="psum">Plansum for which the report is going to be generated.</param>
        /// <param name="rootPath">root directory for the report.  This method creates a subdirectory
        ///  'patientid' under the root, then creates the xml and html reports in the subdirectory.</param>
        /// <param name="userId">User whose id will be stamped on the report.</param>
        //---------------------------------------------------------------------------------------------
        override protected void dumpReportXML(Patient patient, StructureSet ss, PlanningItem plan_, string sXMLPath)
        {
            if (!(plan_ is PlanSum))
            {
                throw new ApplicationException("PlanSumReporter should be used only for PlanSum types!");
            }

            PlanSum psum = (PlanSum)plan_;

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent      = true;
            settings.IndentChars = ("\t");
            System.IO.MemoryStream mStream = new System.IO.MemoryStream();
            XmlWriter writer = XmlWriter.Create(mStream, settings);

            writer.WriteStartDocument(true);
            writer.WriteStartElement("PlanQualityReport");
            writer.WriteAttributeString("created", DateTime.Now.ToString());
            writer.WriteAttributeString("userid", currentuser);
            writer.WriteAttributeString("eclipseVersion", eclipseVersion);
            writer.WriteAttributeString("scriptVersion", scriptVersion);
            writer.WriteStartElement("Patient");
            WritePatientXML(patient, writer);
            writer.WriteStartElement("PlanSum");
            psum.WriteXml(writer);
            foreach (PlanSetup plan in psum.PlanSetups)
            {
                WritePlanXML(plan, writer, CtrlPtSelector.IncludeControlPoints);
            }
            writer.WriteEndElement(); // </PlanSum>
            writer.WriteEndElement(); // </Patient>

            writer.WriteStartElement("DoseStatistics");
            WriteDoseStatisticsXML_Target(patient, ss, psum, writer);
            WriteDoseStatisticsXML_Prostate2GyOrLess(patient, ss, psum, writer);
            WriteDoseStatisticsXML_HeadAndNeck2GyOrLess(patient, ss, psum, writer);
            writer.WriteEndElement(); // </DoseStatistics>

            writer.WriteEndElement(); // </PlanQualityReport>
            writer.WriteEndDocument();
            writer.Flush();
            mStream.Flush();

            // write the XML file report.
            using (System.IO.FileStream file = new System.IO.FileStream(sXMLPath, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                // Have to rewind the MemoryStream in order to read its contents.
                mStream.Position = 0;
                mStream.CopyTo(file);
                file.Flush();
                file.Close();
            }

            writer.Close();
            mStream.Close();
        }
Exemplo n.º 37
0
        public static XDocument LoadXmlDocument(this IHttpRequest request)
        {
            // If there is no input stream, then there is no XML document
            if (request.Stream == null || request.Stream == Stream.Null)
            {
                return(null);
            }

            // If there is no data,
            var contentLengthString = request.GetHeaderValue("Content-Length");

            if (contentLengthString != null)
            {
                int contentLength;
                if (!int.TryParse(contentLengthString, out contentLength) || contentLength == 0)
                {
                    return(null);
                }
            }

            // Obtain an XML document from the stream
            var xDocument = XDocument.Load(request.Stream);

#if DEBUG
            // Dump the XML document to the logging
            if (xDocument.Root != null && s_log.IsLogEnabled(LogLevel.Debug))
            {
                // Format the XML document as an in-memory text representation
                using (var ms = new System.IO.MemoryStream())
                {
                    using (var xmlWriter = System.Xml.XmlWriter.Create(ms, new System.Xml.XmlWriterSettings
                    {
                        OmitXmlDeclaration = false,
                        Indent = true,
                        Encoding = System.Text.Encoding.UTF8,
                    }))
                    {
                        // Write the XML document to the stream
                        xDocument.WriteTo(xmlWriter);
                    }

                    // Flush
                    ms.Flush();

                    // Reset stream and write the stream to the result
                    ms.Seek(0, System.IO.SeekOrigin.Begin);

                    // Log the XML text to the logging
                    var reader = new System.IO.StreamReader(ms);
                    s_log.Log(LogLevel.Debug, () => reader.ReadToEnd());
                }
            }
#endif
            // Return the XML document
            return(xDocument);
        }
Exemplo n.º 38
0
 internal static void WriteMeshGeometryXml(XmlTextWriter x, Point3DCollection polyline)
 {
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         WriteDatStream(polyline, ms);
         ms.Flush();
         byte[] data = ms.GetBuffer();
         x.WriteBase64(data, 0, data.Length);
     }
 }
Exemplo n.º 39
0
        private System.IO.MemoryStream CreateStream(byte[] decryptedPackage)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            ms.Write(decryptedPackage, 0, decryptedPackage.Length);
            ms.Flush();
            ms.Position = 0;

            return(ms);
        }
Exemplo n.º 40
0
        private byte[] GetCsv()
        {
            System.IO.MemoryStream ms = _dataTableToCsvMapper.Map(_tableReader.GetDataTable());

            byte[] byteArray = ms.ToArray();
            ms.Flush();
            ms.Close();

            return(byteArray);
        }
Exemplo n.º 41
0
        /// <summary>
        /// Gets the request data from the client.
        /// </summary>
        /// <param name="context">Provides access to the request and response objects.</param>
        /// <returns>The array of request bytes</returns>
        public virtual byte[] GetRequestData(IHttpContext context)
        {
            System.IO.Stream       inputRequest = null;
            System.IO.MemoryStream memoryOutput = null;

            HttpListenerRequest httpRequest = null;

            try
            {
                // Get the request and response context.
                httpRequest = context.HttpContext.Request;

                // Read the request stream data and write
                // to the memory stream.
                inputRequest = httpRequest.InputStream;
                memoryOutput = new System.IO.MemoryStream();
                HttpResponseContent.TransferData(inputRequest, memoryOutput);

                // Properly flush and close the output stream
                inputRequest.Flush();
                memoryOutput.Flush();
                inputRequest.Close();
                memoryOutput.Close();

                // Get the request data.
                byte[] requestData = memoryOutput.ToArray();

                // Return the request data.
                return(requestData);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                try
                {
                    if (inputRequest != null)
                    {
                        inputRequest.Close();
                    }
                }
                catch { }

                try
                {
                    if (memoryOutput != null)
                    {
                        memoryOutput.Close();
                    }
                }
                catch { }
            }
        }
Exemplo n.º 42
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            int port = 5000;

            try
            {
                // 複雜影像至剪貼簿(Clipboard)
                SendMessage(hwnd, WM_CAP_EDIT_COPY, 0, 0);

                // 自剪貼簿(Clipboard)取得物件
                IDataObject data = Clipboard.GetDataObject();

                // 建立記憶體的資料流
                System.IO.MemoryStream memStream = new System.IO.MemoryStream();

                if (data.GetDataPresent(typeof(System.Drawing.Bitmap)))
                {
                    Image image = ((Image)(data.GetData(typeof(System.Drawing.Bitmap))));

                    // 將影像依指定格式儲存至指定的資料流
                    image.Save(memStream, ImageFormat.Bmp);
                }

                // 將影像依指定格式儲存至指定的資料流
                picLocal.Image.Save(memStream, ImageFormat.Jpeg);

                // 回傳記憶體資料流之位元組陣列
                byte[] buffer = memStream.GetBuffer();

                // 建立用戶端TcpClient
                TcpClient tcpClient = new TcpClient(txtHost.Text, port);
                // 取得用戶端的輸出入串流
                clientStream = tcpClient.GetStream();

                // 建立BinaryWriter
                BinaryWriter binarywriter = new BinaryWriter(clientStream);
                binarywriter.Write(buffer);
                binarywriter.Flush();
                binarywriter.Close();

                memStream.Flush();
                memStream.Close();

                clientStream.Flush();
                clientStream.Close();

                tcpClient.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 43
0
    public static void Main(string [] args)
    {
        var source = new List <string>();

        source.Add("a");
        source.Add("b");
        using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) {
            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(List <string>));
            serializer.WriteObject(stream, source);
            stream.Flush();
        }
    }
Exemplo n.º 44
0
        public static byte[] Serialize <T>(T structure)
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();

                formatter.Serialize(stream, structure);

                stream.Flush();

                return(stream.ToArray());
            }
        }
Exemplo n.º 45
0
/*
 #if !MONO
 * public Object[] remove_instance_from_hash (String instance)
 * {
 *  Object[] ret = new Object[1];
 *
 * //    assem_perm_list.Remove (instance);
 *  instances.Remove (instance);
 *
 *  ret[0]=(Boolean) true;
 *  return ret;
 * }
 *
 * public Object[] add_assem_to_sec_hash (String assem_name)
 * {
 *  Object[] ret = new Object[1];
 *
 * //    assem_perm_list [assem_name] = 1;
 *
 *  ret[0]=(Boolean) true;
 *  return ret;
 * }
 #endif
 */

    #endregion

    #region helper funcs
    private static byte[] obj_serialize_int(Object new_instance, IFormatter bf)
    {
        Object [] ret = new Object[2];

        System.IO.MemoryStream mem_strim = new System.IO.MemoryStream();
        bf.Serialize(mem_strim, new_instance);
        mem_strim.Flush();

        byte [] byte_array = new byte [] {};
        byte_array = mem_strim.ToArray();

        return(byte_array);
    }
Exemplo n.º 46
0
        public byte[] SerializarObj(Mensaje obj)
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                formatter.Serialize(stream, obj);

                byte[] bytes = stream.ToArray();
                stream.Flush();

                return bytes;
            }
        }
Exemplo n.º 47
0
 public static byte[] Serialize(this ISerializable s)
 {
     if (s == null)
     {
         return(new byte[0]);
     }
     using (var mem = new System.IO.MemoryStream())
     {
         s.Serialize(mem);
         mem.Flush();
         return(mem.ToArray());
     }
 }
Exemplo n.º 48
0
        /// <summary>
        /// 获取输出信息
        /// </summary>
        /// <returns></returns>
        public string GetAllString()
        {
            string outinfo = Encoding.UTF8.GetString(outputstream.ToArray());

            //等待命令结束字符
            while (!outinfo.Trim().EndsWith(waitMark))
            {
                System.Threading.Thread.Sleep(200);
                outinfo = Encoding.UTF8.GetString(outputstream.ToArray());
            }
            outputstream.Flush();
            return(outinfo.ToString());
        }
Exemplo n.º 49
0
 public static System.Drawing.Image byteArrayToImage(byte[] byteArrayIn)
 {
     if (byteArrayIn == null)
     {
         return(null);
     }
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArrayIn))
     {
         System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
         ms.Flush();
         return(returnImage);
     }
 }
Exemplo n.º 50
0
 //Serialize 1 object để có thể gửi qua WebService
 public byte[] SerializeObject(object iObject)
 {
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     bf.Serialize(ms, iObject);
     ms.Flush();
     ms.Position = 0;
     byte[] bytBuffer = new byte[ms.Length + 1];
     ms.Read(bytBuffer, 0, Convert.ToInt32(ms.Length));
     ms.Close();
     ms = null;
     bf = null;
     return(bytBuffer);
 }
Exemplo n.º 51
0
        /// <summary>
        /// 获取输出信息
        /// </summary>
        /// <returns></returns>
        public string GetAllString()
        {
            string outinfo = Encoding.Default.GetString(outputstream.ToArray());

            outinfo = outinfo.Trim();
            while (!outinfo.EndsWith(waitMark1) && !outinfo.EndsWith(waitMark2))
            {
                System.Threading.Thread.Sleep(200);
                outinfo = Encoding.Default.GetString(outputstream.ToArray());
                outinfo = outinfo.Trim();
            }
            outputstream.Flush();
            return(outinfo.ToString());
        }
Exemplo n.º 52
0
        /// <summary>
        /// 处理响应
        /// </summary>
        /// <param name="stream"></param>
        protected override void ProcessResponse(Stream stream)
        {
            ResultStream = new System.IO.MemoryStream();
            var buffer = new byte[Client.Setting.ReadBufferSize];
            var count  = 0;

            while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ResultStream.Write(buffer, 0, count);
            }
            ResultStream.Flush();
            ProcessFinalResponse();
            ResultStream.Seek(0, SeekOrigin.Begin);
        }
Exemplo n.º 53
0
        /// <summary>
        /// 导出数据到EXCEL
        /// </summary>
        /// <param name="ds" name="fileName">ds 是System.Data.DataSet;fileName是文件名不包含,扩展名</param>
        public static byte[] ExportExcel(DataTable dt)
        {
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            int a = 1;

            //foreach (DataTable dt in ds.Tables)
            //{
            NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("sheet" + a);
            NPOI.SS.UserModel.IRow   row   = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
            }
            NPOI.SS.UserModel.ICell cell;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    cell = row2.CreateCell(j);
                    try
                    {
                        if (dt.Columns[i].DataType == typeof(DateTime) && dt.Rows[i][j] != DBNull.Value)
                        {
                            cell.SetCellValue(Convert.ToDateTime(dt.Rows[i][j]).ToString("yyyy-MM-dd hh:mm:ss"));
                        }
                        else
                        {
                            cell.SetCellValue(dt.Rows[i][j].ToString());
                        }
                    }
                    catch
                    {
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                    }
                }
            }
            a++;
            //}

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

            book.Write(ms);
            ms.Flush();
            ms.Position = 0;
            byte[] data = ms.ToArray();


            return(data);
        }
Exemplo n.º 54
0
        public void Serialize(PCAxis.Paxiom.PXModel model, ResponseBucket cacheResponse)
        {
            cacheResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=" + System.Text.Encoding.Default.WebName;
            PCAxis.Excel.XlsxSerializer serializer = new PCAxis.Excel.XlsxSerializer();
            serializer.InformationLevel = PCAxis.Paxiom.InformationLevelType.AllInformation;
            serializer.DoubleColumn     = PCAxis.Paxiom.Settings.Files.DoubleColumnFile;

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                serializer.Serialize(model, stream);
                stream.Flush();
                cacheResponse.ResponseData = stream.ToArray();
            }
        }
Exemplo n.º 55
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)
        {
            try
            {
                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";
                Response.AppendHeader("content-length", stream.Length.ToString());

                byte[] data1 = new byte[stream.Length];
                stream.Read(data1, 0, data1.Length);
                stream.Close();
                Response.BinaryWrite(data1);
                Response.Flush();

                //  Feb2015: Needed to replace "Response.End();" with the following 3 lines, to make sure the Excel was fully written to the Response
                System.Web.HttpContext.Current.Response.Flush();
                System.Web.HttpContext.Current.Response.SuppressContent = true;
                System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();

                return(true);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Failed, exception thrown: " + ex.Message);

                //  Display an error on the webpage.
                System.Web.UI.Page page = System.Web.HttpContext.Current.CurrentHandler as System.Web.UI.Page;
                page.ClientScript.RegisterStartupScript(page.GetType(), "log", "console.log('Failed, exception thrown: " + ex.Message + "')", true);

                return(false);
            }
        }
Exemplo n.º 56
0
        //使用流文件扩展session
        public static void SetStream <T>(this ISession session, string key, T value)
        {
            System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            string result = string.Empty;

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                bf.Serialize(ms, value);
                byte[] byt = new byte[ms.Length];
                byt    = ms.ToArray();
                result = System.Convert.ToBase64String(byt);
                ms.Flush();
                session.SetString(key, result);
            }
        }
Exemplo n.º 57
0
    //serialize
    public static byte[] SerializeObj(object obj)
    {
        using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
        {
            BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            using (var ds = new DeflateStream(stream, CompressionMode.Compress, true))
                formatter.Serialize(stream, obj);

            stream.Flush();
            stream.Position = 0;
            byte[] bytes = stream.ToArray();

            return(bytes);
        }
    }
Exemplo n.º 58
0
        public static string SerializeObject <T>(T obj)
        {
            string result = null;
            var    lateBoundSerializer = new DataContractJsonSerializer(typeof(T));

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                lateBoundSerializer.WriteObject(ms, obj);
                ms.Flush();
                ms.Position = 0;
                System.IO.StreamReader sr = new System.IO.StreamReader(ms);
                result = sr.ReadToEnd();
            }
            return(result);
        }
Exemplo n.º 59
0
 public static void Rewind(this System.IO.MemoryStream stream)
 {
     if (stream.Position > 0)
     {
         stream.Position = 0;
     }
     if (stream.Length > 0)
     {
         stream.Flush();
     }
     if (stream.CanSeek)
     {
         stream.Seek(0, SeekOrigin.Begin);
     }
 }
Exemplo n.º 60
0
        /// <summary>
        /// 序列化实体类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SerializeObject <T>(T 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 = new byte[ms.Length];
                byt    = ms.ToArray();
                result = System.Convert.ToBase64String(byt);
                ms.Flush();
            }
            return(result);
        }