Пример #1
0
        public static string ZipCompress(this string value)
        {
            //Transform string into byte[]  
            byte[] byteArray = new byte[value.Length];
            int indexBA = 0;
            foreach (char item in value.ToCharArray())
            {
                byteArray[indexBA++] = (byte)item;
            }

            //Prepare for compress
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,
                System.IO.Compression.CompressionMode.Compress);

            //Compress
            sw.Write(byteArray, 0, byteArray.Length);
            //Close, DO NOT FLUSH cause bytes will go missing...
            sw.Close();

            //Transform byte[] zip data to string
            byteArray = ms.ToArray();
            System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
            foreach (byte item in byteArray)
            {
                sB.Append((char)item);
            }
            ms.Close();
            sw.Dispose();
            ms.Dispose();
            return sB.ToString();
        }
Пример #2
0
        public static string GetImageMime(byte[] bt64)
        {
            string strImageMime = "image/unknown";

            try
            {
                System.IO.MemoryStream msInputStream = new System.IO.MemoryStream(bt64);
                System.Drawing.Image imgThisImage = System.Drawing.Image.FromStream(msInputStream);

                foreach (System.Drawing.Imaging.ImageCodecInfo cdcInfo in System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders())
                {
                    if (cdcInfo.FormatID == imgThisImage.RawFormat.Guid)
                    {
                        strImageMime = cdcInfo.MimeType;
                        break;
                    }
                }

                imgThisImage.Dispose();
                imgThisImage = null;
                msInputStream.Dispose();
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }

            return strImageMime;
        }
        private static async Task <HttpContent> GetCompressedContent(HttpContent originalContent)
        {
            var ms = new System.IO.MemoryStream();

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

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

                var compressedContent = new StreamContent(ms);
                originalContent.CopyHeadersTo(compressedContent);
                compressedContent.Headers.ContentEncoding.Clear();
                compressedContent.Headers.ContentEncoding.Add("gzip");
                compressedContent.Headers.ContentLength = ms.Length;

                originalContent.Dispose();

                return(compressedContent);
            }
            catch
            {
                ms?.Dispose();
                throw;
            }
        }
Пример #4
0
        public static string UnZipCompress(this string value)
        {
            //Transform string into byte[]
            byte[] byteArray = new byte[value.Length];
            int indexBA = 0;
            foreach (char item in value.ToCharArray())
            {
                byteArray[indexBA++] = (byte)item;
            }

            //Prepare for decompress
            System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray);
            System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms,
                System.IO.Compression.CompressionMode.Decompress);

            //Reset variable to collect uncompressed result
            byteArray = new byte[byteArray.Length];

            //Decompress
            int rByte = sr.Read(byteArray, 0, byteArray.Length);

            //Transform byte[] unzip data to string
            System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte);
            //Read the number of bytes GZipStream red and do not a for each bytes in
            //resultByteArray;
            for (int i = 0; i < rByte; i++)
            {
                sB.Append((char)byteArray[i]);
            }
            sr.Close();
            ms.Close();
            sr.Dispose();
            ms.Dispose();
            return sB.ToString();
        }
Пример #5
0
 public static PlayerList FromSerializedString(string s)
 {
     PlayerList p = null;
     XmlSerializer x = new XmlSerializer(typeof(PlayerList));
     System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(s));
     p = (PlayerList)x.Deserialize(ms);
     ms.Dispose();
     return p;
 }
Пример #6
0
 public string GetSerializedString()
 {
     XmlSerializer x = new XmlSerializer(this.GetType());
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     x.Serialize((System.IO.Stream)ms, this);
     var buffer = ms.ToArray();
     ms.Close();
     ms.Dispose();
     string s = System.Text.ASCIIEncoding.ASCII.GetString(buffer);
     return s;
 }
Пример #7
0
        public void TestModifySubjectLine()
        {
            System.IO.Stream inputStream = null;
            System.IO.Stream outputStream = null;

            try
            {
                string testemail = @"P:\Projects\Hygiene\src\TestDocuments\TagActionTestMail.eml";
                byte[] inputBytes = System.IO.File.ReadAllBytes(testemail);
                inputStream = new System.IO.MemoryStream(inputBytes);

                MimeHelper mimeHelper = new MimeHelper(inputStream);

                Guid guid = Guid.NewGuid();
                mimeHelper.PrefixSubjectLine(guid.ToString());

                outputStream = mimeHelper.MimeStream;

                byte[] buffer = new byte[outputStream.Length];
                outputStream.Position = 0;
                int numBytesToRead = (int)outputStream.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    int n = outputStream.Read(buffer, numBytesRead, numBytesToRead);

                    // The end of the file is reached.
                    if (n == 0)
                        break;

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                outputStream.Position = 0;

                string email = System.Text.Encoding.Unicode.GetString(buffer);
                string subjecttofind = "subject: " + guid.ToString() + "Test for PES";
                Assert.Greater(email.IndexOf(subjecttofind), 0);
            }
            catch (System.Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            finally
            {
                if (inputStream != null)
                    inputStream.Dispose();

                if (outputStream != null)
                    outputStream.Dispose();
            }
        }
Пример #8
0
 public static byte[] GZip(this byte[] bytes)
 {
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     GZipStream gs = new GZipStream(ms, CompressionMode.Compress, true);
     gs.Write(bytes, 0, bytes.Length);
     gs.Close();
     gs.Dispose();
     ms.Position = 0;
     bytes = new byte[ms.Length];
     ms.Read(bytes, 0, (int)ms.Length);
     ms.Close();
     ms.Dispose();
     return bytes;
 }
Пример #9
0
        public static Bitmap toBitmap(string base64image)
        {
            System.IO.MemoryStream streamBitmap = null;
            try
            {
                Byte[] bitmapData = Convert.FromBase64String(base64image);
                streamBitmap = new System.IO.MemoryStream(bitmapData);

                Bitmap bitmap = (Bitmap)Image.FromStream(streamBitmap);
                return(bitmap);
            }
            finally
            {
                streamBitmap?.Close();
                streamBitmap?.Dispose();
            }
        }
Пример #10
0
        public static Bitmap GetBackgroundPic(I_DLE device, int address, byte mode, byte g_code_id, ref string desc)
        {
            RGS_SetBackgroundPic_frame frame=null;
            System.IO.MemoryStream ms;
            byte[] cmdText = new byte[] { 0x98, mode, g_code_id };
            SendPackage pkg = new SendPackage(CmdType.CmdQuery, CmdClass.A, address, cmdText);
            device.Send(pkg);
            if (pkg.result != CmdResult.ACK)
                throw new Exception("cmd error:" + pkg.result);

            byte frame_no = pkg.ReturnTextPackage.Text[3]; //0x98 frame_no
            ms = new System.IO.MemoryStream(1024 * 1024*3);
            for (int i = 1; i <= frame_no; i++)
            {
                cmdText = new byte[] {0x98,mode,g_code_id,(byte)i };

                pkg = new SendPackage(CmdType.CmdQuery, CmdClass.A, address, cmdText);

                device.Send(pkg);

                frame = new RGS_SetBackgroundPic_frame(pkg.ReturnTextPackage);

                ms.Write(frame.g_pattern_color, 0, frame.g_pattern_color.Length);

            }

            Bitmap pic = new Bitmap(frame.g_width, frame.g_height);

            ms.Position = 0;

            for(int y =0;y<frame.g_height;y++)
                for (int x = 0; x < frame.g_width; x++)
                {
                   // int r, g, b;
                    //r = ms.ReadByte();
                    //g = ms.ReadByte();
                    //b = ms.ReadByte();
                    pic.SetPixel(x, y, Color.FromArgb(ms.ReadByte(),ms.ReadByte(), ms.ReadByte()));
                }

               desc= System.Text.Encoding.Unicode.GetString(frame.g_desc);

            ms.Dispose();
            return pic;
        }
Пример #11
0
 protected void Page_Load(object sender, EventArgs e)
 {
     VryImgGen gen = new VryImgGen();
     string verifyCode = gen.CreateVerifyCode(4,0);
     HttpCookie cookie = new HttpCookie("VerifyCode", verifyCode.ToUpper());
     cookie.Expires = DateTime.Now.AddSeconds(3000);//过期时间为60秒
     Response.Cookies.Add(cookie);
     System.Drawing.Bitmap bitmap = gen.CreateImage(verifyCode);
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
     Response.Clear();
     Response.ContentType = "image/Png";
     Response.BinaryWrite(ms.GetBuffer());
     bitmap.Dispose();
     ms.Dispose();
     ms.Close();
     Response.End();
 }
Пример #12
0
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.ContentType = ContentType;

            //Check to see if this is done from bytes or physical location
            //  If you're really paranoid you could set a true/false flag in
            //  the constructor.
            if (ImageBytes != null)
            {
                var stream = new System.IO.MemoryStream(ImageBytes);
                stream.WriteTo(response.OutputStream);
                stream.Dispose();
            }
            else
            {
                response.TransmitFile(SourceFilename);
            }
        }
Пример #13
0
 /// <summary> 
 /// 加密数据 
 /// </summary> 
 /// <param name="Text"></param> 
 /// <param name="sKey"></param> 
 /// <returns></returns> 
 public static string Encrypt(string Text, string sKey)
 {
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     byte[] inputByteArray;
     inputByteArray = Encoding.Default.GetBytes(Text);
     des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
     des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     StringBuilder ret = new StringBuilder();
     foreach (byte b in ms.ToArray())
     {
         ret.AppendFormat("{0:X2}", b);
     }
     cs.Close();
     cs.Dispose();
     ms.Close();
     ms.Dispose();            
     return ret.ToString();
 }
Пример #14
0
        private void ExportDetailToExcel(DataTable dt, string sheetName)
        {
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet(sheetName);//雨情
            baseUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.IndexOf(Request.RawUrl));
            #region
            HSSFRow headerRow = (HSSFRow)sheet1.CreateRow(1);
            HSSFCellStyle headStyle = (HSSFCellStyle)book.CreateCellStyle();
            headStyle.Alignment = HorizontalAlignment.Center;
            HSSFFont font = (HSSFFont)book.CreateFont();
            //设置单元格边框 
            headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index;


            font.FontHeightInPoints = 10;
            font.Boldweight = 700;
            headStyle.SetFont(font);
            #endregion

            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("游戏名称");
            row1.CreateCell(1).SetCellValue("版本号");
            row1.CreateCell(2).SetCellValue("更新类型");
            row1.CreateCell(3).SetCellValue("获取包");


            for (int i = 0; i < dt.Rows.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(dt.Rows[i]["gamename"].ToString());
                rowtemp.CreateCell(1).SetCellValue(dt.Rows[i]["version"].ToString());
                rowtemp.CreateCell(2).SetCellValue(dt.Rows[i]["UpdateType"].ToString());
                /*if (!string.IsNullOrEmpty(dt.Rows[i]["Verifycode"].ToString()))
                {
                    rowtemp.CreateCell(3).SetCellValue(baseUrl + "/user/downloadapk.aspx?id=" + dt.Rows[i]["ID"].ToString() + "&vc=" + dt.Rows[i]["Verifycode"].ToString());
                }
                else 
                {
                    rowtemp.CreateCell(3).SetCellValue(dt.Rows[i]["Bak1"].ToString());
                }*/
                rowtemp.CreateCell(3).SetCellValue(baseUrl + "/user/downloadapk.aspx?id=" + dt.Rows[i]["ID"].ToString() + "&vc=" + dt.Rows[i]["Verifycode"].ToString());
                
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", sheetName + DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            Response.BinaryWrite(ms.ToArray());
            book = null;
            ms.Close();
            ms.Dispose();
        }
        public WacomPadForm(wgssSTU.IUsbDevice usbDevice, int points)
        {
            semaphore = true;
            this.minPoints = points;
            if (presingString != null)
            {
                presignText.Text = presingString;
            }
            this.sign = new GraphSign();
            // This is a DPI aware application, so ensure you understand how .NET client coordinates work.
            // Testing using a Windows installation set to a high DPI is recommended to understand how
            // values get scaled or not.
            this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;

            InitializeComponent();

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Calculate the encodingMode that will be used to update the image
            ushort idP = m_tablet.getProductId();
            wgssSTU.encodingFlag encodingFlag = (wgssSTU.encodingFlag)protocolHelper.simulateEncodingFlag(idP, 0);
            bool useColor = false;
            if ((encodingFlag & (wgssSTU.encodingFlag.EncodingFlag_16bit | wgssSTU.encodingFlag.EncodingFlag_24bit)) != 0)
            {
                if (m_tablet.supportsWrite())
                    useColor = true;
            }
            if ((encodingFlag & wgssSTU.encodingFlag.EncodingFlag_24bit) != 0)
            {
                m_encodingMode = m_tablet.supportsWrite() ? wgssSTU.encodingMode.EncodingMode_24bit_Bulk : wgssSTU.encodingMode.EncodingMode_24bit;
            }
            else if ((encodingFlag & wgssSTU.encodingFlag.EncodingFlag_16bit) != 0)
            {
                m_encodingMode = m_tablet.supportsWrite() ? wgssSTU.encodingMode.EncodingMode_16bit_Bulk : wgssSTU.encodingMode.EncodingMode_16bit;
            }
            else
            {
                // assumes 1bit is available
                m_encodingMode = wgssSTU.encodingMode.EncodingMode_1bit;
            }

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

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

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

                gfx.DrawRectangle(Pens.Black, presignText.Bounds);
                gfx.DrawString(presignText.Text, font, Brushes.Black, presignText.Bounds, sf);

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

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

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

            // Now the bitmap has been created, it needs to be converted to device-native
            // format.
            {

                // Unfortunately it is not possible for the native COM component to
                // understand .NET bitmaps. We have therefore convert the .NET bitmap
                // into a memory blob that will be understood by COM.

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

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

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

            // Calculate the size and cache the inking pen.

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

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

            // Initialize the screen
            clearScreen();

            // Enable the pen data on the screen (if not already)
            m_tablet.setInkingMode(0x01);
        }
Пример #16
0
        /// <summary>
        /// 生成读取直接节点数据信息的内容
        /// </summary>
        /// <param name="slot">PLC所在的槽号</param>
        /// <param name="cips">cip指令内容</param>
        /// <returns>最终的指令值</returns>
        public static byte[] PackCommandSpecificData(byte slot, params byte[][] cips)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream( );
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x01);       // 超时
            ms.WriteByte(0x00);
            ms.WriteByte(0x02);       // 项数
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);       // 连接的地址项
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);       // 长度
            ms.WriteByte(0x00);
            ms.WriteByte(0xB2);       // 连接的项数
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);       // 后面数据包的长度,等全部生成后在赋值
            ms.WriteByte(0x00);

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

            int count = 0;

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

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

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

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

            byte[] data = ms.ToArray( );
            ms.Dispose( );
            BitConverter.GetBytes((short)count).CopyTo(data, 24);
            data[14] = BitConverter.GetBytes((short)(data.Length - 16))[0];
            data[15] = BitConverter.GetBytes((short)(data.Length - 16))[1];
            return(data);
        }
Пример #17
0
        public byte[] getData()
        {
            byte[] result = new byte[getNumSamples() * channels * (bitDepth / 8)];
            System.IO.MemoryStream ms = new System.IO.MemoryStream(result);
            System.IO.BinaryWriter wr = new System.IO.BinaryWriter(ms);

            if (bitDepth == 16) {
                for (int i = 0; i < getNumSamples(); i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming signed
                        wr.Write((short)(samples[c][i] * 32768));
                    }
                }
            } else if (bitDepth == 8) {
                for (int i = 0; i < getNumSamples(); i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming unsigned
                        wr.Write((byte)(samples[c][i] * 128 + 128));
                    }
                }
            }
            wr.Dispose();
            ms.Dispose();
            return result;
        }
Пример #18
0
        private void CreateCheckCodeImage(string checkCode, HttpResponseBase response)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 16.5)), 35);
            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成随机生成器
                Random random = new Random();

                //清空图片背景色
                g.Clear(Color.White);
               // Pen drawPen = new Pen(Color.Blue);

               // 添加多种颜色 hooyes
                Color[] colors = { Color.Blue,Color.Silver,Color.SlateGray,Color.Turquoise,Color.Violet,Color.Turquoise,Color.Tomato,Color.Thistle,Color.Teal,Color.SteelBlue };

                //画图片的背景噪音线
                for (int i = 0; i < 9; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    Pen drawPen2 = new Pen(colors[i]);
                    g.DrawLine(drawPen2, x1, y1, x2, y2);

                }
                // drawPen.Dispose(); Tahoma
                Font font = new System.Drawing.Font("Arial", 13, (System.Drawing.FontStyle.Bold));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Black, Color.Gray, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 1);
               // g.DrawString("J", font, brush, 1, 115);
                font.Dispose();
                brush.Dispose();

                //画图片的前景噪音点
                for (int i = 0; i < 20; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(0x8b, 0x8b, 0x8b));
                }

                //画图片的边框线
                Pen borderPen = new Pen(Color.Transparent);
                g.DrawRectangle(borderPen, 0, 0, image.Width - 1, image.Height - 1);
                borderPen.Dispose();

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                byte[] buffer = ms.ToArray();
                ms.Dispose();
                response.ClearContent();
                response.ContentType = "image/bmp";
                response.BinaryWrite(buffer);
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
Пример #19
0
 public void AddWatermark(ref byte[] contents)
 {
     string watermark_enabled = System.Configuration.ConfigurationManager.AppSettings["FileArchiver.Watermark.Enabled"];
     string watermark_filepath = System.Configuration.ConfigurationManager.AppSettings["FileArchiver.Watermark.FilePath"];
     watermark_filepath = HttpContext.Current.Server.MapPath(watermark_filepath);
     string watermark_transparency = System.Configuration.ConfigurationManager.AppSettings["FileArchiver.Watermark.Transparency"];
     string copyright = HttpContext.Current.Request.QueryString["cr"];
     copyright = (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["cr"]) ? HttpContext.Current.Request.QueryString["cr"] : "");
     if (string.IsNullOrEmpty(watermark_transparency)) watermark_transparency = "0.5";
     if (watermark_enabled == "1")
     {
         System.IO.MemoryStream mem = new System.IO.MemoryStream(contents);
         System.IO.MemoryStream mem2 = new System.IO.MemoryStream();
         Image img = Bitmap.FromStream(mem);
         Graphics g = Graphics.FromImage(img);
         Image imgWatermark = Bitmap.FromFile(watermark_filepath);
         int tiles_count_x = (img.Width / imgWatermark.Width) + 1;
         int tiles_count_y = (img.Height / imgWatermark.Height) + 1;
         Image imgBigWatermark = new Bitmap(
             imgWatermark.Width * tiles_count_x,
             imgWatermark.Height * tiles_count_y,
             PixelFormat.Format32bppPArgb);
         Graphics gBigWatermark = Graphics.FromImage(imgBigWatermark);
         for (int i = 0; i < tiles_count_x; i++)
         {
             for (int j = 0; j < tiles_count_y; j++)
             {
                 gBigWatermark.DrawImage(imgWatermark,
                     i * imgWatermark.Width, j * imgWatermark.Height,
                     imgWatermark.Width, imgWatermark.Height);
             }
         }
         // Rotation
         imgBigWatermark = ImageManipulation.ImageTranslate(imgBigWatermark, 0, 0, imgBigWatermark.Width, imgBigWatermark.Height, -30);
         // Transparency
         ImageAttributes imageAttributes = ImageManipulation.GetTransparencyAttributes(Convert.ToSingle(watermark_transparency));
         // Drawing
         int watermark_pos_x = -((imgBigWatermark.Width - img.Width) / 2);
         int watermark_pos_y = -((imgBigWatermark.Height - img.Height) / 2);
         g.DrawImage(imgBigWatermark,
             new Rectangle(watermark_pos_x, watermark_pos_y, imgBigWatermark.Width, imgBigWatermark.Height),
             0, 0, imgBigWatermark.Width, imgBigWatermark.Height,
             GraphicsUnit.Pixel, imageAttributes);
         // Copyright
         if (copyright != "")
         {
             Font copyright_font = new Font("Tahoma", 13);
             g.DrawString(copyright, copyright_font, Brushes.Black, 20f, img.Height - 50);
         }
         // Save
         img.Save(mem2, ImageFormat.Jpeg);
         contents = mem2.ToArray();
         // Disposing
         gBigWatermark.Dispose();
         imgBigWatermark.Dispose();
         imgWatermark.Dispose();
         g.Dispose();
         img.Dispose();
         mem.Close();
         mem.Dispose();
         mem2.Close();
         mem2.Dispose();
     }
 }
Пример #20
0
        // Button Conrols

        protected void BtnNext_Clicked (object sender, EventArgs e)
        {
            if (notebook1.Page == 0)
            {
                // Load Page 1

                btnNext.Sensitive = treeview1.Selection.CountSelectedRows() != 0;
            }
            else if (notebook1.Page == 1)
            {
                // Save Page 1

                string path = "";

                TreeIter iter;
                treeview1.Selection.GetSelected(out iter);

                do
                {
                    path = treestore1.GetValue(iter, 0) + "/" + path;
                }
                while(treestore1.IterParent(out iter, iter));

                path = path.TrimEnd('/');

                generatorData.ExeFile = path;
                generatorData.Folder = entryGameDir.Text;

                // Load Page 2

                path = System.IO.Path.Combine(entryGameDir.Text, path);

                try
                {
                    var assembly = Assembly.LoadFile(path);

                    var ms = new System.IO.MemoryStream();
                    generatorData.Icon = System.Drawing.Icon.ExtractAssociatedIcon(path);
                    generatorData.Icon.Save(ms);
                    imageIcon.Pixbuf = (new Gdk.Pixbuf(ms.GetBuffer())).ScaleSimple(32, 32, Gdk.InterpType.Bilinear);
                    ms.Dispose();

                    entryTitle.Text = GetAttribute(assembly, typeof(AssemblyTitleAttribute));
                    entryVersion.Text = assembly.GetName().Version.ToString();
                    entryCompany.Text = GetAttribute(assembly, typeof(AssemblyCompanyAttribute));
                }
                catch
                { 
                    imageIcon.Pixbuf = null;

                    entryTitle.Text = "";
                    entryVersion.Text = "";
                    entryCompany.Text = "";
                }

                btnNext.Sensitive = Page3NextSensitive();
            }
            else if (notebook1.Page == 2)
            {
                // Save Page 2

                //Icon gets saved on loading because when displaying it we need to resize it
                generatorData.Title = entryTitle.Text;
                generatorData.Version = entryVersion.Text;
                generatorData.Creator = entryCompany.Text;

                // Load Page 3

                btnNext.Label = "Generate";
                btnNext.Sensitive = !string.IsNullOrEmpty(entryOutputDir.Text);
            }
            else if (notebook1.Page == 3)
            {
                // Save Page 3

                generatorData.OutputFolder = entryOutputDir.Text;

                // Load Page 4

                vbox1.Remove(hbox1);

                buildingThread = new Thread(new ThreadStart(this.BuildThread));
                buildingThread.Start();
            }

            notebook1.Page++;
            btnPrev.Sensitive = true;
        }
Пример #21
0
        public static void Brute()
        {
            TerminalBackend.PrefixEnabled = false;
            bool cracked = false;
            var  brute   = Properties.Resources.brute;
            var  str     = new System.IO.MemoryStream(brute);
            var  reader  = new NAudio.Wave.Mp3FileReader(str);
            var  _out    = new NAudio.Wave.WaveOut();

            _out.Init(reader);
            _out.PlaybackStopped += (o, a) =>
            {
                if (cracked == false)
                {
                    cracked = true;
                    TerminalCommands.Clear();
                    ConsoleEx.Bold            = true;
                    ConsoleEx.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(" - access denied - ");
                    ConsoleEx.ForegroundColor = ConsoleColor.Gray;
                    ConsoleEx.Bold            = false;
                    ConsoleEx.Italic          = true;
                    Console.WriteLine("password could not be cracked before connection termination.");
                }
                TerminalBackend.PrefixEnabled = true;
                TerminalBackend.PrintPrompt();
                _out.Dispose();
                reader.Dispose();
                str.Dispose();
            };
            _out.Play();

            var t = new Thread(() =>
            {
                Console.WriteLine("brute - version 1.0");
                Console.WriteLine("Copyright (c) 2018 hacker101. All rights reserved.");
                Console.WriteLine();
                Thread.Sleep(4000);
                Console.WriteLine("Scanning outbound connections...");
                if (string.IsNullOrWhiteSpace(Applications.FileSkimmer.OpenConnection.SystemName))
                {
                    Thread.Sleep(2000);
                    Console.WriteLine(" - no outbound connections to scan, aborting - ");
                    _out.Stop();
                    _out.Dispose();
                    reader.Dispose();
                    str.Dispose();
                }
                else
                {
                    Thread.Sleep(2000);
                    var con = Applications.FileSkimmer.OpenConnection;
                    Console.WriteLine($@"{con.SystemName}
------------------

Active connection: ftp, rts
System name: {con.SystemName}
Users: {con.Users.Count}");
                    Thread.Sleep(500);
                    var user = con.Users.FirstOrDefault(x => x.Permissions == Objects.UserPermissions.Root);
                    if (user == null)
                    {
                        Console.WriteLine(" - no users found with root access - this is a shiftos bug - ");
                    }
                    else
                    {
                        Console.WriteLine(" - starting bruteforce attack on user: "******" - ");

                        char[] pass = new char[user.Password.Length];
                        for (int i = 0; i < pass.Length; i++)
                        {
                            if (cracked == true)
                            {
                                break;
                            }
                            for (char c = (char)0; c < (char)255; c++)
                            {
                                if (!char.IsLetterOrDigit(c))
                                {
                                    continue;
                                }
                                pass[i] = c;
                                if (pass[i] == user.Password[i])
                                {
                                    break;
                                }
                                Console.WriteLine(new string(pass));
                            }
                        }
                        if (cracked == false)
                        {
                            cracked = true;
                            TerminalCommands.Clear();
                            Console.WriteLine(" - credentials cracked. -");
                            Console.WriteLine($@"sysname: {con.SystemName}
user: {user.Username}
password: {user.Password}");
                        }
                    }
                }
            });

            t.Start();
        }
Пример #22
0
        /// <summary>
        /// Use this method to write XMP data to a new PDF
        /// </summary>
        /// <param name="writer"></param>
        private void CreateXmpMetadata(iTextSharp.text.pdf.PdfWriter writer)
        {
            // Set up the buffer to hold the XMP metadata
            byte[] buffer             = new byte[65536];
            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer, true);

            try
            {
                // XMP supports a number of different schemas, which are made available by iTextSharp.
                // Here, the Dublin Core schema is chosen.
                iTextSharp.text.xml.xmp.XmpSchema dc = new iTextSharp.text.xml.xmp.DublinCoreSchema();

                // Add Dublin Core attributes
                iTextSharp.text.xml.xmp.LangAlt title = new iTextSharp.text.xml.xmp.LangAlt();
                title.Add("x-default", "Video rental system by Tripple Bounty");
                dc.SetProperty(iTextSharp.text.xml.xmp.DublinCoreSchema.TITLE, title);

                // Dublin Core allows multiple authors, so we create an XmpArray to hold the values
                iTextSharp.text.xml.xmp.XmpArray author = new iTextSharp.text.xml.xmp.XmpArray(iTextSharp.text.xml.xmp.XmpArray.ORDERED);
                author.Add("Tripple bounty");
                dc.SetProperty(iTextSharp.text.xml.xmp.DublinCoreSchema.CREATOR, author);

                // Multiple subjects are also possible, so another XmpArray is used
                iTextSharp.text.xml.xmp.XmpArray subject = new iTextSharp.text.xml.xmp.XmpArray(iTextSharp.text.xml.xmp.XmpArray.UNORDERED);
                subject.Add("Video casettes");
                subject.Add("Video rental system");
                dc.SetProperty(iTextSharp.text.xml.xmp.DublinCoreSchema.SUBJECT, subject);

                // Create an XmpWriter using the MemoryStream defined earlier
                iTextSharp.text.xml.xmp.XmpWriter xmp = new iTextSharp.text.xml.xmp.XmpWriter(ms);
                xmp.AddRdfDescription(dc); // Add the completed metadata definition to the XmpWriter
                xmp.Close();               // This flushes the XMP metadata into the buffer

                //---------------------------------------------------------------------------------
                // Shrink the buffer to the correct size (discard empty elements of the byte array)
                int bufsize  = buffer.Length;
                int bufcount = 0;
                foreach (byte b in buffer)
                {
                    if (b == 0)
                    {
                        break;
                    }

                    bufcount++;
                }

                System.IO.MemoryStream ms2 = new System.IO.MemoryStream(buffer, 0, bufcount);
                buffer = ms2.ToArray();

                //---------------------------------------------------------------------------------
                // Add all of the XMP metadata to the PDF doc that we're building
                writer.XmpMetadata = buffer;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
                ms.Dispose();
            }
        }
Пример #23
0
        /// <inheritdoc/>
        public override void Draw(object dc, ImageShape image, double dx, double dy, object db, object r)
        {
            var _gfx = dc as Graphics;

            Brush brush = ToSolidBrush(image.Style.Stroke);

            var rect = CreateRect(
                image.TopLeft,
                image.BottomRight,
                dx, dy);

            var srect = new RectangleF(
                _scaleToPage(rect.X),
                _scaleToPage(rect.Y),
                _scaleToPage(rect.Width),
                _scaleToPage(rect.Height));

            if (image.IsFilled)
            {
                _gfx.FillRectangle(
                    ToSolidBrush(image.Style.Fill),
                    srect);
            }

            if (image.IsStroked)
            {
                _gfx.DrawRectangle(
                    ToPen(image.Style, _scaleToPage),
                    srect.X,
                    srect.Y,
                    srect.Width,
                    srect.Height);
            }

            if (_enableImageCache &&
                _biCache.ContainsKey(image.Key))
            {
                _gfx.DrawImage(_biCache[image.Key], srect);
            }
            else
            {
                if (State.ImageCache == null || string.IsNullOrEmpty(image.Key))
                {
                    return;
                }

                var bytes = State.ImageCache.GetImage(image.Key);
                if (bytes != null)
                {
                    var ms = new System.IO.MemoryStream(bytes);
                    var bi = Image.FromStream(ms);
                    ms.Dispose();

                    if (_enableImageCache)
                    {
                        _biCache[image.Key] = bi;
                    }

                    _gfx.DrawImage(bi, srect);

                    if (!_enableImageCache)
                    {
                        bi.Dispose();
                    }
                }
            }

            brush.Dispose();
        }
Пример #24
0
        void tDither_Tick(object sender, EventArgs e)
        {
            if (!bDither)
            {
                return;
            }
            bDither = false;
            int iDResX      = Convert.ToInt32(tDResX.Text);
            int iDResY      = Convert.ToInt32(tDResY.Text);
            int iIResX      = Convert.ToInt32(tIResX.Text);
            int iIResY      = Convert.ToInt32(tIResY.Text);
            int iDitherMode = Convert.ToInt32(tDMode.Text);

            for (int iFile = 0; iFile < sFiles.Length; iFile++)
            {
                string sFile = sFiles[iFile];
                this.Text = iFile + " of " + sFiles.Length +
                            " (preload)"; Application.DoEvents();

                Bitmap bSrc = ResizeBitmap((Bitmap)Bitmap.FromFile(sFile), iDResX, iDResY, false, 2);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                bSrc.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                byte[] bT     = ms.GetBuffer(); ms.Close(); ms.Dispose();
                byte[] bTR    = new byte[iDResX * iDResY];
                byte[] bTG    = new byte[iDResX * iDResY];
                byte[] bTB    = new byte[iDResX * iDResY];
                int    ibTLoc = 54;
                for (int y = 0; y < iDResY; y++)
                {
                    for (int x = 0; x < iDResX; x++)
                    {
                        bTR[(iDResY - y) * iDResX - iDResX + (x)] = bT[ibTLoc + 2];
                        bTG[(iDResY - y) * iDResX - iDResX + (x)] = bT[ibTLoc + 1];
                        bTB[(iDResY - y) * iDResX - iDResX + (x)] = bT[ibTLoc + 0];
                        ibTLoc += 4;
                    }
                }

                this.Text = iFile + " of " + sFiles.Length +
                            " (neut 1)"; Application.DoEvents();

                int iMin = 255, iMinR = 255, iMinG = 255, iMinB = 255;
                for (int y = 0; y < iDResY; y++)
                {
                    for (int x = 0; x < iDResX; x++)
                    {
                        int iTR = bTR[y * (iDResX) + x];
                        int iTG = bTG[y * (iDResX) + x];
                        int iTB = bTB[y * (iDResX) + x];
                        if (iTR < iMinR)
                        {
                            iMinR = iTR;
                        }
                        if (iTG < iMinG)
                        {
                            iMinG = iTG;
                        }
                        if (iTB < iMinB)
                        {
                            iMinB = iTB;
                        }
                    }
                }
                if (iMinR < iMin)
                {
                    iMin = iMinR;
                }
                if (iMinG < iMin)
                {
                    iMin = iMinG;
                }
                if (iMinB < iMin)
                {
                    iMin = iMinB;
                }
                for (int y = 0; y < iDResY; y++)
                {
                    for (int x = 0; x < iDResX; x++)
                    {
                        bTR[y * (iDResX) + x] -= (byte)iMin;
                        bTG[y * (iDResX) + x] -= (byte)iMin;
                        bTB[y * (iDResX) + x] -= (byte)iMin;
                    }
                }

                this.Text = iFile + " of " + sFiles.Length +
                            " (neut 2)"; Application.DoEvents();

                int iMax = 0, iMaxR = 0, iMaxG = 0, iMaxB = 0;
                for (int y = 0; y < iDResY; y++)
                {
                    for (int x = 0; x < iDResX; x++)
                    {
                        int iTR = bTR[y * (iDResX) + x];
                        int iTG = bTG[y * (iDResX) + x];
                        int iTB = bTB[y * (iDResX) + x];
                        if (iTR > iMaxR)
                        {
                            iMaxR = iTR;
                        }
                        if (iTG > iMaxG)
                        {
                            iMaxG = iTG;
                        }
                        if (iTB > iMaxB)
                        {
                            iMaxB = iTB;
                        }
                    }
                }
                if (iMaxR > iMax)
                {
                    iMax = iMaxR;
                }
                if (iMaxG > iMax)
                {
                    iMax = iMaxG;
                }
                if (iMaxB > iMax)
                {
                    iMax = iMaxB;
                }
                double dMul = 255 / iMax;
                for (int y = 0; y < iDResY; y++)
                {
                    for (int x = 0; x < iDResX; x++)
                    {
                        int iTR = (int)Math.Round((double)bTR[y * (iDResX) + x] * dMul);
                        int iTG = (int)Math.Round((double)bTG[y * (iDResX) + x] * dMul);
                        int iTB = (int)Math.Round((double)bTB[y * (iDResX) + x] * dMul);
                        if (iTR > 255)
                        {
                            iTR = 255;
                        }
                        bTR[y * (iDResX) + x] = (byte)iTR;
                        if (iTG > 255)
                        {
                            iTG = 255;
                        }
                        bTG[y * (iDResX) + x] = (byte)iTG;
                        if (iTG > 255)
                        {
                            iTB = 255;
                        }
                        bTB[y * (iDResX) + x] = (byte)iTB;
                    }
                }

                this.Text = iFile + " of " + sFiles.Length +
                            " (map)"; Application.DoEvents();

                int[] iCol = new int[iDResX * iDResY];

                // 2 colours (BW)
                Color[] cMap = new Color[2];
                cMap[0] = Color.FromArgb(000, 000, 000);
                cMap[1] = Color.FromArgb(255, 255, 255);

                if (c4cga.Checked)
                {
                    cMap    = new Color[4]; // 4 colours (CGA)
                    cMap[0] = Color.FromArgb(000, 000, 000);
                    cMap[1] = Color.FromArgb(000, 255, 255);
                    cMap[2] = Color.FromArgb(255, 000, 255);
                    cMap[3] = Color.FromArgb(255, 255, 255);
                }

                if (c8rgbycp.Checked)
                {
                    cMap    = new Color[8]; // 8 colours (RGBYCP)
                    cMap[0] = Color.FromArgb(000, 000, 000);
                    cMap[1] = Color.FromArgb(000, 000, 255);
                    cMap[2] = Color.FromArgb(000, 255, 000);
                    cMap[3] = Color.FromArgb(255, 000, 000);
                    cMap[4] = Color.FromArgb(000, 255, 255);
                    cMap[5] = Color.FromArgb(255, 255, 000);
                    cMap[6] = Color.FromArgb(255, 000, 255);
                    cMap[7] = Color.FromArgb(255, 255, 255);
                }

                if (c16dosvga.Checked)
                {
                    cMap     = new Color[16]; // 16 colours DOS-VGA
                    cMap[0]  = Color.FromArgb(000, 000, 000);
                    cMap[1]  = Color.FromArgb(000, 000, 128);
                    cMap[2]  = Color.FromArgb(000, 128, 000);
                    cMap[3]  = Color.FromArgb(000, 128, 128);
                    cMap[4]  = Color.FromArgb(128, 000, 128);
                    cMap[5]  = Color.FromArgb(128, 000, 128);
                    cMap[6]  = Color.FromArgb(255, 000, 000);
                    cMap[7]  = Color.FromArgb(128, 128, 128);
                    cMap[8]  = Color.FromArgb(032, 032, 032);
                    cMap[9]  = Color.FromArgb(048, 096, 255);
                    cMap[10] = Color.FromArgb(032, 255, 096);
                    cMap[11] = Color.FromArgb(048, 255, 255);
                    cMap[12] = Color.FromArgb(255, 048, 048);
                    cMap[13] = Color.FromArgb(255, 096, 255);
                    cMap[14] = Color.FromArgb(255, 255, 096);
                    cMap[15] = Color.FromArgb(255, 255, 255);
                }

                if (c256rtg.Checked)
                {
                    // 256 colours real-time generated
                    cMap = new Color[216]; int itT = -1;
                    for (int itR = 0; itR <= 256; itR += 51)
                    {
                        for (int itG = 0; itG <= 256; itG += 51)
                        {
                            for (int itB = 0; itB <= 256; itB += 51)
                            {
                                if (itR > 255)
                                {
                                    itR = 255;
                                }
                                if (itG > 255)
                                {
                                    itG = 255;
                                }
                                if (itB > 255)
                                {
                                    itB = 255;
                                }
                                itT++; cMap[itT] =
                                    Color.FromArgb(itR, itG, itB);
                            }
                        }
                    }
                }

                if (c256vga.Checked)
                {
                    int itT = -1;                                    // 256 colours (proper)
                    cMap = new Color[256];                           //8*8*4=256
                    for (int itR = 0; itR <= 256; itR += 36)         //36*7=252
                    {
                        for (int itG = 0; itG <= 256; itG += 36)     //36*7=252
                        {
                            for (int itB = 0; itB <= 256; itB += 85) //85*3=255
                            {
                                if (itR > 255)
                                {
                                    itR = 255;
                                }
                                if (itG > 255)
                                {
                                    itG = 255;
                                }
                                if (itB > 255)
                                {
                                    itB = 255;
                                }
                                itT++; cMap[itT] =
                                    Color.FromArgb(itR, itG, itB);
                            }
                        }
                    }
                }

                for (int i = 0; i < iDResX * iDResY; i++)
                {
                    iCol[i] = -1;
                }
                int  iLastCol     = -1;
                int  iLastColDist = -1;
                bool bScatter     = false;
                for (int y = 0; y < iDResY; y++)
                {
                    for (int x = 0; x < iDResX; x++)
                    {
                        int iT   = y * (iDResX) + x;
                        int iThr = -1;
                        while (iCol[iT] == -1)
                        {
                            iThr += 1;
                            double dTR = (double)bTR[iT];
                            double dTG = (double)bTG[iT];
                            double dTB = (double)bTB[iT];
                            for (int c = 0; c < cMap.Length; c++)
                            {
                                if (iCol[iT] == -1)
                                {
                                    if (Math.Abs(dTR - (double)cMap[c].R) <= iThr &&
                                        Math.Abs(dTG - (double)cMap[c].G) <= iThr &&
                                        Math.Abs(dTB - (double)cMap[c].B) <= iThr)
                                    {
                                        if (bScatter)
                                        {
                                            if (iLastCol != c)
                                            {
                                                iCol[iT]     = c;
                                                iLastCol     = -1;
                                                iLastColDist = iThr;
                                                bScatter     = false;
                                            }
                                        }
                                        else
                                        {
                                            iCol[iT] = c;
                                            iLastCol = c;
                                            if (iDitherMode == 2)
                                            {
                                                iLastColDist -= iThr;
                                            }
                                            if (iDitherMode == 1)
                                            {
                                                iLastColDist = -1;
                                            }
                                            if (iDitherMode == 0)
                                            {
                                                iLastColDist = 1;
                                            }
                                            if (iLastColDist < 0)
                                            {
                                                bScatter = true;
                                            }
                                            if (iThr < 4)
                                            {
                                                bScatter = false;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                this.Text = iFile + " of " + sFiles.Length +
                            " (export)"; Application.DoEvents();

                Bitmap bRes = new Bitmap(iDResX, iDResY);
                for (int y = 0; y < iDResY; y++)
                {
                    for (int x = 0; x < iDResX; x++)
                    {
                        bRes.SetPixel(x, y, cMap[iCol[y * (iDResX) + x]]);
                    }
                }
                ResizeBitmap(bRes, iDResX, iDResY, false, 3).Save
                    (iFile + ".png", System.Drawing.Imaging.ImageFormat.Png);
                //("c:/dos/qb45/output.png", System.Drawing.Imaging.ImageFormat.Png);

                /*System.IO.StreamWriter sw;
                 * sw = System.IO.File.CreateText("c:/dos/qb45/pic.bas");
                 * sw.WriteLine("SCREEN 7");
                 * sw.WriteLine("COLOR 15, 0");
                 * sw.WriteLine("CLS");
                 * for (int y = 0; y < iResY; y++)
                 *  for (int x = 0; x < iResX; x++)
                 *  {
                 *      sw.WriteLine("PSET (" + x + ", " + y + "), " + iCol[y * (iResX) + x]);
                 *  }
                 * sw.WriteLine("while inkey$ = \"\"");
                 * sw.WriteLine("wend");
                 * sw.Flush(); sw.Close(); sw.Dispose();
                 * System.Diagnostics.Process.Start("c:/dos/qb45/bc.exe", "pic.bas pic.obj nul.lst");
                 * System.Diagnostics.Process.Start("c:/dos/qb45/link.exe", "pic.obj");*/
            }
        }
Пример #25
0
        private void AddLayerClassNode(layerObj layer, TreeNode layernode)
        {
            if ((layer == null) || (layernode == null)) return;
            int iClassCount = layer.numclasses;
            for (int i = 0; i < iClassCount; i++)
            {
                classObj pClass = layer.getClass(i);
                imageObj pSymbolImage = pClass.createLegendIcon(m_pMap, layer, 16, 16);

                byte[] buffer = pSymbolImage.getBytes();
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                ms.Write(buffer, 0, buffer.Length);
                imageListLeg.Images.Add(Image.FromStream(ms));
                ms.Dispose();
                pSymbolImage.Dispose();

                int iIndex = imageListLeg.Images.Count - 1;

                TreeNode subNode2 = new TreeNode("", iIndex, iIndex);
                layernode.Nodes.Add(subNode2);
            }
        }
Пример #26
0
        private string GetXML()
        {
            System.IO.MemoryStream memStream = new System.IO.MemoryStream();
            DataTable dtData = null;
            System.IO.StreamReader sr = null;
            string ret = null;

            try
            {
                dtData = (DataTable)dataGridView.DataSource;

                //	<DocumentElement>
                //		<(TableName)>
                //			<(FieldName)>(FieldValue)</(FieldName)>
                //			[...]
                //		</(TableName)>
                //		[...]
                //	</DocumentElement>
                dtData.TableName = "Item";
                dtData.WriteXml(memStream);
                dtData.TableName = "";

                sr = new System.IO.StreamReader(memStream);
                memStream.Position = 0;
                ret = sr.ReadToEnd();

                ret = Strings.Replace(ret, "DocumentElement>", objectType + ">");
                return ret;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Dispose();
                }
                if (memStream != null)
                {
                    memStream.Dispose();
                }
            }
        }
Пример #27
0
        public override XmlDocument ToAsciiArt(Bitmap bmp)
        {
            //�o�͗pxml
            var xml = new XmlDocument();

            //�{�����̍ۂ�XmlDocument�ł͏������x������Writer��g��
            var memory = new System.IO.MemoryStream();
            var xmlWriter = XmlTextWriter.Create(memory);
            xmlWriter.WriteStartDocument();
            try
            {
                //�`��p�̃G���A�𐶐�<AsciiArt>
                xmlWriter.WriteStartElement("AsciiArt");

                //char�^�ł͏������߂Ȃ��̂�String�ɕϊ��B
                var aaString = new string[_chars.Length];
                for (int i = 0; i < aaString.Length; i++)
                {
                    aaString[i] = _chars[i].ToString();
                }

                #region Xml�����o��
                int int_nextTurn = 0;
                for (int i = 0; i <= bmp.Height - 1; i++)
                {
                    //<line>
                    xmlWriter.WriteStartElement("line");
                    for (int j = 0; j <= bmp.Width - 1; j++)
                    {
                        //16�i�@�ɕϊ�����B
                        string red = System.Convert.ToString(int.Parse(bmp.GetPixel(j, i).R.ToString()), 16);
                        string gre = System.Convert.ToString(int.Parse(bmp.GetPixel(j, i).G.ToString()), 16);
                        string blu = System.Convert.ToString(int.Parse(bmp.GetPixel(j, i).B.ToString()), 16);

                        //<char color="#ffffff">��</char>
                        xmlWriter.WriteStartElement("char");
                        xmlWriter.WriteAttributeString("color", "#" + red + gre + blu);

                        //�{����
                        xmlWriter.WriteString(aaString[int_nextTurn].ToString());
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteString("\r\n");

                        int_nextTurn++;
                        if (int_nextTurn >= aaString.Length)
                            int_nextTurn = 0;
                    }
                    //</line>
                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteString("\r\n");
                }
                #endregion

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

                xmlWriter.Flush();
                memory.Position = 0;
                xml.Load(memory);
            }
            finally
            {
                xmlWriter.Close();
                memory.Dispose();
            }
            return xml;
        }
Пример #28
0
        //Console.WriteLine("helo ha:"+args[0]); //普通输出
        //Console.WriteLine("<WARN> 这是一个严重的问题。");//警告输出,黄字
        //Console.WriteLine("<WARN|aaaa.cs(1)> 这是ee一个严重的问题。");//警告输出,带文件名行号
        //Console.WriteLine("<ERR> 这是一个严重的问题。");//错误输出,红字
        //Console.WriteLine("<ERR|aaaa.cs> 这是ee一个严重的问题。");//错误输出,带文件名
        //Console.WriteLine("SUCC");//输出这个表示编译成功
        //控制台输出约定了特别的语法
        public static void Main(string[] args)
        {
            var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText("class A{public  int aaa(){return 3;}}");

            var op   = new CSharpCompilationOptions(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary);
            var ref1 = MetadataReference.CreateFromFile("needlib\\mscorlib.dll");
            var comp = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("aaa.dll", new[] { tree },
                                                                              new[] { ref1 }, op);

            var fs     = new System.IO.MemoryStream();
            var fspdb  = new System.IO.MemoryStream();
            var result = comp.Emit(fs, fspdb);

            fs.Seek(0, System.IO.SeekOrigin.Begin);
            fspdb.Seek(0, System.IO.SeekOrigin.Begin);
            //set console
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            var log = new DefLogger();

            log.Log("Neo.Compiler.MSIL(Debug) console app v" + Assembly.GetEntryAssembly().GetName().Version);
            if (args.Length == 0)
            {
                log.Log("need one param for DLL filename.");
                return;
            }
            string filename = args[0];
            string onlyname = System.IO.Path.GetFileNameWithoutExtension(filename);
            //string filepdb = onlyname + ".pdb";

            ILModule mod = new ILModule();

            //System.IO.Stream fs = null;
            //System.IO.Stream fspdb = null;

            //open file
            //try
            //{
            //    fs = System.IO.File.OpenRead(filename);

            //    if (System.IO.File.Exists(filepdb))
            //    {
            //        fspdb = System.IO.File.OpenRead(filepdb);
            //    }

            //}
            //catch (Exception err)
            //{
            //    log.Log("Open File Error:" + err.ToString());
            //    return;
            //}
            //load module
            try
            {
                mod.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                return;
            }
            byte[] bytes   = null;
            bool   bSucc   = false;
            string jsonstr = null;
            //convert and build
            NeoModule neoM = null;

            MyJson.JsonNode_Object abijson = null;
            try
            {
                var conv = new ModuleConverter(log);

                NeoModule am = conv.Convert(mod);
                neoM  = am;
                bytes = am.Build();
                log.Log("convert succ");


                try
                {
                    abijson = vmtool.FuncExport.Export(am, bytes);
                    StringBuilder sb = new StringBuilder();
                    abijson.ConvertToStringWithFormat(sb, 0);
                    jsonstr = sb.ToString();
                    log.Log("gen abi succ");
                }
                catch (Exception err)
                {
                    log.Log("gen abi Error:" + err.ToString());
                }
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return;
            }
            //write bytes
            try
            {
                string bytesname = onlyname + ".avm";

                System.IO.File.Delete(bytesname);
                System.IO.File.WriteAllBytes(bytesname, bytes);
                log.Log("write:" + bytesname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return;
            }
            try
            {
                string abiname = onlyname + ".abi.json";

                System.IO.File.Delete(abiname);
                System.IO.File.WriteAllText(abiname, jsonstr);
                log.Log("write:" + abiname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write abi Error:" + err.ToString());
                return;
            }
            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }
            if (bSucc)
            {
                _DebugOutput.DebugOutput(neoM, bytes, abijson);
                log.Log("SUCC");
            }
        }
Пример #29
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="gfx"></param>
        /// <param name="image"></param>
        /// <param name="dx"></param>
        /// <param name="dy"></param>
        /// <param name="db"></param>
        /// <param name="r"></param>
        public void Draw(object gfx, XImage image, double dx, double dy, ImmutableArray<ShapeProperty> db, Record r)
        {
            var _gfx = gfx as Graphics;

            Brush brush = ToSolidBrush(image.Style.Stroke);

            var rect = CreateRect(
                image.TopLeft,
                image.BottomRight,
                dx, dy);

            var srect = new RectangleF(
                _scaleToPage(rect.X),
                _scaleToPage(rect.Y),
                _scaleToPage(rect.Width),
                _scaleToPage(rect.Height));

            if (image.IsFilled)
            {
                _gfx.FillRectangle(
                    ToSolidBrush(image.Style.Fill),
                    srect);
            }

            if (image.IsStroked)
            {
                _gfx.DrawRectangle(
                    ToPen(image.Style, _scaleToPage),
                    srect.X,
                    srect.Y,
                    srect.Width,
                    srect.Height);
            }

            if (_enableImageCache
                && _biCache.ContainsKey(image.Path))
            {
                _gfx.DrawImage(_biCache[image.Path], srect);
            }
            else
            {
                if (_state.ImageCache == null || string.IsNullOrEmpty(image.Path))
                    return;

                var bytes = _state.ImageCache.GetImage(image.Path);
                if (bytes != null)
                {
                    var ms = new System.IO.MemoryStream(bytes);
                    var bi = Image.FromStream(ms);
                    ms.Dispose();

                    if (_enableImageCache)
                        _biCache[image.Path] = bi;

                    _gfx.DrawImage(bi, srect);

                    if (!_enableImageCache)
                        bi.Dispose();
                }
            }

            brush.Dispose();
        }
Пример #30
0
 public void ProcessRequest(HttpContext context)
 {
     string root_abs_path = VirtualPathUtility.ToAbsolute("~/");
     string archive_file_vpath = "~/" + context.Request.RawUrl.Substring(root_abs_path.Length).Replace(".fa.aspx?", "?");
     archive_file_vpath = archive_file_vpath.Substring(0, archive_file_vpath.IndexOf("?"));
     string archive_file = context.Server.MapPath(archive_file_vpath);
     string filename = (!string.IsNullOrEmpty(context.Request.QueryString["n"]) ? context.Request.QueryString["n"] : "");
     string requesttype = (!string.IsNullOrEmpty(context.Request.QueryString["t"]) ? context.Request.QueryString["t"] : "");
     string hashcode = (!string.IsNullOrEmpty(context.Request.QueryString["u"]) ? context.Request.QueryString["u"] : "");
     string width = (!string.IsNullOrEmpty(context.Request.QueryString["w"]) ? context.Request.QueryString["w"] : "");
     string fixed_height = (!string.IsNullOrEmpty(context.Request.QueryString["fh"]) ? context.Request.QueryString["fh"] : "t");
     string watermark = (!string.IsNullOrEmpty(context.Request.QueryString["wm"]) ? context.Request.QueryString["wm"] : "0");
     try
     {
         if (Security.CheckSecurity(hashcode))
         {
             FileArchiverCore core = new FileArchiverCore(archive_file);
             if (requesttype == "thumb")
             {
                 context.Response.ContentType = "image/png";
                 Bitmap thumb = core.GetIcon(filename, width, fixed_height);
                 System.IO.MemoryStream memresult = new System.IO.MemoryStream();
                 thumb.Save(memresult, System.Drawing.Imaging.ImageFormat.Png);
                 memresult.WriteTo(context.Response.OutputStream);
                 thumb.Dispose();
                 memresult.Dispose();
                 thumb = null;
                 memresult = null;
             }
             if (requesttype == "full")
             {
                 byte[] contents = core.GetFileContents(filename);
                 AddWatermark(ref contents);
                 context.Response.BinaryWrite(contents);
                 context.Response.ContentType = MimeTypes.GetMimeType(System.IO.Path.GetExtension(filename));
             }
             if (requesttype == "down")
             {
                 byte[] contents = core.GetFileContents(filename);
                 AddWatermark(ref contents);
                 context.Response.BinaryWrite(contents);
                 context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
             }
             if (requesttype == "up")
             {
                 if (context.Request.Files.Count > 0)
                 {
                     core.AddFile(
                         context.Request.Files[0].FileName,
                         context.Request.Files[0].InputStream);
                     context.Response.Write("{status:'success'}");
                 }
             }
             if (requesttype == "del")
             {
                 core.RemoveFile(filename);
                 context.Response.Write("{status:'success'}");
             }
             if (requesttype == "list")
             {
                 string files = "";
                 for (int i = 0; i < core.Files.Length; i++)
                     files += core.Files[i].Name + "|";
                 if (files.EndsWith("|")) files = files.Remove(files.Length - 1);
                 context.Response.Write(files);
             }
         }
         else
         {
             throw new Exception("Not logged in.");
         }
     }
     catch (Exception ex)
     {
         context.Response.Write("{status:'error',msg:'" + ex.Message.Replace("'", "\\'").Replace("\\", "\\\\") + "',detail:'" + ex.ToString().Replace("'", "\\'").Replace("\\", "\\\\") + "'}");
     }
 }
Пример #31
0
        protected void ExportButton_Click(object sender, EventArgs e)
        {
            OrderSearchInfo orderSearch = new OrderSearchInfo();

            orderSearch.OrderNumber  = ShopCommon.ConvertToT <string>(OrderNumber.Text);
            orderSearch.OrderStatus  = intOrderStatus;
            orderSearch.Consignee    = ShopCommon.ConvertToT <string>(Consignee.Text);
            orderSearch.StartAddDate = ShopCommon.ConvertToT <DateTime>(StartAddDate.Text);
            orderSearch.EndAddDate   = ShopCommon.SearchEndDate(ShopCommon.ConvertToT <DateTime>(EndAddDate.Text));
            var data = OrderBLL.SearchList(1, 1000, orderSearch, ref Count);

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

            NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
            row.Height = 20 * 20;
            row.CreateCell(0).SetCellValue("订单号");
            row.CreateCell(1).SetCellValue("订单金额");
            row.CreateCell(2).SetCellValue("类型");
            row.CreateCell(3).SetCellValue("收货方式");
            row.CreateCell(4).SetCellValue("收货人");
            //row.CreateCell(3).SetCellValue("收货地址");
            row.CreateCell(5).SetCellValue("订单状态");
            row.CreateCell(6).SetCellValue("下单时间");
            row.CreateCell(7).SetCellValue("最近操作时间");

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

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

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

            //取得订单最后一次操作的时间
            var orderActinList = OrderActionBLL.ReadListLastDate(data.Select(k => k.Id).ToArray());

            foreach (var entity in data)
            {
                NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(data.IndexOf(entity) + 1);
                dataRow.CreateCell(0).SetCellValue(entity.OrderNumber);
                dataRow.CreateCell(1).SetCellValue((entity.ProductMoney + entity.ShippingMoney + entity.OtherMoney).ToString());
                dataRow.CreateCell(2).SetCellValue(EnumHelper.ReadEnumChineseName <OrderKind>(entity.IsActivity));
                dataRow.CreateCell(3).SetCellValue(entity.SelfPick == 1 ? "自提" : "配送");
                dataRow.CreateCell(4).SetCellValue(entity.Consignee);
                //dataRow.CreateCell(3).SetCellValue(entity.Address);
                dataRow.CreateCell(5).SetCellValue(OrderBLL.ReadOrderStatus(entity.OrderStatus, entity.IsDelete));
                dataRow.CreateCell(6).SetCellValue(entity.AddDate.ToString());

                var orderAction = orderActinList.FirstOrDefault(k => k.OrderId == entity.Id) ?? new OrderActionInfo();
                dataRow.CreateCell(7).SetCellValue(orderAction.OrderId > 0 ? orderAction.Date.ToString() : "");

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

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            Response.BinaryWrite(ms.ToArray());
            book = null;
            ms.Close();
            ms.Dispose();
            Response.End();
        }
Пример #32
0
 public Attachement(System.IO.Stream s, string n)
 {
     s.Position = 0;
     System.IO.MemoryStream ms=new System.IO.MemoryStream();
     s.CopyTo(ms);
     this._stream = ms.GetBuffer();
     ms.Close(); ms.Dispose();
     this._name = n;
     size = s.Length;
 }
Пример #33
0
        public void ProcessRequest(HttpContext context)
        {
            VerifyImageHttpHandle v = new VerifyImageHttpHandle();

            v.Length = this.length;
            v.Chaos = this.chaos;
            v.BackgroundColor = this.backgroundColor;
            v.CodeSerial = this.codeSerial;
            v.Colors = this.colors;
            v.Fonts = this.fonts;
            v.Padding = this.padding;
            string code = v.CreateVerifyCode();
            HttpResponse Response = context.Response;
            Response.Cache.SetExpires(DateTime.Now.AddHours(-1));
            Response.CacheControl = "no-cache";
            //  将生成的图片发回客户端
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                Bitmap image = this.CreateImageCode(code);
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                code = new EncryHelper().DoEncrypt(code.ToUpper(), "VCode", Encoding.UTF8);
                Response.Cookies.Add(new HttpCookie("VerifyCode", code));
                Response.ClearContent(); //需要输出图象信息 要修改HTTP头
                Response.ContentType = "image/jpeg";
                Response.BinaryWrite(ms.GetBuffer());
                image.Dispose();
                ms.Close();
                ms.Dispose();
                Response.End();
            }
        }
Пример #34
0
    public Image ToImage(System.Drawing.Imaging.ImageFormat format_)
    {
      Chart.DataBind();
      Chart.InvalidateLayers();

      System.IO.MemoryStream ms = new System.IO.MemoryStream();
      Chart.SaveTo(ms, format_);
      Image ret = Image.FromStream(ms);
      ms.Close();
      ms.Dispose();

      return ret;
    }
Пример #35
0
        private void ExportDetailToExcel(DataTable dt, string sheetName)
        {
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet(sheetName);//雨情
            #region
            HSSFRow headerRow = (HSSFRow)sheet1.CreateRow(1);
            HSSFCellStyle headStyle = (HSSFCellStyle)book.CreateCellStyle();
            headStyle.Alignment = HorizontalAlignment.Center;
            HSSFFont font = (HSSFFont)book.CreateFont();
            //设置单元格边框 
            headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index;


            font.FontHeightInPoints = 10;
            font.Boldweight = 700;
            headStyle.SetFont(font);
            #endregion

            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("游戏名称");
            row1.CreateCell(1).SetCellValue("礼包名称");
            row1.CreateCell(2).SetCellValue("礼包类型");
            row1.CreateCell(3).SetCellValue("可用状态");
            row1.CreateCell(4).SetCellValue("修改时间");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(dt.Rows[i]["gamename"].ToString());
                rowtemp.CreateCell(1).SetCellValue(dt.Rows[i]["CardName"].ToString());
                rowtemp.CreateCell(2).SetCellValue(dt.Rows[i]["CardType"].ToString());
                rowtemp.CreateCell(3).SetCellValue(dt.Rows[i]["Status"].ToString());
                rowtemp.CreateCell(4).SetCellValue(dt.Rows[i]["UpdateDate"].ToString());
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", sheetName + DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            Response.BinaryWrite(ms.ToArray());
            book = null;
            ms.Close();
            ms.Dispose();
        }
Пример #36
0
        public void Connect(string ip, int port)
        {
            if (socket != null)
            {
                DisConnect();
            }

            this.socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            this.socket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));

            if (this.watchLoop == null)
            {
                this.watchLoop = Task.Run(() =>
                {
                    isStop = false;
                    while (!isStop)
                    {
                        this.socket.Send(this.sendMessage);

                        int receiveLength = socket.Receive(this.resBuffer);
                        flexData resData  = null;

                        using (var ms = new System.IO.MemoryStream())
                        {
                            try
                            {
                                var length = ParseHeader(this.resBuffer, 0);
                                //System.Diagnostics.Debug.WriteLine(length);
                                ms.Write(this.resBuffer, 8, length);
                                ms.Position = 0;

                                if (length == 0)
                                {
                                    continue;
                                }

                                resData = (flexData)serializer.Deserialize(ms);

                                if (resData.notifications != null)
                                {
                                    //resData.notifications.ToList().ForEach(n =>
                                    //{
                                    //    Console.Error.WriteLine($"{n.code}: {n.message}");
                                    //});

                                    //Thread.Sleep(1000);
                                    continue;
                                }


                                var updateData = resData.dataExchange.dataUpdate[0].data[0].r;

                                var info = new RobotInfo
                                {
                                    Tcp = new Position
                                    {
                                        X     = (float)updateData[0],
                                        Y     = (float)updateData[1],
                                        Z     = (float)updateData[2],
                                        Role  = (float)updateData[3],
                                        Pitch = (float)updateData[4],
                                        Yaw   = (float)updateData[5],
                                    },
                                    Time = DateTime.Now.ToFileTime(),
                                };
                                this.RobotInfoUpdated?.Invoke(info);

                                Thread.Sleep(1);
                            }
                            catch (System.Exception err)
                            {
                                Console.WriteLine(err.ToString());
                                Thread.Sleep(5000);
                                return;
                            }
                            finally
                            {
                                ms.Dispose();
                            }
                        }
                    }
                });

                IsLogging = true;
            }
        }
Пример #37
0
        private void TabManagerMain_PageAdded(object sender, DevExpress.XtraTabbedMdi.MdiTabPageEventArgs e)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            e.Page.MdiChild.Icon.Save(ms);
            e.Page.Image = Image.FromStream(ms);
            ms.Close(); ms.Dispose();
            //if (e.Page.MdiChild.GetType())
            //{

            //}
        }
Пример #38
0
 public void Close()
 {
     package?.Dispose();
     generatedDocument?.Dispose();
 }
Пример #39
0
		/// <summary> Retrieves and reads all marker segments found in the main header during
		/// the first pass.
		/// 
		/// </summary>
		private void  readFoundMainMarkSeg()
		{
			//UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
			//System.IO.BinaryReader dis;
			System.IO.MemoryStream bais;
			
			// SIZ marker segment
			if ((nfMarkSeg & SIZ_FOUND) != 0)
			{
				bais = new System.IO.MemoryStream((byte[])ht["SIZ"]);
				readSIZ(new CSJ2K.Util.EndianBinaryReader(bais, true));
                bais.Dispose();
			}
			
			// COM marker segments
			if ((nfMarkSeg & COM_FOUND) != 0)
			{
				for (int i = 0; i < nCOMMarkSeg; i++)
				{
					bais = new System.IO.MemoryStream((byte[])ht["COM" + i]);
					readCOM(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, i);
                    bais.Dispose();
				}
			}
			
			// CRG marker segment
			if ((nfMarkSeg & CRG_FOUND) != 0)
			{
				bais = new System.IO.MemoryStream((byte[])ht["CRG"]);
				readCRG(new CSJ2K.Util.EndianBinaryReader(bais, true));
                bais.Dispose();
			}
			
			// COD marker segment
			if ((nfMarkSeg & COD_FOUND) != 0)
			{
				bais = new System.IO.MemoryStream((byte[])ht["COD"]);
				readCOD(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0);
                bais.Dispose();
			}
			
			// COC marker segments
			if ((nfMarkSeg & COC_FOUND) != 0)
			{
				for (int i = 0; i < nCOCMarkSeg; i++)
				{
					bais = new System.IO.MemoryStream((byte[])ht["COC" + i]);
					readCOC(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0);
                    bais.Dispose();
				}
			}
			
			// RGN marker segment
			if ((nfMarkSeg & RGN_FOUND) != 0)
			{
				for (int i = 0; i < nRGNMarkSeg; i++)
				{
					bais = new System.IO.MemoryStream((byte[])ht["RGN" + i]);
					readRGN(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0);
                    bais.Dispose();
				}
			}
			
			// QCD marker segment
			if ((nfMarkSeg & QCD_FOUND) != 0)
			{
				bais = new System.IO.MemoryStream((byte[])ht["QCD"]);
				readQCD(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0);
                bais.Dispose();
			}
			
			// QCC marker segments
			if ((nfMarkSeg & QCC_FOUND) != 0)
			{
				for (int i = 0; i < nQCCMarkSeg; i++)
				{
					bais = new System.IO.MemoryStream((byte[])ht["QCC" + i]);
					readQCC(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0);
                    bais.Dispose();
				}
			}
			
			// POC marker segment
			if ((nfMarkSeg & POC_FOUND) != 0)
			{
				bais = new System.IO.MemoryStream((byte[])ht["POC"]);
				readPOC(new CSJ2K.Util.EndianBinaryReader(bais, true), true, 0, 0);
                bais.Dispose();
			}
			
			// PPM marker segments
			if ((nfMarkSeg & PPM_FOUND) != 0)
			{
				for (int i = 0; i < nPPMMarkSeg; i++)
				{
					bais = new System.IO.MemoryStream((byte[])ht["PPM" + i]);
					readPPM(new CSJ2K.Util.EndianBinaryReader(bais));
                    bais.Dispose();
				}
			}
			
			// Reset the hashtable
			ht = null;
		}
Пример #40
0
        public void ProcessRequest(HttpContext context)
        {
            String data = context.Request["t"];
            if (!string.IsNullOrEmpty(data))
            {
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                qrCodeEncoder.QRCodeScale = 4;
                qrCodeEncoder.QRCodeVersion = 8;
                qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                System.Drawing.Image image = qrCodeEncoder.Encode(data);
                System.IO.MemoryStream MStream = new System.IO.MemoryStream();
                image.Save(MStream, System.Drawing.Imaging.ImageFormat.Png);

                System.IO.MemoryStream MStream1 = new System.IO.MemoryStream();
                CombinImage(image, context.Server.MapPath("~/images/iconappli1.png")).Save(MStream1, System.Drawing.Imaging.ImageFormat.Png);
                context.Response.ClearContent();
                context.Response.ContentType = "image/png";
                context.Response.BinaryWrite(MStream1.ToArray());
                MStream.Dispose();
                MStream1.Dispose();
            }
            context.Response.Flush();
            context.Response.End();
        }
Пример #41
0
 public void Dispose()
 {
     _memoryStream.Dispose();
     GC.SuppressFinalize(this);
 }
Пример #42
0
        public void accept(string txtName)
        {
            textName = txtName;
            string type = Request.ContentType;
            int separator = type.IndexOf("/");
            string compressionFormat = type.Substring(separator+1);

            int len = txtName.Length;

            //compress
            byte[] stringToByte=new byte[len+1];
            int byteIndex=0;
            foreach(char c in txtName.ToCharArray())
            {
                stringToByte[byteIndex++] = (byte)c;
            }
            var bytes = Encoding.ASCII.GetBytes(txtName);

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            System.IO.Compression.GZipStream gzipStream = new System.IO.Compression.GZipStream(memoryStream,System.IO.Compression.CompressionMode.Compress);

            gzipStream.Write(bytes,0,bytes.Length);
            gzipStream.Close();

            stringToByte = memoryStream.ToArray();

            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(stringToByte.Length);
            foreach(byte b in stringToByte)
            {
                stringBuilder.Append((char)b);
            }
            memoryStream.Close();
            gzipStream.Dispose();
            memoryStream.Dispose();

            string s = stringBuilder.ToString();

            //Decompress
            byte[] decompressStream=new byte[s.Length];
            byteIndex=0;
            foreach(char c in s.ToCharArray())
            {
                decompressStream[byteIndex++]=(byte)c;
            }

            System.IO.MemoryStream ms = new System.IO.MemoryStream(decompressStream);
            System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms,System.IO.Compression.CompressionMode.Decompress);

            int byteRead = gs.Read(decompressStream,0,decompressStream.Length);

            System.Text.StringBuilder builder = new System.Text.StringBuilder(byteRead);
             foreach(byte b in decompressStream)
             {
                 builder.Append((char)b);
             }

             ms.Close();
             gs.Close();
             ms.Dispose();
             gs.Dispose();

             String str = builder.ToString();
             int a = 0;
        }
        private void ParseFile(string filename, uint depth, ref System.Collections.Generic.List <string> outputfiles)
        {
            SFWorkflow.WFFileType.FileType type = SFWorkflow.WFFileType.GetFileType(filename);
            if (type == SFWorkflow.WFFileType.FileType.OlePowerPoint)
            {
                uint fileidx = 0;

                System.Collections.Generic.List <string> pptfiles = new System.Collections.Generic.List <string>();
                DIaLOGIKa.b2xtranslator.StructuredStorage.Reader.StructuredStorageReader ssr = new DIaLOGIKa.b2xtranslator.StructuredStorage.Reader.StructuredStorageReader(filename);
                DIaLOGIKa.b2xtranslator.PptFileFormat.PowerpointDocument ppt = new DIaLOGIKa.b2xtranslator.PptFileFormat.PowerpointDocument(ssr);
                foreach (uint persistId in ppt.PersistObjectDirectory.Keys)
                {
                    UInt32 offset = ppt.PersistObjectDirectory[persistId];
                    ppt.PowerpointDocumentStream.Seek(offset, System.IO.SeekOrigin.Begin);
                    DIaLOGIKa.b2xtranslator.PptFileFormat.ExOleObjStgAtom obj = DIaLOGIKa.b2xtranslator.OfficeDrawing.Record.ReadRecord(ppt.PowerpointDocumentStream) as DIaLOGIKa.b2xtranslator.PptFileFormat.ExOleObjStgAtom;
                    if (obj != null)
                    {
                        string filedir = string.Format("{0}\\{1}", System.IO.Directory.GetParent(filename).FullName, SFWorkflow.WFUtilities.GetNextDirectoryNumber(System.IO.Directory.GetParent(filename).FullName));
                        if (!System.IO.Directory.Exists(filedir))
                        {
                            System.IO.Directory.CreateDirectory(filedir);
                        }
                        if (System.IO.Directory.Exists(filedir))
                        {
                            byte[] data = obj.DecompressData();
                            System.IO.MemoryStream ms = new System.IO.MemoryStream(data);

                            SFWorkflow.WFFileType.FileType oletype = SFWorkflow.WFFileType.GetOleFileType(data);
                            if (oletype == WFFileType.FileType.OlePackage || oletype == WFFileType.FileType.OleContents)
                            {
                                using (OpenMcdf.CompoundFile cf = new OpenMcdf.CompoundFile(ms))
                                {
                                    WriteStorage(cf.RootStorage, filedir, depth, ref pptfiles);
                                }
                            }
                            else
                            {
                                string filenm = String.Format("{0}\\pptembed{1}", filedir, fileidx);
                                using (System.IO.FileStream fs = new System.IO.FileStream(filenm, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                                {
                                    byte[] buffer = new byte[1024];
                                    int    len;
                                    while ((len = ms.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        fs.Write(buffer, 0, len);
                                    }
                                    pptfiles.Add(filenm);
                                }
                                fileidx++;
                                ms.Close();
                                ms.Dispose();
                            }
                        }
                    }
                }
#if false
                foreach (DIaLOGIKa.b2xtranslator.PptFileFormat.ExOleEmbedContainer ole in ppt.OleObjects.Values)
                {
                    string filedir = string.Format("{0}\\{1}", System.IO.Directory.GetParent(filename).FullName, diridx++);
                    if (!System.IO.Directory.Exists(filedir))
                    {
                        System.IO.Directory.CreateDirectory(filedir);
                    }
                    if (System.IO.Directory.Exists(filedir))
                    {
                        string filenm = String.Format("{0}\\pptembed{1}", filedir, ole.SiblingIdx);
                        try
                        {
                            System.IO.FileStream fss = new System.IO.FileStream(filenm, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                            byte[] data = ole.stgAtom.DecompressData();
                            fss.Write(data, 0, data.Length);
                            fss.Flush();
                            fss.Close();
                            fss.Dispose();

                            pptfiles.Add(filenm);
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
#endif
                foreach (DIaLOGIKa.b2xtranslator.OfficeDrawing.Record record in ppt.PicturesContainer._pictures.Values)                 //.Where(x => x.TypeCode == 0xF01C || x.TypeCode == 0xF01D || x.TypeCode == 0xF01E || x.TypeCode == 0xF01F || x.TypeCode == 0xF029 || x.TypeCode == 0xF02A))
                {
                    string filedir = string.Format("{0}\\{1}", System.IO.Directory.GetParent(filename).FullName, "PPTPictures");        //, SFWorkflow.WFUtilities.GetNextDirectoryNumber(System.IO.Directory.GetParent(filename).FullName));
                    if (!System.IO.Directory.Exists(filedir))
                    {
                        System.IO.Directory.CreateDirectory(filedir);
                    }
                    if (System.IO.Directory.Exists(filedir))
                    {
                        string extension = string.Empty;
                        int    skip      = 0;
                        switch (record.TypeCode)
                        {
                        case 0xF01A:
                            extension = ".emf";
                            break;

                        case 0xF01B:
                            extension = ".wmf";
                            break;

                        case 0xF01C:
                            extension = ".pict";
                            break;

                        case 0xF01D:
                        case 0xF02A:
                            extension = ".jpg";
                            skip      = 17;
                            break;

                        case 0xF01E:
                            extension = ".png";
                            skip      = 17;
                            break;

                        case 0xF01F:
                            extension = ".dib";
                            break;

                        case 0xF029:
                            extension = ".tiff";
                            break;
                        }
                        string filenm = String.Format("{0}\\pptembed{1}{2}", filedir, fileidx++, extension);
                        using (System.IO.FileStream fs = new System.IO.FileStream(filenm, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                        {
                            // need to skip 17 byte header in raw data stream
                            byte[] data = ((extension == ".emf" || extension == ".wmf")) ? ((DIaLOGIKa.b2xtranslator.OfficeDrawing.MetafilePictBlip)record).Decrompress() : record.RawData.Skip(skip).ToArray();
                            fs.Write(data, 0, data.Length);
                            fs.Flush();
                            fs.Close();
                            fs.Dispose();

                            pptfiles.Add(filenm);
                        }
                    }
                }
                ssr.Close();
                ssr.Dispose();
                outputfiles.AddRange(pptfiles);
                depth--;
                if (depth > 0)
                {
                    foreach (string fn in pptfiles)
                    {
                        ParseFile(fn, depth, ref outputfiles);
                    }
                }
            }
            else
            {
                using (OpenMcdf.CompoundFile cf = new OpenMcdf.CompoundFile(filename))
                {
                    WriteStorage(cf.RootStorage, System.IO.Directory.GetParent(filename).FullName, depth, ref outputfiles);
                }
            }
        }