Пример #1
1
        private void cartelera_Load(object sender, EventArgs e)
        {
            //frmCiudad ciudad = new frmCiudad();
            String numeroSucursal = lblsucursal.Text;

            string query = string.Format("select TRHORA.idSucursal,MAPELI.iidpelicula, MAPELI.bimagen FROM TRHORARIO TRHORA, MAPELICULA MAPELI WHERE TRHORA.iidpelicula=MAPELI.iidpelicula and TRHORA.idSucursal = '"+ numeroSucursal +"'");
            MySqlCommand comando = new MySqlCommand(query, classCrearConexion.Conexion());
            MySqlDataAdapter da = new MySqlDataAdapter(comando);
            DataSet ds = new DataSet("MAPELICULA");
            da.Fill(ds, "MAPELICULA");
            byte[] datos = new byte[0];
            DataRow dr = ds.Tables["MAPELICULA"].Rows[0];
            datos = (byte[])dr["bimagen"];
            System.IO.MemoryStream ms = new System.IO.MemoryStream(datos);
            pb1.Image = System.Drawing.Bitmap.FromStream(ms);
            /*pb1.Image = Properties.Resources.El_Destino_de_Júpite;
            pb1.Refresh();
            pb2.Image = Properties.Resources.FF2;
            pb2.Refresh();
            pb3.Image = Properties.Resources.In_to_the_Woods_En_el_Bosqu;
            pb3.Refresh();
            pb4.Image = Properties.Resources.Ombis_Alien_Invasion__2015_;
            pb4.Refresh();
            pb5.Image = Properties.Resources.peliculas_2015_15_e1422754101215;
            pb5.Refresh();
            pb6.Image = Properties.Resources.peliculas_2015_rapido_furioso_4;
            pb6.Refresh();
            pb7.Image = Properties.Resources.images;
            pb7.Refresh();*/
        }
		/// <summary> Constructs an extended operation object for aborting a partition operation.
		/// 
		/// </summary>
		/// <param name="partitionDN">The distinguished name of the replica's
		/// partition root.
		/// 
		/// </param>
		/// <param name="flags">Determines whether all servers in the replica ring must
		/// be up before proceeding. When set to zero, the status of the
		/// servers is not checked. When set to Ldap_ENSURE_SERVERS_UP,
		/// all servers must be up for the operation to proceed.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error message
		/// and an Ldap error code.
		/// </exception>
		public AbortPartitionOperationRequest(System.String partitionDN, int flags):base(ReplicationConstants.ABORT_NAMING_CONTEXT_OP_REQ, null)
		{
			
			try
			{
				
				if ((System.Object) partitionDN == null)
					throw new System.ArgumentException(ExceptionMessages.PARAM_ERROR);
				
				System.IO.MemoryStream encodedData = new System.IO.MemoryStream();
				LBEREncoder encoder = new LBEREncoder();
				
				
				Asn1Integer asn1_flags = new Asn1Integer(flags);
				Asn1OctetString asn1_partitionDN = new Asn1OctetString(partitionDN);
				
				asn1_flags.encode(encoder, encodedData);
				asn1_partitionDN.encode(encoder, encodedData);
				
				setValue(SupportClass.ToSByteArray(encodedData.ToArray()));
			}
			catch (System.IO.IOException ioe)
			{
				throw new LdapException(ExceptionMessages.ENCODING_ERROR, LdapException.ENCODING_ERROR, (System.String) null);
			}
		}
Пример #3
0
 public IDictionary<string, object> Deserialize(byte[] packet)
 {
   using (var stream = new System.IO.MemoryStream(packet))
   {
     return serial.Deserialize(stream) as IDictionary<string, object>;
   }
 }
        public override void Splash()
        {
            byte[] imageBytes = null;

            using (var imageStream = new System.IO.MemoryStream())
            {
                imageStream.Write(imageBytes, 0, imageBytes.Length);

                using (var image = Image.FromStream(imageStream))
                using (var displayForm = new Form
                {
                    Width = 500,
                    Height = 340,
                    TopMost = true,
                    BackColor = Color.Black,
                    StartPosition = FormStartPosition.CenterParent,
                    FormBorderStyle = FormBorderStyle.FixedToolWindow,
                    BackgroundImage = image,
                    BackgroundImageLayout = ImageLayout.None,
                    Text = @"ReplaceMe1"
                })
                {
                    displayForm.ShowDialog();
                }
            }
        }
Пример #5
0
		/// <summary> 
		/// Constructs an extended operation object for creating an orphan partition.
		/// 
		/// 
		/// </summary>
		/// <param name="serverDN">   The distinguished name of the server on which
		/// the new orphan partition will reside.
		/// 
		/// </param>
		/// <param name="contextName">The distinguished name of the
		/// new orphan partition.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error message
		/// and an Ldap error code.
		/// </exception>
		public SplitOrphanPartitionRequest(System.String serverDN, System.String contextName):base(ReplicationConstants.CREATE_ORPHAN_NAMING_CONTEXT_REQ, null)
		{
			
			try
			{
				
				if (((System.Object) serverDN == null) || ((System.Object) contextName == null))
					throw new System.ArgumentException(ExceptionMessages.PARAM_ERROR);
				
				System.IO.MemoryStream encodedData = new System.IO.MemoryStream();
				LBEREncoder encoder = new LBEREncoder();
				
				Asn1OctetString asn1_serverDN = new Asn1OctetString(serverDN);
				Asn1OctetString asn1_contextName = new Asn1OctetString(contextName);
				
				asn1_serverDN.encode(encoder, encodedData);
				asn1_contextName.encode(encoder, encodedData);
				
				setValue(SupportClass.ToSByteArray(encodedData.ToArray()));
			}
			catch (System.IO.IOException ioe)
			{
				throw new LdapException(ExceptionMessages.ENCODING_ERROR, LdapException.ENCODING_ERROR, (System.String) null);
			}
		}
Пример #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Elf32Section"/> class.
 /// </summary>
 /// <param name="kind">The kind of the section.</param>
 /// <param name="name">The name.</param>
 /// <param name="virtualAddress">The virtualAddress.</param>
 public Elf32Section(SectionKind kind, string name, IntPtr virtualAddress)
     : base(kind, name, virtualAddress)
 {
     _header = new Elf32SectionHeader();
     _header.Name = Elf32StringTableSection.AddString(name);
     _sectionStream = new System.IO.MemoryStream();
 }
Пример #7
0
        private void busquedaBtn_Click(object sender, RoutedEventArgs e)
        {
            Client cliente = ControllerCliente.Instance.buscarCliente(busquedaBox.Text);
            if (cliente == null)
            {
                MessageBox.Show("No existe con ese carnet");
            }
            else
            {
                ciBox.Text = cliente.ci.ToString();
                nombreBox.Text = cliente.nombre;
                PaternoBox.Text = cliente.apellidoPaterno;
                MaternoBox.Text = cliente.apellidoMaterno;
                DomicilioBox.Text = cliente.domicilio;
                ZonaBox.Text = cliente.zona;
                emailBox.Text = cliente.email;
                telefonoCasaBox.Text = cliente.telefonoCasa;
                telefonoOficinaBox.Text = cliente.telefonoOficina;
                feCNacimientoBox.Text = cliente.fechaNacimiento.ToString();
                sexoBox.Text = cliente.sexo;
                BiometricoBox.Text = cliente.codBiometrico;

                System.IO.MemoryStream stream = new System.IO.MemoryStream(cliente.foto);
                BitmapImage foto = new BitmapImage();
                foto.BeginInit();
                foto.StreamSource = stream;
                foto.CacheOption = BitmapCacheOption.OnLoad;
                foto.EndInit();
                image.Source = foto;
            }
        }
Пример #8
0
		public static void DeserializeVoxelAreaData (byte[] bytes, VoxelArea target) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
			Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			stream.Write(bytes,0,bytes.Length);
			stream.Position = 0;
			zip = Ionic.Zip.ZipFile.Read(stream);
			System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
			
			zip["data"].Extract (stream2);
			stream2.Position = 0;
			System.IO.BinaryReader reader = new System.IO.BinaryReader(stream2);
			
			int width = reader.ReadInt32();
			int depth = reader.ReadInt32();
			if (target.width != width) throw new System.ArgumentException ("target VoxelArea has a different width than the data ("+target.width + " != " + width + ")");
			if (target.depth != depth) throw new System.ArgumentException ("target VoxelArea has a different depth than the data ("+target.depth + " != " + depth + ")");
			LinkedVoxelSpan[] spans = new LinkedVoxelSpan[reader.ReadInt32()];
			
			for (int i=0;i<spans.Length;i++) {
				spans[i].area = reader.ReadInt32();
				spans[i].bottom = reader.ReadUInt32();
				spans[i].next = reader.ReadInt32();
				spans[i].top = reader.ReadUInt32();
			}
			target.linkedSpans = spans;
#else
			throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
		}
Пример #9
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();
     }
 }
Пример #10
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
		}
Пример #11
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
		}
Пример #12
0
        /// <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();
        }
Пример #13
0
        private static void OtherWaysToGetReport()
        {
            string report = @"d:\bla.rdl";

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

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

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

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

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

            }
        }
Пример #14
0
        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);
        }
Пример #15
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;
            }
        }
Пример #16
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();
		}
Пример #17
0
        public static string decryptRJ256(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 keyBytes = Encoding.ASCII.GetBytes(key);
            var ivBytes = Encoding.ASCII.GetBytes(iv);

            var decryptor = rijndael.CreateDecryptor(keyBytes, ivBytes);
            var toDecrypt = Convert.FromBase64String(target);
            var fromEncrypt = new byte[toDecrypt.Length];

            var msDecrypt = new System.IO.MemoryStream(toDecrypt);
            var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read);
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            string data = Encoding.ASCII.GetString(fromEncrypt);
            data = data.Replace("\0", "");

            return data;
        }
Пример #18
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();
     }
 }
Пример #19
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);
        }
Пример #20
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);
        }
Пример #21
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);
                }
            }
        }
Пример #22
0
 private static byte[] EncodeDER(byte[][] data)
 {
     byte[] payload;
     using(var ms = new System.IO.MemoryStream())
     {
         foreach(var b in data)
         {
             ms.WriteByte(0x02);
             var isNegative = (b[0] & 0x80) != 0;
             
             EncodeDERLength(ms, (uint)(b.Length + (isNegative ? 1 : 0)));
             if (isNegative)
                 ms.WriteByte(0);
             ms.Write(b, 0, b.Length);                    
         }
     
         payload = ms.ToArray();
     }
 
     using(var ms = new System.IO.MemoryStream())
     {
         ms.WriteByte(0x30);
         EncodeDERLength(ms, (uint)payload.Length);
         ms.Write(payload, 0, payload.Length);
         return ms.ToArray();
     }
 }
Пример #23
0
 /********************************************************
 * CLASS METHODS
 *********************************************************/
 /// <summary>
 /// 
 /// </summary>
 /// <param name="zipPath"></param>
 /// <param name="filenamesAndData"></param>
 /// <returns></returns>
 public static bool Zip(string zipPath, System.Collections.Generic.Dictionary<string, string> filenamesAndData)
 {
     var success = true;
     var buffer = new byte[4096];
     try
     {
         using (var stream = new ZipOutputStream(System.IO.File.Create(zipPath)))
         {
             foreach (var filename in filenamesAndData.Keys)
             {
                 var file = filenamesAndData[filename].GetBytes();
                 var entry = stream.PutNextEntry(filename);
                 using (var ms = new System.IO.MemoryStream(file))
                 {
                     int sourceBytes;
                     do
                     {
                         sourceBytes = ms.Read(buffer, 0, buffer.Length);
                         stream.Write(buffer, 0, sourceBytes);
                     }
                     while (sourceBytes > 0);
                 }
             }
             stream.Flush();
             stream.Close();
         }
     }
     catch (System.Exception err)
     {
         System.Console.WriteLine("Compression.ZipData(): " + err.Message);
         success = false;
     }
     return success;
 }
Пример #24
0
        public void ActualizarUsuario(String user, String Pwd, String PwdRecover, String PwdAnswer, PictureBox pb)
        {
            try
            {
                sql = new SqlConnection(CadCon.Servidor());
                sql.Open();
                string query = "ActualizarUsuario";
                cmd = new SqlCommand(query, sql);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;

                cmd.Parameters.Add("@usuario", SqlDbType.NVarChar);
                cmd.Parameters.Add("@pass", SqlDbType.NVarChar);
                cmd.Parameters.Add("@PwdRecover", SqlDbType.NVarChar);
                cmd.Parameters.Add("@PwdAnswer", SqlDbType.NVarChar);
                cmd.Parameters.Add("@Foto", SqlDbType.Image);

                cmd.Parameters["@usuario"].Value = user;
                cmd.Parameters["@pass"].Value = Pwd;
                cmd.Parameters["@PwdRecover"].Value = PwdRecover;
                cmd.Parameters["@PwdAnswer"].Value = PwdAnswer;

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                pb.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                cmd.Parameters["@Foto"].Value = ms.GetBuffer();
                int f = cmd.ExecuteNonQuery();
                if (f != 0)
                {
                    MessageBox.Show("Actualizado exitosamente", "Usuario Almacenado",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cmd.Dispose();
                    sql.Close();
                }
            }
            catch (SqlException ex) { MessageBox.Show(ex.Message); }
        }
Пример #25
0
		public ToolLine()
		{
            System.IO.MemoryStream ms = new System.IO.MemoryStream(Genetibase.NuGenAnnotation.Properties.Resources.Line);
            Cursor = new Cursor(ms);
            ms.Close();
			//Cursor = new Cursor(GetType(), "Line.cur");
		}
Пример #26
0
        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;
            }
        }
Пример #27
0
 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;
 }
Пример #28
0
		/// <summary> 
		/// Constructs an extended operation object for receiving all updates from
		/// another directory server for a specific replica.
		/// 
		/// </summary>
		/// <param name="partitionRoot">  The distinguished name of the replica
		/// that will be updated.
		/// 
		/// </param>
		/// <param name="toServerDN">     The distinguished name of the server holding the
		/// replica to be updated.
		/// 
		/// </param>
		/// <param name="fromServerDN">   The distinguished name of the server from which
		/// updates are sent.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error message
		/// and an Ldap error code.
		/// </exception>
		public ReceiveAllUpdatesRequest(System.String partitionRoot, System.String toServerDN, System.String fromServerDN):base(ReplicationConstants.RECEIVE_ALL_UPDATES_REQ, null)
		{
			
			try
			{
				
				if (((System.Object) partitionRoot == null) || ((System.Object) toServerDN == null) || ((System.Object) fromServerDN == null))
					throw new System.ArgumentException(ExceptionMessages.PARAM_ERROR);
				
				System.IO.MemoryStream encodedData = new System.IO.MemoryStream();
				LBEREncoder encoder = new LBEREncoder();
				
				Asn1OctetString asn1_partitionRoot = new Asn1OctetString(partitionRoot);
				Asn1OctetString asn1_toServerDN = new Asn1OctetString(toServerDN);
				Asn1OctetString asn1_fromServerDN = new Asn1OctetString(fromServerDN);
				
				asn1_partitionRoot.encode(encoder, encodedData);
				asn1_toServerDN.encode(encoder, encodedData);
				asn1_fromServerDN.encode(encoder, encodedData);
				
				setValue(SupportClass.ToSByteArray(encodedData.ToArray()));
			}
			catch (System.IO.IOException ioe)
			{
				throw new LdapException(ExceptionMessages.ENCODING_ERROR, LdapException.ENCODING_ERROR, (System.String) null);
			}
		}
Пример #29
0
 public static object Deserialize(byte[] data)
 {
     var tempStream = new System.IO.MemoryStream();
     tempStream.Write(data, 0, data.Length);
     tempStream.Seek(0, System.IO.SeekOrigin.Begin);
     return formatter.Deserialize(tempStream);
 }
Пример #30
0
 public static WebServerInfo Load(string json)
 {
     using (var r = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(json)))
     {
         return Load(r);
     }
 }
Пример #31
0
        static void PerformanceTest()
        {
            System.IO.File.WriteAllBytes(System.Environment.CurrentDirectory + "\\a.txt", new byte[0]);

            var FileStream = System.IO.File.Open(System.Environment.CurrentDirectory + "\\a.txt", System.IO.FileMode.Truncate);

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

            var Sr = new List <int>();

            var Stream = new StreamCollection <int>(FileStream);

            //// warm up

            Stream.Insert(0);
            Stream.DeleteByPosition(0);

            var Count = 1_000_000;

            var InsertTime = Timing.run(() =>
            {
                for (int i = 0; i < Count; i++)
                {
                    Stream.Insert(i, i);
                }
            });

            var Inserts_Per_Second     = (int)(Count / InsertTime.TotalSeconds);
            var EveryInsert            = (InsertTime.TotalSeconds / Count).ToString("0.##########");
            var EveryInsert_Milisecond = ((InsertTime.TotalSeconds / Count) * 1000).ToString("0.##########");

            var UpdateTime = Timing.run(() =>
            {
                for (int i = 0; i < Count; i++)
                {
                    Stream[i] = i;
                }
            });
            var Update1_Per_Second = (int)(Count / UpdateTime.TotalSeconds);

            var GetTimeByPosition = Timing.run(() =>
            {
                for (int i = 0; i < Count; i++)
                {
                    var c = Stream[i];
                    if (c == null)
                    {
                        throw new Exception();
                    }
                }
            });
            var Get_Position_Per_Second = (int)(Count / GetTimeByPosition.TotalSeconds);

            var DeleteTime = Timing.run(() =>
            {
                for (int i = 0; i < Count; i++)
                {
                    Stream.DeleteByPosition(0);
                }
            });
            var Delete_Per_Second = (int)(Count / DeleteTime.TotalSeconds);
        }
Пример #32
0
        void OnReceive(DebugMessageType type, byte[] buffer)
        {
            if (clientSocket == null || clientSocket.Disconnected)
            {
                return;
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);

            switch (type)
            {
            case DebugMessageType.CSAttach:
            {
                SendAttachResult();
            }
            break;

            case DebugMessageType.CSBindBreakpoint:
            {
                CSBindBreakpoint msg = new Protocol.CSBindBreakpoint();
                msg.BreakpointHashCode = br.ReadInt32();
                msg.IsLambda           = br.ReadBoolean();
                msg.TypeName           = br.ReadString();
                msg.MethodName         = br.ReadString();
                msg.StartLine          = br.ReadInt32();
                msg.EndLine            = br.ReadInt32();
                TryBindBreakpoint(msg);
            }
            break;

            case DebugMessageType.CSDeleteBreakpoint:
            {
                CSDeleteBreakpoint msg = new Protocol.CSDeleteBreakpoint();
                msg.BreakpointHashCode = br.ReadInt32();
                ds.DeleteBreakpoint(msg.BreakpointHashCode);
            }
            break;

            case DebugMessageType.CSExecute:
            {
                CSExecute msg = new Protocol.CSExecute();
                msg.ThreadHashCode = br.ReadInt32();
                ds.ExecuteThread(msg.ThreadHashCode);
            }
            break;

            case DebugMessageType.CSStep:
            {
                CSStep msg = new CSStep();
                msg.ThreadHashCode = br.ReadInt32();
                msg.StepType       = (StepTypes)br.ReadByte();
                ds.StepThread(msg.ThreadHashCode, msg.StepType);
            }
            break;

            case DebugMessageType.CSResolveVariable:
            {
                CSResolveVariable msg = new CSResolveVariable();
                msg.ThreadHashCode = br.ReadInt32();
                msg.Variable       = ReadVariableReference(br);
                VariableInfo info;
                try
                {
                    object res;
                    info = ds.ResolveVariable(msg.ThreadHashCode, msg.Variable, out res);
                }
                catch (Exception ex)
                {
                    info = VariableInfo.GetException(ex);
                }
                if (info.Type != VariableTypes.Pending)
                {
                    SendSCResolveVariableResult(info);
                }
            }
            break;

            case DebugMessageType.CSResolveIndexAccess:
            {
                CSResolveIndexer msg = new CSResolveIndexer();
                msg.ThreadHashCode = br.ReadInt32();
                msg.Body           = ReadVariableReference(br);
                msg.Index          = ReadVariableReference(br);

                VariableInfo info;
                try
                {
                    object res;
                    info = ds.ResolveIndexAccess(msg.ThreadHashCode, msg.Body, msg.Index, out res);
                }
                catch (Exception ex)
                {
                    info = VariableInfo.GetException(ex);
                }
                if (info.Type != VariableTypes.Pending)
                {
                    SendSCResolveVariableResult(info);
                }
            }
            break;

            case DebugMessageType.CSEnumChildren:
            {
                int thId   = br.ReadInt32();
                var parent = ReadVariableReference(br);

                VariableInfo[] info = null;
                try
                {
                    info = ds.EnumChildren(thId, parent);
                }
                catch (Exception ex)
                {
                    info = new VariableInfo[] { VariableInfo.GetException(ex) };
                }
                if (info != null)
                {
                    SendSCEnumChildrenResult(info);
                }
            }
            break;
            }
        }
Пример #33
0
 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()); }
 }
Пример #34
0
        static void Main(string[] args)
        {
            // ReadPdf();

            // TfsRemover.RemoveTFS();
            TreeInfo ti = GetAncestors();

            int maxNumPeople = (int)System.Math.Pow(2.0, (double)ti.MaxGeneration);

            System.Console.WriteLine(maxNumPeople);

            System.Collections.Generic.Dictionary <int, System.Collections.Generic.Dictionary <int
                                                                                               , DataPoint> > dict
                = new System.Collections.Generic.Dictionary <int
                                                             , System.Collections.Generic.Dictionary <int, DataPoint> >();

            PdfSharpCore.Fonts.GlobalFontSettings.FontResolver = new FontResolver();

            MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes
            .ImageSource.ImageSourceImpl = new PdfSharpCore.ImageSharp.ImageSharpImageSource <SixLabors.ImageSharp.PixelFormats.Rgba32>();


            using (PdfSharpCore.Pdf.PdfDocument document = new PdfSharpCore.Pdf.PdfDocument())
            {
                document.Info.Title    = "Family Tree";
                document.Info.Author   = "FamilyTree Ltd. - Stefan Steiger";
                document.Info.Subject  = "Family Tree";
                document.Info.Keywords = "Family Tree, Genealogical Tree, Genealogy, Bloodline, Pedigree";


                PdfSharpCore.Pdf.Security.PdfSecuritySettings securitySettings = document.SecuritySettings;

                // Setting one of the passwords automatically sets the security level to
                // PdfDocumentSecurityLevel.Encrypted128Bit.
                securitySettings.UserPassword  = "******";
                securitySettings.OwnerPassword = "******";

                // Don't use 40 bit encryption unless needed for compatibility
                //securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

                // Restrict some rights.
                securitySettings.PermitAccessibilityExtractContent = false;
                securitySettings.PermitAnnotations      = false;
                securitySettings.PermitAssembleDocument = false;
                securitySettings.PermitExtractContent   = false;
                securitySettings.PermitFormsFill        = true;
                securitySettings.PermitFullQualityPrint = false;
                securitySettings.PermitModifyDocument   = true;
                securitySettings.PermitPrint            = false;


                document.ViewerPreferences.Direction = PdfSharpCore.Pdf.PdfReadingDirection.LeftToRight;

                PdfSharpCore.Pdf.PdfPage page = document.AddPage();

                // page.Width = PdfSettings.PaperFormatSettings.Width
                // page.Height = PdfSettings.PaperFormatSettings.Height

                const double GOLDEN_RATIO = 1.61803398875;

                // https://en.wikipedia.org/wiki/Golden_ratio
                double marginLeft    = 125;
                double marginTop     = marginLeft;
                double textBoxWidth  = 200;
                double textBoxHeight = textBoxWidth / GOLDEN_RATIO;

                double textBoxVdistance      = textBoxHeight / (GOLDEN_RATIO / (GOLDEN_RATIO * GOLDEN_RATIO));
                double textBoxLargeHdistance = textBoxWidth / (GOLDEN_RATIO * GOLDEN_RATIO);
                double textBoxSmallHdistance = textBoxLargeHdistance / (GOLDEN_RATIO * GOLDEN_RATIO);



                int numGenerationsToList = 5;
                int maxGenerationIndex   = numGenerationsToList - 1;
                int numItems             = (int)System.Math.Pow(2, maxGenerationIndex);


                page.Orientation = PdfSharpCore.PageOrientation.Landscape;

                page.Width = marginLeft * 2
                             + numItems * textBoxWidth
                             + (numItems / 2) * textBoxSmallHdistance
                             + (numItems / 2 - 1) * textBoxLargeHdistance
                ;

                page.Height = marginTop * 2
                              + numGenerationsToList * textBoxHeight
                              + (numGenerationsToList - 1) * textBoxVdistance
                ;



                double dblLineWidth = 1.0;
                string strHtmlColor = "#FF00FF";
                PdfSharpCore.Drawing.XColor lineColor = XColorHelper.FromHtml(strHtmlColor);
                PdfSharpCore.Drawing.XPen   pen       = new PdfSharpCore.Drawing.XPen(lineColor, dblLineWidth);

                PdfSharpCore.Drawing.XFont font = new PdfSharpCore.Drawing.XFont("Arial"
                                                                                 , 12.0, PdfSharpCore.Drawing.XFontStyle.Bold
                                                                                 );


                using (PdfSharpCore.Drawing.XGraphics gfx = PdfSharpCore.Drawing.XGraphics.FromPdfPage(page))
                {
                    gfx.MUH = PdfSharpCore.Pdf.PdfFontEncoding.Unicode;

                    PdfSharpCore.Drawing.Layout.XTextFormatter tf = new PdfSharpCore.Drawing.Layout.XTextFormatter(gfx);
                    tf.Alignment = PdfSharpCore.Drawing.Layout.XParagraphAlignment.Left;

                    PdfSharpCore.Drawing.Layout.XTextFormatterEx2 etf = new PdfSharpCore.Drawing.Layout.XTextFormatterEx2(gfx);


                    for (int generationNumber = maxGenerationIndex; generationNumber > -1; --generationNumber)
                    {
                        dict[generationNumber] = new System.Collections.Generic.Dictionary <int, DataPoint>();

                        int num = (int)System.Math.Pow(2.0, generationNumber);

                        for (int i = 0; i < num; ++i)
                        {
                            if (generationNumber != maxGenerationIndex)
                            {
                                var dp1 = dict[generationNumber + 1][i * 2];
                                var dp2 = dict[generationNumber + 1][i * 2 + 1];

                                var rect1 = dp1.rect;
                                var rect2 = dp2.rect;


                                double xNew = (rect1.TopLeft.X + rect2.TopRight.X) / 2.0;
                                double yNew = marginTop
                                              + generationNumber * textBoxHeight
                                              + generationNumber * textBoxVdistance;

                                gfx.DrawLine(pen, xNew, yNew + rect1.Height, rect1.X + rect1.Width / 2.0, rect1.Y);
                                gfx.DrawLine(pen, xNew, yNew + rect1.Height, rect2.X + rect2.Width / 2.0, rect2.Y);

                                xNew = xNew - rect1.Width / 2.0;

                                dict[generationNumber][i] = new DataPoint()
                                {
                                    Person = (
                                        from itemList in ti.ls[generationNumber]
                                        where itemList.Id == dp1.Person.Child
                                        select itemList
                                        ).FirstOrDefault(),
                                    rect = new DataStructures.Rectangle(xNew, yNew, rect1.Width, rect1.Height)
                                };
                            }
                            else
                            {
                                System.Console.WriteLine($"i: {i}");
                                int numSmallSpaces = (i + 1) / 2;
                                System.Console.WriteLine($"numSmallSpaces: {numSmallSpaces}");
                                int numPairs = i / 2;
                                System.Console.WriteLine($"numPairs: {numPairs}");


                                double rectX = marginLeft
                                               + i * textBoxWidth
                                               + numSmallSpaces * textBoxSmallHdistance
                                               + numPairs * textBoxLargeHdistance
                                ;

                                double rectY = marginTop
                                               + generationNumber * textBoxHeight
                                               + generationNumber * textBoxVdistance
                                ;


                                dict[generationNumber][i] = new DataPoint()
                                {
                                    Person = ti.ls[generationNumber][i],
                                    rect   = new DataStructures.Rectangle(rectX, rectY, textBoxWidth, textBoxHeight)
                                };
                            }

                            gfx.DrawRectangle(pen, dict[generationNumber][i].rect.ToXRect());


                            string text = $@"Generation {generationNumber} Person {i}";
                            text = dict[generationNumber][i].Person.composite_name;


                            tf.DrawString(text
                                          , font
                                          , PdfSharpCore.Drawing.XBrushes.Black
                                          , dict[generationNumber][i].rect.ToXRect()
                                          , PdfSharpCore.Drawing.XStringFormats.TopLeft
                                          );
                        } // Next i
                    }     // Next generationNumber
                }         // End Using gfx


                byte[] baPdfDocument;

                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    document.Save(ms, false);
                    ms.Flush();

                    // baPdfDocument = new byte[ms.Length];
                    // ms.Seek(0, System.IO.SeekOrigin.Begin);
                    // ms.Read(baPdfDocument, 0, (int)ms.Length);

                    baPdfDocument = ms.ToArray();
                } // End Using ms


                System.IO.File.WriteAllBytes("FamilyTree.pdf", baPdfDocument);
                //document.Save(filename);
            } // End Using document

            System.Console.WriteLine(System.Environment.NewLine);
            System.Console.WriteLine(" --- Press any key to continue --- ");
            System.Console.ReadKey();
        } // End Sub Main
Пример #35
0
        /// <summary>
        /// Generates a WMS 1.3.0 compliant response based on a <see cref="SharpMap.Map"/> and the current HttpRequest.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The Web Map Server implementation in SharpMap requires v1.3.0 compatible clients,
        /// and support the basic operations "GetCapabilities" and "GetMap"
        /// as required by the WMS v1.3.0 specification. SharpMap does not support the optional
        /// GetFeatureInfo operation for querying.
        /// </para>
        /// <example>
        /// Creating a WMS server in ASP.NET is very simple using the classes in the SharpMap.Web.Wms namespace.
        /// <code lang="C#">
        /// void page_load(object o, EventArgs e)
        /// {
        ///		//Get the path of this page
        ///		string url = (Request.Url.Query.Length>0?Request.Url.AbsoluteUri.Replace(Request.Url.Query,""):Request.Url.AbsoluteUri);
        ///		SharpMap.Web.Wms.Capabilities.WmsServiceDescription description =
        ///			new SharpMap.Web.Wms.Capabilities.WmsServiceDescription("Acme Corp. Map Server", url);
        ///
        ///		// The following service descriptions below are not strictly required by the WMS specification.
        ///
        ///		// Narrative description and keywords providing additional information
        ///		description.Abstract = "Map Server maintained by Acme Corporation. Contact: [email protected]. High-quality maps showing roadrunner nests and possible ambush locations.";
        ///		description.Keywords.Add("bird");
        ///		description.Keywords.Add("roadrunner");
        ///		description.Keywords.Add("ambush");
        ///
        ///		//Contact information
        ///		description.ContactInformation.PersonPrimary.Person = "John Doe";
        ///		description.ContactInformation.PersonPrimary.Organisation = "Acme Inc";
        ///		description.ContactInformation.Address.AddressType = "postal";
        ///		description.ContactInformation.Address.Country = "Neverland";
        ///		description.ContactInformation.VoiceTelephone = "1-800-WE DO MAPS";
        ///		//Impose WMS constraints
        ///		description.MaxWidth = 1000; //Set image request size width
        ///		description.MaxHeight = 500; //Set image request size height
        ///
        ///		//Call method that sets up the map
        ///		//We just add a dummy-size, since the wms requests will set the image-size
        ///		SharpMap.Map myMap = MapHelper.InitializeMap(new System.Drawing.Size(1,1));
        ///
        ///		//Parse the request and create a response
        ///		SharpMap.Web.Wms.WmsServer.ParseQueryString(myMap,description);
        /// }
        /// </code>
        /// </example>
        /// </remarks>
        /// <param name="map">Map to serve on WMS</param>
        /// <param name="description">Description of map service</param>
        public static void ParseQueryString(SharpMap.Map map, Capabilities.WmsServiceDescription description)
        {
            if (map == null)
            {
                throw (new ArgumentException("Map for WMS is null"));
            }
            if (map.Layers.Count == 0)
            {
                throw (new ArgumentException("Map doesn't contain any layers for WMS service"));
            }

            if (System.Web.HttpContext.Current == null)
            {
                throw (new ApplicationException("An attempt was made to access the WMS server outside a valid HttpContext"));
            }

            System.Web.HttpContext context = System.Web.HttpContext.Current;

            //IgnoreCase value should be set according to the VERSION parameter
            //v1.3.0 is case sensitive, but since it causes a lot of problems with several WMS clients, we ignore casing anyway.
            bool ignorecase = true;

            //Check for required parameters
            //Request parameter is mandatory
            if (context.Request.Params["REQUEST"] == null)
            {
                WmsException.ThrowWmsException("Required parameter REQUEST not specified"); return;
            }
            //Check if version is supported
            if (context.Request.Params["VERSION"] != null)
            {
                if (String.Compare(context.Request.Params["VERSION"], "1.3.0", ignorecase) != 0)
                {
                    WmsException.ThrowWmsException("Only version 1.3.0 supported"); return;
                }
            }
            else //Version is mandatory if REQUEST!=GetCapabilities. Check if this is a capabilities request, since VERSION is null
            {
                if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignorecase) != 0)
                {
                    WmsException.ThrowWmsException("VERSION parameter not supplied"); return;
                }
            }

            //If Capabilities was requested
            if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignorecase) == 0)
            {
                //Service parameter is mandatory for GetCapabilities request
                if (context.Request.Params["SERVICE"] == null)
                {
                    WmsException.ThrowWmsException("Required parameter SERVICE not specified"); return;
                }

                if (String.Compare(context.Request.Params["SERVICE"], "WMS") != 0)
                {
                    WmsException.ThrowWmsException("Invalid service for GetCapabilities Request. Service parameter must be 'WMS'");
                }

                System.Xml.XmlDocument capabilities = Wms.Capabilities.GetCapabilities(map, description);
                context.Response.Clear();
                context.Response.ContentType = "text/xml";
                System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(context.Response.OutputStream);
                capabilities.WriteTo(writer);
                writer.Close();
                context.Response.End();
            }
            else if (String.Compare(context.Request.Params["REQUEST"], "GetMap", ignorecase) == 0) //Map requested
            {
                //Check for required parameters
                if (context.Request.Params["LAYERS"] == null)
                {
                    WmsException.ThrowWmsException("Required parameter LAYERS not specified"); return;
                }
                if (context.Request.Params["STYLES"] == null)
                {
                    WmsException.ThrowWmsException("Required parameter STYLES not specified"); return;
                }
                if (context.Request.Params["CRS"] == null)
                {
                    WmsException.ThrowWmsException("Required parameter CRS not specified"); return;
                }
                else if (context.Request.Params["CRS"] != "EPSG:" + map.Layers[0].SRID.ToString())
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported"); return;
                }
                if (context.Request.Params["BBOX"] == null)
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter BBOX not specified"); return;
                }
                if (context.Request.Params["WIDTH"] == null)
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter WIDTH not specified"); return;
                }
                if (context.Request.Params["HEIGHT"] == null)
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter HEIGHT not specified"); return;
                }
                if (context.Request.Params["FORMAT"] == null)
                {
                    WmsException.ThrowWmsException("Required parameter FORMAT not specified"); return;
                }

                //Set background color of map
                if (String.Compare(context.Request.Params["TRANSPARENT"], "TRUE", ignorecase) == 0)
                {
                    map.BackColor = System.Drawing.Color.Transparent;
                }
                else if (context.Request.Params["BGCOLOR"] != null)
                {
                    try { map.BackColor = System.Drawing.ColorTranslator.FromHtml(context.Request.Params["BGCOLOR"]); }
                    catch { WmsException.ThrowWmsException("Invalid parameter BGCOLOR"); return; };
                }
                else
                {
                    map.BackColor = System.Drawing.Color.White;
                }

                //Get the image format requested
                System.Drawing.Imaging.ImageCodecInfo imageEncoder = GetEncoderInfo(context.Request.Params["FORMAT"]);
                if (imageEncoder == null)
                {
                    WmsException.ThrowWmsException("Invalid MimeType specified in FORMAT parameter");
                    return;
                }

                //Parse map size
                int width  = 0;
                int height = 0;
                if (!int.TryParse(context.Request.Params["WIDTH"], out width))
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter WIDTH");
                    return;
                }
                else if (description.MaxWidth > 0 && width > description.MaxWidth)
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter WIDTH too large");
                    return;
                }
                if (!int.TryParse(context.Request.Params["HEIGHT"], out height))
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter HEIGHT");
                    return;
                }
                else if (description.MaxHeight > 0 && height > description.MaxHeight)
                {
                    WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter HEIGHT too large");
                    return;
                }
                map.Size = new System.Drawing.Size(width, height);

                SharpMap.Geometries.BoundingBox bbox = ParseBBOX(context.Request.Params["bbox"]);
                if (bbox == null)
                {
                    WmsException.ThrowWmsException("Invalid parameter BBOX");
                    return;
                }
                map.PixelAspectRatio = ((double)width / (double)height) / (bbox.Width / bbox.Height);
                map.Center           = bbox.GetCentroid();
                map.Zoom             = bbox.Width;

                //Set layers on/off
                if (!String.IsNullOrEmpty(context.Request.Params["LAYERS"])) //If LAYERS is empty, use default layer on/off settings
                {
                    string[] layers = context.Request.Params["LAYERS"].Split(new char[] { ',' });
                    if (description.LayerLimit > 0)
                    {
                        if (layers.Length == 0 && map.Layers.Count > description.LayerLimit ||
                            layers.Length > description.LayerLimit)
                        {
                            WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Too many layers requested");
                            return;
                        }
                    }
                    foreach (SharpMap.Layers.ILayer layer in map.Layers)
                    {
                        layer.Enabled = false;
                    }
                    foreach (string layer in layers)
                    {
                        //SharpMap.Layers.ILayer lay = map.Layers.Find(delegate(SharpMap.Layers.ILayer findlay) { return findlay.LayerName == layer; });
                        SharpMap.Layers.ILayer lay = null;
                        for (int i = 0; i < map.Layers.Count; i++)
                        {
                            if (String.Equals(map.Layers[i].LayerName, layer, StringComparison.InvariantCultureIgnoreCase))
                            {
                                lay = map.Layers[i];
                            }
                        }



                        if (lay == null)
                        {
                            WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, "Unknown layer '" + layer + "'");
                            return;
                        }
                        else
                        {
                            lay.Enabled = true;
                        }
                    }
                }

                //Render map
                System.Drawing.Image img = map.GetMap();

                //Png can't stream directy. Going through a memorystream instead
                System.IO.MemoryStream MS = new System.IO.MemoryStream();
                img.Save(MS, imageEncoder, null);
                img.Dispose();
                byte[] buffer = MS.ToArray();
                context.Response.Clear();
                context.Response.ContentType = imageEncoder.MimeType;
                context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                context.Response.End();
            }
            else
            {
                WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Invalid request");
            }
        }
Пример #36
0
 private System.Drawing.Bitmap createBitmap(Texture2D texture) // turns textures to bitmap
 {
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     texture.SaveAsPng(ms, texture.Width, texture.Height);
     return(new System.Drawing.Bitmap(ms));
 }
Пример #37
0
        public async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            Message message = messageEventArgs.Message;

            if (message == null || message.Type != MessageType.TextMessage)
            {
                return;
            }
            _chatid = message.Chat.Id;
            try
            {
                Logger.ColoredConsoleWrite(ConsoleColor.Red, "[TelegramAPI] Got Request from " + message.From.Username + " | " + message.Text);
                string username       = _clientSettings.TelegramName;
                string telegramAnswer = string.Empty;

                if (username != message.From.Username)
                {
                    using (System.IO.Stream stream = new System.IO.MemoryStream())
                    {
                        Properties.Resources.norights.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        stream.Position = 0;
                        await _telegram.SendPhotoAsync(_chatid, new FileToSend("norights.jpg", stream), replyMarkup : new ReplyKeyboardHide());
                    }
                    return;
                }

                // [0]-Commando; [1+]-Argument
                string[]         textCMD = message.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                TelegramUtilTask cmd     = getTask(textCMD[0]);
                switch (cmd)
                {
                case TelegramUtilTask.UNKNOWN:
                    telegramAnswer = string.Format("Usage:\r\n{0}\r\n{1}\r\n{2}\r\n{3}\r\n{4}",
                                                   @"/stats - Get Current Stats",
                                                   @"/livestats - Enable/Disable Live Stats",
                                                   @"/information - Enable/Disable Informations",
                                                   @"/top <HowMany?> - Outputs Top (?) Pokemons",
                                                   @"/forceevolve - Forces Evolve");
                    break;

                case TelegramUtilTask.GET_STATS:
                    var inventory = await _client.GetInventory();

                    var profil = await _client.GetProfile();

                    IEnumerable <PlayerStats> stats = inventory.InventoryDelta.InventoryItems
                                                      .Select(i => i.InventoryItemData.PlayerStats)
                                                      .Where(i => i != null);
                    foreach (PlayerStats ps in stats)
                    {
                        int l = ps.Level;

                        long   expneeded     = ((ps.NextLevelXp - ps.PrevLevelXp) - StringUtils.getExpDiff(ps.Level));
                        long   curexp        = ((ps.Experience - ps.PrevLevelXp) - StringUtils.getExpDiff(ps.Level));
                        double curexppercent = (Convert.ToDouble(curexp) / Convert.ToDouble(expneeded)) * 100;
                        string curloc        = _client.CurrentLat + "%20" + _client.CurrentLng;
                        curloc = curloc.Replace(",", ".");
                        string curlochtml = "https://www.google.de/maps/search/" + curloc + "/";
                        double shortenLng = Math.Round(_client.CurrentLng, 3);
                        double shortenLat = Math.Round(_client.CurrentLat, 3);
                        string pokemap    = shortenLat + ";" + shortenLng;
                        pokemap = pokemap.Replace(",", ".").Replace(";", ",");
                        string pokevishtml = "https://skiplagged.com/pokemon/#" + pokemap + ",14";
                        telegramAnswer +=
                            "\nNickname: " + profil.Profile.Username
                            + "\nLevel: " + ps.Level
                            + "\nEXP Needed: " + ((ps.NextLevelXp - ps.PrevLevelXp) - StringUtils.getExpDiff(ps.Level))
                            + $"\nCurrent EXP: {curexp} ({Math.Round(curexppercent)}%)"
                            + "\nEXP to Level up: " + ((ps.NextLevelXp) - (ps.Experience))
                            + "\nKM walked: " + ps.KmWalked
                            + "\nPokeStops visited: " + ps.PokeStopVisits
                            + "\nStardust: " + profil.Profile.Currency.ToArray()[1].Amount
                            + "\nPokemons: " + await _inventory.getPokemonCount() + "/" + profil.Profile.PokeStorage
                            + "\nItems: " + await _inventory.getInventoryCount() + " / " + profil.Profile.ItemStorage
                            + "\nCurentLocation:\n" + curlochtml
                            + "\nPokevision:\n" + pokevishtml;
                    }
                    break;

                case TelegramUtilTask.GET_TOPLIST:
                    int shows = 10;
                    if (textCMD.Length > 1 && !int.TryParse(textCMD[1], out shows))
                    {
                        telegramAnswer += $"Error! This is not a Number: {textCMD[1]}\nNevermind...\n";
                        shows           = 10; //TryParse error will reset to 0
                    }
                    telegramAnswer += "Showing " + shows + " Pokemons...\nSorting...";
                    await _telegram.SendTextMessageAsync(_chatid, telegramAnswer, replyMarkup : new ReplyKeyboardHide());

                    var myPokemons = await _inventory.GetPokemons();

                    myPokemons = myPokemons.OrderByDescending(x => x.Cp);
                    var profile = await _client.GetProfile();

                    telegramAnswer = $"Top {shows} Pokemons of {profile.Profile.Username}:";

                    IEnumerable <PokemonData> topPokemon = myPokemons.Take(shows);
                    foreach (PokemonData pokemon in topPokemon)
                    {
                        telegramAnswer += string.Format("\n{0} ({1})  |  CP: {2} ({3}% perfect)",
                                                        pokemon.PokemonId,
                                                        StringUtils.getPokemonNameGer(pokemon.PokemonId),
                                                        pokemon.Cp,
                                                        PokemonInfo.CalculatePokemonPerfection(pokemon));
                    }
                    break;

                case TelegramUtilTask.SWITCH_LIVESTATS:
                    _livestats = SwitchAndGetAnswer(_livestats, out telegramAnswer, "Live Stats");
                    break;

                case TelegramUtilTask.SWITCH_INFORMATION:
                    _informations = SwitchAndGetAnswer(_informations, out telegramAnswer, "Information");
                    break;

                case TelegramUtilTask.RUN_FORCEEVOLVE:
                    IEnumerable <PokemonData> pokemonToEvolve = await _inventory.GetPokemonToEvolve(null);

                    if (pokemonToEvolve.Count() > 3)
                    {
                        await _inventory.UseLuckyEgg(_client);
                    }
                    foreach (PokemonData pokemon in pokemonToEvolve)
                    {
                        if (_clientSettings.pokemonsToEvolve.Contains(pokemon.PokemonId))
                        {
                            var evolvePokemonOutProto = await _client.EvolvePokemon((ulong)pokemon.Id);

                            if (evolvePokemonOutProto.Result == EvolvePokemonOut.Types.EvolvePokemonStatus.PokemonEvolvedSuccess)
                            {
                                await _telegram.SendTextMessageAsync(_chatid, $"Evolved {pokemon.PokemonId} successfully for {evolvePokemonOutProto.ExpAwarded}xp", replyMarkup : new ReplyKeyboardHide());
                            }
                            else
                            {
                                await _telegram.SendTextMessageAsync(_chatid, $"Failed to evolve {pokemon.PokemonId}. EvolvePokemonOutProto.Result was {evolvePokemonOutProto.Result}, stopping evolving {pokemon.PokemonId}", replyMarkup : new ReplyKeyboardHide());
                            }
                            await RandomHelper.RandomDelay(1000, 2000);
                        }
                    }
                    telegramAnswer = "Done.";
                    break;
                }

                await _telegram.SendTextMessageAsync(_chatid, telegramAnswer, replyMarkup : new ReplyKeyboardHide());
            }
            catch (Exception ex)
            {
                if (ex is ApiRequestException)
                {
                    await _telegram.SendTextMessageAsync(_chatid, (ex as ApiRequestException).Message, replyMarkup : new ReplyKeyboardHide());
                }
            }
        }
Пример #38
0
 public LuaByteBuffer(System.IO.MemoryStream stream)
 {
     buffer = stream.GetBuffer();
     Length = (int)stream.Length;
 }
Пример #39
0
 public override void handlePOSTRequest(HttpProcessor p, System.IO.MemoryStream inputData)
 {
     p.writeFailure();
     p.outputStream.WriteLine("ACCESS DENIED");
 }
Пример #40
0
        protected void btnExport_Click(object sender, EventArgs e)
        {
            var list = DAL.WorkPlanRule.Get().Where(a => a.PublishTime.Year == Common.St.ToInt32(selYear.Value)).Select(a =>
            {
                int pid      = 0, id = 0;
                string pname = "", name = "";
                GetIDAndName(a.Project, ref pid, ref id, ref pname, ref name);
                return(new { ID_0 = pid, ID_1 = id, Name_0 = pname, Name_1 = name, M = a.PublishTime.Month, PublishTime = a.PublishTime, Name_3 = a.Project.Name });
            }).GroupBy(a => a.ID_1).Select(a =>
            {
                return(new
                {
                    PName = a.First().Name_0,
                    Name = a.First().Name_1,
                    M1 = a.Where(b => b.M == 1).Count(),
                    M2 = a.Where(b => b.M == 2).Count(),
                    M3 = a.Where(b => b.M == 3).Count(),
                    M4 = a.Where(b => b.M == 4).Count(),
                    M5 = a.Where(b => b.M == 5).Count(),
                    M6 = a.Where(b => b.M == 6).Count(),
                    M7 = a.Where(b => b.M == 7).Count(),
                    M8 = a.Where(b => b.M == 8).Count(),
                    M9 = a.Where(b => b.M == 9).Count(),
                    M10 = a.Where(b => b.M == 10).Count(),
                    M11 = a.Where(b => b.M == 11).Count(),
                    M12 = a.Where(b => b.M == 12).Count(),
                    S1 = string.Join("\n", a.Where(b => b.M == 1).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray()),
                    S2 = string.Join("\n", a.Where(b => b.M == 2).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray()),
                    S3 = string.Join("\n", a.Where(b => b.M == 3).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray()),
                    S4 = string.Join("\n", a.Where(b => b.M == 4).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray()),
                    S5 = string.Join("\n", a.Where(b => b.M == 5).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray()),
                    S6 = string.Join("\n", a.Where(b => b.M == 6).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray()),
                    S7 = string.Join("\n", a.Where(b => b.M == 7).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray()),
                    S8 = string.Join("\n", a.Where(b => b.M == 8).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray()),
                    S9 = string.Join("\n", a.Where(b => b.M == 9).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray()),
                    S10 = string.Join("\n", a.Where(b => b.M == 10).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray()),
                    S11 = string.Join("\n", a.Where(b => b.M == 11).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray()),
                    S12 = string.Join("\n", a.Where(b => b.M == 12).Select(b => b.PublishTime.ToString("M.d") + "(" + b.Name_3 + ")").ToArray())
                });
            }).OrderBy(a => a.PName).Where(a => (txtProjectParent.Value.Trim() == "" || a.PName.IndexOf(txtProjectParent.Value.Trim()) >= 0) && (txtProject.Value.Trim() == "" || a.Name.IndexOf(txtProject.Value.Trim()) >= 0));

            NPOI.HSSF.UserModel.HSSFWorkbook book  = new NPOI.HSSF.UserModel.HSSFWorkbook(new System.IO.FileStream(Server.MapPath("~/template/template_statistics_project.xls"), System.IO.FileMode.Open, System.IO.FileAccess.Read));
            NPOI.SS.UserModel.ISheet         sheet = book.GetSheet("科教组项目");


            // 内容
            int i = 1;

            foreach (var o in list)
            {
                NPOI.SS.UserModel.IRow  row2  = sheet.CreateRow(i);
                NPOI.SS.UserModel.ICell cell0 = row2.CreateCell(0);
                cell0.SetCellValue(o.PName);
                NPOI.SS.UserModel.ICell cell1 = row2.CreateCell(1);
                cell1.SetCellValue(o.Name);
                NPOI.SS.UserModel.ICell cell2 = row2.CreateCell(2);
                cell2.SetCellValue(o.M1);
                NPOI.SS.UserModel.ICell cell3 = row2.CreateCell(3);
                cell3.SetCellValue(o.M2);
                NPOI.SS.UserModel.ICell cell4 = row2.CreateCell(4);
                cell4.SetCellValue(o.M3);
                NPOI.SS.UserModel.ICell cell5 = row2.CreateCell(5);
                cell5.SetCellValue(o.M4);
                NPOI.SS.UserModel.ICell cell6 = row2.CreateCell(6);
                cell6.SetCellValue(o.M5);
                NPOI.SS.UserModel.ICell cell7 = row2.CreateCell(7);
                cell7.SetCellValue(o.M6);
                NPOI.SS.UserModel.ICell cell8 = row2.CreateCell(8);
                cell8.SetCellValue(o.M7);
                NPOI.SS.UserModel.ICell cell9 = row2.CreateCell(9);
                cell9.SetCellValue(o.M8);
                NPOI.SS.UserModel.ICell cell10 = row2.CreateCell(10);
                cell10.SetCellValue(o.M9);
                NPOI.SS.UserModel.ICell cell11 = row2.CreateCell(11);
                cell11.SetCellValue(o.M10);
                NPOI.SS.UserModel.ICell cell12 = row2.CreateCell(12);
                cell12.SetCellValue(o.M11);
                NPOI.SS.UserModel.ICell cell13 = row2.CreateCell(13);
                cell13.SetCellValue(o.M12);
                i++;
            }



            NPOI.SS.UserModel.IRow row3 = sheet.CreateRow(i);
            row3.CreateCell(0).SetCellValue("总计");
            row3.CreateCell(1).SetCellValue(list.Sum(a => a.M1 + a.M2 + a.M3 + a.M4 + a.M5 + a.M6 + a.M7 + a.M8 + a.M9 + a.M10 + a.M11 + a.M12));
            row3.CreateCell(2).SetCellValue(list.Sum(a => a.M1));
            row3.CreateCell(3).SetCellValue(list.Sum(a => a.M2));
            row3.CreateCell(4).SetCellValue(list.Sum(a => a.M3));
            row3.CreateCell(5).SetCellValue(list.Sum(a => a.M4));
            row3.CreateCell(6).SetCellValue(list.Sum(a => a.M5));
            row3.CreateCell(7).SetCellValue(list.Sum(a => a.M6));
            row3.CreateCell(8).SetCellValue(list.Sum(a => a.M7));
            row3.CreateCell(9).SetCellValue(list.Sum(a => a.M8));
            row3.CreateCell(10).SetCellValue(list.Sum(a => a.M9));
            row3.CreateCell(11).SetCellValue(list.Sum(a => a.M10));
            row3.CreateCell(12).SetCellValue(list.Sum(a => a.M11));
            row3.CreateCell(13).SetCellValue(list.Sum(a => a.M12));



            NPOI.SS.UserModel.ISheet sheet2 = book.GetSheet("上线明细表");


            // 内容
            int j = 1;

            foreach (var o in list)
            {
                NPOI.SS.UserModel.IRow  row2  = sheet2.CreateRow(j);
                NPOI.SS.UserModel.ICell cell0 = row2.CreateCell(0);
                cell0.SetCellValue(o.Name);
                NPOI.SS.UserModel.ICell cell1 = row2.CreateCell(1);
                cell1.SetCellValue(o.S1);
                NPOI.SS.UserModel.ICell cell2 = row2.CreateCell(2);
                cell2.SetCellValue(o.S2);
                NPOI.SS.UserModel.ICell cell3 = row2.CreateCell(3);
                cell3.SetCellValue(o.S3);
                NPOI.SS.UserModel.ICell cell4 = row2.CreateCell(4);
                cell4.SetCellValue(o.S4);
                NPOI.SS.UserModel.ICell cell5 = row2.CreateCell(5);
                cell5.SetCellValue(o.S5);
                NPOI.SS.UserModel.ICell cell6 = row2.CreateCell(6);
                cell6.SetCellValue(o.S6);
                NPOI.SS.UserModel.ICell cell7 = row2.CreateCell(7);
                cell7.SetCellValue(o.S7);
                NPOI.SS.UserModel.ICell cell8 = row2.CreateCell(8);
                cell8.SetCellValue(o.S8);
                NPOI.SS.UserModel.ICell cell9 = row2.CreateCell(9);
                cell9.SetCellValue(o.S9);
                NPOI.SS.UserModel.ICell cell10 = row2.CreateCell(10);
                cell10.SetCellValue(o.S10);
                NPOI.SS.UserModel.ICell cell11 = row2.CreateCell(11);
                cell11.SetCellValue(o.S11);
                NPOI.SS.UserModel.ICell cell12 = row2.CreateCell(12);
                cell12.SetCellValue(o.S12);
                j++;
            }

            // 写入到客户端
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", System.Web.HttpUtility.UrlEncode(selYear.Value + "年项目上线频度表"), System.Text.Encoding.UTF8));
            Response.BinaryWrite(ms.ToArray());
            book = null;
            ms.Close();
            ms.Dispose();
        }
        public object Execute(ExecutorContext context)
        {
            System.IO.MemoryStream _Code_ZipFileStream = null;

            try
            {
                var cmdletContext = context as CmdletContext;
                // create request
                var request = new Amazon.Synthetics.Model.CreateCanaryRequest();

                if (cmdletContext.ArtifactS3Location != null)
                {
                    request.ArtifactS3Location = cmdletContext.ArtifactS3Location;
                }

                // populate Code
                var requestCodeIsNull = true;
                request.Code = new Amazon.Synthetics.Model.CanaryCodeInput();
                System.String requestCode_code_Handler = null;
                if (cmdletContext.Code_Handler != null)
                {
                    requestCode_code_Handler = cmdletContext.Code_Handler;
                }
                if (requestCode_code_Handler != null)
                {
                    request.Code.Handler = requestCode_code_Handler;
                    requestCodeIsNull    = false;
                }
                System.String requestCode_code_S3Bucket = null;
                if (cmdletContext.Code_S3Bucket != null)
                {
                    requestCode_code_S3Bucket = cmdletContext.Code_S3Bucket;
                }
                if (requestCode_code_S3Bucket != null)
                {
                    request.Code.S3Bucket = requestCode_code_S3Bucket;
                    requestCodeIsNull     = false;
                }
                System.String requestCode_code_S3Key = null;
                if (cmdletContext.Code_S3Key != null)
                {
                    requestCode_code_S3Key = cmdletContext.Code_S3Key;
                }
                if (requestCode_code_S3Key != null)
                {
                    request.Code.S3Key = requestCode_code_S3Key;
                    requestCodeIsNull  = false;
                }
                System.String requestCode_code_S3Version = null;
                if (cmdletContext.Code_S3Version != null)
                {
                    requestCode_code_S3Version = cmdletContext.Code_S3Version;
                }
                if (requestCode_code_S3Version != null)
                {
                    request.Code.S3Version = requestCode_code_S3Version;
                    requestCodeIsNull      = false;
                }
                System.IO.MemoryStream requestCode_code_ZipFile = null;
                if (cmdletContext.Code_ZipFile != null)
                {
                    _Code_ZipFileStream      = new System.IO.MemoryStream(cmdletContext.Code_ZipFile);
                    requestCode_code_ZipFile = _Code_ZipFileStream;
                }
                if (requestCode_code_ZipFile != null)
                {
                    request.Code.ZipFile = requestCode_code_ZipFile;
                    requestCodeIsNull    = false;
                }
                // determine if request.Code should be set to null
                if (requestCodeIsNull)
                {
                    request.Code = null;
                }
                if (cmdletContext.ExecutionRoleArn != null)
                {
                    request.ExecutionRoleArn = cmdletContext.ExecutionRoleArn;
                }
                if (cmdletContext.FailureRetentionPeriodInDay != null)
                {
                    request.FailureRetentionPeriodInDays = cmdletContext.FailureRetentionPeriodInDay.Value;
                }
                if (cmdletContext.Name != null)
                {
                    request.Name = cmdletContext.Name;
                }

                // populate RunConfig
                var requestRunConfigIsNull = true;
                request.RunConfig = new Amazon.Synthetics.Model.CanaryRunConfigInput();
                System.Int32?requestRunConfig_runConfig_MemoryInMB = null;
                if (cmdletContext.RunConfig_MemoryInMB != null)
                {
                    requestRunConfig_runConfig_MemoryInMB = cmdletContext.RunConfig_MemoryInMB.Value;
                }
                if (requestRunConfig_runConfig_MemoryInMB != null)
                {
                    request.RunConfig.MemoryInMB = requestRunConfig_runConfig_MemoryInMB.Value;
                    requestRunConfigIsNull       = false;
                }
                System.Int32?requestRunConfig_runConfig_TimeoutInSecond = null;
                if (cmdletContext.RunConfig_TimeoutInSecond != null)
                {
                    requestRunConfig_runConfig_TimeoutInSecond = cmdletContext.RunConfig_TimeoutInSecond.Value;
                }
                if (requestRunConfig_runConfig_TimeoutInSecond != null)
                {
                    request.RunConfig.TimeoutInSeconds = requestRunConfig_runConfig_TimeoutInSecond.Value;
                    requestRunConfigIsNull             = false;
                }
                // determine if request.RunConfig should be set to null
                if (requestRunConfigIsNull)
                {
                    request.RunConfig = null;
                }
                if (cmdletContext.RuntimeVersion != null)
                {
                    request.RuntimeVersion = cmdletContext.RuntimeVersion;
                }

                // populate Schedule
                var requestScheduleIsNull = true;
                request.Schedule = new Amazon.Synthetics.Model.CanaryScheduleInput();
                System.Int64?requestSchedule_schedule_DurationInSecond = null;
                if (cmdletContext.Schedule_DurationInSecond != null)
                {
                    requestSchedule_schedule_DurationInSecond = cmdletContext.Schedule_DurationInSecond.Value;
                }
                if (requestSchedule_schedule_DurationInSecond != null)
                {
                    request.Schedule.DurationInSeconds = requestSchedule_schedule_DurationInSecond.Value;
                    requestScheduleIsNull = false;
                }
                System.String requestSchedule_schedule_Expression = null;
                if (cmdletContext.Schedule_Expression != null)
                {
                    requestSchedule_schedule_Expression = cmdletContext.Schedule_Expression;
                }
                if (requestSchedule_schedule_Expression != null)
                {
                    request.Schedule.Expression = requestSchedule_schedule_Expression;
                    requestScheduleIsNull       = false;
                }
                // determine if request.Schedule should be set to null
                if (requestScheduleIsNull)
                {
                    request.Schedule = null;
                }
                if (cmdletContext.SuccessRetentionPeriodInDay != null)
                {
                    request.SuccessRetentionPeriodInDays = cmdletContext.SuccessRetentionPeriodInDay.Value;
                }
                if (cmdletContext.Tag != null)
                {
                    request.Tags = cmdletContext.Tag;
                }

                // populate VpcConfig
                var requestVpcConfigIsNull = true;
                request.VpcConfig = new Amazon.Synthetics.Model.VpcConfigInput();
                List <System.String> requestVpcConfig_vpcConfig_SecurityGroupId = null;
                if (cmdletContext.VpcConfig_SecurityGroupId != null)
                {
                    requestVpcConfig_vpcConfig_SecurityGroupId = cmdletContext.VpcConfig_SecurityGroupId;
                }
                if (requestVpcConfig_vpcConfig_SecurityGroupId != null)
                {
                    request.VpcConfig.SecurityGroupIds = requestVpcConfig_vpcConfig_SecurityGroupId;
                    requestVpcConfigIsNull             = false;
                }
                List <System.String> requestVpcConfig_vpcConfig_SubnetId = null;
                if (cmdletContext.VpcConfig_SubnetId != null)
                {
                    requestVpcConfig_vpcConfig_SubnetId = cmdletContext.VpcConfig_SubnetId;
                }
                if (requestVpcConfig_vpcConfig_SubnetId != null)
                {
                    request.VpcConfig.SubnetIds = requestVpcConfig_vpcConfig_SubnetId;
                    requestVpcConfigIsNull      = false;
                }
                // determine if request.VpcConfig should be set to null
                if (requestVpcConfigIsNull)
                {
                    request.VpcConfig = null;
                }

                CmdletOutput output;

                // issue call
                var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
                try
                {
                    var    response       = CallAWSServiceOperation(client, request);
                    object pipelineOutput = null;
                    pipelineOutput = cmdletContext.Select(response, this);
                    output         = new CmdletOutput
                    {
                        PipelineOutput  = pipelineOutput,
                        ServiceResponse = response
                    };
                }
                catch (Exception e)
                {
                    output = new CmdletOutput {
                        ErrorResponse = e
                    };
                }

                return(output);
            }
            finally
            {
                if (_Code_ZipFileStream != null)
                {
                    _Code_ZipFileStream.Dispose();
                }
            }
        }
Пример #42
0
        private void DataGrid_User_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SqlConnection con1 = new SqlConnection(PublicVar.ConnectionString);

            con1.Open();
            object itemOne = DataGrid_User.SelectedItem;
            string idfinder;

            try{
                idfinder = (DataGrid_User.SelectedCells[0].Column.GetCellContent(itemOne) as TextBlock).Text;
            }
            catch
            {
                idfinder = "";
            }
            try
            {
                SqlCommand Commandcmd = new SqlCommand(
                    "SELECT (UserImage) FROM Users WHERE UserID = " + idfinder,
                    con1);
                SqlDataReader rdr1 = null;
                rdr1 = Commandcmd.ExecuteReader();
                while (rdr1.Read())
                {
                    Images.Fill = new ImageBrush
                    {
                        ImageSource = new BitmapImage(new Uri("/pic/User.jpg", UriKind.Relative))
                    };
                    if (rdr1 != null)
                    {
                        byte[] data = (byte[])rdr1[0]; // 0 is okay if you only selecting one column
                                                       //And use:
                        using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
                        {
                            var imageSource = new BitmapImage();
                            imageSource.BeginInit();
                            imageSource.StreamSource = ms;
                            imageSource.CacheOption  = BitmapCacheOption.OnLoad;
                            imageSource.EndInit();

                            // Assign the Source property of your image
                            //  MyImage.Source = imageSource;
                            Images.Fill = new ImageBrush
                            {
                                ImageSource = imageSource
                            };
                        }
                    }
                }
            }
            catch (Exception excepstion)
            {
                Images.Fill = new ImageBrush
                {
                    //  ImageSource = new BitmapImage(new Uri("/pic/download.png", UriKind.Relative))
                };
            }

            try
            {
                SqlCommand myCommand   = new SqlCommand("SELECT (UserEstakhr) FROM Users where UserID = " + idfinder, con1);
                object     result      = myCommand.ExecuteScalar();
                string     estakhrshow = Convert.ToString(result);
                if (estakhrshow == "True")
                {
                    EstakhrIcon.Source = new BitmapImage(new Uri("/pic/newpic/Snap/1.png", UriKind.Relative));
                }
                else
                {
                    EstakhrIcon.Source = new BitmapImage(new Uri("/img/no.png", UriKind.Relative));
                }



                SqlCommand myCommands   = new SqlCommand("SELECT (UserBime) FROM Users where UserID = " + idfinder, con1);
                object     results      = myCommands.ExecuteScalar();
                string     estakhrshows = Convert.ToString(results);
                if (estakhrshows == "True")
                {
                    BimeIcon.Source = new BitmapImage(new Uri("/pic/newpic/Snap/1.png", UriKind.Relative));
                }
                else
                {
                    BimeIcon.Source = new BitmapImage(new Uri("/img/no.png", UriKind.Relative));
                }



                SqlCommand myCommandss   = new SqlCommand("SELECT (UserKhososi) FROM Users where UserID = " + idfinder, con1);
                object     resultss      = myCommandss.ExecuteScalar();
                string     estakhrshowss = Convert.ToString(resultss);
                if (estakhrshowss == "True")
                {
                    KhososiIcon.Source = new BitmapImage(new Uri("/pic/newpic/Snap/1.png", UriKind.Relative));
                }
                else
                {
                    KhososiIcon.Source = new BitmapImage(new Uri("/img/no.png", UriKind.Relative));
                }


                SqlCommand myCommandsss   = new SqlCommand("SELECT (UserBarnameQazaiy) FROM Users where UserID = " + idfinder, con1);
                object     resultsss      = myCommandsss.ExecuteScalar();
                string     estakhrshowsss = Convert.ToString(resultsss);
                if (estakhrshowsss == "True")
                {
                    BarnameIcon.Source = new BitmapImage(new Uri("/pic/newpic/Snap/1.png", UriKind.Relative));
                }
                else
                {
                    BarnameIcon.Source = new BitmapImage(new Uri("/img/no.png", UriKind.Relative));
                }
            }
            catch
            {
            }

            con1.Close();
        }
Пример #43
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;
                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));
                        }
            }
        }
Пример #44
0
        void OnReceiveMessage(DebugMessageType type, byte[] buffer)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer))
            {
                using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms))
                {
                    switch (type)
                    {
                    case DebugMessageType.SCAttachResult:
                    {
                        SCAttachResult result = new SCAttachResult();
                        result.Result             = (AttachResults)br.ReadByte();
                        result.DebugServerVersion = br.ReadInt32();
                        RemoteDebugVersion        = result.DebugServerVersion;
                        waitingAttach             = false;
                    }
                    break;

                    case DebugMessageType.SCBindBreakpointResult:
                    {
                        SCBindBreakpointResult msg = new SCBindBreakpointResult();
                        msg.BreakpointHashCode = br.ReadInt32();
                        msg.Result             = (BindBreakpointResults)br.ReadByte();
                        OnReceivSendSCBindBreakpointResult(msg);
                    }
                    break;

                    case DebugMessageType.SCBreakpointHit:
                    {
                        SCBreakpointHit msg = new SCBreakpointHit();
                        msg.BreakpointHashCode = br.ReadInt32();
                        msg.ThreadHashCode     = br.ReadInt32();
                        msg.StackFrame         = ReadStackFrames(br);

                        OnReceiveSCBreakpointHit(msg);
                    }
                    break;

                    case DebugMessageType.SCStepComplete:
                    {
                        SCStepComplete msg = new SCStepComplete();
                        msg.ThreadHashCode = br.ReadInt32();
                        msg.StackFrame     = ReadStackFrames(br);
                        OnReceiveSCStepComplete(msg);
                    }
                    break;

                    case DebugMessageType.SCThreadStarted:
                    {
                        SCThreadStarted msg = new SCThreadStarted();
                        msg.ThreadHashCode = br.ReadInt32();
                        OnReceiveSCThreadStarted(msg);
                    }
                    break;

                    case DebugMessageType.SCThreadEnded:
                    {
                        SCThreadEnded msg = new SCThreadEnded();
                        msg.ThreadHashCode = br.ReadInt32();
                        OnReceiveSCThreadEnded(msg);
                    }
                    break;

                    case DebugMessageType.SCModuleLoaded:
                    {
                        SCModuleLoaded msg = new SCModuleLoaded();
                        msg.ModuleName = br.ReadString();

                        OnReceiveSCModuleLoaded(msg);
                    }
                    break;

                    case DebugMessageType.SCResolveVariableResult:
                    {
                        resolved = ReadVariableInfo(br);
                    }
                    break;
                    }
                }
            }
        }
Пример #45
0
        private void frm_packsGp2_eventSaveToNew()
        {
            frmPackM           = new frm_InpackGP();
            frmPackM.pmStatus  = ItemsPublic.IndexStatus.toNew;
            frmPackM.IndexPack = null;
            frmPackM.isNew     = true;
            //	 frmPackM.

            var frmAddPersons = new aorc.gatepass.Gp2.Pack.frm_SelectOrAddPersonsGp2();

            frmAddPersons.ShowDialog();
            if (true || frmAddPersons.DialogResult == DialogResult.OK)
            {
                //	frmAddPersons.ShowDialog();
                if (frmAddPersons.State)
                {
                    //MainRadGridView.DataSource=null;
                    //MainRadGridView.SelectAll();
                    //frmPackM.MainRadGridView.AllowAddNewRow = true;
                    frmPackM.IsnewRowAdded = true;
                    //frmPackM.MainRadGridView.CurrentRow = null;
                    //MainRadGridView.Rows.RemoveAt(0);
                    //frmPackM.MainRadGridView.DataSource = null;
                    //MainRadGridView.EndInit();
                    //MainRadGridView.EndUpdate();
                    //	MainRadGridView.EndEdit();
                    //while (MainRadGridView.Rows.Count > 0)
                    //{
                    //    MainRadGridView.Rows.RemoveAt(0);
                    //}

                    for (int count = 0; count < frmAddPersons.radGridViewSelected.Rows.Count; count++)
                    {
                        #region set rows

                        frmPackM.MainRadGridView.Rows.AddNew();
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_ID"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_ID"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_NationalCode"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_NationalCode"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_isWoman"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_isWoman"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_IdentifyCode"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_IdentifyCode"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_LicenseDriverCode"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_LicenseDriverCode"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_Name"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_Name"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_Surname"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_Surname"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_FatherName"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_FatherName"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_BirthCity"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_BirthCity"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_RegisterCity"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_RegisterCity"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_Nationality"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_Nationality"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_BirthDate"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_BirthDate"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_Phone1"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_Phone1"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_Phone2"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_Phone2"].Value;
                        //						frmPackM.MainRadGridView.CurrentRow.Cells["Person_Picture"].Value = frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_Picture"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_HaveForm"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_HaveForm"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_RegisterCode"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_RegisterCode"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Person_LabelIsWoman"].Value =
                            frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_LabelIsWoman"].Value;
                        frmPackM.MainRadGridView.CurrentRow.Cells["Gatepass_ID"].Value       = -1;
                        frmPackM.MainRadGridView.CurrentRow.Cells["GatePass_IntPrint"].Value = -1;
                        frmPackM.MainRadGridView.CurrentRow.Cells["GatePass_IsDriver"].Value = false;
                        frmPackM.MainRadGridView.CurrentRow.Cells["GatePass_TimeLock"].Value = null;
                        frmPackM.MainRadGridView.CurrentRow.Cells["GatePass_LockerId"].Value = -1;
                        frmPackM.MainRadGridView.CurrentRow.Cells["package_Id"].Value        = -1;
                        if (frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_Picture"].Value != null)
                        {
                            using (var ms = new System.IO.MemoryStream())
                            {
                                ((Bitmap)frmAddPersons.radGridViewSelected.Rows[count].Cells["Person_Picture"].Value).
                                Save(ms,
                                     System.
                                     Drawing
                                     .
                                     Imaging
                                     .
                                     ImageFormat
                                     .Jpeg);
                                var picture = ms.ToArray();
                                frmPackM.MainRadGridView.CurrentRow.Cells["Person_Picture"].Value = picture.Length > 0
                                                                                                                                ? picture
                                                                                                                                : null;
                            }
                        }
                        else
                        {
                            frmPackM.MainRadGridView.CurrentRow.Cells["Person_Picture"].Value = null;
                        }

                        #endregion
                    }
                    frmPackM.MainRadGridView.AllowAddNewRow = false;
                    frmPackM.IsnewRowAdded = false;
                    //frmPackM.MainRadGridView.Refresh();
                }

                var frmSet = new aorc.gatepass.Gp2.Pack.frm_SettingPackGatePlaceGp2();
                frmSet.ShowDialog();
                frmPackM.SetSetting(frmSet.v2UC_NewPackDetailsGp21);
                frmPackM.ShowDialog();
                //result = frmPackM.gotResult ();
                result = frmPackM.DialogResult == DialogResult.OK ? frmPackM.gotResult() : null;

                frmPackM.Close();
                frmPackM.Dispose();
                frmSet.Close();
                frmSet.Dispose();
                frmAddPersons.Close();
                frmAddPersons.Dispose();
            }
        }
Пример #46
0
        protected void btnPdf_Click(object sender, EventArgs e)
        {
            try
            {
                string    customerJSON = Request.Form["CustomerJSON"];
                DataTable dataTable    = JsonConvert.DeserializeObject <DataTable>(customerJSON);
                string    Name         = "AccountData";
                string[]  columnNames  = (from dc in dataTable.Columns.Cast <DataColumn>()
                                          select dc.ColumnName).ToArray();
                int      Cell  = 0;
                int      count = columnNames.Length;
                object[] array = new object[count];

                dataTable.Rows.Add(array);

                Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
                System.IO.MemoryStream mStream = new System.IO.MemoryStream();
                PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, mStream);
                int       cols   = dataTable.Columns.Count;
                int       rows   = dataTable.Rows.Count;


                HeaderFooter header = new HeaderFooter(new Phrase(Name), false);

                // Remove the border that is set by default
                header.Border = iTextSharp.text.Rectangle.TITLE;
                // Align the text: 0 is left, 1 center and 2 right.
                header.Alignment = Element.ALIGN_CENTER;
                pdfDoc.Header    = header;
                // Header.
                pdfDoc.Open();
                iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
                pdfTable.BorderWidth = 0; pdfTable.Width = 80;
                pdfTable.Padding     = 0; pdfTable.Spacing = 4;

                //creating table headers
                //for (int i = 0; i < cols; i++)
                //{
                //    Cell cellCols = new Cell();
                //    Chunk chunkCols = new Chunk();
                //    cellCols.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#548B54"));
                //    iTextSharp.text.Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.WHITE);

                //    chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);

                //    cellCols.Add(chunkCols);
                //    pdfTable.AddCell(cellCols);
                //}


                for (int k = 0; k < rows; k++)
                {
                    for (int j = 0; j < cols; j++)
                    {
                        Cell cellRows = new Cell();
                        //if (k % 2 == 0)
                        //{
                        //    cellRows.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#cccccc")); ;
                        //}
                        //else { cellRows.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#ffffff")); }
                        iTextSharp.text.Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 10);
                        Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
                        cellRows.Add(chunkRows);

                        pdfTable.AddCell(cellRows);
                    }
                }

                pdfDoc.Add(pdfTable);
                pdfDoc.Close();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Name + "_" + DateTime.Now.ToString() + ".pdf");
                Response.Clear();
                Response.BinaryWrite(mStream.ToArray());
                Response.End();
            }
            catch (Exception ex)
            {
            }
        }
Пример #47
0
 internal ChartResult(System.IO.MemoryStream item)
 {
     mItem = item;
 }
Пример #48
0
        private void CreateCheckCodeImage(string[] checkCode)
        {
            if (checkCode == null || checkCode.Length <= 0)
            {
                return;
            }

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

            try
            {
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.Silver);

                //画图片的背景噪音线
                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.SkyBlue), x1, y1, x2, y2);
                }

                //定义颜色
                Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
                //定义字体
                string[] f = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };

                for (int k = 0; k <= checkCode.Length - 1; k++)
                {
                    int cindex = random.Next(7);
                    int findex = random.Next(5);

                    Font drawFont = new Font(f[findex], 16, (System.Drawing.FontStyle.Bold));



                    SolidBrush drawBrush = new SolidBrush(c[cindex]);

                    float x      = 5.0F;
                    float y      = 0.0F;
                    float width  = 20.0F;
                    float height = 25.0F;
                    int   sjx    = random.Next(10);
                    int   sjy    = random.Next(image.Height - (int)height);

                    RectangleF drawRect = new RectangleF(x + sjx + (k * 25), y + sjy, width, height);

                    StringFormat drawFormat = new StringFormat();
                    drawFormat.Alignment = StringAlignment.Center;

                    g.DrawString(checkCode[k], drawFont, drawBrush, drawRect, drawFormat);
                }

                //画图片的前景噪音点
                for (int i = 0; i < 100; 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.ContentType = "image/Gif";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
Пример #49
0
        // TODO 遇到很长的信息仍然会出现分开两次接收的情况
        /// <summary>
        /// 接受消息回调 ( Standard Receive )
        /// </summary>
        /// <param name="ar"></param>
        private void ReadCallBack_For_StandardReceive(IAsyncResult ar)
        {
            int totalBytesRead   = 0; // 读取总长度 -- 用于累积超出 s_BufferSize 时
            int lastestBytesRead = 0; // 当前读取总长度

            NetworkStream networkStream;

            try
            {
                networkStream = (NetworkStream)ar.AsyncState;

                lastestBytesRead = networkStream.EndRead(ar);
                totalBytesRead   = totalBytesRead + lastestBytesRead;

                if (mMsContent == null)
                {
                    mMsContent = new System.IO.MemoryStream();
                }

                // 首次获取写入内容
                mMsContent.Write
                (
                    buffOfNetworkStream,
                    0,
                    lastestBytesRead
                );

                if (networkStream.DataAvailable)
                {
                    return;
                }

                byte[] contentByteArr = mMsContent.GetBuffer();
                r = (mReceiveEncoding ?? Encoding.UTF8).GetString(contentByteArr, 0, contentByteArr.Length);

                // 由于无法提前知晓信息长度, 故需要处理多出来的 \0
                r = r.Trim('\0');

                if (r.IsNullOrWhiteSpace() == true && mTcpClient.Client.IsConnectedAdv() == false)
                {
                    throw new Exception("与服务器已断开连接(可能是服务端已停止服务)");
                }

                DateTime receiveDateTime = DateTime.Now;
                onStatusChange(msg: $"接收到信息: 信息长度{r.Length}", consoleMsgType: Util.UIModel.ConsoleMsgType.INFO, entryTime: receiveDateTime);
                onReceiveText(new TcpXxxEventArgs(r, mTcpClient.Client.RemoteEndPoint.ToString(), receiveDateTime));

                networkStream = null;

                mMsContent.Close();
                mMsContent = null;
            }
            catch (System.IO.IOException ioEx)
            {
                if (mContinue == false) // 用户点击了断开连接, 此时会进入本方法, 但由于稍后会 mTcpClient.Client.Close(), 导致执行
                {
                    // Do nothing
                }
                else
                {
                    // 1. 用户点击了断开连接, 此时会进入本方法, 但由于稍后会 mTcpClient.Client.Close(), 导致执行
                    // 2. 服务器断开了连接
                    mContinue = false;
                    onStatusChange(ioEx.GetFullInfo(), Util.UIModel.ConsoleMsgType.ERROR);
                }
            }
            catch (Exception e)
            {
                // 判断是否与服务器断开了连接
                if (mTcpClient.Client.IsConnectedAdv() == false)
                {
                    mContinue = false;
                    onStatusChange("与服务器已断开连接(可能是服务端已停止服务)", Util.UIModel.ConsoleMsgType.ERROR);
                }
                else
                {
                    onStatusChange(e.GetFullInfo(), Util.UIModel.ConsoleMsgType.ERROR);
                }
            }
            finally
            {
                mTcpListen_AutoSetEvent.Set();
            }
        }
        public Control_DefaultKeycapBackglow(KeyboardKey key, string image_path)
        {
            InitializeComponent();

            associatedKey = key.tag;

            this.Width  = key.width.Value;
            this.Height = key.height.Value;

            //Keycap adjustments
            if (string.IsNullOrWhiteSpace(key.image))
            {
                keyBorder.BorderThickness = new Thickness(1.5);
            }
            else
            {
                keyBorder.BorderThickness = new Thickness(0.0);
            }
            keyBorder.IsEnabled = key.enabled.Value;

            if (!key.enabled.Value)
            {
                ToolTipService.SetShowOnDisabled(keyBorder, true);
                keyBorder.ToolTip = new ToolTip {
                    Content = "Changes to this key are not supported"
                };
            }

            if (string.IsNullOrWhiteSpace(key.image))
            {
                keyCap.Text = key.visualName;
                keyCap.Tag  = key.tag;
                if (key.font_size != null)
                {
                    keyCap.FontSize = key.font_size.Value;
                }
                keyCap.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                keyCap.Visibility        = System.Windows.Visibility.Hidden;
                grid_backglow.Visibility = Visibility.Hidden;

                if (System.IO.File.Exists(image_path))
                {
                    var         memStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(image_path));
                    BitmapImage image     = new BitmapImage();
                    image.BeginInit();
                    image.StreamSource = memStream;
                    image.EndInit();

                    if (key.tag == DeviceKeys.NONE)
                    {
                        keyBorder.Background = new ImageBrush(image);
                    }
                    else
                    {
                        keyBorder.Background  = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 0, 0, 0));
                        keyBorder.OpacityMask = new ImageBrush(image);
                    }

                    isImage = true;
                }
            }
        }
Пример #51
0
        } // End Function GenerateKey

        public string Encrypt(string plainText)
        {
            string retValue = null;

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                byte[] baCipherTextBuffer     = null;
                byte[] baPlainTextBuffer      = null;
                byte[] baEncryptionKey        = HexStringToByteArray(this.m_key);
                byte[] baInitializationVector = HexStringToByteArray(this.m_iv);


                aes.Key = baEncryptionKey;
                aes.IV  = baInitializationVector;


                //Get an encryptor.
                using (System.Security.Cryptography.ICryptoTransform transform =
                           aes.CreateEncryptor(baEncryptionKey, baInitializationVector))
                {
                    //Encrypt the data.
                    using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
                    {
                        using (System.Security.Cryptography.CryptoStream csEncrypt =
                                   new System.Security.Cryptography.CryptoStream(
                                       msEncrypt
                                       , transform
                                       , System.Security.Cryptography.CryptoStreamMode.Write
                                       )
                               )
                        {
                            //Convert the data to a byte array.
                            baPlainTextBuffer = this.m_encoding.GetBytes(plainText);

                            //Write all data to the crypto stream and flush it.
                            csEncrypt.Write(baPlainTextBuffer, 0, baPlainTextBuffer.Length);
                            csEncrypt.FlushFinalBlock();

                            //Get encrypted array of bytes.
                            baCipherTextBuffer = msEncrypt.ToArray();
                            csEncrypt.Clear();
                        } // End Using csEncrypt
                    }     // End Using msEncrypt
                }         // End Using transform


                retValue = ByteArrayToHexString(baCipherTextBuffer);

                System.Array.Clear(baCipherTextBuffer, 0, baCipherTextBuffer.Length);
                System.Array.Clear(baPlainTextBuffer, 0, baPlainTextBuffer.Length);
                System.Array.Clear(baEncryptionKey, 0, baEncryptionKey.Length);
                System.Array.Clear(baInitializationVector, 0, baInitializationVector.Length);

                baCipherTextBuffer     = null;
                baPlainTextBuffer      = null;
                baEncryptionKey        = null;
                baInitializationVector = null;
            } // End Using aes

            return(retValue);
        } // End Function Encrypt
Пример #52
0
        /// <summary>
        /// 接受消息回调 ( Howe 自定义接收 )
        /// 优点
        /// 1 接收信息头包含信息长度
        /// 2 接收信息有开始符、结束符
        /// </summary>
        /// <param name="ar"></param>
        private void ReadCallBack(IAsyncResult ar)
        {
            int totalBytesRead = 0; // 读取总长度 -- 用于累积超出 s_BufferSize 时
            int startCharIndex = -1;
            int endCharIndex   = -1;

            int lastestBytesRead = 0; // 当前读取总长度

            NetworkStream networkStream;

            try
            {
                networkStream = (NetworkStream)ar.AsyncState;

                lastestBytesRead = networkStream.EndRead(ar);
                totalBytesRead   = totalBytesRead + lastestBytesRead;

                // 定位 StartChar
                for (int i = 0; i < buffOfNetworkStream.Length; i++)
                {
                    if (Util.Web.TcpClientUtils.s_StartChar == Convert.ToChar(buffOfNetworkStream[i]))
                    {
                        startCharIndex = i;
                        break;
                    }
                }

                if (startCharIndex < 0)
                {
                    throw new Exception("缺少(Char)Start");
                }

                // 获取内容长度 ( int类型, 共 4 个字节 )
                int contentLength = BitConverter.ToInt32(buffOfNetworkStream, startCharIndex + 1); // 内容长度

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

                // 首次获取写入内容
                msContent.Write
                (
                    buffOfNetworkStream,
                    startCharIndex + 1 + 4, // (Char)Start 起始位置 + 1( (char)Start 1 个字节 ) + 4( 内容长度 4 个字节 )
                    lastestBytesRead - (startCharIndex + 1 + 4)
                );

                while (totalBytesRead <
                       1 + 4 + contentLength + 1)                                                                        // 1( (char)Start 1 个字节 ) + 4( 内容长度 4 个字节 ) + contentLength ( 读取出来的长度信息 ) + 1( (char)End 1 个字节 )
                {
                    lastestBytesRead = networkStream.Read(buffOfNetworkStream, 0, Util.Web.TcpClientUtils.s_BufferSize); // 再次获取剩余的内容
                    totalBytesRead   = totalBytesRead + lastestBytesRead;
                    msContent.Write(buffOfNetworkStream, 0, lastestBytesRead);
                }

                byte[] contentByteArr = msContent.GetBuffer();

                r = (mReceiveEncoding ?? Encoding.UTF8).GetString(contentByteArr, 0, contentByteArr.Length);

                // 定位 EndChar
                endCharIndex = r.IndexOf(Util.Web.TcpClientUtils.s_EndChar);
                if (endCharIndex < 0)
                {
                    throw new Exception("缺少(Char)End");
                }

                r = r.Substring(0, endCharIndex);

                DateTime receiveDateTime = DateTime.Now;
                onStatusChange(msg: $"接收到信息: 信息长度{r.Length}", consoleMsgType: Util.UIModel.ConsoleMsgType.INFO, entryTime: receiveDateTime);
                onReceiveText(new TcpXxxEventArgs(r, mTcpClient.Client.RemoteEndPoint.ToString(), receiveDateTime));

                networkStream = null;

                msContent.Close();
                msContent = null;
            }
            catch (System.IO.IOException ioEx)
            {
                if (mContinue == false) // 用户点击了断开连接, 此时会进入本方法, 但由于稍后会 mTcpClient.Client.Close(), 导致执行
                {
                    // Do nothing
                }
                else
                {
                    // 1. 用户点击了断开连接, 此时会进入本方法, 但由于稍后会 mTcpClient.Client.Close(), 导致执行
                    mContinue = false;
                    onStatusChange(ioEx.GetFullInfo(), Util.UIModel.ConsoleMsgType.ERROR);
                }
            }
            catch (Exception e)
            {
                // 判断是否与服务器断开了连接
                if (mTcpClient.Client.IsConnectedAdv() == false)
                {
                    mContinue = false;
                    onStatusChange("与服务器已断开连接(可能是服务端已停止服务)", Util.UIModel.ConsoleMsgType.ERROR);
                }
                else
                {
                    onStatusChange(e.GetFullInfo(), Util.UIModel.ConsoleMsgType.ERROR);
                }
            }
            finally
            {
                mTcpListen_AutoSetEvent.Set();
            }
        }
        // <summary>
        // Called automatically whenever an activity finishes
        // </summary>
        // <param name = "requestCode" ></ param >
        // < param name="resultCode"></param>
        /// <param name="data"></param>
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            if (requestCode == 100)
            {
                SetContentView(Resource.Layout.IsThis);
                //var txtName = FindViewById<TextView>(Resource.Id.isThis);  //these are the variables for the IsThis layout
                //var yesbtn = FindViewById<Button>(Resource.Id.ybtn);
                //var nobtn = FindViewById<Button>(Resource.Id.nbtn);
            }
            if (resultCode == Result.FirstUser)
            {
                data.GetStringExtra("newAnswer");
                var myintent = new Intent(this, typeof(InGoogle));
                StartActivity(myintent);
            }
            // Display in ImageView. We will resize the bitmap to fit the display.
            // Loading the full sized image will consume too much memory
            // and cause the application to crash.
            ImageView imageView = FindViewById <ImageView>(Resource.Id.takenPictureImageView);
            //TextView googleResponse = FindViewById<TextView>(Resource.Id.whatBe);
            //TextView googleResp1 = FindViewById<TextView>(Resource.Id.whatBe1);
            //TextView googleResp2 = FindViewById<TextView>(Resource.Id.whatBe2);
            //var isItString = FindViewById<TextView>(Resource.Id.isThis); //don't need this var
            int height = Resources.DisplayMetrics.HeightPixels;
            int width  = imageView.Height;

            //AC: workaround for not passing actual files
            Android.Graphics.Bitmap bitmap = (Android.Graphics.Bitmap)data.Extras.Get("data");

            //convert bitmap into stream to be sent to Google API
            string bitmapString = "";

            using (var stream = new System.IO.MemoryStream())
            {
                bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);

                var bytes = stream.ToArray();
                bitmapString = System.Convert.ToBase64String(bytes);
            }

            //credential is stored in "assets" folder
            string credPath = "google_api.json";

            Google.Apis.Auth.OAuth2.GoogleCredential cred;

            //Load credentials into object form
            using (var stream = Assets.Open(credPath))
            {
                cred = Google.Apis.Auth.OAuth2.GoogleCredential.FromStream(stream);
            }
            cred = cred.CreateScoped(Google.Apis.Vision.v1.VisionService.Scope.CloudPlatform);

            // By default, the library client will authenticate
            // using the service account file (created in the Google Developers
            // Console) specified by the GOOGLE_APPLICATION_CREDENTIALS
            // environment variable. We are specifying our own credentials via json file.
            var client = new Google.Apis.Vision.v1.VisionService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                ApplicationName       = "subtle-isotope-190917",
                HttpClientInitializer = cred
            });

            //set up request
            var request = new Google.Apis.Vision.v1.Data.AnnotateImageRequest();

            request.Image         = new Google.Apis.Vision.v1.Data.Image();
            request.Image.Content = bitmapString;

            //tell google that we want to perform label detection
            request.Features = new List <Google.Apis.Vision.v1.Data.Feature>();
            request.Features.Add(new Google.Apis.Vision.v1.Data.Feature()
            {
                Type = "LABEL_DETECTION"
            });
            var batch = new Google.Apis.Vision.v1.Data.BatchAnnotateImagesRequest();

            batch.Requests = new List <Google.Apis.Vision.v1.Data.AnnotateImageRequest>();
            batch.Requests.Add(request);

            //send request.  Note that I'm calling execute() here, but you might want to use
            //ExecuteAsync instead
            var apiResult = client.Images.Annotate(batch).Execute();

            //googleResponse.Text = apiResult.Responses[0].LabelAnnotations[0].Description;
            //googleResp1.Text = apiResult.Responses[0].LabelAnnotations[1].Description;
            //googleResp2.Text = apiResult.Responses[0].LabelAnnotations[2].Description;
            var txtName = FindViewById <TextView>(Resource.Id.isThis);  //these are the variables for the IsThis layout
            var yesbtn  = FindViewById <Button>(Resource.Id.ybtn);
            var nobtn   = FindViewById <Button>(Resource.Id.nbtn);


            // turn confidence float into decimal notation and then to string in percentage.
            // Using this data for GoogleResponse Activity if user wishes to see the confidence and range of labelAnnotations.
            for (int i = 0; i <= 3; i++)
            {
                float percentConfident = (float)apiResult.Responses[0].LabelAnnotations[i].Score * 100;
                int   confidence       = (int)percentConfident;

                string percent = confidence.ToString() + "%";
                string thing   = apiResult.Responses[0].LabelAnnotations[i].Description;
                MainActivity.Items.Add(new Items(thing, percent));
            }

            var isIt = MainActivity.Items[position]; //bug here 0 v position
            //String whatBe = "Is this a " + apiResult.Responses[0].LabelAnnotations[0].Description + " at " + apiResult.Responses[0].LabelAnnotations[0].Score + " ?!"
            //    "I am " + apiResult.Responses[0].LabelAnnotations[0].Score;

            String whatBe = "Is this a " + isIt.Thing + " ?! I am " + isIt.Percent + " confident.";

            txtName.Text = whatBe;
            //var intent = new Intent(this, typeof(IsItActivity));
            //intent.PutExtra("apiResult", myConfidence);
            //StartActivity(intent); dont need this chunk of code because not passing between activities. Will use a public class instead


            FindViewById <Button>(Resource.Id.nbtn).Click += DarnActivityClick;
            FindViewById <Button>(Resource.Id.ybtn).Click += SuccessActivity;
            // Below are the button onClick methods to direct to the Succeed or Darn layouts.

            //whatBe = apiResult.Responses[0].LabelAnnotations[0].Description;
            if (bitmap != null)
            {
                imageView.SetImageBitmap(bitmap);
                imageView.Visibility = Android.Views.ViewStates.Visible;
                bitmap = null;
            }

            // Dispose of the Java side bitmap.
            System.GC.Collect();
        }
Пример #54
0
        public async System.Threading.Tasks.Task <SoftmakeAll.SDK.OperationResult <System.Byte[]> > DownloadAsync(System.String ContainerName, System.Collections.Generic.Dictionary <System.String, System.String> StorageFileNames)
        {
            SoftmakeAll.SDK.CloudStorage.Azure.Environment.Validate();

            SoftmakeAll.SDK.OperationResult <System.Byte[]> OperationResult = new SoftmakeAll.SDK.OperationResult <System.Byte[]>();

            if ((System.String.IsNullOrWhiteSpace(ContainerName)) || (StorageFileNames == null) || (StorageFileNames.Count == 0))
            {
                OperationResult.Message = "The ContainerName and StorageFileName cannot be null.";
                return(OperationResult);
            }

            try
            {
                global::Azure.Storage.Blobs.BlobContainerClient BlobContainerClient = new global::Azure.Storage.Blobs.BlobContainerClient(SoftmakeAll.SDK.CloudStorage.Azure.Environment._ConnectionString, ContainerName);
                if (StorageFileNames.Count == 1)
                {
                    global::Azure.Storage.Blobs.BlobClient BlobClient = BlobContainerClient.GetBlobClient(StorageFileNames.First().Key);
                    if (!(await BlobClient.ExistsAsync()))
                    {
                        OperationResult.Message = "The file could not be found.";
                        return(OperationResult);
                    }

                    using (System.IO.MemoryStream MemoryStream = new System.IO.MemoryStream())
                    {
                        await BlobClient.DownloadToAsync(MemoryStream);

                        OperationResult.Data = MemoryStream.ToArray();
                    }
                }
                else
                {
                    using (System.Threading.SemaphoreSlim SemaphoreSlim = new System.Threading.SemaphoreSlim(StorageFileNames.Count))
                    {
                        System.Collections.Generic.List <System.Threading.Tasks.Task> DownloadTasks = new System.Collections.Generic.List <System.Threading.Tasks.Task>();
                        foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> StorageFileName in StorageFileNames)
                        {
                            global::Azure.Storage.Blobs.BlobClient BlobClient = BlobContainerClient.GetBlobClient(StorageFileName.Key);
                            if (!(await BlobClient.ExistsAsync()))
                            {
                                continue;
                            }

                            await SemaphoreSlim.WaitAsync();

                            DownloadTasks.Add(System.Threading.Tasks.Task.Run(async() => { await BlobClient.DownloadToAsync(StorageFileName.Key); SemaphoreSlim.Release(); }));
                        }

                        if (DownloadTasks.Any())
                        {
                            await System.Threading.Tasks.Task.WhenAll(DownloadTasks);
                        }
                    }

                    OperationResult.Data = SoftmakeAll.SDK.Files.Compression.CreateZipArchive(StorageFileNames);

                    foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> StorageFileName in StorageFileNames)
                    {
                        if (System.IO.File.Exists(StorageFileName.Key))
                        {
                            try { System.IO.File.Delete(StorageFileName.Key); } catch { }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                if (StorageFileNames.Count > 0)
                {
                    foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> StorageFileName in StorageFileNames)
                    {
                        if (System.IO.File.Exists(StorageFileName.Key))
                        {
                            try { System.IO.File.Delete(StorageFileName.Key); } catch { }
                        }
                    }
                }

                OperationResult.Message = ex.Message;
                return(OperationResult);
            }

            OperationResult.ExitCode = 0;
            return(OperationResult);
        }
Пример #55
0
 public LocalFile(RemoteFile remoteFile, string fullPath)
 {
     this.m_FullPath     = fullPath;
     this.m_MemoryStream = remoteFile.MemoryStream;
 }
Пример #56
0
        public object Execute(ExecutorContext context)
        {
            System.IO.MemoryStream _CertificateStream      = null;
            System.IO.MemoryStream _CertificateChainStream = null;

            try
            {
                var cmdletContext = context as CmdletContext;
                // create request
                var request = new Amazon.ACMPCA.Model.ImportCertificateAuthorityCertificateRequest();

                if (cmdletContext.Certificate != null)
                {
                    _CertificateStream  = new System.IO.MemoryStream(cmdletContext.Certificate);
                    request.Certificate = _CertificateStream;
                }
                if (cmdletContext.CertificateAuthorityArn != null)
                {
                    request.CertificateAuthorityArn = cmdletContext.CertificateAuthorityArn;
                }
                if (cmdletContext.CertificateChain != null)
                {
                    _CertificateChainStream  = new System.IO.MemoryStream(cmdletContext.CertificateChain);
                    request.CertificateChain = _CertificateChainStream;
                }

                CmdletOutput output;

                // issue call
                var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
                try
                {
                    var    response       = CallAWSServiceOperation(client, request);
                    object pipelineOutput = null;
                    pipelineOutput = cmdletContext.Select(response, this);
                    output         = new CmdletOutput
                    {
                        PipelineOutput  = pipelineOutput,
                        ServiceResponse = response
                    };
                }
                catch (Exception e)
                {
                    output = new CmdletOutput {
                        ErrorResponse = e
                    };
                }

                return(output);
            }
            finally
            {
                if (_CertificateStream != null)
                {
                    _CertificateStream.Dispose();
                }
                if (_CertificateChainStream != null)
                {
                    _CertificateChainStream.Dispose();
                }
            }
        }
Пример #57
0
        protected void Page_Load(object sender, EventArgs e)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            switch (Action)
            {
            case "text":
            {
                FontPack model = new FontPack().FromJson(Request["model"]);
                if (string.IsNullOrEmpty(model.text))
                {
                    throw new Exception("文字内容不能为空");
                }
                int bmpLen   = 0;
                int maxWidth = 0;                                         //用于list.aspx,不可超过原有的最大宽度
                maxWidth = model.direction == "vertical" ? 0:DataConvert.CLng(Request["width"]);
                int size = GetFontSize(model.text, maxWidth, ref bmpLen); //自动计算出文字大小
                //根据字体,进行一定程度的缩放0.8-1(特殊要求,不可超过原宽度)
                switch (model.family)
                {
                case "architech":
                    size = (int)(size * 0.83);
                    break;

                case "harlow solid italic":
                    size = (int)(size * 0.90);
                    break;
                }
                //"Aileron_Light|BPdotsDiamond|Bauhaus|balloon|architech|belshaw|bpreplay|noodle_script|harlow_solid_italic|arial|arial_narrow|Arial_Rounded_MT_bold"
                //------------------------------------
                //根据方向生成不同的宽度的图片
                Font   mFont = new Font(model.family, size, FontStyle.Regular);
                Bitmap empty = null;
                //有的字体未定义小写字母
                switch (model.direction)
                {
                case "vertical":
                {
                    model.text = model.text.ToUpper();                //垂直下强制大写
                    empty      = new Bitmap((int)(size * 1.5), (int)(bmpLen * 1.3));
                    Graphics g = Graphics.FromImage(empty);
                    g.Clear(Color.FromArgb(0));
                    //每个字为一行
                    char[]     chars = model.text.ToCharArray();
                    SolidBrush brush = new SolidBrush(model.ColorHx16toRGB(model.color)); //Color.FromArgb(100,255,255,255)
                    int        lastY = 0;                                                 //最近一次的Y轴定位
                    for (int i = 0; i < chars.Length; i++)
                    {
                        int    x    = 0;
                        string text = chars[i] + "";
                        //空格不用占过多宽
                        if (text == " ")
                        {
                            lastY += 8; continue;
                        }
                        else if (i == 0)
                        {
                        }
                        else
                        {
                            lastY = lastY + (int)(model.size * 2.5);
                        }
                        //Char.IsLower(chars[i]) ||
                        if (text == "I")
                        {
                            x = model.size / 2;
                        }

                        g.DrawString(text, mFont, brush, new Point(x, lastY));
                    }
                }
                break;

                default:            //
                {
                    //水平下做自动居中处理(即图片宽度不变,前后留空)
                    int bmpWidth = bmpLen;
                    if (maxWidth > 0 && maxWidth > bmpLen)
                    {
                        bmpWidth = maxWidth;
                    }
                    int bmpStart = (int)((bmpWidth - bmpLen) / 2);
                    //throw new Exception(bmpStart + "|" + bmpWidth + "|" + bmpLen);

                    empty = new Bitmap(bmpWidth, (int)(size * 1.5));
                    Graphics g = Graphics.FromImage(empty);
                    //g.Clear(model.ColorHx16toRGB(model.bkcolor));//清除画面,填充背景
                    g.Clear(Color.FromArgb(0));
                    g.DrawString(model.text, mFont,
                                 new SolidBrush(model.ColorHx16toRGB(model.color)),      //Color.FromArgb(100,255,255,255)
                                 new Point(bmpStart, 0));
                }
                break;
                }

                empty.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            }
            break;

            case "logo":
            default:
            {
                //int LogoID = DataConvert.CLng(Request.QueryString["LogoID"]);
                //string svgPath = Server.MapPath(iconBll.PlugDir + "assets/icons/" + LogoID + ".svg");
                //SvgDocument svg = SvgDocument.Open(svgPath);
                //Bitmap bmp = svg.Draw();
                //System.Drawing.Image empty = ImgHelper.ReadImgToMS(iconBll.PlugDir + "assets/empty.png");
                //Graphics g = Graphics.FromImage(empty);
                ////SizeF textSize = g.MeasureString(CompName, new Font(""));
                //g.DrawImage(bmp, new Point() { X = 95, Y = 40 });//400,400,商标也固定大小
                //                                                 //添加文字
                //Font mFont = new Font(SelFont("m"), GetFontSize(CompName), FontStyle.Regular);
                //Font sFont = new Font(SelFont("s"), (GetFontSize(SubTitle) / 2), FontStyle.Regular);
                //g.DrawString(CompName, mFont,
                //    new SolidBrush(Color.FromArgb(100, 0, 0, 0)),
                //    GetPosition(empty, g.MeasureString(CompName, mFont), 265));
                //g.DrawString(SubTitle, sFont,
                //    new SolidBrush(Color.FromArgb(100, 102, 102, 102)),
                //    GetPosition(empty, g.MeasureString(SubTitle, sFont), 305 + (int)mFont.Size));
                //empty.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            }
            break;
            }

            //------------
            Response.Cache.SetNoStore();
            Response.ClearContent();
            Response.ContentType = "image/gif";
            Response.BinaryWrite(ms.ToArray());
        }
Пример #58
0
 public LocalFile(RemoteFile remoteFile, Identity.WebServiceAccount webServiceAccount)
 {
     this.m_FullPath     = System.IO.Path.Combine(webServiceAccount.LocalFileDownloadDirectory, remoteFile.FileName);
     this.m_MemoryStream = remoteFile.MemoryStream;
 }
Пример #59
0
        public static TVShowInfo GetTVShowDetails(int showid, bool noncache = false)
        {
            TVShowInfo entry;

            if (!cacheshow.TryGetValue(showid, out entry) || noncache)
            {
                var    url = String.Format("http://thetvdb.com/api/{1}/series/{0}/all/en.zip", showid, tvdbkey);
                byte[] xmlData;

                using (var wc = new System.Net.WebClient())
                {
                    xmlData = wc.DownloadData(url);
                }

                var        xmlStream = new System.IO.MemoryStream(xmlData);
                ZipArchive archive   = new ZipArchive(xmlStream, ZipArchiveMode.Read);

                foreach (var a in archive.Entries)
                {
                    if (a.Name == "en.xml")
                    {
                        var memoryStream = new System.IO.MemoryStream();
                        var x            = a.Open();
                        x.CopyTo(memoryStream);
                        var t = memoryStream.ToArray();

                        string xmlStr = System.Text.Encoding.UTF8.GetString(t);
                        var    xmlDoc = new System.Xml.XmlDocument();
                        xmlDoc.LoadXml(xmlStr);

                        entry             = new TVShowInfo();
                        entry.ID          = showid;
                        entry.Name        = xmlDoc.SelectSingleNode("//SeriesName").InnerText;
                        entry.LastUpdated = System.Int64.Parse(xmlDoc.SelectSingleNode(".//lastupdated").InnerText);
                        entry.IMDBID      = xmlDoc.SelectSingleNode("//IMDB_ID").InnerText;
                        entry.TVEpisodes  = new List <TVEpisode>();

                        var airtime = xmlDoc.SelectSingleNode("//Airs_Time").InnerText;

                        var episodes = xmlDoc.SelectNodes("//Episode");
                        foreach (XmlNode ep in episodes)
                        {
                            var seasoninfo = new TVEpisode();
                            seasoninfo.FirstAired = new System.DateTime();

                            var epnum      = ep.SelectSingleNode(".//EpisodeNumber").InnerText;
                            var seasonnum  = ep.SelectSingleNode(".//SeasonNumber").InnerText;
                            var title      = ep.SelectSingleNode(".//EpisodeName").InnerText;
                            var firstaired = ep.SelectSingleNode(".//FirstAired").InnerText;
                            var absnumber  = ep.SelectSingleNode(".//absolute_number").InnerText;

                            DateTime faired;
                            if (!String.IsNullOrEmpty(firstaired))
                            {
                                if (DateTime.TryParse(firstaired + " " + airtime, out faired))
                                {
                                    seasoninfo.FirstAired = faired;
                                }
                            }

                            seasoninfo.Episode = (int)Math.Ceiling(System.Double.Parse(epnum, new System.Globalization.CultureInfo("en-US")));
                            seasoninfo.Season  = (int)Math.Ceiling(System.Double.Parse(seasonnum, new System.Globalization.CultureInfo("en-US")));
                            seasoninfo.Title   = title;
                            if (!string.IsNullOrEmpty(absnumber))
                            {
                                seasoninfo.AbsoluteNumber = (System.Int32.Parse(absnumber, new System.Globalization.CultureInfo("en-US")));
                            }
                            seasoninfo.EpisodeId = (System.Int32.Parse(ep.SelectSingleNode(".//EpisodeNumber").InnerText, new System.Globalization.CultureInfo("en-US")));

                            entry.TVEpisodes.Add(seasoninfo);
                        }
                        cacheshow.AddOrUpdate(showid, entry, (key, oldvalue) => (oldvalue.LastUpdated > entry.LastUpdated ? oldvalue : entry));
                    }
                }
            }
            return(entry);
        }
Пример #60
0
        //生产图片
        public static byte[] CreateImage(string validateNum)
        {
            byte[] data = null;
            if (validateNum == null || validateNum.Trim() == string.Empty)
            {
                return(data);
            }
            //拆分字符,随机字体颜色

            Color[]  color   = { Color.Black, Color.Blue, Color.Orange, Color.SkyBlue, Color.DarkOrange, Color.DarkRed, Color.DodgerBlue, Color.SaddleBrown, Color.SlateGray };
            string[] strFont = { "Arial", "宋体", "华文彩云", "Harrington", "Century", "Century", "Calibri", "Bell MT" };
            char[]   ch      = validateNum.ToCharArray();
            //生成BitMap图像
            //Bitmap image = new Bitmap(validateNum.Length * 12 + 12, 22);
            Bitmap   image = new Bitmap(130, 55);
            Graphics g     = Graphics.FromImage(image);

            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景
                g.Clear(Color.White);
                //画图片的背景噪音线
                for (int i = 0; i < 25; 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, x2, y1, y2);
                }

                for (int i = 0; i < ch.Length; i++)
                {
                    Font font = new Font(strFont[random.Next(strFont.Length)], random.Next(35, 40), (FontStyle.Bold | FontStyle.Italic));
                    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), color[random.Next(color.Length)], color[random.Next(color.Length)], 1.2f, true);
                    g.DrawString(ch[i].ToString(), font, brush, i * 27 + random.Next(2, 3), random.Next(2, 5));
                }


                //画图片的前景噪音点
                for (int i = 0; i < 100; 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);
                data = ms.GetBuffer();
                //return File(data, "image/jpeg");
                return(data);
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }