Beispiel #1
0
        public static byte[] Build(Xml.FileGroupXml group, string spriteFile)
        {
            var bmps = group.Files.Select(x => new System.Drawing.Bitmap(x.Path));

            var maxWidth = bmps.Max(x => x.Width);
            var totalHeight = bmps.Sum(x => x.Height);

            int top = 0;
            using (var sprite = new System.Drawing.Bitmap(maxWidth, totalHeight))
            using (var mem = new System.IO.MemoryStream())
            using (var g = System.Drawing.Graphics.FromImage(sprite))
            {
                foreach (var bmp in bmps)
                {
                    using (bmp)
                    {
                        g.DrawImage(bmp, new System.Drawing.Rectangle(0, top, bmp.Width, bmp.Height), new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.GraphicsUnit.Pixel);
                        top += bmp.Height;
                    }
                }

                sprite.Save(mem, GetFormat(spriteFile) ?? System.Drawing.Imaging.ImageFormat.Png);
                return mem.ToArray();
            }
        }
Beispiel #2
0
 public void ProcessRequest(HttpContext context)
 {
     string TrueName = Utils.GetQueryStringValue("TrueName");
     string CardNo = Utils.GetQueryStringValue("CardNo");
     System.Drawing.Image img = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(VipCardTemplate));
     Graphics g = Graphics.FromImage(img);
     g.DrawImage(img, 0, 0, img.Width, img.Height);
     //设置高质量插值法
     g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
     //设置高质量,低速度呈现平滑程度
     g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
     Font f = new Font("宋体", 17.5f, FontStyle.Bold);
     Brush br = new SolidBrush(Color.FromArgb(100, 80, 80, 80));
     g.DrawString(TrueName, f, br, 52, 200);
     Font f1 = new Font("Arial", 12, FontStyle.Regular);
     Brush br1 = new SolidBrush(Color.FromArgb(100, 102, 102, 102));
     g.DrawString("No:" + CardNo, f1, br1, 25, 225);
     g.Dispose();
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
     byte[] imgbyte = ms.ToArray();
     if (imgbyte != null)
     {
         HttpContext.Current.Response.ClearContent();
         HttpContext.Current.Response.ContentType = "image/Jpeg";
         HttpContext.Current.Response.AddHeader("Content-Length", imgbyte.Length.ToString());
         HttpContext.Current.Response.BinaryWrite(imgbyte);
         HttpContext.Current.Response.Flush();
         HttpContext.Current.Response.End();
     }
 }
Beispiel #3
0
		public static byte[] SerializeVoxelAreaCompactData (VoxelArea v) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
			
			writer.Write (v.width);
			writer.Write (v.depth);
			writer.Write (v.compactCells.Length);
			writer.Write(v.compactSpans.Length);
			writer.Write(v.areaTypes.Length);
			
			for (int i=0;i<v.compactCells.Length;i++) {
				writer.Write(v.compactCells[i].index);
				writer.Write(v.compactCells[i].count);
			}
			
			for (int i=0;i<v.compactSpans.Length;i++) {
				writer.Write(v.compactSpans[i].con);
				writer.Write(v.compactSpans[i].h);
				writer.Write(v.compactSpans[i].reg);
				writer.Write(v.compactSpans[i].y);
			}
			for (int i=0;i<v.areaTypes.Length;i++) {
				//TODO: RLE encoding
				writer.Write(v.areaTypes[i]);
			}
			writer.Close();
			return stream.ToArray();
#else
			throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
		}
Beispiel #4
0
        public static void SubmitResult(Uri testVaultServer, string session, string project, string buildname, string testgroup, string testname, TestOutcome outcome, bool personal)
        {
            try
            {
                using ( var client = new WebClient() ){

                    client.BaseAddress = testVaultServer.ToString();
                    client.CachePolicy = new System.Net.Cache.RequestCachePolicy( System.Net.Cache.RequestCacheLevel.NoCacheNoStore );
                    client.Headers.Add("Content-Type", "text/xml");

                    var result = new TestResult()
                    {
                        Group = new TestGroup() { Name = testgroup, Project = new TestProject() { Project = project } },
                        Name = testname,
                        Outcome = outcome,
                        TestSession = session,
                        IsPersonal = personal,
                        BuildID = buildname,
                    };

                    var xc = new XmlSerializer(result.GetType());
                    var io = new System.IO.MemoryStream();
                    xc.Serialize( io, result );

                    client.UploadData( testVaultServer.ToString(), io.ToArray() );

                }
            } catch ( Exception e )
            {
                Console.Error.WriteLine( e );
            }
        }
Beispiel #5
0
		public static byte[] SerializeVoxelAreaData (VoxelArea v) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
			
			writer.Write (v.width);
			writer.Write (v.depth);
			writer.Write (v.linkedSpans.Length);
			
			for (int i=0;i<v.linkedSpans.Length;i++) {
				writer.Write(v.linkedSpans[i].area);
				writer.Write(v.linkedSpans[i].bottom);
				writer.Write(v.linkedSpans[i].next);
				writer.Write(v.linkedSpans[i].top);
			}
			
			//writer.Close();
			writer.Flush();
			Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
			stream.Position = 0;
			zip.AddEntry ("data",stream);
			System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
			zip.Save(stream2);
			byte[] bytes = stream2.ToArray();
			stream.Close();
			stream2.Close();
			return bytes;
#else
			throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
		}
Beispiel #6
0
        /// <summary>
        /// Encrypt a message using AES in CBC (cipher-block chaining) mode.
        /// </summary>
        /// <param name="plaintext">The message (plaintext) to encrypt</param>
        /// <param name="key">An AES key</param>
        /// <param name="iv">The IV to use or null to use a 0 IV</param>
        /// <param name="addHmac">When set, a SHA256-based HMAC (HMAC256) of 32 bytes using the same key is added to the plaintext
        /// before it is encrypted.</param>
        /// <returns>The ciphertext derived by encrypting the orignal message using AES in CBC mode</returns>
        public static byte[] EncryptAesCbc(byte[] plaintext, byte[] key, byte[] iv = null, bool addHmac = false)
        {
            using (Aes aes =Aes.Create())
//            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.Key = key;
                if (iv == null)
                    iv = NullIv;
                aes.Mode = CipherMode.CBC;
                aes.IV = iv;

                // Encrypt the message with the key using CBC and InitializationVector=0
                byte[] cipherText;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(plaintext, 0, plaintext.Length);
                        if (addHmac)
                        {
                            byte[] hmac = new HMACSHA256(key).ComputeHash(plaintext);
                            cs.Write(hmac, 0, hmac.Length);
                        }
                        cs.Flush();
                    }
                    cipherText = ciphertext.ToArray();
                }

                return cipherText;
            }
        }
        /// <summary>
        /// 创建图片
        /// </summary>
        /// <param name="checkCode"></param>
        private void CreateImage(string checkCode)
        {
            int iwidth = (int)(checkCode.Length * 11);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 19);
            Graphics g = Graphics.FromImage(image);
            g.Clear(Color.White);
            //定义颜色
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Chocolate, Color.Brown, Color.DarkCyan, Color.Purple };
            Random rand = new Random();

            //输出不同字体和颜色的验证码字符
            for (int i = 0; i < checkCode.Length; i++)
            {
                int cindex = rand.Next(7);
                Font f = new System.Drawing.Font("Microsoft Sans Serif", 11);
                Brush b = new System.Drawing.SolidBrush(c[cindex]);
                g.DrawString(checkCode.Substring(i, 1), f, b, (i * 10) + 1, 0, StringFormat.GenericDefault);
            }
            //画一个边框
            g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);

            //输出到浏览器
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            Response.ClearContent();
            Response.ContentType = "image/Jpeg";
            Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        }
Beispiel #8
0
		/// <summary>Compresses the specified byte range using the
		/// specified compressionLevel (constants are defined in
		/// java.util.zip.Deflater). 
		/// </summary>
		public static byte[] Compress(byte[] value_Renamed, int offset, int length, int compressionLevel)
		{
			/* Create an expandable byte array to hold the compressed data.
			* You cannot use an array that's the same size as the orginal because
			* there is no guarantee that the compressed data will be smaller than
			* the uncompressed data. */
			System.IO.MemoryStream bos = new System.IO.MemoryStream(length);

            SupportClass.SharpZipLib.Deflater compressor = SupportClass.SharpZipLib.CreateDeflater();
			
			try
			{
				compressor.SetLevel(compressionLevel);
				compressor.SetInput(value_Renamed, offset, length);
				compressor.Finish();
				
				// Compress the data
				byte[] buf = new byte[1024];
				while (!compressor.IsFinished)
				{
					int count = compressor.Deflate(buf);
					bos.Write(buf, 0, count);
				}
			}
			finally
			{
			}
			
			return bos.ToArray();
		}
        public static string encryptRJ256(string target, string key, string iv)
        {
            var rijndael = new System.Security.Cryptography.RijndaelManaged()
            {
                Padding = System.Security.Cryptography.PaddingMode.Zeros,
                Mode = System.Security.Cryptography.CipherMode.CBC,
                KeySize = 256,
                BlockSize = 256
            };

            var bytesKey = Encoding.ASCII.GetBytes(key);
            var bytesIv = Encoding.ASCII.GetBytes(iv);

            var encryptor = rijndael.CreateEncryptor(bytesKey, bytesIv);

            var msEncrypt = new System.IO.MemoryStream();
            var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write);

            var toEncrypt = Encoding.ASCII.GetBytes(target);

            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();

            var encrypted = msEncrypt.ToArray();
            return Convert.ToBase64String(encrypted);
        }
Beispiel #10
0
 public byte[] GetCaptchaImage(string checkCode)
 {
     Bitmap image = new Bitmap(Convert.ToInt32(Math.Ceiling((decimal)(checkCode.Length * 15))), 25);
     Graphics g = Graphics.FromImage(image);
     try
     {
         Random random = new Random();
         g.Clear(Color.AliceBlue);
         Font font = new Font("Comic Sans MS", 14, FontStyle.Bold);
         string str = "";
         System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
         for (int i = 0; i < checkCode.Length; i++)
         {
             str = str + checkCode.Substring(i, 1);
         }
         g.DrawString(str, font, new SolidBrush(Color.Blue), 0, 0);
         g.Flush();
         System.IO.MemoryStream ms = new System.IO.MemoryStream();
         image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
         return ms.ToArray();
     }
     finally
     {
         g.Dispose();
         image.Dispose();
     }
 }
Beispiel #11
0
        public override DecodedObject<object> decodeAny(DecodedObject<object> decodedTag, System.Type objectClass, ElementInfo elementInfo, System.IO.Stream stream)
        {
            int bufSize = elementInfo.MaxAvailableLen;
            if (bufSize == 0)
                return null;
            System.IO.MemoryStream anyStream = new System.IO.MemoryStream(1024);
            /*int tagValue = (int)decodedTag.Value;
            for (int i = 0; i < decodedTag.Size; i++)
            {
                anyStream.WriteByte((byte)tagValue);
                tagValue = tagValue >> 8;
            }*/

            if(bufSize<0)
                bufSize = 1024;
            int len = 0;
            if (bufSize > 0)
            {
                byte[] buffer = new byte[bufSize];
                int readed = stream.Read(buffer, 0, buffer.Length);
                while (readed > 0)
                {
                    anyStream.Write(buffer, 0, readed);
                    len += readed;
                    if (elementInfo.MaxAvailableLen > 0)
                        break;
                    readed = stream.Read(buffer, 0, buffer.Length);
                }
            }
            CoderUtils.checkConstraints(len, elementInfo);
            return new DecodedObject<object>(anyStream.ToArray(), len);
        }
Beispiel #12
0
        // GET: Api/Post/Add3
        public JsonResult Add3()
        {
            PostModel model = new PostModel();
            model.PDate = DateTime.Now;

            string fileName = Server.MapPath("~/App_Data/test3.json");
            model.PText = fileName;

            System.Runtime.Serialization.Json.DataContractJsonSerializer ser =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(PostModel));

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

            ser.WriteObject(stream1, model);

            using (System.IO.FileStream f2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create))
            {
                byte[] jsonArray = stream1.ToArray();

                using (System.IO.Compression.GZipStream gz =
                    new System.IO.Compression.GZipStream(f2, System.IO.Compression.CompressionMode.Compress))
                {
                    gz.Write(jsonArray, 0, jsonArray.Length);
                }
            }

            return Json(model, JsonRequestBehavior.AllowGet);
        }
Beispiel #13
0
        private void SaveWebPost(string fileName, PostModel model)
        {
            WebPostModel wPost = new WebPostModel()
            {
                PTitle = model.PTitle,
                PText = model.PText,
                PLink = model.PLink,
                PImage = model.PImage,
                PDate = model.PDate.ToString("yyyy-MM-ddTHH:mm:ss"),
                PPrice = model.PPrice
            };

            System.IO.MemoryStream msPost = new System.IO.MemoryStream();
            System.Runtime.Serialization.Json.DataContractJsonSerializer dcJsonPost =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(WebPostModel));
            dcJsonPost.WriteObject(msPost, wPost);

            using (System.IO.FileStream f2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create))
            {
                byte[] jsonArray = msPost.ToArray();

                using (System.IO.Compression.GZipStream gz =
                    new System.IO.Compression.GZipStream(f2, System.IO.Compression.CompressionMode.Compress))
                {
                    gz.Write(jsonArray, 0, jsonArray.Length);
                }
            }
        }
        Color GetColorFromImage(Point p)
        {
            try
            {
                Rect bounds = VisualTreeHelper.GetDescendantBounds(this);
                RenderTargetBitmap rtb = new RenderTargetBitmap((Int32)bounds.Width, (Int32)bounds.Height, 96, 96, PixelFormats.Default);
                rtb.Render(this);

                byte[] arr;
                PngBitmapEncoder png = new PngBitmapEncoder();
                png.Frames.Add(BitmapFrame.Create(rtb));
                using (var stream = new System.IO.MemoryStream())
                {
                    png.Save(stream);
                    arr = stream.ToArray();
                }

                BitmapSource bitmap = BitmapFrame.Create(new System.IO.MemoryStream(arr));

                byte[] pixels = new byte[4];
                CroppedBitmap cb = new CroppedBitmap(bitmap, new Int32Rect((int)p.X, (int)p.Y, 1, 1));
                cb.CopyPixels(pixels, 4, 0);
                return Color.FromArgb(pixels[3], pixels[2], pixels[1], pixels[0]);
            }
            catch (Exception)
            {
                return this.ColorBox.Color;
            }
        }
 public ActionDefinition(ActionLibrary parent, string name, int id)
 {
     Library = parent;
     GameMakerVersion = 520;
     Name = name;
     ActionID = id;
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     Properties.Resources.DefaultAction.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
     OriginalImage = ms.ToArray();
     ms.Close();
     Image = new System.Drawing.Bitmap(24, 24, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
     System.Drawing.Graphics.FromImage(Image).DrawImage(Properties.Resources.DefaultAction, new System.Drawing.Rectangle(0, 0, 24, 24), new System.Drawing.Rectangle(0, 0, 24, 24), System.Drawing.GraphicsUnit.Pixel);
     (Image as System.Drawing.Bitmap).MakeTransparent(Properties.Resources.DefaultAction.GetPixel(0, Properties.Resources.DefaultAction.Height - 1));
     Hidden = false;
     Advanced = false;
     RegisteredOnly = false;
     Description = string.Empty;
     ListText = string.Empty;
     HintText = string.Empty;
     Kind = ActionKind.Normal;
     InterfaceKind = ActionInferfaceKind.Normal;
     IsQuestion = false;
     ShowApplyTo = true;
     ShowRelative = true;
     ArgumentCount = 0;
     Arguments = new ActionArgument[8];
     for (int i = 0; i < 8; i++) Arguments[i] = new ActionArgument();
     ExecutionType = ActionExecutionType.None;
     FunctionName = string.Empty;
     Code = string.Empty;
 }
Beispiel #16
0
        public static Icon PngIconFromImage(Image img, int size = 16)
        {
            using (var bmp = new Bitmap(img, new Size(size, size)))
            {
                byte[] png;
                using (var fs = new System.IO.MemoryStream())
                {
                    bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
                    fs.Position = 0;
                    png = fs.ToArray();
                }

                using (var fs = new System.IO.MemoryStream())
                {
                    if (size >= 256) size = 0;
                    Pngiconheader[6] = (byte)size;
                    Pngiconheader[7] = (byte)size;
                    Pngiconheader[14] = (byte)(png.Length & 255);
                    Pngiconheader[15] = (byte)(png.Length / 256);
                    Pngiconheader[18] = (byte)(Pngiconheader.Length);

                    fs.Write(Pngiconheader, 0, Pngiconheader.Length);
                    fs.Write(png, 0, png.Length);
                    fs.Position = 0;
                    return new Icon(fs);
                }
            }
        }
        public static byte[] ToByteArray(this System.IO.Stream strm)
        {
            if(strm is System.IO.MemoryStream)
            {
                return (strm as System.IO.MemoryStream).ToArray();
            }

            long originalPosition = -1;
            if(strm.CanSeek)
            {
                originalPosition = strm.Position;
            }

            try
            {
                using (var ms = new System.IO.MemoryStream())
                {
                    ms.CopyTo(ms);
                    return ms.ToArray();
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (originalPosition >= 0) strm.Position = originalPosition;
            }
        }
Beispiel #18
0
 private void photographPictureBox_DragDrop(object sender, DragEventArgs e)
 {
     if (e.Data.GetDataPresent(DataFormats.FileDrop))
     {
         string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);
         if (filePaths.Length > 0)
         {
             // Attempt to load, may not be valid image
             string path = filePaths[0];
             try
             {
                 using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(path)))
                 {
                     Image tempImage = Image.FromStream(memoryStream);
                     photographPictureBox.Image = new Bitmap(tempImage);
                     photographByteArray = memoryStream.ToArray();
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show("Error loading file: " + ex.Message);
             }
         }
     }
 }
Beispiel #19
0
		public static byte[] SerializeVoxelAreaData (VoxelArea v) {
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
			
			writer.Write (v.width);
			writer.Write (v.depth);
			writer.Write (v.linkedSpans.Length);
			
			for (int i=0;i<v.linkedSpans.Length;i++) {
				writer.Write(v.linkedSpans[i].area);
				writer.Write(v.linkedSpans[i].bottom);
				writer.Write(v.linkedSpans[i].next);
				writer.Write(v.linkedSpans[i].top);
			}
			
			//writer.Close();
			writer.Flush();
			Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
			stream.Position = 0;
			zip.AddEntry ("data",stream);
			System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
			zip.Save(stream2);
			byte[] bytes = stream2.ToArray();
			stream.Close();
			stream2.Close();
			return bytes;
		}
Beispiel #20
0
		public static byte[] SerializeVoxelAreaCompactData (VoxelArea v) {
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
			
			writer.Write (v.width);
			writer.Write (v.depth);
			writer.Write (v.compactCells.Length);
			writer.Write(v.compactSpans.Length);
			writer.Write(v.areaTypes.Length);
			
			for (int i=0;i<v.compactCells.Length;i++) {
				writer.Write(v.compactCells[i].index);
				writer.Write(v.compactCells[i].count);
			}
			
			for (int i=0;i<v.compactSpans.Length;i++) {
				writer.Write(v.compactSpans[i].con);
				writer.Write(v.compactSpans[i].h);
				writer.Write(v.compactSpans[i].reg);
				writer.Write(v.compactSpans[i].y);
			}
			for (int i=0;i<v.areaTypes.Length;i++) {
				//TODO: RLE encoding
				writer.Write(v.areaTypes[i]);
			}
			writer.Close();
			return stream.ToArray();
		}
        public static byte[] CreateAvatar(int sideLength, System.IO.Stream fromStream)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            using (var image = System.Drawing.Image.FromStream(fromStream))
            using (var thumbBitmap = new System.Drawing.Bitmap(sideLength, sideLength))
            {

                var a = Math.Min(image.Width, image.Height);

                var x = (image.Width - a) / 2;

                var y = (image.Height - a) / 2;

                using (var thumbGraph = System.Drawing.Graphics.FromImage(thumbBitmap))
                {

                    thumbGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                    thumbGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    thumbGraph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                    var imgRectangle = new System.Drawing.Rectangle(0, 0, sideLength, sideLength);

                    thumbGraph.DrawImage(image, imgRectangle, x, y, a, a, System.Drawing.GraphicsUnit.Pixel);

                    thumbBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                }

            }
            return (ms.ToArray());
        }
        public ActionResult AddDocuments(PatientDocumentViewModel patientDocumentViewModel)
        {
            if (!ModelState.IsValid)
            {
                patientDocumentViewModel.PatientDocumentViewEntity.Patients = GetPatients();
                return View(patientDocumentViewModel);
            }

            if (patientDocumentViewModel.PatientDocumentViewEntity.Patients.SelectedItemId == "-1")
            {
                ModelState.AddModelError("", "Please select patient");
                patientDocumentViewModel.PatientDocumentViewEntity.Patients = GetPatients();
                return View(patientDocumentViewModel);
            }

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            patientDocumentViewModel.PatientDocumentViewEntity.DocumentToUpload.InputStream.CopyTo(memoryStream);
            byte[] documentInByteArray = memoryStream.ToArray();

            Document document = new Document();
            DocumentRepository documentRepository = new DocumentRepository();

            document.ProviderId = int.Parse(Session["ProviderId"].ToString());
            document.PatientId = int.Parse(patientDocumentViewModel.PatientDocumentViewEntity.Patients.SelectedItemId);
            document.DocumentType = patientDocumentViewModel.PatientDocumentViewEntity.DocumentType;
            document.Document1 = documentInByteArray;
            document.CreationTime = DateTime.Now;
            documentRepository.AddDocuments(document);

            return RedirectToAction("AddDocuments", new { patientId = document.PatientId });
        }
        public static ActionResult JsonOrJsonP(this Controller controller, object data, string callback, bool serialize = true)
        {
            bool isJsonP = (controller.Request != null && controller.Request.HttpMethod == "GET");
            string serializedData;

            if (isJsonP)
            {
                if (serialize)
                {
                    using (var ms = new System.IO.MemoryStream())
                    {
                        var serializer = new DataContractJsonSerializer(data.GetType());
                        serializer.WriteObject(ms, data);
                        serializedData = System.Text.Encoding.UTF8.GetString(ms.ToArray());
                    }
                }
                else
                    serializedData = (string) data;
                string serializedDataWithCallback = String.Format("{0}({1})", callback, serializedData);

                return new ContentResult { Content = serializedDataWithCallback, ContentType = "application/javascript" };
            }

            if (serialize)
            {
                return new JsonDataContractActionResult(data);
            }
            else
            {
                serializedData = (string) data;
                return new ContentResult { Content = serializedData, ContentType = "application/json" };
            }
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            Sodao.FastSocket.SocketBase.Log.Trace.EnableConsole();
            Sodao.FastSocket.SocketBase.Log.Trace.EnableDiagnostic();

            var client = new Sodao.FastSocket.Client.AsyncBinarySocketClient(8192, 8192, 3000, 3000);
            //注册服务器节点,这里可注册多个(name不能重复)
            client.RegisterServerNode("127.0.0.1:8401", new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 8401));
            //client.RegisterServerNode("127.0.0.1:8402", new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.2"), 8401));

            //组织sum参数, 格式为<<i:32-limit-endian,....N>>
            //这里的参数其实也可以使用thrift, protobuf, bson, json等进行序列化,
            byte[] bytes = null;
            using (var ms = new System.IO.MemoryStream())
            {
                for (int i = 1; i <= 1000; i++) ms.Write(BitConverter.GetBytes(i), 0, 4);
                bytes = ms.ToArray();
            }
            //发送sum命令
            client.Send("sum", bytes, res => BitConverter.ToInt32(res.Buffer, 0)).ContinueWith(c =>
            {
                if (c.IsFaulted)
                {
                    // Console.WriteLine(c.Exception.ToString());
                    return;
                }
                // Console.WriteLine(c.Result);
            });

            Console.ReadLine();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // 用于显示的数字.
            string number = Request["NO"];

            if (String.IsNullOrEmpty(number))
            {
                number = "123456";
            }

            // 定义图片大小.
            System.Drawing.Bitmap image =
                new System.Drawing.Bitmap(400, 200);

            Graphics g = Graphics.FromImage(image);

            // 字体.
            Font codeFont = new System.Drawing.Font("Vijaya", 32, (System.Drawing.FontStyle.Bold));

            LinearGradientBrush brush =
                new LinearGradientBrush(
                    new Rectangle(0, 0, image.Width, image.Height),
                        Color.Blue, Color.White, 1.2f, true);

            g.DrawString(number, codeFont, brush, 20, 20);

            // 用于模拟图片长时间下载.
            Thread.Sleep(2500);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }
Beispiel #26
0
 public void Write(string key, LocationCacheRecord lcr)
 {
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     formatter.Serialize(ms, lcr);
     cache.Write(key, ms.ToArray(), true);
 }
Beispiel #27
0
        public override IData GetMessagesData(IList<Message> messages)
        {
            IData data = null;
            byte[] buffer;
            long index = 0;
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                foreach (Message message in messages)
                {
                    stream.Write(new byte[4], 0, 4);
                    short typevalue = TypeMapper.GetValue(message.Type);
                    if (typevalue == 0)
						throw new Exception (string.Format ("{0} type value not registed", message.Type));
                      
                    byte[] typedata = BitConverter.GetBytes(typevalue);
                    stream.Write(typedata, 0, typedata.Length);
                    if (message.Value != null)
                        ProtoBuf.Meta.RuntimeTypeModel.Default.Serialize(stream, message.Value);
                    buffer = stream.GetBuffer();
                    BitConverter.GetBytes((int)stream.Length - 4 - (int)index).CopyTo(buffer, index);
                    index = stream.Position;
                }
                byte[] array = stream.ToArray();
                data = new Data(array,0, array.Length);
             

            }
            return data;
        }
Beispiel #28
0
		private static void BinWriteDataSetToStream(System.IO.Stream stream, System.Data.DataSet ds)
		{
			//Version
			IO.StreamPersistence.Write(stream, c_BinaryVersion);

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

			//Tables
			for (int iTable = 0; iTable < ds.Tables.Count; iTable++)
			{
				System.Data.DataTable table = ds.Tables[iTable];
				//Only the current Rows
				System.Data.DataRow[] rows = table.Select(null, null, System.Data.DataViewRowState.CurrentRows);
				IO.StreamPersistence.Write(stream, rows.Length);
				//Rows
				for (int r = 0; r < rows.Length; r++)
				{
					//Columns
					for (int c = 0; c < table.Columns.Count; c++)
						BinWriteFieldToStream(stream, rows[r][c], table.Columns[c].DataType);
				}
			}
		}
Beispiel #29
0
        //Look at http://code.google.com/p/zxing/wiki/BarcodeContents for formatting

        /// <summary>
        /// Returns a QRCode with the data embedded
        /// </summary>
        /// <param name="data">The data to embed in a QRCode.</param>
        public Task<ImageResult> QRCode(string data)
        {
            return AsyncHelper.RunAsync(() =>
            {
                var qrCode = new MultiFormatWriter();
                var byteIMG = qrCode.encode(data, BarcodeFormat.QR_CODE, 200, 200);
                sbyte[][] img = byteIMG.Array;
                var bmp = new Bitmap(200, 200);
                var g = Graphics.FromImage(bmp);
                g.Clear(Color.White);
                for (var y = 0; y <= img.Length - 1; y++)
                {
                    for (var x = 0; x <= img[y].Length - 1; x++)
                    {
                        g.FillRectangle(
                            img[y][x] == 0 ? Brushes.Black : Brushes.White, x, y, 1, 1);
                    }
                }

                var stream = new System.IO.MemoryStream();
                bmp.Save(stream, ImageFormat.Jpeg);
                var imageBytes = stream.ToArray();
                stream.Close();

                return this.Image(imageBytes, "image/jpeg");
            });
        }
Beispiel #30
0
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="text">待解密的串</param> 
        /// <param name="key">密钥</param> 
        /// <returns></returns> 
        public static string Decrypt(string text, string key)
        {
            using (var des = new DESCryptoServiceProvider())
            {
                int len;
                len = text.Length / 2;
                var inputByteArray = new byte[len];
                int x, i;
                for (x = 0; x < len; x++)
                {
                    i = Convert.ToInt32(text.Substring(x * 2, 2), 16);
                    inputByteArray[x] = (byte)i;
                }

                des.Key = ASCIIEncoding.ASCII.GetBytes(GetMd5(key).Substring(0, 8));
                des.IV = ASCIIEncoding.ASCII.GetBytes(GetMd5(key).Substring(0, 8));
                using (var ms = new System.IO.MemoryStream())
                {
                    var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    return Encoding.Default.GetString(ms.ToArray());
                }
            }
        }
Beispiel #31
0
        public static async Task UploadDocumentAsync(string webUrl, string bearerToken, System.IO.Stream document,
                                                     string folderServerRelativeUrl, string fileName)
        {
            try
            {
                const string SharePointUploadRestApi =
                    "{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/Files/add(url='{2}',overwrite=true)";
                string SharePointUploadUrl = string.Format(SharePointUploadRestApi, webUrl, folderServerRelativeUrl, fileName);

                using (var handler = new HttpClientHandler())
                {
                    using (var client = new HttpClient(handler))
                    {
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Add("Accept", "application/json;odata=nometadata");
                        client.DefaultRequestHeaders.Add("binaryStringRequestBody", "true");
                        client.MaxResponseContentBufferSize        = 2147483647;
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
                        //Creating Content
                        var destination = new System.IO.MemoryStream();
                        if (document.GetType() != typeof(System.IO.MemoryStream))
                        {
                            document.CopyTo(destination);
                        }
                        else
                        {
                            destination = document as System.IO.MemoryStream;
                        }
                        ByteArrayContent content = new ByteArrayContent(destination?.ToArray());

                        //Perform post
                        HttpResponseMessage response = await client.PostAsync(SharePointUploadUrl, content).ConfigureAwait(false);

                        //Ensure 200 (Ok)
                        response.EnsureSuccessStatusCode();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Error uploading document {fileName} call on folder {folderServerRelativeUrl}. {ex.Message}", ex);
            }
            finally
            {
                document?.Dispose();
            }
        }
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {
            case Resource.Id.menu_send:
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                bitmap?.Compress(Bitmap.CompressFormat.Png, 0, stream);
                byte[] bitmapData = stream?.ToArray();
                new UsuariosController().AddChangeColaborador(PerpetualEngine.Storage.SimpleStorage.EditGroup("Login").Get("Empresa_Id"), txtNombre.Text, txtApellidos.Text,
                                                              txtCorreo.Text, txtTelefono.Text, txtCelular.Text, txtProfesion.Text,
                                                              txtPuesto.Text, txtHabilidades.Text, txtNacimiento.ToString(),
                                                              colaborador_id, (spGenero.SelectedItemId + 1).ToString(), bitmapData);
                break;

            default:
                //StartActivity(new Intent(this, typeof(TabColaboradoresActivity)));
                Finish();
                break;
            }
            return(base.OnOptionsItemSelected(item));
        }
        public override string SanitizeTextBody(string contentType, string body)
        {
            if (contentType.Contains("json"))
            {
                try
                {
                    // Check for auth calls to readact any access tokens
                    var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(body).AsSpan(), true, new JsonReaderState());
                    if (JsonDocument.TryParseValue(ref reader, out var doc) &&
                        doc.RootElement.GetProperty("token_type").GetString() == "Bearer")
                    {
                        // If we found an auth call, sanitize it
                        using (var stream = new System.IO.MemoryStream())
                        {
                            using (var writer = new Utf8JsonWriter(stream))
                            {
                                writer.WriteStartObject();
                                foreach (var property in doc.RootElement.EnumerateObject())
                                {
                                    switch (doc.RootElement.GetProperty(property.Name).ValueKind)
                                    {
                                    case JsonValueKind.Null:
                                        writer.WriteNull(property.Name);
                                        break;

                                    case JsonValueKind.True:
                                        writer.WriteBoolean(property.Name, true);
                                        break;

                                    case JsonValueKind.False:
                                        writer.WriteBoolean(property.Name, false);
                                        break;

                                    case JsonValueKind.Number:
                                        writer.WriteNumber(property.Name, property.Value.GetDouble());
                                        break;

                                    case JsonValueKind.String:
                                        writer.WriteString(
                                            property.Name,
                                            property.Name == "access_token" ?
                                            SanitizeValue :
                                            property.Value.GetString());
                                        break;
                                        // Ignore nested objects and arrays...
                                    }
                                }
                                writer.WriteEndObject();
                            }
                            return(Encoding.UTF8.GetString(stream.ToArray()));
                        }
                    }
                }
                catch
                {
                }
            }
            else if (contentType.Contains("urlencoded"))
            {
                try
                {
                    // If it's been URL encoded, make sure it doesn't contain
                    // a client_secret
                    var builder = new UriBuilder()
                    {
                        Query = body
                    };
                    var query = new UriQueryParamsCollection(body);
                    if (query.ContainsKey("client_secret"))
                    {
                        query["client_secret"] = SanitizeValue;
                    }
                    return(query.ToString());
                }
                catch
                {
                }
            }

            // If anything goes wrong, don't sanitize
            return(body);
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.PerfilCardEditarLayout);
            miembro = JsonConvert.DeserializeObject <UsuarioModel>(Intent.GetStringExtra("Miembro"));
            FindViewById <ImageButton>(Resource.Id.ibCerrar).Click += (sender, e) => OnBackPressed();

            imgPerfil = FindViewById <ImageView>(Resource.Id.ivPerfil);
            if (!string.IsNullOrEmpty(miembro.Usuario_Fotografia))
            {
                miembro.Usuario_Fotografia_Perfil = new UploadImages().DownloadFileFTP(miembro.Usuario_Fotografia, usuario_imagen_path);
                photo = BitmapFactory.DecodeByteArray(miembro.Usuario_Fotografia_Perfil, 0, miembro.Usuario_Fotografia_Perfil.Length);
                imgPerfil.SetImageBitmap(ImagesHelper.GetRoundedShape(BitmapFactory.DecodeByteArray(miembro.Usuario_Fotografia_Perfil, 0, miembro.Usuario_Fotografia_Perfil.Length)));
            }
            else
            {
                imgPerfil.SetImageResource(Resource.Mipmap.ic_profile_empty);
            }
            imgFondo = FindViewById <ImageView>(Resource.Id.imgFondo);
            if (!string.IsNullOrEmpty(miembro.Usuario_Fotografia_Fondo))
            {
                miembro.Usuario_Fotografia_FondoPerfil = new UploadImages().DownloadFileFTP(miembro.Usuario_Fotografia_Fondo, usuario_imagen_path);
                background = BitmapFactory.DecodeByteArray(miembro.Usuario_Fotografia_FondoPerfil, 0, miembro.Usuario_Fotografia_FondoPerfil.Length);
                imgFondo.SetImageBitmap(background);
            }

            FindViewById <Button>(Resource.Id.btnGuardar).Click += delegate
            {
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                photo?.Compress(Bitmap.CompressFormat.Jpeg, 0, stream);
                miembro.Usuario_Fotografia_Perfil = stream?.ToArray();
                stream = new System.IO.MemoryStream();
                background?.Compress(Bitmap.CompressFormat.Jpeg, 0, stream);
                miembro.Usuario_Fotografia_FondoPerfil = stream?.ToArray();
                if (new UsuariosController().UpdateDataMiembros(miembro.Usuario_Id, FindViewById <EditText>(Resource.Id.txtNombre).Text,
                                                                FindViewById <EditText>(Resource.Id.txtApellidos).Text, miembro.Usuario_Correo_Electronico, miembro.Usuario_Telefono,
                                                                miembro.Usuario_Celular, miembro.Usuario_Descripcion, DateTime.Parse(miembro.Usuario_Fecha_Nacimiento), miembro.Usuario_Fotografia_Perfil, miembro.Usuario_Fotografia_FondoPerfil))
                {
                    miembro.Redes_Sociales.AsParallel().ToList().ForEach(red =>
                    {
                        if (!string.IsNullOrEmpty(red.Usuario_Red_Social_Id) || !string.IsNullOrEmpty(red.Red_Social_Enlace))
                        {
                            new RedesSocialesController().SetRedSocial(miembro.Usuario_Id, miembro.Usuario_Tipo, red.Red_Social_Id, red.Red_Social_Enlace, red.Usuario_Red_Social_Id);
                        }
                    });
                    new EmpresaController().UpdateUsuarioEmpresaPerfil(miembro.Empresa_Actual.Empresa_Id, miembro.Usuario_Id, "",
                                                                       miembro.Empresa_Actual.Empresa_Nombre, miembro.Empresa_Actual.Empresa_Correo_Electronico,
                                                                       miembro.Empresa_Actual.Empresa_Pagina_Web, miembro.Usuario_Puesto, miembro.Empresa_Actual.Empresa_Logotipo_Perfil);
                    Toast.MakeText(this, Resource.String.str_general_save, ToastLength.Short).Show();
                    Intent intent = new Intent(this, typeof(PerfilCardActivity));
                    intent.PutExtra("Miembro", JsonConvert.SerializeObject(new UsuariosController().GetMemberData(miembro.Usuario_Id, miembro.Usuario_Tipo)));
                    StartActivity(intent);
                    Finish();
                }
                else
                {
                    Toast.MakeText(this, Resource.String.str_general_save_error, ToastLength.Short).Show();
                }
            };

            FindViewById <ImageView>(Resource.Id.btnCamara).Click += delegate
            {
                Width = Height = 400;
                CreateDirectoryForPictures();
                IsThereAnAppToTakePictures();
                Intent intent = new Intent(MediaStore.ActionImageCapture);
                _file = new File(_dir, String.Format("{0}.jpg", Guid.NewGuid()));
                intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(_file));
                StartActivityForResult(intent, TakePicture);
                flag = true;
            };

            FindViewById <ImageView>(Resource.Id.btnCamaraFondo).Click += delegate
            {
                Width  = 1500;
                Height = 500;
                CreateDirectoryForPictures();
                IsThereAnAppToTakePictures();
                Intent intent = new Intent(MediaStore.ActionImageCapture);
                _file = new File(_dir, String.Format("{0}.jpg", Guid.NewGuid()));
                intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(_file));
                StartActivityForResult(intent, TakePicture);
                flag = false;
            };

            FindViewById <EditText>(Resource.Id.txtNombre).Text    = miembro.Usuario_Nombre;
            FindViewById <EditText>(Resource.Id.txtApellidos).Text = miembro.Usuario_Apellidos;
            FindViewById <TextView>(Resource.Id.lblEmpresa).Text   = miembro.Usuario_Empresa_Nombre;

            ViewPager _viewPager = FindViewById <ViewPager>(Resource.Id.vpPerfil);

            _viewPager.Adapter = new PerfilEditarPageAdapter(this, new List <string> {
                Resources.GetString(Resource.String.str_profile_about_me), Resources.GetString(Resource.String.str_profile_social), Resources.GetString(Resource.String.str_profile_work)
            }, ref miembro);

            PagerSlidingTabStrip tabs = FindViewById <PagerSlidingTabStrip>(Resource.Id.tabs);

            tabs.SetTextColorResource(Resource.Color.comment_pressed);
            tabs.SetViewPager(_viewPager);
        }
Beispiel #35
0
        private void DoWork(object sender, DoWorkEventArgs e)
        {
            CGDTool      gdt          = new CGDTool();
            DriveService driveService = gdt.Authenticate(context);

            var fileId = id;

            try
            {
                if (export)
                {
                    var request = driveService.Files.Export(fileId, this.mimetype);
                    var stream  = new System.IO.MemoryStream();
                    request.MediaDownloader.ProgressChanged +=
                        (IDownloadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case DownloadStatus.Downloading:
                        {
                            UpateStatus("bytes" + progress.BytesDownloaded, false);
                            break;
                        }

                        case DownloadStatus.Completed:
                        {
                            data = stream.ToArray();
                            UpateStatus("Download complete", true);
                            break;
                        }

                        case DownloadStatus.Failed:
                        {
                            UpateStatus("Download failed: " + progress.Exception.Message, true);
                            break;
                        }
                        }
                    };
                    request.Download(stream);
                }
                else
                {
                    var stream = new System.IO.MemoryStream();

                    // https://docs.google.com/forms/d/171SteVTr-P8HtM5N5p8ftGFlEq_1LVQcTQ2p9yMUmDY/downloadresponses?tz_offset=7200000

                    Google.Apis.Drive.v3.FilesResource.GetRequest request = driveService.Files.Get(fileId);

                    request.MediaDownloader.ProgressChanged +=
                        (IDownloadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case DownloadStatus.Downloading:
                        {
                            UpateStatus("bytes" + progress.BytesDownloaded, false);
                            break;
                        }

                        case DownloadStatus.Completed:
                        {
                            data = stream.ToArray();
                            UpateStatus("Download complete", true);
                            break;
                        }

                        case DownloadStatus.Failed:
                        {
                            UpateStatus("Download failed 1: " + progress.Exception.Message, true);
                            break;
                        }
                        }
                    };



                    request.Alt = Google.Apis.Drive.v3.DriveBaseServiceRequest <Google.Apis.Drive.v3.Data.File> .AltEnum.Json;
                    request.Download(stream);
                }
            }
            catch (Exception err)
            {
                UpateStatus("Download failed 2: " + err.Message, true);
            }
        }
Beispiel #36
0
        /// <summary>
        /// Gets the string encoded in the aztec code bits
        /// </summary>
        /// <param name="correctedBits">The corrected bits.</param>
        /// <returns>the decoded string</returns>
        private static String getEncodedData(bool[] correctedBits)
        {
            var endIndex   = correctedBits.Length;
            var latchTable = Table.UPPER; // table most recently latched to
            var shiftTable = Table.UPPER; // table to use for the next read
            var strTable   = UPPER_TABLE;
            var index      = 0;


            // Final decoded string result
            // (correctedBits-5) / 4 is an upper bound on the size (all-digit result)
            var result = new StringBuilder((correctedBits.Length - 5) / 4);

            // Intermediary buffer of decoded bytes, which is decoded into a string and flushed
            // when character encoding changes (ECI) or input ends.
            using (var decodedBytes = new System.IO.MemoryStream())
            {
                var encoding = DEFAULT_ENCODING;

                while (index < endIndex)
                {
                    if (shiftTable == Table.BINARY)
                    {
                        if (endIndex - index < 5)
                        {
                            break;
                        }
                        int length = readCode(correctedBits, index, 5);
                        index += 5;
                        if (length == 0)
                        {
                            if (endIndex - index < 11)
                            {
                                break;
                            }
                            length = readCode(correctedBits, index, 11) + 31;
                            index += 11;
                        }
                        for (int charCount = 0; charCount < length; charCount++)
                        {
                            if (endIndex - index < 8)
                            {
                                index = endIndex; // Force outer loop to exit
                                break;
                            }
                            int code = readCode(correctedBits, index, 8);
                            decodedBytes.WriteByte((byte)code);
                            index += 8;
                        }
                        // Go back to whatever mode we had been in
                        shiftTable = latchTable;
                        strTable   = codeTables[shiftTable];
                    }
                    else
                    {
                        int size = shiftTable == Table.DIGIT ? 4 : 5;
                        if (endIndex - index < size)
                        {
                            break;
                        }
                        int code = readCode(correctedBits, index, size);
                        index += size;
                        String str = getCharacter(strTable, code);
                        if ("FLG(n)".Equals(str))
                        {
                            if (endIndex - index < 3)
                            {
                                break;
                            }
                            int n = readCode(correctedBits, index, 3);
                            index += 3;
                            //  flush bytes, FLG changes state
                            if (decodedBytes.Length > 0)
                            {
                                var byteArray = decodedBytes.ToArray();
                                result.Append(encoding.GetString(byteArray, 0, byteArray.Length));
                                decodedBytes.SetLength(0);
                            }
                            switch (n)
                            {
                            case 0:
                                result.Append((char)29);      // translate FNC1 as ASCII 29
                                break;

                            case 7:
                                throw new FormatException("FLG(7) is reserved and illegal");

                            default:
                                // ECI is decimal integer encoded as 1-6 codes in DIGIT mode
                                int eci = 0;
                                if (endIndex - index < 4 * n)
                                {
                                    break;
                                }
                                while (n-- > 0)
                                {
                                    int nextDigit = readCode(correctedBits, index, 4);
                                    index += 4;
                                    if (nextDigit < 2 || nextDigit > 11)
                                    {
                                        throw new FormatException("Not a decimal digit");
                                    }
                                    eci = eci * 10 + (nextDigit - 2);
                                }
                                CharacterSetECI charsetECI = CharacterSetECI.getCharacterSetECIByValue(eci);
                                encoding = CharacterSetECI.getEncoding(charsetECI);
                                if (encoding == null)
                                {
                                    throw new FormatException("Encoding for ECI " + eci + " can't be resolved");
                                }
                                break;
                            }
                            // Go back to whatever mode we had been in
                            shiftTable = latchTable;
                            strTable   = codeTables[shiftTable];
                        }
                        else if (str.StartsWith("CTRL_"))
                        {
                            // Table changes
                            // ISO/IEC 24778:2008 prescribes ending a shift sequence in the mode from which it was invoked.
                            // That's including when that mode is a shift.
                            // Our test case dlusbs.png for issue #642 exercises that.
                            latchTable = shiftTable;  // Latch the current mode, so as to return to Upper after U/S B/S
                            shiftTable = getTable(str[5]);
                            strTable   = codeTables[shiftTable];
                            if (str[6] == 'L')
                            {
                                latchTable = shiftTable;
                            }
                        }
                        else
                        {
                            // Though stored as a table of strings for convenience, codes actually represent 1 or 2 *bytes*.
#if (PORTABLE || NETSTANDARD1_0 || NETSTANDARD1_1 || NETFX_CORE)
                            var b = StringUtils.PLATFORM_DEFAULT_ENCODING_T.GetBytes(str);
#else
                            var b = Encoding.ASCII.GetBytes(str);
#endif
                            decodedBytes.Write(b, 0, b.Length);
                            // Go back to whatever mode we had been in
                            shiftTable = latchTable;
                            strTable   = codeTables[shiftTable];
                        }
                    }
                }

                if (decodedBytes.Length > 0)
                {
                    var byteArray = decodedBytes.ToArray();
                    result.Append(encoding.GetString(byteArray, 0, byteArray.Length));
                }
            }
            return(result.ToString());
        }
Beispiel #37
0
        public void EncryptPSW()
        {
            byte[] keyBytes;
            keyBytes = Encoding.Unicode.GetBytes(REVISOFT_CRIPT_STRONG_KEY);
            Rfc2898DeriveBytes derivedKey  = new Rfc2898DeriveBytes(REVISOFT_CRIPT_STRONG_KEY, keyBytes);
            RijndaelManaged    rijndaelCSP = new RijndaelManaged();

            rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8);
            rijndaelCSP.IV  = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8);
            ICryptoTransform encryptor = rijndaelCSP.CreateEncryptor();

            byte[] encrypted = Encoding.Unicode.GetBytes(this.Psw);
            byte[] cipherTextBytes;
            using (var memoryStream = new System.IO.MemoryStream())
            {
                using (var encryptStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    encryptStream.Write(encrypted, 0, encrypted.Length);
                    encryptStream.FlushFinalBlock();
                    rijndaelCSP.Clear();
                    encryptStream.Close();
                    cipherTextBytes = memoryStream.ToArray();
                    encryptStream.Close();
                }
                memoryStream.Close();
            }

            this.Psw = Convert.ToBase64String(cipherTextBytes);
            //CryptoStream encryptStream =
            //  new CryptoStream(outputFileStream, encryptor, CryptoStreamMode.Write);
            //encryptStream.Write(encrypted, 0, encrypted.Length);
            //encryptStream.FlushFinalBlock();
            //rijndaelCSP.Clear();
            //encryptStream.Close();
            //outputFileStream.Close();

            /*private static string Encrypt(string plainText)
             * {
             * string PasswordHash = "P@@Sw0rd";
             * string SaltKey = "S@LT&KEY";
             * string VIKey = "@1B2c3D4e5F6g7H8";
             *
             * byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
             *
             * byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
             * var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
             * var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
             *
             * byte[] cipherTextBytes;
             *
             * using (var memoryStream = new MemoryStream())
             * {
             * using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
             * {
             * cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
             * cryptoStream.FlushFinalBlock();
             * cipherTextBytes = memoryStream.ToArray();
             * cryptoStream.Close();
             * }
             * memoryStream.Close();
             * }
             * return Convert.ToBase64String(cipherTextBytes);
             * }*/
        }
Beispiel #38
0
        public void Transfer(string s)
        {
            if (!ValidString(s, out var why))
            {
                throw new InvalidOperationException(why);
            }

            Reset();

            byte[] code = new byte[16];

            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] >= '0' && s[i] <= '9')
                {
                    code[i] = (byte)(s[i] - '0');
                }
                else
                {
                    throw new InvalidOperationException("s must be numeric only");
                }
            }

            var result = new System.IO.MemoryStream();

            for (int i = 0; i < 33; i++)
            {
                result.WriteByte(8);
            }

            result.WriteByte(0);
            result.WriteByte(8);
            result.WriteByte(0);

            int sum = 0;

            if (s.Length == MAX_DIGITS)
            {
                for (int i = 0; i < 6; i++)
                {
                    if (prefixParityType[code[0], i] != 0)
                    {
                        for (int j = 0; j < 7; j++)
                        {
                            result.WriteByte(dataLeftOdd[code[i + 1], j]);
                        }
                    }
                    else
                    {
                        for (int j = 0; j < 7; j++)
                        {
                            result.WriteByte(dataLeftEven[code[i + 1], j]);
                        }
                    }
                }

                result.WriteByte(8);
                result.WriteByte(0);
                result.WriteByte(8);
                result.WriteByte(0);
                result.WriteByte(8);

                for (int i = 7; i < 12; i++)
                {
                    for (int j = 0; j < 7; j++)
                    {
                        result.WriteByte(dataRight[code[i], j]);
                    }
                }

                for (int i = 0; i < 12; i++)
                {
                    sum += code[i] * ((i & 1) != 0 ? 3 : 1);
                }
            }
            else             // s.Length == MIN_DIGITS
            {
                for (int i = 0; i < 4; i++)
                {
                    for (int j = 0; j < 7; j++)
                    {
                        result.WriteByte(dataLeftOdd[code[i], j]);
                    }
                }

                result.WriteByte(8);
                result.WriteByte(0);
                result.WriteByte(8);
                result.WriteByte(0);
                result.WriteByte(8);

                for (int i = 4; i < 7; i++)
                {
                    for (int j = 0; j < 7; j++)
                    {
                        result.WriteByte(dataRight[code[i], j]);
                    }
                }


                for (int i = 0; i < 7; i++)
                {
                    sum += code[i] * ((i & 1) != 0 ? 3 : 1);
                }
            }
            sum = (10 - (sum % 10)) % 10;

            for (int j = 0; j < 7; j++)
            {
                result.WriteByte(dataRight[sum, j]);
            }

            result.WriteByte(0);
            result.WriteByte(8);
            result.WriteByte(0);

            for (int i = 0; i < 32; i++)
            {
                result.WriteByte(8);
            }

            data = result.ToArray();

            cycles = CC_INTERVAL;
            output = streamoutput;
        }
Beispiel #39
0
        protected void btnExportExcel_ServerClick(object sender, EventArgs e)
        {
            HttpCookie getCookies = Request.Cookies["UserLogin"];

            if (getCookies != null)
            {
                var timeSearch = string.Empty;
                if (string.IsNullOrEmpty(txtTimeSelect.Value.Trim()))
                {
                    var dtBegin = DateTime.Now.ToString("yyyy/MM/dd");
                    var dtEnd   = DateTime.Now.ToString("yyyy/MM/dd");
                    timeSearch = dtBegin + " - " + dtEnd;
                }
                else
                {
                    timeSearch = txtTimeSelect.Value.Trim();
                }
                var getBadProData = SearchDataClass.GetSearchUserRechargeInfoData(txtRechargeTel.Value.Trim(), drpRechargeStatus.SelectedValue, timeSearch);


                ArrayList ColTitle = new ArrayList()
                {
                    "充值流水号", "充值日期", "充值手机", "充值人", "充值金额",
                    "充值名称", "充值状态"
                };

                //string[] strTitle = new string[] { "ASNNo", "SKU", "SKUDescrC", "ExpectedQty", "ReceivedQty", "UOM", "ReceivingLocation", "ReceivedTime", "CustomerID", "CodeName_C" };
                if (getBadProData.ToList().Count > 0)
                {
                    Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
                    //创建一个sheet
                    Aspose.Cells.Worksheet sheet = workbook.Worksheets[0];
                    //为单元格添加样式
                    Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
                    style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
                    style.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle   = Aspose.Cells.CellBorderType.Thin;                  //应用边界线 左边界线
                    style.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle  = Aspose.Cells.CellBorderType.Thin;                  //应用边界线 右边界线
                    style.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle    = Aspose.Cells.CellBorderType.Thin;                  //应用边界线 上边界线
                    style.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = Aspose.Cells.CellBorderType.Thin;                  //应用边界线 下边界线

                    //给各列的标题行PutValue赋值
                    int  currow = 0;
                    byte curcol = 0;
                    sheet.Cells.ImportCustomObjects((System.Collections.ICollection)getBadProData,
                                                    null, true, 0, 0, getBadProData.Count, true, "yyyy/MM/dd HH:mm:ss", false);
                    // 设置内容样式
                    for (int i = 0; i < getBadProData.ToList().Count; i++)
                    {
                        sheet.Cells[i + 1, 0].PutValue(getBadProData[i].RecNo);
                        sheet.Cells[i + 1, 1].PutValue(getBadProData[i].RecTime);
                        sheet.Cells[i + 1, 2].PutValue(getBadProData[i].Tel);
                        sheet.Cells[i + 1, 3].PutValue(getBadProData[i].UserName);
                        sheet.Cells[i + 1, 4].PutValue(getBadProData[i].RecMoeny);
                        var recstatus   = string.Empty;
                        var successinfo = string.Empty;
                        switch (getBadProData[i].RecStatus)
                        {
                        case 'N':
                            recstatus = "交易失败"; successinfo = "充值失败";
                            break;

                        case 'Y':
                            recstatus   = "交易成功";
                            successinfo = "充值成功";
                            break;

                        //case 'S':
                        //	recstatus = "分红成功";
                        //	successinfo = "充值成功";
                        //	break;
                        case 'C':
                            recstatus   = "撤销充值";
                            successinfo = "撤销充值成功";
                            break;
                        }
                        //if (getBadProData[i].RecStatus == 'N')
                        //{
                        //	recstatus = "交易失败";
                        //	successinfo = "充值失败";
                        //}
                        //else
                        //{
                        //	recstatus = "交易成功";
                        //	successinfo = "充值成功";
                        //}
                        sheet.Cells[i + 1, 5].PutValue(getBadProData[i].RecContent == "" ? "东方柏农-" + getBadProData[i].RecTime.ToString("yyyy.MM.dd") + "-" + successinfo : getBadProData[i].RecContent);

                        sheet.Cells[i + 1, 6].PutValue(recstatus);
                        for (int j = 0; j < 7; j++)
                        {
                            sheet.Cells[i + 1, j].Style        = style;
                            sheet.Cells[i + 1, 1].Style.Custom = "yyyy/MM/dd HH:mm:ss";
                            //sheet.Cells[i + 1, 5].Style.Custom = "yyyy/MM/dd HH:mm:ss";
                        }
                    }
                    // 设置标题样式及背景色
                    foreach (string s in ColTitle)
                    {
                        sheet.Cells[currow, curcol].PutValue(s);
                        style.ForegroundColor             = System.Drawing.Color.FromArgb(153, 204, 0);
                        style.Pattern                     = Aspose.Cells.BackgroundType.Solid;
                        style.Font.IsBold                 = true;
                        sheet.Cells[currow, curcol].Style = style;
                        curcol++;
                    }

                    Aspose.Cells.Cells cells = sheet.Cells;
                    //设置标题行高
                    cells.SetRowHeight(0, 30);
                    //让各列自适应宽度
                    sheet.AutoFitColumns();
                    //生成数据流
                    System.IO.MemoryStream ms = workbook.SaveToStream();
                    byte[] bt = ms.ToArray();
                    //客户端保存的文件名
                    string fileName = "用户充值列表导出_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                    //以字符流的形式下载文件
                    //     Response.ContentType = "application/vnd.ms-excel";
                    //通知浏览器下载文件而不是打开
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                    Response.BinaryWrite(bt);
                    Response.Flush();
                    Response.End();
                }
            }
        }
Beispiel #40
0
        public void RepackFolder(string path, bool newFormat)
        {
            newUnpack = newFormat;
            string[] files  = System.IO.Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories);
            string   folder = System.IO.Path.GetDirectoryName(path);
            string   file   = folder + "\\" + System.IO.Path.GetFileName(path) + ".dat";

            NameOfFile = file.ToLower();
            string tmpFile = folder + "\\" + System.IO.Path.GetFileName(path) + ".tmp";

            System.IO.FileStream   fsTmp = new System.IO.FileStream(tmpFile, System.IO.FileMode.Create);
            System.IO.FileStream   fs2   = new System.IO.FileStream(file, System.IO.FileMode.Create);
            System.IO.BinaryWriter bw    = new System.IO.BinaryWriter(fs2);
            int           offset         = 0;
            ArchiveHeader header         = new ArchiveHeader();

            foreach (string i in files)
            {
                byte[]     buffer = PackFile(i, out int uncompressedSize, out int compressedSize);
                FileHeader f      = new FileHeader()
                {
                    Name           = i.Replace(path + "\\", ""),
                    Offset         = offset,
                    Size           = uncompressedSize,
                    EncryptedSize  = buffer.Length,
                    CompressedSize = compressedSize
                };
                fsTmp.Write(buffer, 0, buffer.Length);
                header.Files.Add(f.Name, f);
                offset += buffer.Length;
            }

            System.IO.MemoryStream ms  = new System.IO.MemoryStream();
            System.IO.BinaryWriter bw2 = new System.IO.BinaryWriter(ms);
            foreach (FileHeader i in header.Files.Values)
            {
                bw2.Write(i.Name.Length);
                bw2.Write(Encoding.Unicode.GetBytes(i.Name));
                ms.Position++;
                bw2.Write((byte)1);
                bw2.Write((byte)1);
                ms.Position++;
                bw2.Write(i.Size);
                bw2.Write(i.CompressedSize);
                bw2.Write(i.EncryptedSize);
                bw2.Write(i.Offset);
                ms.Position += 60;
            }
            fsTmp.Flush();
            byte[] table = ms.ToArray();
            header.TableSize           = table.Length;
            table                      = packAndEncrypt(table);
            header.TableCompressedSize = table.Length;

            bw.Write(0x45534f55);
            bw.Write(0x424c4144);
            bw.Write((byte)2);

            fs2.Position = 21;
            bw.Write(header.Files.Count);
            bw.Write((byte)1);
            bw.Write((byte)1);
            fs2.Position = 89;
            bw.Write(header.TableCompressedSize);
            bw.Write(header.TableSize);
            bw.Write(table);
            bw.Write((int)(fs2.Position + 4));

            fsTmp.Position = 0;
            foreach (FileHeader i in header.Files.Values)
            {
                byte[] buf = new byte[i.EncryptedSize];
                fsTmp.Read(buf, 0, i.EncryptedSize);
                bw.Write(buf);
            }
            fsTmp.Close();
            bw.Flush();
            fs2.Flush();
            fs2.Close();
            System.IO.File.Delete(tmpFile);
        }
Beispiel #41
0
        /// <summary>
        /// Overridden OnRead to handle 4 Socks5 states...
        /// </summary>
        /// <param name="sock"></param>
        /// <param name="buf"></param>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public override bool OnRead(Bedrock.Net.BaseSocket sock, byte[] buf, int offset, int length)
        {
            switch (m_state)
            {
            case States.WaitingForAuth:
                m_headerstream.Write(buf, offset, length);
                int state = 0;
                int line  = 0;
                foreach (byte b in buf)
                {
                    // Look for \r\n\r\n for end of response header
                    switch (state)
                    {
                    case 0:
                        if (b == '\r')
                        {
                            state++;
                        }
                        break;

                    case 1:
                        if (b == '\n')
                        {
                            byte[] hs = m_headerstream.ToArray();
                            string s  = System.Text.Encoding.UTF8.GetString(hs);
                            Debug.Write("PRECV: " + s);
                            m_headers.Add(s);
                            m_headerstream.SetLength(0);
                            state++;
                            line++;
                        }
                        else
                        {
                            state = 0;
                        }
                        break;

                    case 2:
                        if (b == '\r')
                        {
                            state++;
                        }
                        else
                        {
                            state = 0;
                        }
                        break;

                    case 3:
                        if (b == '\n')
                        {
                            Debug.WriteLine("End of proxy headers");
                            string line0 = (string)m_headers[0];
                            if (line0.IndexOf("200") == -1)
                            {
                                Debug.WriteLine("200 response not detected.  Closing.");
                                m_state = States.Error;
                                this.Close();
                            }
                            else
                            {
                                Debug.WriteLine("Proxy connected");
                                m_listener.OnConnect(sock); // tell the real listener that we're connected.
                                m_state = States.Running;
                            }
                            // they'll call RequestRead(), so we can return false here.
                            return(false);
                        }
                        else
                        {
                            state = 0;
                        }
                        break;
                    }
                }
                return(true);

            case States.Error:
                throw new InvalidOperationException("Cannot read after error");

            default:
                return(base.OnRead(sock, buf, offset, length));
            }
        }
Beispiel #42
0
        private T PerformRequestInternal <T>(string method, string endpoint, Dictionary <string, string> queryparams)
        {
            queryparams["format"] = "json";

            string query = EncodeQueryString(queryparams);

            // TODO: This can interfere with running backups,
            // as the System.Net.ServicePointManager is shared with
            // all connections doing ftp/http requests
            using (var httpOptions = new Duplicati.Library.Modules.Builtin.HttpOptions())
            {
                httpOptions.Configure(m_options);

                var req =
                    (System.Net.HttpWebRequest)System.Net.WebRequest.Create(
                        new Uri(m_apiUri + endpoint + '?' + query));
                req.Method = method;
                req.Headers.Add("Accept-Charset", ENCODING.BodyName);
                if (m_xsrftoken != null)
                {
                    req.Headers.Add(XSRF_HEADER, m_xsrftoken);
                }
                req.UserAgent = "Duplicati TrayIcon Monitor, v" +
                                System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                req.Headers.Add(TRAYICONPASSWORDSOURCE_HEADER, m_TrayIconHeaderValue);
                if (req.CookieContainer == null)
                {
                    req.CookieContainer = new System.Net.CookieContainer();
                }

                if (m_authtoken != null)
                {
                    req.CookieContainer.Add(new System.Net.Cookie(AUTH_COOKIE, m_authtoken, "/", req.RequestUri.Host));
                }
                if (m_xsrftoken != null)
                {
                    req.CookieContainer.Add(new System.Net.Cookie(XSRF_COOKIE, m_xsrftoken, "/", req.RequestUri.Host));
                }

                //Wrap it all in async stuff
                var areq = new Library.Utility.AsyncHttpRequest(req);
                req.AllowWriteStreamBuffering = true;

                //Assign the timeout, and add a little processing time as well
                if (endpoint.Equals("/serverstate", StringComparison.OrdinalIgnoreCase) &&
                    queryparams.ContainsKey("duration"))
                {
                    areq.Timeout = (int)(Duplicati.Library.Utility.Timeparser.ParseTimeSpan(queryparams["duration"]) +
                                         TimeSpan.FromSeconds(5)).TotalMilliseconds;
                }

                using (var r = (System.Net.HttpWebResponse)areq.GetResponse())
                    using (var s = areq.GetResponseStream())
                        if (typeof(T) == typeof(string))
                        {
                            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                            {
                                s.CopyTo(ms);
                                return((T)(object)ENCODING.GetString(ms.ToArray()));
                            }
                        }
                        else
                        {
                            using (var sr = new System.IO.StreamReader(s, ENCODING, true))
                                return(Serializer.Deserialize <T>(sr));
                        }
            }
        }
Beispiel #43
0
        public void ShowPublish()
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            LayoutInflater liView = LayoutInflater;

            customView = liView.Inflate(Resource.Layout.PublishLayout, null, true);

            customView.FindViewById <TextView>(Resource.Id.lblNombre).Text = nombre;
            customView.FindViewById <TextView>(Resource.Id.lblPuesto).Text = puesto;
            ImageView imgPerfil = customView.FindViewById <ImageView>(Resource.Id.imgPerfil);

            if (foto != null)
            {
                imgPerfil.SetImageBitmap(BitmapFactory.DecodeByteArray(foto, 0, foto.Length));
            }
            else
            {
                imgPerfil.SetImageResource(Resource.Mipmap.ic_profile_empty);
            }
            customView.FindViewById <TextView>(Resource.Id.lblFecha).Text                = DateTime.Now.ToString("d");
            customView.FindViewById <ImageButton>(Resource.Id.imgPicture).Visibility     = ViewStates.Gone;
            customView.FindViewById <ImageButton>(Resource.Id.btnDeleteImage).Visibility = ViewStates.Gone;
            customView.FindViewById <ImageButton>(Resource.Id.imgPicture).Click         += delegate
            {
                AndHUD.Shared.ShowImage(this, Drawable.CreateFromPath(_file.ToPath().ToString()));
            };

            customView.FindViewById <EditText>(Resource.Id.txtPublicacion).TextChanged += (sender, e) =>
            {
                if (!string.IsNullOrEmpty(((EditText)sender).Text))
                {
                    customView.FindViewById <Button>(Resource.Id.btnPublishApply).Enabled = true;
                }
                else
                {
                    customView.FindViewById <Button>(Resource.Id.btnPublishApply).Enabled = false;
                }
            };

            customView.FindViewById <ImageButton>(Resource.Id.btnDeleteImage).Click += delegate
            {
                ImageButton imgPicture = customView.FindViewById <ImageButton>(Resource.Id.imgPicture);
                imgPicture.SetImageURI(null);
                imgPicture.Visibility = ViewStates.Gone;
                _file = null;
                customView.FindViewById <ImageButton>(Resource.Id.btnDeleteImage).Visibility = ViewStates.Gone;
            };

            customView.FindViewById <ImageButton>(Resource.Id.btnTakePicture).Click += delegate
            {
                CreateDirectoryForPictures();
                IsThereAnAppToTakePictures();
                Intent intent = new Intent(MediaStore.ActionImageCapture);
                _file = new File(_dir, String.Format("{0}.jpg", Guid.NewGuid()));
                intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(_file));
                StartActivityForResult(intent, TakePicture);
            };

            customView.FindViewById <ImageButton>(Resource.Id.btnAttachImage).Click += delegate
            {
                var imageIntent = new Intent();
                imageIntent.SetType("image/*");
                imageIntent.SetAction(Intent.ActionGetContent);
                StartActivityForResult(
                    Intent.CreateChooser(imageIntent, "Select photo"), PickImageId);
            };
            customView.FindViewById <Button>(Resource.Id.btnPublishApply).Click += async delegate
            {
                try
                {
                    System.IO.MemoryStream stream = new System.IO.MemoryStream();
                    bitmap?.Compress(Bitmap.CompressFormat.Jpeg, 0, stream);
                    byte[] bitmapData = stream?.ToArray();
                    if (new EscritorioController().SetPost(localStorage.Get("Usuario_Id"), localStorage.Get("Usuario_Tipo"),
                                                           customView.FindViewById <EditText>(Resource.Id.txtPublicacion).Text,
                                                           bitmapData))
                    {
                        page  = 0;
                        posts = DashboardController.GetMuroPosts(localStorage.Get("Usuario_Id"), localStorage.Get("Usuario_Tipo"));
                        await FillPosts();

                        dialog.Dismiss();
                        customView.FindViewById <ImageView>(Resource.Id.imgPicture).Visibility       = ViewStates.Gone;
                        customView.FindViewById <ImageButton>(Resource.Id.btnDeleteImage).Visibility = ViewStates.Gone;
                    }
                    else
                    {
                        Toast.MakeText(this, Resource.String.str_general_save_error, ToastLength.Short);
                    }
                }
                catch (Exception e) { SlackLogs.SendMessage(e.Message, GetType().Name, "ShowPublish"); }
                dialog.Dismiss();
            };

            builder.SetView(customView);
            builder.Create();
            dialog = builder.Show();
            dialog.Window.SetGravity(GravityFlags.Top | GravityFlags.Center);
        }
Beispiel #44
0
        public static void threadproc(object obj)
        {
            MainForm frm = (MainForm)obj;

            StringBuilder sb = new StringBuilder();

            sb.Append("username="******"&password="******"&short_desc=" + HttpUtility.UrlEncode(frm.textBoxShortDescription.Text));
            sb.Append("&projectid=" + Convert.ToString(Program.project_id));
            if (frm.radioButtonUpdateExisting.Checked)
            {
                sb.Append("&bugid=" + frm.textBoxBugId.Text);
            }
            sb.Append("&attachment_content_type=image/jpg");
            sb.AppendFormat("&attachment_filename=screenshot_{0}.jpg", DateTime.Now.ToString("yyyyMMdd'_'HHmmss"));



            //Ash <2010-08-03>
            //sb.Append("&attachment_desc=screenshot");
            sb.Append("&attachment_desc=" + HttpUtility.UrlEncode(frm.textBoxShortDescription.Text));
            //End Ash <2010-08-03>
            sb.Append("&attachment=");

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            frm.getBitmap().Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            string base64 = System.Convert.ToBase64String(ms.ToArray());

            ms.Close();
            ms.Dispose();
            sb.Append(HttpUtility.UrlEncode(base64));

            //  System.Byte[] byte_array2 = System.Convert.FromBase64String(base64);

            byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());

            // send request to web server
            HttpWebResponse res = null;

            try
            {
                HttpWebRequest req = (HttpWebRequest)System.Net.WebRequest.Create(Program.url + "/insert_bug.aspx");


                req.Credentials     = CredentialCache.DefaultCredentials;
                req.PreAuthenticate = true;

                //req.Timeout = 200; // maybe?
                //req.KeepAlive = false; // maybe?

                req.Method        = "POST";
                req.ContentType   = "application/x-www-form-urlencoded";
                req.ContentLength = bytes.Length;
                System.IO.Stream request_stream = req.GetRequestStream();
                request_stream.Write(bytes, 0, bytes.Length);
                request_stream.Close();

                res = (HttpWebResponse)req.GetResponse();
                frm.BeginInvoke(new MainForm.ResponseDelegate(frm.handleResponse), res);
            }
            catch (Exception e2)
            {
                frm.BeginInvoke(new MainForm.ResponseDelegate(frm.handleResponse), e2);
            }
        }
Beispiel #45
0
        private void button1_Click(object sender, EventArgs e)
        {
            int n = Text.Length;
            List <coder.symbol> luminescence =
                new List <coder.symbol>
            {
                new coder.symbol(' ', 0, 1),   //1
                new coder.symbol('U', 1, 2),   //2
                new coder.symbol('M', 2, 3),   //3
                new coder.symbol('I', 3, 4),   //4
                new coder.symbol('N', 4, 5),   //5
                new coder.symbol('E', 5, 6),   //6
                new coder.symbol('L', 6, 8),   //7
                new coder.symbol('S', 8, 9),   //8
                new coder.symbol('T', 9, 10),  //9
                new coder.symbol('C', 11, 12), //10
                new coder.symbol('N', 13, 14)  //11
            };

            List <coder.symbol> hexcodes =
                new List <coder.symbol>
            {
                new coder.symbol('0', 0, 1),   //0x00
                new coder.symbol('1', 1, 2),   //0x01
                new coder.symbol('2', 2, 3),   //0x02
                new coder.symbol('3', 3, 4),   //0x03
                new coder.symbol('4', 4, 5),   //0x04
                new coder.symbol('5', 5, 6),   //0x05
                new coder.symbol('6', 6, 7),   //0x06
                new coder.symbol('7', 7, 8),   //0x07
                new coder.symbol('8', 8, 9),   //0x08
                new coder.symbol('9', 9, 10),  //0x09
                new coder.symbol('A', 10, 11), //0x10
                new coder.symbol('B', 11, 12), //0x11
                new coder.symbol('C', 12, 13), //0x12
                new coder.symbol('D', 13, 14), //0x13
                new coder.symbol('E', 14, 15), //0x14
                new coder.symbol('F', 15, 16)  //0x15
            };



            string test, expand_test, compressed = "";

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

            coder c;

            test = "LUMINESCENCE";

            c = new coder(luminescence);

            c.Scale = 20;

            mem_test = c.compress(test);

            foreach (byte b in mem_test.ToArray())
            {
                compressed += b.ToString();
            }

            expand_test = c.expand(mem_test, test.Length);

            tb1.Text += " Compressed " + mem_test.Length + " bytes :\n" + compressed + "\r\n";
            tb1.Text += " Expanded :" + expand_test + "\r\n";
            tb1.Text += " % compressed  :" + (70.0 - 100.0 / n).ToString("F2") + "\r\n";
        }
Beispiel #46
0
        private static IDictionary <string, object> ToDictionaryOut(this System.Net.Http.HttpRequestMessage message)
        {
            Dictionary <string, object> d = new Dictionary <string, object>();

            foreach (var item in message.Properties)
            {
                if (routeData.Contains(item.Key.ToLower()))
                {
                    RouteDataValueProvider provider = item.Value as RouteDataValueProvider;
                    if (provider != null)
                    {
                        foreach (var kvp in provider.GetKeysFromPrefix(""))
                        {
                            string key = kvp.Key;
                            ValueProviderResult vpr = (ValueProviderResult)provider.GetValue(key);
                            object o = vpr.RawValue;
                            if (key.Equals("controller", StringComparison.OrdinalIgnoreCase))
                            {
                                d.Add("xf-request.route-data.controller", String.Format("{0}.Controller", o.ToString()));
                            }
                            else
                            {
                                if (o.GetType().IsClass)
                                {
                                    d.Add(String.Format("xf-request.route-data.{0}", key), vpr.AttemptedValue);
                                }
                                else
                                {
                                    d.Add(String.Format("xf-request.route-data.{0}", key), o);
                                }
                            }
                        }
                    }
                }
                else if (item.Key.Equals("MS_HttpActionDescriptor"))
                {
                    ReflectedHttpActionDescriptor descriptor = item.Value as ReflectedHttpActionDescriptor;
                    if (descriptor != null && descriptor.ReturnType != null && !String.IsNullOrWhiteSpace(descriptor.ActionName))
                    {
                        d.Add("xf-request.controller-method.name", descriptor.ActionName);
                        d.Add("xf-request.controller-method.return-type", descriptor.ReturnType.Name);
                    }
                }
            }
            if (actions.Contains(message.Method.ToString().ToLower()))
            {
                var ctx = message.Properties["MS_HttpContext"] as HttpContextWrapper;
                if (ctx != null && ctx.Request.ContentLength > 0)
                {
                    using (var stream = new System.IO.MemoryStream())
                    {
                        ctx.Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                        ctx.Request.InputStream.CopyTo(stream);
                        string body = Encoding.UTF8.GetString(stream.ToArray());
                        d.Add("xf-request.message.body", body);
                    }
                }
            }
            var    responseCtx       = message.Properties["MS_HttpContext"] as HttpContextWrapper;
            int    status            = responseCtx.Response.StatusCode;
            string statusDescription = responseCtx.Response.StatusDescription;

            d.Add("xf-request.response.status-code", responseCtx.Response.StatusCode.ToString());
            d.Add("xf-request.response.status-description", responseCtx.Response.StatusDescription);
            return(d);
        }
Beispiel #47
0
        private void CreateCheckCodeImage(string checkCode)
        {  //将验证码生成图片显示
            if (checkCode == null || checkCode.Trim() == String.Empty)
            {
                return;
            }

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(imgWidth, imgheight);
            Graphics g = Graphics.FromImage(image);

            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            try
            {
                //生成随机生成器
                Random random = new Random();

                //清空图片背景色
                g.Clear(Color.White);

                StringFormat sf = new StringFormat(StringFormatFlags.NoClip);
                sf.Alignment     = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;


                //List<FontStyle> a = GetRndColor(checkCode.Length);
                FontStyle fontcolor = GetColorList[random.Next(0, GetColorList.Count)];
                //画文字
                int charX, CharY, charSize, charFontSize;

                //移除宽度
                int delwidth = 0;
                //旋转角度
                int    rotatefont = 0;
                Matrix mat        = new Matrix();
                for (int i = 0; i < checkCode.Length; i++)
                {
                    if (i != 0)
                    {
                        delwidth = rnd.Next(fontsize / 4, fontsize / 3);
                    }
                    rotatefont   = random.Next(-30, 30);
                    charFontSize = rnd.Next(fontsize - 5, fontsize);
                    charSize     = (imgWidth - 5) / checkCode.Length;
                    charX        = charSize * (i) + rnd.Next(2, 15);
                    CharY        = rnd.Next(1, imgheight - (charFontSize)) - 7;

                    mat.RotateAt(rotatefont, new PointF(charX, fontsize));
                    g.Transform = mat;

                    g.DrawString(checkCode[i].ToString(), new System.Drawing.Font("garamond", charFontSize, (System.Drawing.FontStyle.Bold)), new SolidBrush(fontcolor.FontColor), charX - delwidth, CharY);

                    mat.RotateAt(rotatefont * -1, new PointF(charX, fontsize));
                    g.Transform = mat;
                }

                g.Transform = new Matrix();

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

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                Response.ClearContent();
                Response.ContentType = "image/x-png";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
 private static byte[] zs(byte[] o)
 {
     using (var c = new System.IO.MemoryStream(o))
         using (var z = new System.IO.Compression.GZipStream(c, System.IO.Compression.CompressionMode.Decompress))
             using (var r = new System.IO.MemoryStream()){ z.CopyTo(r); return(r.ToArray()); }
 }
        public ActionResult ExportApproverSecondAgentHis(string UserId)
        {
            var list = IUserInfoService.ApproverSecondAgentHisLoad(UserId);

            if (list != null && list.Count > 0)
            {
                XSSFWorkbook book = new XSSFWorkbook();
                #region var headerStyle = book.CreateCellStyle();
                var headerStyle = book.CreateCellStyle();

                var headerFontStyle = book.CreateFont();
                headerFontStyle.Color              = NPOI.HSSF.Util.HSSFColor.White.Index;
                headerFontStyle.Boldweight         = short.MaxValue;
                headerFontStyle.FontHeightInPoints = 10;

                headerStyle.FillPattern         = NPOI.SS.UserModel.FillPattern.SolidForeground;
                headerStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightOrange.Index;
                headerStyle.Alignment           = HorizontalAlignment.Center;
                headerStyle.SetFont(headerFontStyle);
                #endregion
                var sheet = book.CreateSheet("report");
                var row   = sheet.CreateRow(0);
                #region header
                sheet.SetColumnWidth(0, 30 * 256);
                sheet.SetColumnWidth(1, 30 * 256);
                sheet.SetColumnWidth(2, 30 * 256);
                sheet.SetColumnWidth(3, 30 * 256);
                sheet.SetColumnWidth(4, 30 * 256);
                sheet.SetColumnWidth(5, 30 * 256);
                sheet.SetColumnWidth(6, 30 * 256);


                var cell = row.CreateCell(0);
                cell.SetCellValue("申请人姓名");
                cell.CellStyle = headerStyle;
                cell           = row.CreateCell(1);
                cell.SetCellValue("申请人MUDID");
                cell.CellStyle = headerStyle;
                cell           = row.CreateCell(2);
                cell.SetCellValue("代理人姓名");
                cell.CellStyle = headerStyle;
                cell           = row.CreateCell(3);
                cell.SetCellValue("代理人MUDID");
                cell.CellStyle = headerStyle;
                cell           = row.CreateCell(4);
                cell.SetCellValue("开始日期");
                cell.CellStyle = headerStyle;
                cell           = row.CreateCell(5);
                cell.SetCellValue("结束日期");
                cell.CellStyle = headerStyle;
                cell           = row.CreateCell(6);
                cell.SetCellValue("是否启用");
                cell.CellStyle = headerStyle;
                cell           = row.CreateCell(7);
                cell.SetCellValue("操作人");
                cell.CellStyle = headerStyle;
                cell           = row.CreateCell(8);
                cell.SetCellValue("操作日期");
                cell.CellStyle = headerStyle;



                #endregion
                #region var dataCellStyle = book.CreateCellStyle();
                var dataCellStyle = book.CreateCellStyle();
                var dataFontStyle = book.CreateFont();
                dataFontStyle.Color              = NPOI.HSSF.Util.HSSFColor.Black.Index;
                dataFontStyle.Boldweight         = short.MaxValue;
                dataFontStyle.FontHeightInPoints = 10;

                dataCellStyle.FillPattern         = NPOI.SS.UserModel.FillPattern.SolidForeground;
                dataCellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.White.Index;
                //dataCellStyle.Alignment = HorizontalAlignment.Center;
                dataCellStyle.SetFont(dataFontStyle);
                #endregion
                P_UserDelegatePreHis disItm;
                int dataCnt = list.Count;
                for (int i = 0; i < dataCnt; i++)
                {
                    disItm = list[i];
                    row    = sheet.CreateRow(1 + i);
                    #region data cell
                    cell = row.CreateCell(0);
                    cell.SetCellValue(disItm.UserName);                                                                          // 审批人姓名
                    cell = row.CreateCell(1);
                    cell.SetCellValue(disItm.UserMUDID);                                                                         //申请人MUDID
                    cell = row.CreateCell(2);
                    cell.SetCellValue(disItm.DelegateUserName);                                                                  // 代理人姓名
                    cell = row.CreateCell(3);
                    cell.SetCellValue(disItm.DelegateUserMUDID);                                                                 // 代理人MUDID
                    cell = row.CreateCell(4);
                    cell.SetCellValue(disItm.StartTime == null ? "" : disItm.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));         // 开始日期
                    cell = row.CreateCell(5);
                    cell.SetCellValue(disItm.EndTime == null ? "" : disItm.EndTime.ToString("yyyy-MM-dd HH:mm:ss"));             // 结束日期
                    cell = row.CreateCell(6);
                    cell.SetCellValue(disItm.IsEnable == 0 ? "否" : "是");                                                         // 是否启用
                    cell = row.CreateCell(7);
                    cell.SetCellValue(disItm.OperatorMUDID);                                                                     // 操作人
                    cell = row.CreateCell(8);
                    cell.SetCellValue(disItm.OperationTime == null ? "" : disItm.OperationTime.ToString("yyyy-MM-dd HH:mm:ss")); // 操作日期
                    cell = row.CreateCell(9);

                    #endregion
                }

                byte[] excelData;
                using (System.IO.MemoryStream _ms = new System.IO.MemoryStream())
                {
                    book.Write(_ms);
                    excelData = _ms.ToArray();
                    //_ms.Close();
                }

                ViewBag.Msg = "导出成功!";
                return(File(excelData, "application/vnd.ms-excel", HttpUtility.UrlEncode("ApproverSecondAgentHis_" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx", System.Text.Encoding.UTF8)));
            }
            else
            {
                ViewBag.Msg = "无符合条件数据!";
                return(View());
            }
        }
Beispiel #50
0
        public static void Save(string shpFileName, IEnumerable <IEsriShape> shapes, bool createDbf = false, bool overwrite = false, SrsBase srs = null)
        {
            if (shapes.IsNullOrEmpty())
            {
                return;
            }

            var directory = System.IO.Path.GetDirectoryName(shpFileName);

            if (!System.IO.Directory.Exists(directory) && !string.IsNullOrEmpty(directory))
            {
                System.IO.Directory.CreateDirectory(directory);
            }

            IEsriShapeCollection collection = new EsriShapeCollection <IEsriShape>(shapes);

            EsriShapeType shapeType = shapes.First().Type;

            using (System.IO.MemoryStream featureWriter = new System.IO.MemoryStream())
            {
                int recordNumber = 0;

                foreach (IEsriShape item in shapes)
                {
                    featureWriter.Write(ShpWriter.WriteHeaderToByte(++recordNumber, item), 0, 2 * ShapeConstants.IntegerSize);

                    featureWriter.Write(item.WriteContentsToByte(), 0, 2 * item.ContentLength);
                }

                using (System.IO.MemoryStream shpWriter = new System.IO.MemoryStream())
                {
                    int fileLength = (int)featureWriter.Length / 2 + 50;

                    shpWriter.Write(ShpWriter.WriteMainHeader(collection, fileLength, shapeType), 0, 100);

                    shpWriter.Write(featureWriter.ToArray(), 0, (int)featureWriter.Length);

                    //var mode = overwrite ? System.IO.FileMode.Create : System.IO.FileMode.CreateNew;
                    var mode = Shapefile.GetMode(shpFileName, overwrite);

                    System.IO.FileStream stream = new System.IO.FileStream(shpFileName, mode);

                    shpWriter.WriteTo(stream);

                    stream.Close();

                    shpWriter.Close();

                    featureWriter.Close();
                }
            }

            ShxWriter.Write(Shapefile.GetShxFileName(shpFileName), collection, shapeType, overwrite);

            if (createDbf)
            {
                Dbf.DbfFile.WriteDefault(Shapefile.GetDbfFileName(shpFileName), collection.Count, overwrite);
            }

            //try to automatically find srs
            if (srs == null)
            {
                var srid = shapes.First()?.Srid ?? 0;

                srs = SridHelper.AsSrsBase(srid);
            }

            if (srs != null)
            {
                SaveAsPrj(shpFileName, srs, overwrite);
            }
        }
 /// <summary>
 /// Convierte una imagen en byte
 /// </summary>
 /// <param name="imageIn">Imagen a converti</param>
 /// <returns></returns>
 public byte[] fg_img_byt(Image imageIn)
 {
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
     return(ms.ToArray());
 }
Beispiel #52
0
        protected override void Update()
        {
            this.activeWormWalkers.RemoveAll((GameObject o) => o == null);
            this.activeWormTrees.RemoveAll((GameObject o) => o == null);
            this.activeWormSingle.RemoveAll((GameObject o) => o == null);
            this.activeWormAngels.RemoveAll((GameObject o) => o == null);
            if (this.activeWormWalkers.Count > 0 || this.activeWormAngels.Count > 0 || this.activeWormTrees.Count > 0)
            {
                this.anyFormSpawned = true;
            }
            else
            {
                this.anyFormSpawned = false;
            }
            if (this.activeWormSingle.Count == 0 && this.init)
            {
                if (GameSetup.IsMpServer || GameSetup.IsSinglePlayer)
                {
                    long Exp;
                    switch (ModSettings.difficulty)
                    {
                    case ModSettings.Difficulty.Easy:
                        Exp = 5000;
                        break;

                    case ModSettings.Difficulty.Veteran:
                        Exp = 20000;
                        break;

                    case ModSettings.Difficulty.Elite:
                        Exp = 100000;
                        break;

                    case ModSettings.Difficulty.Master:
                        Exp = 3000000;
                        break;

                    case ModSettings.Difficulty.Challenge1:
                        Exp = 50000000;
                        break;

                    case ModSettings.Difficulty.Challenge2:
                        Exp = 100000000;
                        break;

                    case ModSettings.Difficulty.Challenge3:
                        Exp = 500000000;
                        break;

                    case ModSettings.Difficulty.Challenge4:
                        Exp = 1000000000;
                        break;

                    case ModSettings.Difficulty.Challenge5:
                        Exp = 5000000000;
                        break;

                    default:
                        Exp = 10000000000;
                        break;
                    }
                    if (GameSetup.IsMpServer)
                    {
                        using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                        {
                            using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                            {
                                w.Write(10);
                                w.Write(Exp);
                                w.Close();
                            }
                            Network.NetworkManager.SendLine(answerStream.ToArray(), Network.NetworkManager.Target.Everyone);
                            answerStream.Close();
                        }
                    }
                    else
                    {
                        ModdedPlayer.instance.AddKillExperience(Exp);
                    }
                    int itemCount = UnityEngine.Random.Range(15, 26);
                    for (int i = 0; i < itemCount; i++)
                    {
                        Network.NetworkManager.SendItemDrop(ItemDataBase.GetRandomItem(Exp), LocalPlayer.Transform.position + Vector3.up * 2);
                    }
                }
                UnityEngine.Object.Destroy(base.gameObject);
            }
        }
Beispiel #53
0
        public async Task <buildResult> buildSrc(string src, string temppath)
        {
            Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create();
            var path = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);
            //build proj
            var bts      = System.Text.Encoding.UTF8.GetBytes(src);
            var hashname = ToHexString(sha1.ComputeHash(bts));
            var outpath  = System.IO.Path.Combine(path, temppath, hashname);

            lock (lockobj)//不要同时搞目录
            {
                if (System.IO.Directory.Exists(outpath))
                {
                    System.IO.Directory.Delete(outpath, true);
                }
                if (System.IO.Directory.Exists(outpath) == false)
                {
                    System.IO.Directory.CreateDirectory(outpath);
                }
                System.IO.File.Copy(System.IO.Path.Combine(path, "sample_contract\\mscorlib.dll"), System.IO.Path.Combine(outpath, "mscorlib.dll"), true);
                System.IO.File.Copy(System.IO.Path.Combine(path, "sample_contract\\Neo.SmartContract.Framework.dll"), System.IO.Path.Combine(outpath, "Neo.SmartContract.Framework.dll"), true);
                System.IO.File.Copy(System.IO.Path.Combine(path, "sample_contract\\sample_contract.csproj"), System.IO.Path.Combine(outpath, "sample_contract.csproj"), true);
                System.IO.File.WriteAllText(System.IO.Path.Combine(outpath, "Contract.cs"), src);
            }
            //srcfile
            var     projfile = System.IO.Path.Combine(outpath, "sample_contract.csproj");
            Project proj     = null;

            try
            {
                proj = await workspace.OpenProjectAsync(projfile);

                var com = await proj.GetCompilationAsync();

                var         diag = com.GetDiagnostics();
                buildResult br   = new buildResult();

                foreach (var d in diag)
                {
                    if (d.Severity == DiagnosticSeverity.Warning)
                    {
                        Log item = new Log();
                        item.msg = d.GetMessage();
                        item.id  = d.Id;
                        if (d.Location.IsInSource)
                        {
                            var span = d.Location.GetLineSpan();
                            item.line = span.Span.Start.Line;
                            item.col  = span.Span.Start.Character;
                        }
                        //item.line =d.Location
                        br.warnings.Add(item);
                    }
                    else if (d.Severity == DiagnosticSeverity.Error)
                    {
                        Log item = new Log();
                        item.msg = d.GetMessage();
                        item.id  = d.Id;
                        if (d.Location.IsInSource)
                        {
                            var span = d.Location.GetLineSpan();
                            item.line = span.Span.Start.Line;
                            item.col  = span.Span.Start.Character;
                        }
                        br.errors.Add(item);
                    }
                }
                var ms    = new System.IO.MemoryStream();
                var mspdb = new System.IO.MemoryStream();
                com.Emit(ms, mspdb);
                br.dll = ms.ToArray();
                br.pdb = mspdb.ToArray();
                ms.Close();
                mspdb.Close();
                return(br);
            }
            catch (Exception err)
            {
                return(null);
            }
        }
        public void ExportApproval(string HTCode, string ApplierMUDID, string BUHeadMUDID, string Category, string Type)
        {
            #region 抓取数据
            int total = 0;
            var list  = PreApprovalService.QueryLoad(HTCode, ApplierMUDID, BUHeadMUDID, Category, Type, int.MaxValue, 1, out total
                                                     ).Select(a => new
            {
                c1  = FormatterNull(a.c1),
                c2  = FormatterNull(a.c2),
                c3  = FormatterNull(a.c3),
                c4  = FormatterNull(a.c4),
                c5  = FormatterNull(a.c5),
                c6  = FormatterNull(a.c6),
                c7  = FormatterNull(a.c7),
                c8  = FormatterNull(a.c8),
                c9  = FormatterNull(a.c9),
                c10 = FormatterNull(a.c10),
                c11 = FormatterNull(a.c11),
                c12 = FormatterNull(a.c12),
                c13 = FormatterNull(a.c13)
            }).ToArray();;
            #endregion

            #region 构建Excel
            HSSFWorkbook wk    = new HSSFWorkbook();
            ISheet       sheet = wk.CreateSheet("Cater");
            IRow         row   = sheet.CreateRow(0);

            //ICellStyle style = wk.CreateCellStyle();
            //style.WrapText = true;
            //style.Alignment = HorizontalAlignment.Center;
            //IFont font = wk.CreateFont();
            //font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
            //font.FontHeightInPoints = 10;
            //style.SetFont(font);
            ICellStyle style = wk.CreateCellStyle();
            style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightOrange.Index;
            style.FillPattern         = NPOI.SS.UserModel.FillPattern.SolidForeground;
            style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightOrange.Index;
            style.Alignment           = HorizontalAlignment.Center;
            IFont font = wk.CreateFont();
            font.Color              = NPOI.HSSF.Util.HSSFColor.White.Index;
            font.Boldweight         = short.MaxValue;
            font.FontHeightInPoints = 10;
            style.SetFont(font);
            #endregion

            #region 生成表头
            var title = new string[] { "HT编号", "申请人姓名", "申请人MUDID", "流程类别", "流程状态", "提交日期", "提交时间", "审批人MUDID", "审批人姓名", "审批动作", "审批理由", "审批日期", "审批时间" };

            sheet.DefaultRowHeight = 200 * 2;

            for (var i = 0; i < title.Length; i++)
            {
                sheet.SetColumnWidth(i, 15 * 256);
            }

            for (var i = 0; i < title.Length; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(title[i]);
                cell.SetCellType(CellType.String);
                cell.CellStyle = style;
            }
            #endregion

            #region 制作表体
            for (var i = 1; i <= list.Length; i++)
            {
                var item = list[i - 1];
                row = sheet.CreateRow(i);
                ICell cell = null;

                //2018-1-12 史强 注释掉序号列
                //cell = row.CreateCell(0);
                //cell.SetCellValue(i);

                var j = 0;
                if (item != null)
                {
                    cell = row.CreateCell(j);
                    cell.SetCellValue(item.c1);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c2);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c3);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c4);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c5);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c6);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c7);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c8);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c9);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c10);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c11);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c12);
                    cell = row.CreateCell(++j);
                    cell.SetCellValue(item.c13);
                    cell = row.CreateCell(++j);
                }
            }
            #endregion

            #region 写入到客户端
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                wk.Write(ms);
                Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
                Response.ContentType = "application/vnd.ms-excel";
                Response.BinaryWrite(ms.ToArray());
            }
            #endregion
        }
        private byte[] GetMultipartFormDataBytes(List <KeyValuePair <string, object> > postParameters, string boundary)
        {
            if (postParameters == null || !postParameters.Any())
            {
                throw new Exception("Cannot convert data to multipart/form-data format. No data found.");
            }

            Encoding encoding = Encoding.UTF8;

            using (var formDataStream = new System.IO.MemoryStream())
            {
                bool needsCLRF = false;

                foreach (var param in postParameters)
                {
                    // Add a CRLF to allow multiple parameters to be added.
                    // Skip it on the first parameter, add it to subsequent parameters.
                    if (needsCLRF)
                    {
                        formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
                    }

                    needsCLRF = true;

                    if (param.Value is HttpFile || IsByteArrayConvertableToHttpFile(param.Value))
                    {
                        HttpFile httpFileToUpload = param.Value is HttpFile
                                            ? (HttpFile)param.Value
                                            : new HttpFile(null, null, (byte[])param.Value);

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

                        formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));

                        // Write the file data directly to the Stream, rather than serializing it to a string.
                        formDataStream.Write(httpFileToUpload.Buffer, 0, httpFileToUpload.Buffer.Length);
                    }
                    else
                    {
                        string objString = "";
                        if (param.Value != null)
                        {
                            var typeConverter = param.Value.GetType().GetToStringConverter();
                            if (typeConverter != null)
                            {
                                objString = typeConverter.ConvertToString(null, Settings.CultureInfo, param.Value);
                            }
                            else
                            {
                                throw new Exception(String.Format("Type \"{0}\" cannot be converted to string", param.Value.GetType().FullName));
                            }
                        }

                        string postData =
                            string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                                          boundary,
                                          param.Key,
                                          objString);
                        formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
                    }
                }

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

                byte[] formData = formDataStream.ToArray();

                return(formData);
            }
        }
Beispiel #56
0
        void ShowPublish()
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            LayoutInflater liView = LayoutInflater;

            customView = liView.Inflate(Resource.Layout.PublishLayout, null, true);

            ImageView imgPerfil = customView.FindViewById <ImageView>(Resource.Id.imgPerfil);

            if (post.Usuario.Usuario_Fotografia_Perfil != null)
            {
                imgPerfil.SetImageBitmap(BitmapFactory.DecodeByteArray(post.Usuario.Usuario_Fotografia_Perfil, 0, post.Usuario.Usuario_Fotografia_Perfil.Length));
            }
            else
            {
                imgPerfil.SetImageResource(Resource.Mipmap.ic_profile_empty);
            }
            customView.FindViewById <TextView>(Resource.Id.lblNombre).Text = post.Usuario.Usuario_Nombre;
            customView.FindViewById <TextView>(Resource.Id.lblPuesto).Text = post.Usuario.Usuario_Puesto;

            customView.FindViewById <TextView>(Resource.Id.lblFecha).Text                = DateTime.Now.ToString("d");
            customView.FindViewById <ImageButton>(Resource.Id.imgPicture).Visibility     = ViewStates.Gone;
            customView.FindViewById <ImageButton>(Resource.Id.btnDeleteImage).Visibility = ViewStates.Gone;

            customView.FindViewById <ImageButton>(Resource.Id.imgPicture).Click += delegate
            {
                AndHUD.Shared.ShowImage(this, Drawable.CreateFromPath(_file.ToPath().ToString()));
            };

            customView.FindViewById <EditText>(Resource.Id.txtPublicacion).TextChanged += (sender, e) =>
            {
                if (!string.IsNullOrEmpty(((EditText)sender).Text))
                {
                    customView.FindViewById <Button>(Resource.Id.btnPublishApply).Enabled = true;
                }
                else
                {
                    customView.FindViewById <Button>(Resource.Id.btnPublishApply).Enabled = false;
                }
            };

            customView.FindViewById <ImageButton>(Resource.Id.btnDeleteImage).Click += delegate
            {
                ImageButton imgPicture = customView.FindViewById <ImageButton>(Resource.Id.imgPicture);
                imgPicture.SetImageURI(null);
                imgPicture.Visibility = ViewStates.Gone;
                _file = null;
                customView.FindViewById <ImageButton>(Resource.Id.btnDeleteImage).Visibility = ViewStates.Gone;
            };

            customView.FindViewById <ImageButton>(Resource.Id.btnTakePicture).Click += delegate
            {
                CreateDirectoryForPictures();
                IsThereAnAppToTakePictures();
                Intent intent = new Intent(MediaStore.ActionImageCapture);
                _file = new File(_dir, String.Format("{0}.png", Guid.NewGuid()));
                intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(_file));
                StartActivityForResult(intent, TakePicture);
            };

            customView.FindViewById <ImageButton>(Resource.Id.btnAttachImage).Click += delegate
            {
                var imageIntent = new Intent();
                imageIntent.SetType("image/*");
                imageIntent.SetAction(Intent.ActionGetContent);
                StartActivityForResult(
                    Intent.CreateChooser(imageIntent, "Select photo"), PickImageId);
            };
            customView.FindViewById <Button>(Resource.Id.btnPublishApply).Click += delegate
            {
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                bitmap?.Compress(Bitmap.CompressFormat.Png, 0, stream);
                byte[] bitmapData = stream?.ToArray();
                if (bitmapData.Length != 0 || customView.FindViewById <EditText>(Resource.Id.txtPublicacion).Text.Trim().Length != 0)
                {
                    if (DashboardController.CommentPost(post_id, localStorage.Get("Usuario_Id"), localStorage.Get("Usuario_Tipo"), customView.FindViewById <EditText>(Resource.Id.txtPublicacion).Text, bitmapData))
                    {
                        customView.FindViewById <EditText>(Resource.Id.txtPublicacion).Text = "";
                        customView.FindViewById <EditText>(Resource.Id.txtPublicacion).ClearFocus();
                        comentarios = DashboardController.GetComentariosPost(post_id, localStorage.Get("Usuario_Id"), localStorage.Get("Usuario_Tipo"), page, sizePage);
                        FillComments();
                        svComentarios.ScrollY = svComentarios.Height;
                    }
                    else
                    {
                        Toast.MakeText(this, Resource.String.str_general_save_error, ToastLength.Short);
                    }
                }
                else
                {
                    Toast.MakeText(this, "Escribe o envía una imagen", ToastLength.Short).Show();
                }
                dialog.Dismiss();
            };

            builder.SetView(customView);
            builder.Create();
            dialog = builder.Show();
            dialog.Window.SetGravity(GravityFlags.Top | GravityFlags.Center);
        }
Beispiel #57
0
        private void CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
            {
                return;
            }
            int      iWordWidth  = 20;
            int      iImageWidth = checkCode.Length * iWordWidth;
            Bitmap   image       = new Bitmap(iImageWidth, 30);
            Graphics g           = Graphics.FromImage(image);

            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);

                //画图片的背景噪音点
                for (int i = 0; i < 20; 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);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                //画图片的背景噪音线
                for (int i = 0; i < 2; i++)
                {
                    int x1 = 0;
                    int x2 = image.Width;
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    if (i == 0)
                    {
                        g.DrawLine(new Pen(Color.Gray, 2), x1, y1, x2, y2);
                    }
                }
                for (int i = 0; i < checkCode.Length; i++)
                {
                    string Code  = checkCode[i].ToString();
                    int    xLeft = iWordWidth * (i);
                    random = new Random(xLeft);
                    int iSeed  = DateTime.Now.Millisecond;
                    int iValue = random.Next(iSeed) % 4;
                    if (iValue == 0)
                    {
                        Font                font  = new Font("Arial", 18, (FontStyle.Bold | System.Drawing.FontStyle.Italic));
                        Rectangle           rc    = new Rectangle(xLeft, 0, iWordWidth, image.Height);
                        LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.Red, 1.5f, true);
                        g.DrawString(Code, font, brush, xLeft, 2);
                    }
                    else if (iValue == 1)
                    {
                        Font                font  = new System.Drawing.Font("楷体", 18, (FontStyle.Bold));
                        Rectangle           rc    = new Rectangle(xLeft, 0, iWordWidth, image.Height);
                        LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.DarkRed, 1.3f, true);
                        g.DrawString(Code, font, brush, xLeft, 2);
                    }
                    else if (iValue == 2)
                    {
                        Font                font  = new System.Drawing.Font("宋体", 18, (System.Drawing.FontStyle.Bold));
                        Rectangle           rc    = new Rectangle(xLeft, 0, iWordWidth, image.Height);
                        LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Green, Color.Blue, 1.2f, true);
                        g.DrawString(Code, font, brush, xLeft, 2);
                    }
                    else if (iValue == 3)
                    {
                        Font                font  = new System.Drawing.Font("黑体", 18, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Bold));
                        Rectangle           rc    = new Rectangle(xLeft, 0, iWordWidth, image.Height);
                        LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.Green, 1.8f, true);
                        g.DrawString(Code, font, brush, xLeft, 2);
                    }
                }
                //////画图片的前景噪音点
                //for (int i = 0; i < 8; i++)
                //{
                //    int x = random.Next(image.Width);
                //    int y = random.Next(image.Height);
                //    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                //}
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                Response.ClearContent();

                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
Beispiel #58
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            var codeNum = 4;
            int ranNum;

            char[] cArray    = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            string checkCode = string.Empty;
            Random random2   = new Random();

            for (int i = 0; i < codeNum; i++)
            {
                ranNum     = random2.Next(10);
                checkCode += cArray[ranNum];
            }
            context.Response.Cookies.Add(new HttpCookie("WebCheckCode", checkCode));

            if (checkCode == null || checkCode.Trim() == string.Empty)
            {
                return;
            }
            Bitmap   image = new Bitmap((int)Math.Ceiling(checkCode.Length * 13.5), 29);
            Graphics g     = Graphics.FromImage(image);

            try
            {
                Random random = new Random();
                g.Clear(Color.White);
                //画背景干扰线
                for (int i = 0; i < 2; 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);
                    g.DrawLine(new Pen(Color.OrangeRed), x1, y1, x2, y2);
                }
                Font font = new Font("Segoe Print", 13, (FontStyle.Bold));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.DarkGreen, Color.DarkOrchid, 1.2f, true);

                g.DrawString(checkCode, font, brush, 2, 2);

                //画图片前景噪音点
                for (int i = 0; i < 30; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //画图片边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                context.Response.ClearContent();
                context.Response.ContentType = "image/Gif";
                context.Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        public byte[] CreatePDF(DataTable dataTable, Rectangle pageSize = null)
        {
            byte[] result      = null;
            int    _dtColCount = dataTable.Columns.Count;
            int    _colWidth   = ColWidth.Count;

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                using (Document document = new Document(pageSize ?? PageSize.A4, 25f, 25f, 80f, 40f))
                {
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    // Our custom Header and Footer is done using Event Handler
                    ITextPageEvents PageEventHandler = new ITextPageEvents();
                    // Define the page header
                    PageEventHandler.HeaderFont       = FontFactory.GetFont(BaseFont.HELVETICA, 10, Font.NORMAL);
                    PageEventHandler.HeaderCondoName  = CondoName;
                    PageEventHandler.HeaderReportName = ReportName;
                    PageEventHandler.HeaderUserName   = CreatedBy;
                    writer.PageEvent = PageEventHandler;
                    document.Open();

                    if (FilterData.Any())
                    {
                        PdfPTable tableFilter = new PdfPTable(2);
                        tableFilter.WidthPercentage = 100;
                        tableFilter.SetWidths(new float[2] {
                            20f, 80f
                        });
                        tableFilter.DefaultCell.Border = Rectangle.NO_BORDER;

                        PdfPCell cellLabel = new PdfPCell(new Phrase("Filters Applied :", FontFactory.GetFont(BaseFont.HELVETICA, 10, Font.BOLD)));

                        cellLabel.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        cellLabel.VerticalAlignment   = PdfPCell.ALIGN_CENTER;
                        cellLabel.Border  = Rectangle.NO_BORDER;
                        cellLabel.Colspan = 2;
                        tableFilter.AddCell(cellLabel);
                        foreach (var item in FilterData)
                        {
                            PdfPCell cellFilterName = new PdfPCell(new Phrase(item.Key, FontFactory.GetFont(BaseFont.HELVETICA, 8, Font.NORMAL)));
                            cellFilterName.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            cellFilterName.VerticalAlignment   = PdfPCell.ALIGN_CENTER;
                            cellFilterName.Border = Rectangle.NO_BORDER;
                            tableFilter.AddCell(cellFilterName);

                            PdfPCell cellFilterValue = new PdfPCell(new Phrase(item.Value, FontFactory.GetFont(BaseFont.HELVETICA, 8, Font.NORMAL)));
                            cellFilterValue.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cellFilterValue.VerticalAlignment   = PdfPCell.ALIGN_CENTER;
                            cellFilterValue.Border = Rectangle.NO_BORDER;
                            tableFilter.AddCell(cellFilterValue);
                        }
                        PdfPCell cellEmpty = new PdfPCell(new Phrase("\n", FontFactory.GetFont(BaseFont.HELVETICA, 8, Font.NORMAL)));
                        cellEmpty.Border  = Rectangle.NO_BORDER;
                        cellEmpty.Colspan = 2;
                        cellEmpty.Padding = 8;
                        tableFilter.AddCell(cellEmpty);
                        document.Add(tableFilter);
                    }

                    PdfPTable tableData = new PdfPTable(_dtColCount);
                    tableData.WidthPercentage = 100;
                    if (_dtColCount == _colWidth)
                    {
                        tableData.SetWidths(ColWidth.ToArray());
                    }

                    //Set columns names in the pdf file
                    for (int k = 0; k < dataTable.Columns.Count; k++)
                    {
                        PdfPCell cell = new PdfPCell(new Phrase(dataTable.Columns[k].ColumnName, FontFactory.GetFont(BaseFont.HELVETICA, 10, Font.BOLD, BaseColor.WHITE)));
                        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        cell.VerticalAlignment   = PdfPCell.ALIGN_CENTER;
                        cell.BackgroundColor     = BaseColor.GRAY;
                        tableData.AddCell(cell);
                    }
                    tableData.HeaderRows = 1;

                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        for (int j = 0; j < dataTable.Columns.Count; j++)
                        {
                            PdfPCell cell = null;
                            if (dataTable.Columns[j].DataType == typeof(System.DateTime) && !(string.IsNullOrEmpty(dataTable.Rows[i][j].ToString())))
                            {
                                cell = new PdfPCell(new Phrase(((DateTime)dataTable.Rows[i][j]).ToString("dd/MM/yyyy"), FontFactory.GetFont(BaseFont.HELVETICA, 8, Font.NORMAL)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            }
                            else if (dataTable.Columns[j].ColumnName.ToUpper().Contains("RM"))
                            {
                                cell = new PdfPCell(new Phrase(String.Format("{0:N2}", dataTable.Rows[i][j]), FontFactory.GetFont(BaseFont.HELVETICA, 8, Font.NORMAL)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            }
                            else
                            {
                                cell = new PdfPCell(new Phrase(dataTable.Rows[i][j].ToString(), FontFactory.GetFont(BaseFont.HELVETICA, 8, Font.NORMAL)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            }
                            cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
                            tableData.AddCell(cell);
                        }
                    }
                    //Adding footer
                    if (FooterData.Rows.Count > 0)
                    {
                        var colSpan = _dtColCount - 2; //need to look into this count
                        for (int i = 0; i < FooterData.Rows.Count; i++)
                        {
                            for (int j = 0; j < FooterData.Columns.Count; j++)
                            {
                                PdfPCell cell     = null;
                                decimal  parseVal = 0;
                                if (decimal.TryParse(FooterData.Rows[i][j].ToString(), out parseVal))
                                {
                                    cell = new PdfPCell(new Phrase(String.Format("{0:N2}", FooterData.Rows[i][j]), FontFactory.GetFont(BaseFont.HELVETICA, 9, Font.NORMAL, BaseColor.BLACK)));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                }
                                else
                                {
                                    cell = new PdfPCell(new Phrase(FooterData.Rows[i][j].ToString(), FontFactory.GetFont(BaseFont.HELVETICA, 9, Font.NORMAL, BaseColor.BLACK)));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                }
                                if (j == 0)
                                {
                                    cell.Colspan = colSpan;
                                }
                                cell.BackgroundColor   = BaseColor.LIGHT_GRAY;
                                cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
                                tableData.AddCell(cell);
                            }
                        }
                    }

                    document.Add(tableData);
                    document.Close();
                    result = ms.ToArray();
                }
            }

            return(result);
        }
Beispiel #60
0
        public ActionResult FileResultDemo()
        {
            //1.0 构造一个位图
            #region 1.0 验证码的第一种形式
            //using (Image img = new Bitmap(65, 25))
            //{
            //    using (Graphics g = Graphics.FromImage(img))
            //    {
            //        //清除位图背景
            //        g.Clear(Color.White);

            //        //画边框
            //        g.DrawRectangle(Pens.Blue, 0, 0, img.Width - 1, img.Height - 1);

            //        //画验证码
            //        string vcode = "123a";
            //        g.DrawString(vcode, new Font("黑体", 16
            //            , FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout)
            //            , new SolidBrush(Color.Red)
            //            , 0, 0);
            //    }
            //    Response.ContentType = "image/jpeg"; //告诉浏览器解析的是图片
            //    img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            //}
            #endregion
            //Response.ContentType = "image/jpeg";
            //Response.OutputStream
            //return File();

            #region 2.0 利用FileResult的形式将验证码响应回去(MVC中推荐使用)
            byte[] imgbuffer = null;

            using (Image img = new Bitmap(65, 25))
            {
                using (Graphics g = Graphics.FromImage(img))
                {
                    //清除位图背景
                    g.Clear(Color.White);

                    //画边框
                    g.DrawRectangle(Pens.Blue, 0, 0, img.Width - 1, img.Height - 1);

                    //画验证码
                    string vcode = "123a";
                    g.DrawString(vcode, new Font("黑体", 16
                                                 , FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout)
                                 , new SolidBrush(Color.Red)
                                 , 0, 0);
                }

                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    //将图片保存到了内存流对象ms中
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    //将ms流中的数据转换成byte[]数组
                    imgbuffer = ms.ToArray();
                }
            }
            #endregion
            //利用FileResult子类将图片响应回浏览器
            return(File(imgbuffer, "image/jpeg"));
        }