Пример #1
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
		}
        /// <summary>
        /// 加密字符串
        /// </summary>
        public static string Encrypt(string PlainText)
        {
            System.Security.Cryptography.DESCryptoServiceProvider key = new System.Security.Cryptography.DESCryptoServiceProvider();
            byte[] bk = System.Text.Encoding.Unicode.GetBytes(CryKey);
            byte[] bs = new byte[8];
            for (int i = 0; i < bs.Length; i++)
            {
                bs[i] = bk[i];
            }
            key.Key = bs;
            key.IV = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };

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

            System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(ms, key.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

            System.IO.StreamWriter sw = new System.IO.StreamWriter(encStream);
            sw.WriteLine(PlainText);
            sw.Close();
            encStream.Close();

            byte[] buffer = ms.ToArray();
            ms.Close();

            string s = "";
            for (int i = 0; i < buffer.Length; i++)
            {
                s += buffer[i].ToString("X2");
            }
            return s;
        }
Пример #3
0
 public string recv()
 {
     System.Text.Encoding enc = System.Text.Encoding.UTF8;
     //サーバーから送られたデータを受信する
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     byte[] resBytes = new byte[1];
     int resSize;
     ns.ReadTimeout = 100;
     do
     {
         //データの一部を受信する
         resSize = ns.Read(resBytes,0,1);
         //Readが0を返した時はサーバーが切断したと判断
         if (resSize == 0)
         {
             Console.WriteLine("サーバーが切断しました。");
             return "";
         }
         if (resBytes[0] == ';')
         {
             break;
         }
         //受信したデータを蓄積する
         ms.Write(resBytes, 0,1);
         
     } while (ns.DataAvailable);
     //受信したデータを文字列に変換
     string resMsg = enc.GetString(ms.ToArray());
     ms.Close();
     Console.WriteLine(resMsg);
     return resMsg;
 }
        private static string CryKey = "Xky_Lq_Py_Hu_Lp_Jhj_Zxt"; //密钥

        #endregion Fields

        #region Methods

        /// <summary>
        /// 解密字符串
        /// </summary>
        public static string Decrypt(string CypherText)
        {
            System.Security.Cryptography.DESCryptoServiceProvider key = new System.Security.Cryptography.DESCryptoServiceProvider();
            byte[] bk = System.Text.Encoding.Unicode.GetBytes(CryKey);
            byte[] bs = new byte[8];
            for (int i = 0; i < bs.Length; i++)
            {
                bs[i] = bk[i];
            }
            key.Key = bs;
            key.IV = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };

            byte[] bc = new byte[CypherText.Length / 2];
            for (int i = 0; i < bc.Length; i++)
            {
                try
                {
                    bc[i] = Convert.ToByte(CypherText.Substring(2 * i, 2), 16);
                }
                catch { }
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream(bc);
            System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(ms, key.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read);
            System.IO.StreamReader sr = new System.IO.StreamReader(encStream);

            string val = sr.ReadLine();

            sr.Close();
            encStream.Close();
            ms.Close();

            return val;
        }
Пример #5
0
 /// <summary>
 /// DES encryption
 /// </summary>
 /// <param name="strToEncrypt"></param>
 /// <param name="sKey">the key length must equals 8</param>
 /// <returns> Base64 format</returns>
 public string Encrypt(string strToEncrypt, string sKey)
 {
     if (sKey.Length > 8)
     {
         throw new Exception("the key length must be less than or equal to 8!");
     }
     if (sKey.Length < 8)
     {
         string sKeyOther = "abcdefgh";
         sKey += sKeyOther.Substring(0, 8 - sKey.Length);
     }
     using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
     {
         byte[] inputByteArray = Encoding.UTF8.GetBytes(strToEncrypt);
         des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
         des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
         System.IO.MemoryStream ms = new System.IO.MemoryStream();
         using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
         {
             cs.Write(inputByteArray, 0, inputByteArray.Length);
             cs.FlushFinalBlock();
             cs.Close();
         }
         string str = Convert.ToBase64String(ms.ToArray());
         ms.Close();
         return str;
     }
 }
Пример #6
0
        /// <summary>
        /// DES decryption  --by edgar on 2013-9-10
        /// </summary>
        /// <param name="strToDecrypt"></param>
        /// <param name="sKey">the key's length must equals 8</param>
        /// <returns></returns>
        public string Decrypt(string strToDecrypt, string sKey)
        {
            if (sKey.Length < 8)
            {
                string sKeyOther = "abcdefgh";
                sKey += sKeyOther.Substring(0, 8 - sKey.Length);
            }

            byte[] inputByteArray = Convert.FromBase64String(strToDecrypt);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }
Пример #7
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");
		}
Пример #8
0
        //Look at http://code.google.com/p/zxing/wiki/BarcodeContents for formatting

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

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

                return this.Image(imageBytes, "image/jpeg");
            });
        }
Пример #9
0
                //static Logger logger = SimpleLogger.setLogger("Common");

                #region �Í����֌W

                /// <summary>
                /// ��������������
                /// </summary>
                /// <param name="str">�Í������镶����</param>
                /// <param name="key">�p�X���[�h</param>
                /// <returns>�Í������ꂽ������</returns>
                public static string EncryptString(string str, string key)
                {
                    //�������o�C�g�^�z��ɂ���
                    byte[] bytesIn = System.Text.Encoding.UTF8.GetBytes(str);

                    //DESCryptoServiceProvider�I�u�W�F�N�g�̍쐬
                    System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();

                    //���L�L�[�Ə������x�N�^�����
                    //�p�X���[�h��o�C�g�z��ɂ���
                    byte[] bytesKey = System.Text.Encoding.UTF8.GetBytes(key);
                    //���L�L�[�Ə������x�N�^��ݒ�
                    des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
                    des.IV = ResizeBytesArray(bytesKey, des.IV.Length);

                    //�Í������ꂽ�f�[�^������o�����߂�MemoryStream
                    MemoryStream msOut = new System.IO.MemoryStream();
                    //DES�Í����I�u�W�F�N�g�̍쐬
                    System.Security.Cryptography.ICryptoTransform desdecrypt = des.CreateEncryptor();
                    //�������ނ��߂�CryptoStream�̍쐬
                    System.Security.Cryptography.CryptoStream cryptStreem = new System.Security.Cryptography.CryptoStream(msOut, desdecrypt, System.Security.Cryptography.CryptoStreamMode.Write);
                    //��������
                    cryptStreem.Write(bytesIn, 0, bytesIn.Length);
                    cryptStreem.FlushFinalBlock();
                    //�Í������ꂽ�f�[�^��擾
                    byte[] bytesOut = msOut.ToArray();

                    //�‚���
                    cryptStreem.Close();
                    msOut.Close();

                    //Base64�ŕ�����ɕύX���Č��ʂ�Ԃ�
                    return System.Convert.ToBase64String(bytesOut).Replace("=", "");
                }
Пример #10
0
        /// <summary>
        /// Returns the contents of a WPF Visual as a Bitmap in PNG format.
        /// </summary>
        /// <param name="visual">A WPF Visual.</param>
        /// <returns>A GDI+ System.Drawing.Bitmap.</returns>
        public static Bitmap PngBitmap(this Visual visual)
        {
            // Get height and width
            int height = (int)(double)visual.GetValue(FrameworkElement.ActualWidthProperty);
            int width = (int)(double)visual.GetValue(FrameworkElement.ActualHeightProperty);

            // Render
            RenderTargetBitmap rtb =
                new RenderTargetBitmap(
                    height,
                    width,
                    96,
                    96,
                    PixelFormats.Default);
            rtb.Render(visual);

            // Encode
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(rtb));
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            encoder.Save(stream);

            // Create Bitmap
            Bitmap bmp = new Bitmap(stream);
            stream.Close();

            return bmp;
        }
Пример #11
0
        public void TestBooleanQuerySerialization()
        {
            Lucene.Net.Search.BooleanQuery lucQuery = new Lucene.Net.Search.BooleanQuery();

            lucQuery.Add(new Lucene.Net.Search.TermQuery(new Lucene.Net.Index.Term("field", "x")), Occur.MUST);

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bf.Serialize(ms, lucQuery);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            Lucene.Net.Search.BooleanQuery lucQuery2 = (Lucene.Net.Search.BooleanQuery)bf.Deserialize(ms);
            ms.Close();

            Assert.AreEqual(lucQuery, lucQuery2, "Error in serialization");

            Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(dir, true);

            int hitCount = searcher.Search(lucQuery, 20).TotalHits;

            searcher.Close();
            searcher = new Lucene.Net.Search.IndexSearcher(dir, true);

            int hitCount2 = searcher.Search(lucQuery2, 20).TotalHits;

            Assert.AreEqual(hitCount, hitCount2, "Error in serialization - different hit counts");
        }
Пример #12
0
        /// <summary>
        /// Desencripta dado el Cifrado Rijndael
        /// </summary>
        /// <param name="data">Información a Desencriptar</param>
        /// <param name="cypher">Clave a Utilizar para descifrar</param>
        /// <returns>Información Desencriptada</returns>
        public static string Decrypt(string data, string cypher, Boolean webSafe)
        {
            if (webSafe)
            {
                data = Gale.Serialization.FromBase64(data);
            }

            string ciphertext = data;
            try
            {
                RijndaelManaged rijndaelCipher = new RijndaelManaged();

                byte[] ciphertextByte = Convert.FromBase64String(ciphertext);
                byte[] saltByte = Encoding.ASCII.GetBytes(cypher.Length.ToString());

                PasswordDeriveBytes secretKey = new PasswordDeriveBytes(cypher, saltByte);
                ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(ciphertextByte);
                CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

                byte[] plainText = new byte[ciphertextByte.Length + 1];
                int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);

                memoryStream.Close();
                cryptoStream.Close();

                return Encoding.UTF8.GetString(plainText, 0, decryptedCount);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        public string recive()
        {
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] resBytes = new byte[256];
            int resSize = 0;

            if (ns.DataAvailable)
            {

                do
                {
                    //データの一部を受信する
                    resSize = ns.Read(resBytes, 0, resBytes.Length);

                    //受信したデータを蓄積する
                    ms.Write(resBytes, 0, resSize);

                    // 受信を続ける
                } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');

                //受信したデータを文字列に変換
                string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
                ms.Close();
                //末尾の\nを削除
                resMsg = resMsg.TrimEnd('\n');

                return resMsg;
            }
            else
            {
                return "0";
            }
        }
Пример #14
0
		public static byte[] SerializeVoxelAreaData (VoxelArea v) {
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
			
			writer.Write (v.width);
			writer.Write (v.depth);
			writer.Write (v.linkedSpans.Length);
			
			for (int i=0;i<v.linkedSpans.Length;i++) {
				writer.Write(v.linkedSpans[i].area);
				writer.Write(v.linkedSpans[i].bottom);
				writer.Write(v.linkedSpans[i].next);
				writer.Write(v.linkedSpans[i].top);
			}
			
			//writer.Close();
			writer.Flush();
			Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
			stream.Position = 0;
			zip.AddEntry ("data",stream);
			System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
			zip.Save(stream2);
			byte[] bytes = stream2.ToArray();
			stream.Close();
			stream2.Close();
			return bytes;
		}
Пример #15
0
 public static System.Drawing.Image FromBase64(string source)
 {
     System.IO.MemoryStream memStream = new System.IO.MemoryStream(Convert.FromBase64String(source));
     System.Drawing.Image result = System.Drawing.Image.FromStream(memStream);
     memStream.Close();
     return result;
 }
Пример #16
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;
 }
Пример #17
0
        public void CloseAndFlush()
        {
            var memStream = new System.IO.MemoryStream();

            memStream.Close();
            memStream.Flush();
        }
Пример #18
0
        public void ProcessRequest(HttpContext context)
        {
            int NumCount = 5;//預設產生5位亂數
            if (!string.IsNullOrEmpty(context.Request.QueryString["NumCount"]))
            {//有指定產生幾位數

                //字串轉數字,轉型成功的話儲存到 NumCount,不成功的話,NumCount會是0
                Int32.TryParse(context.Request.QueryString["NumCount"].Replace("'", "''"), out NumCount);
            }
            if (NumCount == 0) NumCount = 5;
            //取得亂數
            string str_ValidateCode = this.GetRandomNumberString(NumCount);
            /*用於驗證的Session*/
            context.Session["ValidateNumber"] = str_ValidateCode;

            //取得圖片物件
            System.Drawing.Image image = this.CreateCheckCodeImage(context, str_ValidateCode);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            /*輸出圖片*/
            context.Response.Clear();
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(ms.ToArray());
            ms.Close();
        }
Пример #19
0
        public static string ZipCompress(this string value)
        {
            //Transform string into byte[]  
            byte[] byteArray = new byte[value.Length];
            int indexBA = 0;
            foreach (char item in value.ToCharArray())
            {
                byteArray[indexBA++] = (byte)item;
            }

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

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

            //Transform byte[] zip data to string
            byteArray = ms.ToArray();
            System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
            foreach (byte item in byteArray)
            {
                sB.Append((char)item);
            }
            ms.Close();
            sw.Dispose();
            ms.Dispose();
            return sB.ToString();
        }
Пример #20
0
		public ToolPolygon()
		{
            System.IO.MemoryStream ms = new System.IO.MemoryStream(Genetibase.NuGenAnnotation.Properties.Resources.Pencil);
            Cursor = new Cursor(ms);
            ms.Close();
			//Cursor = new Cursor(GetType(), "Pencil.cur");
		}
Пример #21
0
 private void Form1_Load(object sender, EventArgs e)
 {
     String pic = "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDABMNDxEPDBMREBEWFRMXHTAfHRsbHTsqLSMwRj5KSUU+RENNV29eTVJpU0NEYYRiaXN3fX59S12Jkoh5kW96fXj/2wBDARUWFh0ZHTkfHzl4UERQeHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHj/wAARCAAfACEDAREAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAQDBQb/xAAjEAACAgICAgEFAAAAAAAAAAABAgADBBESIRMxBSIyQXGB/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/APawEBAQEBAgy8i8ZTVV3UY6V1eU2XoWDDZB19S646Gz39w9fkKsW1r8Wm2yo1PYis1be0JG9H9QNYCAgc35Cl3yuVuJZl0cB41rZQa32dt2y6OuOiOxo61vsLcVblxaVyXD3hFFjL6La7I/sDWAgICAgICB/9k=";
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(Convert.FromBase64String(pic));
     this.pictureBox1.Image = new System.Drawing.Bitmap(memoryStream);
     memoryStream.Close();
 }
Пример #22
0
        public static string UnZipCompress(this string value)
        {
            //Transform string into byte[]
            byte[] byteArray = new byte[value.Length];
            int indexBA = 0;
            foreach (char item in value.ToCharArray())
            {
                byteArray[indexBA++] = (byte)item;
            }

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

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

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

            //Transform byte[] unzip data to string
            System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte);
            //Read the number of bytes GZipStream red and do not a for each bytes in
            //resultByteArray;
            for (int i = 0; i < rByte; i++)
            {
                sB.Append((char)byteArray[i]);
            }
            sr.Close();
            ms.Close();
            sr.Dispose();
            ms.Dispose();
            return sB.ToString();
        }
Пример #23
0
        private static void SendMessage(object radarData)
        {
            try
            {
                if (server == null || server.continueUpdate)
                {
                    server = new Server(Common.ServerPort);
                    server.Start();
                }
                var data = (radarData as RadarData);

                if (data == null) return;

                if (Common.IgnoreWoWWindowActive)
                {
                    data.IsWowWindowActive = true;
                }

                byte[] buffer = null;
                using (var ms = new System.IO.MemoryStream())
                {
                    BlackRain.Serialization.BinarySerializer.SerializeObject<RadarData>(ms, data);
                    buffer = ms.GetBuffer();
                    ms.Close();
                }
                server.SendMessage(buffer);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
        }
Пример #24
0
        public static void Thumbize(string pPage, string pThumb, Document document, Page page)
        {
            System.IO.MemoryStream cryptoStream = new System.IO.MemoryStream(Utility.Security.AES.DecryptStream(page.Token, System.IO.File.ReadAllBytes(System.IO.Path.Combine(pPage, page.Filename))).ToArray());
            using (var srcImage = System.Drawing.Image.FromStream(cryptoStream))
            {
                var newWidth = 300;
                var newHeight = 200;

                using (var newImage = new Bitmap(newWidth, newHeight))
                using (var graphics = Graphics.FromImage(newImage))
                {
                    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    graphics.DrawImage(srcImage, new System.Drawing.Rectangle(0, 0, newWidth, newHeight));

                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
                    parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                    System.Drawing.Imaging.ImageCodecInfo jpegEncoder = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.FormatDescription == "JPEG");
                    newImage.Save(ms, jpegEncoder, parms);
                    System.IO.File.WriteAllBytes(System.IO.Path.Combine(pThumb, string.Format("{0}.jpg", document.Id.ToString())), SoftFluent.Samples.GED.Utility.Security.AES.EncryptStream(document.Token, ms.ToArray()).ToArray());
                    ms.Close();
                }
            }
        }
Пример #25
0
        /// <summary>
        /// Converts a byte array to a bitmap
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static Bitmap GetBitmap(byte[] bytes)
        {
            if (bytes == null)
                return null;

            if (bytes.Length == 0)
                return null;

            System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
            Bitmap b = new Bitmap(stream);
            stream.Close();
            try
            {
                return (Bitmap)b.Clone();
            }
            catch(Exception ex)
            {
                Trace.WriteLine(ex);
            }
            finally
            {
                b.Dispose();
            }
            return null;
        }
        /// <summary>
        /// Get EditorsTable from server response.
        /// </summary>
        /// <param name="subResponse">The sub response from server.</param>
        /// <param name="site">Transfer ITestSite into this operation, for this operation to use ITestSite's function.</param>
        /// <returns>The instance of EditorsTable.</returns>
        public static EditorsTable GetEditorsTableFromResponse(FsshttpbResponse subResponse, ITestSite site)
        {
            if (subResponse == null || subResponse.DataElementPackage == null || subResponse.DataElementPackage.DataElements == null)
            {
                site.Assert.Fail("The parameter CellResponse is not valid, check whether the CellResponse::DataElementPackage or CellResponse::DataElementPackage::DataElements is null.");
            }

            foreach (DataElement de in subResponse.DataElementPackage.DataElements)
            {
                if (de.Data.GetType() == typeof(ObjectGroupDataElementData))
                {
                    ObjectGroupDataElementData ogde = de.Data as ObjectGroupDataElementData;

                    if (ogde.ObjectGroupData == null || ogde.ObjectGroupData.ObjectGroupObjectDataList.Count == 0)
                    {
                        continue;
                    }

                    for (int i = 0; i < ogde.ObjectGroupData.ObjectGroupObjectDataList.Count; i++)
                    {
                        if (IsEditorsTableHeader(ogde.ObjectGroupData.ObjectGroupObjectDataList[i].Data.Content.ToArray()))
                        {
                            string editorsTableXml = null;

                            // If the current object group object data is the header byte array 0x1a, 0x5a, 0x3a, 0x30, 0, 0, 0, 0, then the immediate following object group object data will contain the Editor table xml. 
                            byte[] buffer = ogde.ObjectGroupData.ObjectGroupObjectDataList[i + 1].Data.Content.ToArray();
                            System.IO.MemoryStream ms = null;
                            try
                            {
                                ms = new System.IO.MemoryStream();
                                ms.Write(buffer, 0, buffer.Length);
                                ms.Position = 0;
                                using (DeflateStream stream = new DeflateStream(ms, CompressionMode.Decompress))
                                {
                                    stream.Flush();
                                    byte[] decompressBuffer = new byte[buffer.Length * 3];
                                    stream.Read(decompressBuffer, 0, buffer.Length * 3);
                                    stream.Close();
                                    editorsTableXml = System.Text.Encoding.UTF8.GetString(decompressBuffer);
                                }

                                ms.Close();
                            }
                            finally
                            {
                                if (ms != null)
                                {
                                    ms.Dispose();
                                }
                            }

                            return GetEditorsTable(editorsTableXml);
                        }
                    }
                }
            }

            throw new InvalidOperationException("Cannot find any data group object data contain editor tables information.");
        }
 /// <summary>
 /// 写入数据区
 /// </summary>
 /// <param name="stream"></param>
 protected override void WriteBody(System.IO.Stream stream)
 {
     using (var ms = new System.IO.MemoryStream(Data))
     {
         CopyStream(ms, stream, Data.Length);
         ms.Close();
     }
 }
Пример #28
0
        public static void ExtractImagesFromPDF(string password, string key, string docPath, string pagePath, PageCollection pages)
        {
            Page page = null;
            // NOTE:  This will only get the first image it finds per page.
            PdfReader pdf = new PdfReader(Utility.Security.AES.DecryptFile(key, docPath));
            //RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(p);

            try
            {
                for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
                {
                    PdfDictionary pg = pdf.GetPageN(pageNumber);

                    // recursively search pages, forms and groups for images.
                    PdfObject obj = FindImageInPDFDictionary(pg);
                    if (obj != null)
                    {

                        int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                        PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
                        PdfStream pdfStrem = (PdfStream)pdfObj;
                        byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                        if ((bytes != null))
                        {
                            using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
                            {
                                memStream.Position = 0;
                                System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
                                // must save the file while stream is open.

                                page = new Page();
                                page.Order = pages.Count;
                                page.Save();
                                page.Token = Utility.Security.AES.GetToken(page.Id, password);
                                //string path = System.IO.Path.Combine(page.Filename, String.Format(@"{0}.jpg", pageNumber));
                                System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
                                parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                                System.Drawing.Imaging.ImageCodecInfo jpegEncoder = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.FormatDescription == "JPEG");
                                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                                img.Save(ms, jpegEncoder, parms);
                                System.IO.File.WriteAllBytes(System.IO.Path.Combine(pagePath, page.Filename), SoftFluent.Samples.GED.Utility.Security.AES.EncryptStream(page.Token, ms.ToArray()).ToArray());
                                ms.Close();
                                pages.Add(page);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                pdf.Close();
                //raf.Close();
            }
        }
Пример #29
0
 /// <summary>
 /// Serialize the object to xml
 /// </summary>
 /// <returns>String of xml representing the object</returns>
 public virtual string ToXml()
 {
     System.IO.MemoryStream stream = new System.IO.MemoryStream();
     System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(this.GetType());
     serializer.Serialize(stream, this);
     string xml = System.Text.Encoding.UTF8.GetString(stream.ToArray()).Replace(Environment.NewLine, "");
     stream.Close();
     return xml;
 }
Пример #30
0
 public static string MD5FromString(string text)
 {
     string result = "";
     System.Security.Cryptography.MD5 md5 = new MD5CryptoServiceProvider();
     System.IO.MemoryStream stream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(text));
     result = ByteToString(md5.ComputeHash(stream));
     stream.Close();
     return result;
 }
Пример #31
0
        public static Bitmap toBitmap(string base64image)
        {
            System.IO.MemoryStream streamBitmap = null;
            try
            {
                Byte[] bitmapData = Convert.FromBase64String(base64image);
                streamBitmap = new System.IO.MemoryStream(bitmapData);

                Bitmap bitmap = (Bitmap)Image.FromStream(streamBitmap);
                return(bitmap);
            }
            finally
            {
                streamBitmap?.Close();
                streamBitmap?.Dispose();
            }
        }
Пример #32
0
        private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (GetMapServiceDetailsFailed != null)
                {
                    GetMapServiceDetailsFailed(this, new ExceptionEventArgs(e.Error, e.UserState));
                }
                return;
            }

            if (string.IsNullOrEmpty(e.Result))
            {
                if (GetMapServiceDetailsFailed != null)
                {
                    GetMapServiceDetailsFailed(this, new ExceptionEventArgs(new Exception("Empty response"), e.UserState));
                }
                return;
            }

            MapServiceInfo mapServiceInfo = null;

            try
            {
                string json  = e.Result;
                byte[] bytes = Encoding.Unicode.GetBytes(json);
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes))
                {
                    DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(MapServiceInfo));
                    mapServiceInfo = dataContractJsonSerializer.ReadObject(memoryStream) as MapServiceInfo;
                    memoryStream.Close();
                }

                if (mapServiceInfo == null)
                {
                    if (GetMapServiceDetailsFailed != null)
                    {
                        GetMapServiceDetailsFailed(this, new ExceptionEventArgs(new Exception("Unable to deserialize response"), e.UserState));
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                if (GetMapServiceDetailsFailed != null)
                {
                    GetMapServiceDetailsFailed(this, new ExceptionEventArgs(ex, e.UserState));
                }
                return;
            }

            List <Resource> childResources = new List <Resource>();

            if (mapServiceInfo.Layers != null)
            {
                foreach (LayerInfo layerInfo in mapServiceInfo.Layers)
                {
                    if (layerInfo.SubLayerIds == null)
                    {
                        childResources.Add(new Resource()
                        {
                            DisplayName  = layerInfo.Name,
                            ResourceType = ResourceType.Layer,
                            Url          = string.Format("{0}/{1}", Uri, layerInfo.ID),
                        });
                    }
                    else
                    {
                        childResources.Add(new Resource()
                        {
                            DisplayName  = layerInfo.Name,
                            ResourceType = ResourceType.GroupLayer,
                            Url          = string.Format("{0}/{1}", Uri, layerInfo.ID),
                        });
                    }
                }
            }

            if (GetMapServiceDetailsCompleted != null)
            {
                GetMapServiceDetailsCompleted(this, new GetMapServiceDetailsCompletedEventArgs()
                {
                    ChildResources = childResources, MapServiceInfo = mapServiceInfo, UserState = e.UserState
                });
            }
        }
Пример #33
0
        private void GetDataFromServer(object obj)
        {
            NetSimplifyClient simplifyClient = new HslCommunication.Enthernet.NetSimplifyClient("118.24.36.220", 18467);

            HslCommunication.OperateResult <HslCommunication.NetHandle, string> read = simplifyClient.ReadCustomerFromServer(1000, HslCommunication.BasicFramework.SoftBasic.FrameworkVersion.ToString( ));
            if (!read.IsSuccess)
            {
                return;
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.Unicode.GetBytes(read.Content2));
            System.IO.StreamReader sr = new System.IO.StreamReader(ms, Encoding.Unicode);


            Dictionary <string, long> loginData = new Dictionary <string, long>( );

            while (true)
            {
                string city = sr.ReadLine( );
                if (city == null)
                {
                    break;
                }

                string count = sr.ReadLine( );
                loginData.Add(city, long.Parse(count));
            }
            sr.Close( );
            ms.Close( );


            List <dataMy> list = new List <dataMy>( );

            foreach (var m in loginData)
            {
                list.Add(new dataMy(m.Key, m.Value));
            }
            list.Sort( );
            list.Reverse( );

            // 统计省份功能
            string[] province = new string[]
            {
                "北京",
                "浙江",
                "河北",
                "山西",
                "内蒙",
                "辽宁",
                "吉林",
                "黑龙江",
                "江苏",
                "安徽",
                "福建",
                "江西",
                "山东",
                "河南",
                "湖北",
                "湖南",
                "广东",
                "广西",
                "海南",
                "四川",
                "贵州",
                "云南",
                "西藏",
                "陕西",
                "甘肃",
                "青海",
                "宁夏",
                "新疆",
                "台湾",
                "天津",
                "上海",
                "重庆",
                "香港",
                "澳门",
            };
            List <dataMy> shengfen = new List <dataMy>( );

            for (int i = 0; i < list.Count; i++)
            {
                string tmp = string.Empty;
                for (int j = 0; j < province.Length; j++)
                {
                    if (list[i].Key.Contains(province[j]))
                    {
                        tmp = province[j];
                    }
                    else
                    {
                        continue;
                    }
                }

                if (string.IsNullOrEmpty(tmp))
                {
                    continue;
                }
                dataMy dataMy = shengfen.Find(m => m.Key == tmp);
                if (dataMy == null)
                {
                    shengfen.Add(new dataMy(tmp, list[i].Value));
                }
                else
                {
                    dataMy.Value += list[i].Value;
                }
            }


            Invoke(new Action(() =>
            {
                long max = shengfen.Max(m => m.Value);
                for (int i = 0; i < shengfen.Count; i++)
                {
                    int color = 255 - (int)(shengfen[i].Value * 222 / max);
                    if (shengfen[i].Value > 0 && shengfen[i].Value < 10 && color < 5)
                    {
                        color = 5;
                    }
                    hslChinaMap1.SetProvinceBackColor(shengfen[i].Key, Color.FromArgb(color, 0, 0));
                }
            }));
        }
Пример #34
0
        public ActionResult PdfResultsView(string all)
        {
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                Document document = new Document(PageSize.A4, 10, 10, 10, 10);

                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                document.Open();
                Story         modelStory = new Story();
                DropdownModel model      = new DropdownModel();

                //Create a single column table
                var t = new PdfPTable(1);

                //Tell it to fill the page horizontally
                t.WidthPercentage = 100;

                //Create a single cell
                var c = new PdfPCell();

                //Tell the cell to vertically align in the middle
                c.VerticalAlignment = Element.ALIGN_MIDDLE;

                //Tell the cell to fill the page vertically
                c.MinimumHeight = document.PageSize.Height - (document.BottomMargin + document.TopMargin);

                //Create a test paragraph
                //var p = new Paragraph("                    EBook Custom Favorite Recipes from whatscookingtreasures.com");
                //Add it a couple of times
                //c.AddElement(p);

                var imagePath1             = Server.MapPath("~/content/album.jpg");
                iTextSharp.text.Image pic1 = iTextSharp.text.Image.GetInstance(imagePath1);

                c.AddElement(pic1);

                //Add the cell to the paragraph
                t.AddCell(c);

                //Add the table to the document
                document.Add(t);
                document.NewPage();



                string[] rowschosen = all.Split('|');
                int      length     = rowschosen.Length;

                for (int i = 0; i < length; i++)
                {
                    var        jatakaID     = Convert.ToInt16(rowschosen[i]);
                    GetLookups myGetLookups = new GetLookups();

                    modelStory = myGetLookups.GetSpecificStory(jatakaID, "ID");
                    var Stories = modelStory.Stories;

                    Paragraph para = new Paragraph(Stories);
                    para.Font = FontFactory.GetFont(FontFactory.HELVETICA, 14f);
                    document.Add(para);
                    if (i != length - 1)
                    {
                        document.NewPage();
                    }
                    document.NewPage();
                }

                //Phrase phrase = new Phrase("This is from Phrase.");
                //document.Add(phrase);

                //Paragraph para = new Paragraph("This is from paragraph.");
                //document.Add(para);

                //string text = "you are successfully created PDF file.";
                //Paragraph paragraph = new Paragraph();
                //paragraph.SpacingBefore = 10;
                //paragraph.SpacingAfter = 10;
                //paragraph.Alignment = Element.ALIGN_LEFT;
                ////paragraph.Font = FontFactory.GetFont(FontFactory.HELVETICA, 12f, BaseColor.GREEN);
                //paragraph.Font = FontFactory.GetFont(FontFactory.HELVETICA, 12f);
                //paragraph.Add(text);
                //document.Add(paragraph);

                document.Close();
                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
                Response.Clear();
                Response.ContentType = "application/pdf";

                string pdfName = "User";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + pdfName + ".pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer      = true;
                Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
                Response.Close();
            }

            //using (MemoryStream ms = new MemoryStream())
            //using (Document document = new Document(PageSize.A4, 25, 25, 30, 30))
            //using (PdfWriter writer = PdfWriter.GetInstance(document, ms))
            //{
            //    document.Open();

            //    document.NewPage();


            //    //Create a single column table
            //    var t = new PdfPTable(1);

            //    //Tell it to fill the page horizontally
            //    t.WidthPercentage = 100;

            //    //Create a single cell
            //    var c = new PdfPCell();

            //    //Tell the cell to vertically align in the middle
            //    c.VerticalAlignment = Element.ALIGN_MIDDLE;

            //    //Tell the cell to fill the page vertically
            //    c.MinimumHeight = document.PageSize.Height - (document.BottomMargin + document.TopMargin);

            //    //Create a test paragraph
            //    //var p = new Paragraph("                    EBook Custom Favorite Recipes from whatscookingtreasures.com");
            //    //Add it a couple of times
            //    //c.AddElement(p);

            //    var imagePath1 = Server.MapPath("~/images/worldmap3.jpg");
            //    iTextSharp.text.Image pic1 = iTextSharp.text.Image.GetInstance(imagePath1);
            //    c.AddElement(pic1);

            //    //Add the cell to the paragraph
            //    t.AddCell(c);

            //    //Add the table to the document
            //    document.Add(t);

            //    var rows = all;

            //    rows = all.Trim();

            //    if (rows.EndsWith("|"))
            //    {
            //        rows = rows.Remove(rows.Length - 1, 1);
            //    }
            //    //ViewData["all"] = rows;
            //    Story modelStory = new Story();
            //    DropdownModel model = new DropdownModel();


            //    string[] rowschosen = rows.Split('|');
            //    int length = rowschosen.Length;

            //    for (int i = 0; i < length; i++)
            //    {
            //        var jatakaID = Convert.ToInt16(rowschosen[i]);
            //        GetLookups myGetLookups = new GetLookups();

            //        modelStory = myGetLookups.GetSpecificStory(jatakaID);
            //        var Stories = modelStory.Stories;

            //        document.NewPage();
            //        //define a bold font to be used
            //        Font boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12);

            //        var phrase = new Phrase();
            //        phrase.Add(new Chunk(s.Title, boldFont));
            //        Paragraph paragraph1 = new Paragraph();

            //        paragraph1.Add(phrase);

            //        document.Add(paragraph1);

            //        PdfPTable table = new PdfPTable(2);
            //        table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;



            //        Paragraph paragraphBreak = new Paragraph();
            //        paragraphBreak.Add("   ");
            //        document.Add(paragraphBreak);
            //        //document.Add(paragraphBreak);



            //        string comments = Stories;
            //        //comments = HttpUtility.HtmlDecode(comments);

            //        if (comments.Length > 0)
            //        {
            //            StringWriter myWriter = new StringWriter();

            //            // Decode the encoded string.
            //            HttpUtility.HtmlDecode(comments, myWriter);
            //            comments = myWriter.ToString();

            //            MemoryStream memStream = new MemoryStream();
            //            TextReader xmlString = new StringReader(comments);
            //            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(comments);
            //            MemoryStream msComments = new MemoryStream(byteArray);
            //            XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, msComments, System.Text.Encoding.UTF8);
            //        }

            //        document.Add(paragraphBreak);
            //        //document.Add(paragraphBreak);


            //            document.Add(table);
            //            //document.Add(new Paragraph(IngredHTML));
            //        }



            //    }

            //    document.Close();
            //    writer.Close();
            //    ms.Close();
            //    Response.ContentType = "pdf/application";
            //    Response.AddHeader("content-disposition", "attachment;filename=whatscookingtreasures_PDF_document.pdf");
            //    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
            //}

            //return View("PdfResultsView");
            return(View());
        }
Пример #35
0
        public static void CreatePlayerBlackHole()
        {
            float     damage = (ModdedPlayer.Stats.spell_blackhole_damage + ModdedPlayer.Stats.spellFlatDmg * ModdedPlayer.Stats.spell_blackhole_damageScaling) * ModdedPlayer.Stats.TotalMagicDamageMultiplier;
            Transform t      = Camera.main.transform;

            Vector3 point = Vector3.zero;
            var     hits1 = Physics.RaycastAll(t.position, t.forward, 35f);

            foreach (var hit in hits1)
            {
                if (hit.transform.root != LocalPlayer.Transform.root)
                {
                    point = hit.point;
                    break;
                }
            }
            if (point == Vector3.zero)
            {
                point = LocalPlayer.Transform.position + t.forward * 30;
            }
            //RaycastHit[] hits = Physics.RaycastAll(Camera.main.transform.position,Camera.main.transform.forward, 160f);
            //for (int i = 0; i < hits.Length; i++)
            //{
            //    if (hits[i].transform.root != LocalPlayer.Transform.root)
            //{
            using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
            {
                using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                {
                    w.Write(3);
                    w.Write(1);
                    w.Write(point.x);
                    w.Write(point.y - 1);
                    w.Write(point.z);
                    w.Write(false);
                    w.Write(damage);
                    w.Write(ModdedPlayer.Stats.spell_blackhole_duration);
                    w.Write(ModdedPlayer.Stats.spell_blackhole_radius);
                    w.Write(ModdedPlayer.Stats.spell_blackhole_pullforce);
                    w.Write(ModdedPlayer.Stats.i_sparkOfLightAfterDark ? ModReferences.ThisPlayerID : "");
                    w.Close();
                }
                ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Everyone);
                answerStream.Close();
            }
            //        return;
            //    }
            //}
            //Vector3 pos = Camera.main.transform.position + Camera.main.transform.forward * 10;
            //using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
            //{
            //    using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
            //    {
            //        w.Write(3);
            //        w.Write(1);
            //        w.Write(pos.x);
            //        w.Write(pos.y);
            //        w.Write(pos.z);
            //        w.Write(false);
            //        w.Write(damage);
            //        w.Write(BLACKHOLE_duration);
            //        w.Write(BLACKHOLE_radius);
            //        w.Write(BLACKHOLE_pullforce);
            //    w.Close();
            //    }
            //    ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Everyone);
            //    answerStream.Close();
            //}
        }
Пример #36
0
        protected void btnExport_Click(object sender, EventArgs e)
        {
            //http://www.itnose.net/detail/476834.html
            //http://blog.csdn.net/gjban/article/details/39030669

            var list = GetData();

            NPOI.HSSF.UserModel.HSSFWorkbook book  = new NPOI.HSSF.UserModel.HSSFWorkbook(new System.IO.FileStream(Server.MapPath("~/template/template_workplan.xls"), System.IO.FileMode.Open, System.IO.FileAccess.Read));
            NPOI.SS.UserModel.ISheet         sheet = book.GetSheet("工作计划表");

            NPOI.SS.UserModel.ICellStyle style = book.CreateCellStyle();
            style.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            style.BorderTop         = NPOI.SS.UserModel.BorderStyle.Thin;
            style.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Thin;
            style.BorderRight       = NPOI.SS.UserModel.BorderStyle.Thin;
            style.WrapText          = true;
            style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;

            // 内容
            int i = 3;

            foreach (var o in list)
            {
                NPOI.SS.UserModel.IRow  row2  = sheet.CreateRow(i);
                NPOI.SS.UserModel.ICell cell0 = row2.CreateCell(0);
                cell0.CellStyle = style;
                cell0.SetCellValue(i - 2);
                NPOI.SS.UserModel.ICell cell1 = row2.CreateCell(1);
                cell1.CellStyle = style;
                cell1.SetCellValue(o.SheepNo);
                NPOI.SS.UserModel.ICell cell2 = row2.CreateCell(2);
                cell2.CellStyle = style;
                cell2.SetCellValue(o.Project.Name);
                NPOI.SS.UserModel.ICell cell3 = row2.CreateCell(3);
                cell3.CellStyle = style;
                cell3.SetCellValue(o.WorkRemark);
                NPOI.SS.UserModel.ICell cell4 = row2.CreateCell(4);
                cell4.CellStyle = style;
                cell4.SetCellValue(o.PlanTypeStr);
                NPOI.SS.UserModel.ICell cell5 = row2.CreateCell(5);
                cell5.CellStyle = style;
                cell5.SetCellValue(Common.St.ToDateTimeString(o.StartTime, "yyyy-MM-dd"));
                NPOI.SS.UserModel.ICell cell6 = row2.CreateCell(6);
                cell6.CellStyle = style;
                cell6.SetCellValue(Common.St.ToDateTimeString(o.RealStartTime, "yyyy-MM-dd"));
                NPOI.SS.UserModel.ICell cell7 = row2.CreateCell(7);
                cell7.CellStyle = style;
                cell7.SetCellValue(Common.St.ToDateTimeString(o.EndTime, "yyyy-MM-dd"));
                NPOI.SS.UserModel.ICell cell8 = row2.CreateCell(8);
                cell8.CellStyle = style;
                cell8.SetCellValue(Common.St.ToDateTimeString(o.RealEndTime, "yyyy-MM-dd"));
                NPOI.SS.UserModel.ICell cell9 = row2.CreateCell(9);
                cell9.CellStyle = style;
                cell9.SetCellValue(o.StateStr);
                NPOI.SS.UserModel.ICell cell10 = row2.CreateCell(10);
                cell10.CellStyle = style;
                cell10.SetCellValue(o.Needer.RealName);
                NPOI.SS.UserModel.ICell cell11 = row2.CreateCell(11);
                cell11.CellStyle = style;
                cell11.SetCellValue(o.Remark);
                i++;
            }

            // 写入到客户端
            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("工作计划表", System.Text.Encoding.UTF8)));
            Response.BinaryWrite(ms.ToArray());
            book = null;
            ms.Close();
            ms.Dispose();
        }
Пример #37
0
        public byte[] CreateCheckCode(int nLen, ref string strKey)
        {
            int nBmpWidth  = 13 * nLen + 15;  // 图片宽度,能容纳完
            int nBmpHeight = 25;

            // 定义一个 Bitmap
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(nBmpWidth, nBmpHeight);

            // 生成随机背景颜色
            int nRed, nGreen, nBlue;

            // 生成三元色[128 - 255]
            System.Random rd = new Random((int)System.DateTime.Now.Ticks);
            nRed   = rd.Next(255) % 128 + 128;
            nGreen = rd.Next(255) % 128 + 128;
            nBlue  = rd.Next(255) % 128 + 128;

            // 创建 Bitmap 的画布
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp);
            graph.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.AliceBlue), 0, 0, nBmpWidth, nBmpHeight);

            // 绘制干扰线条,采用比背景略深一些的颜色
            int nLines = 3;

            System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(nRed - 17, nGreen - 17, nBlue - 17), 2);
            for (int a = 0; a < nLines; a++)
            {
                // 随机位置、随机长度的直线
                int x1 = rd.Next(nBmpWidth);
                int y1 = rd.Next(nBmpHeight);
                int x2 = rd.Next(nBmpWidth);
                int y2 = rd.Next(nBmpHeight);
                graph.DrawLine(pen, x1, y1, x2, y2);
            }
            //画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = rd.Next(bmp.Width);
                int y = rd.Next(bmp.Height);

                bmp.SetPixel(x, y, System.Drawing.Color.FromArgb(rd.Next()));   // 像素点颜色
            }

            // 确定字体
            System.Drawing.Font font = new System.Drawing.Font("Courier New", 14 + rd.Next() % 4, System.Drawing.FontStyle.Bold);

            // 渐变画刷
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(
                new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);

            graph.DrawString(strKey, font, brush, 2, 2);

            // 输出字节流
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            bmp.Dispose();
            graph.Dispose();
            byte[] byteReturn = stream.ToArray();
            stream.Close();
            return(byteReturn);
        }
Пример #38
0
        public override void PreProcess(System.Net.Sockets.Socket socket, System.IO.Stream stream)
        {
            // Address:Port info.
            string localAddress  = "";
            int    localPort     = 0;
            string remoteAddress = "";
            int    remotePort    = 0;

            string start = System.DateTime.UtcNow.ToString();

            byte[]           request_bytes  = null;
            byte[]           response_bytes = null;
            System.Exception error          = null;

            System.IO.MemoryStream        requestStream  = new System.IO.MemoryStream();
            System.IO.MemoryStream        responseStream = new System.IO.MemoryStream();
            Bamboo.WebServer.TappedStream tappedStream   = new Bamboo.WebServer.TappedStream(stream, requestStream, responseStream);

            Bamboo.WebServer.HttpRequest  request  = new Bamboo.WebServer.HttpRequest();
            Bamboo.WebServer.HttpResponse response = new Bamboo.WebServer.HttpResponse();
            byte[] buffer = new byte[8192];

            try
            {
                // Address:Port info.
                string localEndPoint = socket.LocalEndPoint.ToString();
                int    index         = localEndPoint.LastIndexOf(":");
                localAddress = localEndPoint.Substring(0, index);
                localPort    = Int32.Parse(localEndPoint.Substring(index + 1));
                string remoteEndPoint = socket.RemoteEndPoint.ToString();
                index         = remoteEndPoint.LastIndexOf(":");
                remoteAddress = remoteEndPoint.Substring(0, index);
                remotePort    = Int32.Parse(remoteEndPoint.Substring(index + 1));

                socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.SendTimeout, 15000);
                socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReceiveTimeout, 15000);

                ReadRequest(socket, tappedStream, request, buffer);

                this._processor.Process(request, response);
                KeepCookies(request, response);
                WriteResponse(response, tappedStream);

                tappedStream.Flush();
                //TODO DELETE tappedStream.Close();
            }
            catch (System.Exception exception)
            {
                error = exception;
            }
            finally
            {
                if (buffer != null)
                {
                    buffer = null;
                }
                if (request != null)
                {
                    request = null;
                }
                if (response != null)
                {
                    response = null;
                }
            }

            requestStream.Flush();
            responseStream.Flush();

            request_bytes  = requestStream.ToArray();
            response_bytes = responseStream.ToArray();

            requestStream.Close();
            requestStream = null;

            responseStream.Close();
            responseStream = null;

            string end = System.DateTime.UtcNow.ToString();

            this.Log(localAddress, localPort, remoteAddress, remotePort, start, end, request_bytes, response_bytes, request, response, error);

            if (request != null)
            {
                request = null;
            }
            if (response != null)
            {
                response = null;
            }

            //TODO set everyting = null
        }
Пример #39
0
        public static void CastMagicArrow()
        {
            float damage = 55 + ModdedPlayer.instance.SpellDamageBonus * 3.2f + ModdedPlayer.instance.RangedDamageBonus / 2;

            damage = damage * ModdedPlayer.instance.SpellAMP * 2;
            if (MagicArrowCrit)
            {
                BashBleedDmg *= ModdedPlayer.instance.CritDamageBuff * 4;
            }
            Vector3 pos = Camera.main.transform.position;
            Vector3 dir = Camera.main.transform.forward;

            if (GameSetup.IsSinglePlayer || GameSetup.IsMpServer)
            {
                MagicArrow.Create(pos, dir, damage, ModReferences.ThisPlayerID, MagicArrowDuration, MagicArrowDoubleSlow, MagicArrowDmgDebuff);
                if (BoltNetwork.isRunning)
                {
                    using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                    {
                        using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                        {
                            w.Write(3);
                            w.Write(7);
                            w.Write(pos.x);
                            w.Write(pos.y);
                            w.Write(pos.z);
                            w.Write(dir.x);
                            w.Write(dir.y);
                            w.Write(dir.z);
                            w.Write(damage);
                            w.Write(ModReferences.ThisPlayerID);
                            w.Write(MagicArrowDuration);
                            w.Write(MagicArrowDoubleSlow);
                            w.Write(MagicArrowDmgDebuff);
                            w.Close();
                        }
                        ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Others);
                        answerStream.Close();
                    }
                }
            }
            else if (GameSetup.IsMpClient)
            {
                MagicArrow.CreateEffect(pos, dir, MagicArrowDmgDebuff, MagicArrowDuration);
                using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                {
                    using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                    {
                        w.Write(3);
                        w.Write(7);
                        w.Write(pos.x);
                        w.Write(pos.y);
                        w.Write(pos.z);
                        w.Write(dir.x);
                        w.Write(dir.y);
                        w.Write(dir.z);
                        w.Write(damage);
                        w.Write(ModReferences.ThisPlayerID);
                        w.Write(MagicArrowDuration);
                        w.Write(MagicArrowDoubleSlow);
                        w.Write(MagicArrowDmgDebuff);
                        w.Close();
                    }
                    ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Others);
                    answerStream.Close();
                }
            }
        }
Пример #40
0
        /// <summary>
        /// HttpWebRequest读取网页 字符集将自动匹配如果找不倒指定字符集,则使用utf-8
        /// </summary>
        /// <param name="url">url</param>
        /// <param name="parament">一个用于区分的参数 </param>
        private static string GetWeb(string url, string encoding)
        {
            string strHtmlContent = "";

            //字符集编码

            if (url.IndexOf("http") == -1)//如果米有HTTP
            {
                throw new Exception("请提供完整的HTTP地址");
            }
            System.Net.HttpWebRequest myrequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            myrequest.Timeout = 600000;//超时时间 10 分钟
            //设置没有缓存
            myrequest.Headers.Set("Pragma", "no-cache");
            System.IO.Stream           mystream   = new System.IO.MemoryStream();
            System.Net.HttpWebResponse myresponse = (System.Net.HttpWebResponse)myrequest.GetResponse();
            mystream = myresponse.GetResponseStream();
            //用于读取数据的内存流
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

            #region 自动判断编码字符集

            //查看流长时是不是有效数据
            int    len  = 0;
            byte[] buff = new byte[512];
            while ((len = mystream.Read(buff, 0, buff.Length)) > 0)
            {
                memoryStream.Write(buff, 0, len);
            }

            if (memoryStream.Length > 0)
            {
                //设置流指向头
                memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                int DetLen = 0;
                //编码字符体的buffer 默认需要4KB的数据
                byte[] DetectBuff = new byte[4096];
                //开始取得编码
                UniversalDetector Det = new UniversalDetector(null);
                //从当前流中读取块并写入到buff中
                while ((DetLen = memoryStream.Read(DetectBuff, 0, DetectBuff.Length)) > 0 && !Det.IsDone())
                {
                    Det.HandleData(DetectBuff, 0, DetectBuff.Length);
                }
                Det.DataEnd();
                //得到字符集合
                if (Det.GetDetectedCharset() != null)
                {
                    if (encoding == "")
                    {
                        //得到字符集
                        encoding = Det.GetDetectedCharset();
                    }
                }
                //设置流指向头
                memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
            }

            #endregion
            System.Text.Encoding   myencoding     = System.Text.Encoding.GetEncoding(encoding);
            System.IO.StreamReader mystreamreader = new System.IO.StreamReader(memoryStream, myencoding);
            strHtmlContent = mystreamreader.ReadToEnd();
            mystream.Close();
            mystreamreader.Dispose();
            mystream.Close();
            mystream.Dispose();
            return(strHtmlContent);
        }
        private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                OnGetMapServiceDetailsFailed(new ExceptionEventArgs(e.Error, e.UserState));
                return;
            }

            if (string.IsNullOrEmpty(e.Result))
            {
                OnGetMapServiceDetailsFailed(new ExceptionEventArgs(new Exception("Empty response"), e.UserState));
                return;
            }

            MapServiceInfo mapServiceInfo = null;

            try
            {
                string    json = e.Result;
                Exception ex   = Utils.CheckJsonForException(json);
                if (ex != null)
                {
                    OnGetMapServiceDetailsFailed(new ExceptionEventArgs(ex, e.UserState));
                    return;
                }
                byte[] bytes = Encoding.Unicode.GetBytes(json);
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes))
                {
                    DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(MapServiceInfo));
                    mapServiceInfo = dataContractJsonSerializer.ReadObject(memoryStream) as MapServiceInfo;
                    memoryStream.Close();
                }

                if (mapServiceInfo == null)
                {
                    OnGetMapServiceDetailsFailed(new ExceptionEventArgs(new Exception("Unable to deserialize response"), e.UserState));
                    return;
                }
            }
            catch (Exception ex)
            {
                OnGetMapServiceDetailsFailed(new ExceptionEventArgs(ex, e.UserState));
                return;
            }

            List <Resource> childResources = new List <Resource>();

            if (mapServiceInfo.Layers != null)
            {
                foreach (MapServiceLayerInfo layerInfo in mapServiceInfo.Layers)
                {
                    if (layerInfo.ParentLayerId != -1) // only had layers at the root of the map service node (no parent)
                    {
                        continue;
                    }
                    if (layerInfo.SubLayerIds == null)
                    {
                        childResources.Add(new Resource()
                        {
                            DisplayName  = layerInfo.Name,
                            ResourceType = ResourceType.Layer,
                            Url          = string.Format("{0}/{1}", Uri, layerInfo.ID),
                            Tag          = layerInfo.ID,
                        });
                    }
                    else
                    {
                        childResources.Add(new Resource()
                        {
                            DisplayName  = layerInfo.Name,
                            ResourceType = ResourceType.GroupLayer,
                            Url          = string.Format("{0}/{1}", Uri, layerInfo.ID),
                            Tag          = layerInfo.ID,
                        });
                    }
                }
            }

            // Workaround for the fact that DataContractJsonSerializer doesn't call the default contructor
            // http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
            if (mapServiceInfo.SpatialReference != null)
            {
                if (mapServiceInfo.SpatialReference.WKID == default(int))
                {
                    mapServiceInfo.SpatialReference.WKID = -1;
                }
            }

            OnGetMapServiceDetailsCompleted(new GetMapServiceDetailsCompletedEventArgs()
            {
                ChildResources = childResources, MapServiceInfo = mapServiceInfo, UserState = e.UserState
            });
        }
Пример #42
0
        public virtual void  TestIndexAndMerge()
        {
            System.IO.MemoryStream sw          = new System.IO.MemoryStream();
            System.IO.StreamWriter out_Renamed = new System.IO.StreamWriter(sw);

            Directory   directory = FSDirectory.Open(indexDir);
            IndexWriter writer    = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);

            SegmentInfo si1 = IndexDoc(writer, "test.txt");

            PrintSegment(out_Renamed, si1);

            SegmentInfo si2 = IndexDoc(writer, "test2.txt");

            PrintSegment(out_Renamed, si2);
            writer.Close();

            SegmentInfo siMerge = Merge(si1, si2, "merge", false);

            PrintSegment(out_Renamed, siMerge);

            SegmentInfo siMerge2 = Merge(si1, si2, "merge2", false);

            PrintSegment(out_Renamed, siMerge2);

            SegmentInfo siMerge3 = Merge(siMerge, siMerge2, "merge3", false);

            PrintSegment(out_Renamed, siMerge3);

            directory.Close();
            out_Renamed.Close();
            sw.Close();
            System.String multiFileOutput = System.Text.ASCIIEncoding.ASCII.GetString(sw.ToArray());
            //System.out.println(multiFileOutput);

            sw          = new System.IO.MemoryStream();
            out_Renamed = new System.IO.StreamWriter(sw);

            directory = FSDirectory.Open(indexDir);
            writer    = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);

            si1 = IndexDoc(writer, "test.txt");
            PrintSegment(out_Renamed, si1);

            si2 = IndexDoc(writer, "test2.txt");
            PrintSegment(out_Renamed, si2);
            writer.Close();

            siMerge = Merge(si1, si2, "merge", true);
            PrintSegment(out_Renamed, siMerge);

            siMerge2 = Merge(si1, si2, "merge2", true);
            PrintSegment(out_Renamed, siMerge2);

            siMerge3 = Merge(siMerge, siMerge2, "merge3", true);
            PrintSegment(out_Renamed, siMerge3);

            directory.Close();
            out_Renamed.Close();
            sw.Close();
            System.String singleFileOutput = System.Text.ASCIIEncoding.ASCII.GetString(sw.ToArray());

            Assert.AreEqual(multiFileOutput, singleFileOutput);
        }
Пример #43
0
        static void Main(string[] args)
        {
            System.Net.IPAddress l_ip =
                System.Net.IPAddress.Parse("127.0.0.1");

            int l_port = 2001;

            System.Net.Sockets.TcpListener l_listener =
                new System.Net.Sockets.TcpListener(l_ip, l_port);

            l_listener.Start();

            Console.WriteLine("Listenを開始しました({0} : {1})",
                              ((System.Net.IPEndPoint)l_listener.LocalEndpoint).Address,
                              ((System.Net.IPEndPoint)l_listener.LocalEndpoint).Port);

            System.Net.Sockets.TcpClient l_client =
                l_listener.AcceptTcpClient();

            Console.WriteLine("client({0} : {1})と接続しました",
                              ((System.Net.IPEndPoint)l_client.Client.RemoteEndPoint).Address,
                              ((System.Net.IPEndPoint)l_client.Client.RemoteEndPoint).Port);

            System.Net.Sockets.NetworkStream l_ns = l_client.GetStream();

            l_ns.ReadTimeout  = 10000;
            l_ns.WriteTimeout = 10000;

            System.Text.Encoding l_enc = System.Text.Encoding.UTF8;

            bool l_disconnected = false;

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

            byte[] l_resBytes = new byte[256];
            int    l_resSize  = 0;

            do
            {
                l_resSize = l_ns.Read(l_resBytes, 0, l_resBytes.Length);
                if (l_resSize == 0)
                {
                    l_disconnected = true;
                    Console.WriteLine("clientが切断しました");
                    break;
                }
                l_ms.Write(l_resBytes, 0, l_resSize);
            } while (l_ns.DataAvailable || l_resBytes[l_resSize - 1] != '\n');

            string l_resMsg = l_enc.GetString(l_ms.GetBuffer(), 0, (int)l_ms.Length);

            l_ms.Close();

            l_resMsg = l_resMsg.TrimEnd('\n');
            Console.WriteLine(l_resMsg);

            if (!l_disconnected)
            {
                string l_sendMsg   = l_resMsg.Length.ToString();
                byte[] l_sendBytes = l_enc.GetBytes(l_sendMsg + '\n');
                Console.WriteLine(l_sendMsg);
            }

            l_ns.Close();
            l_client.Close();
            Console.WriteLine("clientとの接続を閉じました");

            l_listener.Stop();
            Console.WriteLine("Listenerを閉じました。");

            Console.ReadLine();
        }
Пример #44
0
        /// <summary>
        /// 生成图片验证码
        /// </summary>
        /// <param name="nLen">验证码的长度</param>
        /// <param name="strKey">输出参数,验证码的内容</param>
        /// <param name="PureBlackBackGround">是否黑白色</param>
        /// <returns>图片字节流</returns>
        private byte[] GenerateVerifyImage(int keyLength,
                                           ref string imageCodeKey,
                                           bool pureBlackBackGround,
                                           bool drawDisturbLine)
        {
            int bmpWidth  = 26 * keyLength + 8;
            int bmpHeight = 20;

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(bmpWidth, bmpHeight);

            // 1. 生成随机背景颜色
            int red, green, blue;  // 背景的三元色

            System.Random rd = new Random((int)System.DateTime.Now.Ticks);
            if (!pureBlackBackGround)
            {
                red   = rd.Next(255) % 128 + 128;
                green = rd.Next(255) % 128 + 128;
                blue  = rd.Next(255) % 128 + 128;
            }
            else
            {
                red   = 255;
                green = 255;
                blue  = 255;
            }

            // 2. 填充位图背景
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp);
            graph.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(red, green, blue))
                                , 0
                                , 0
                                , bmpWidth
                                , bmpHeight);


            // 3. 绘制干扰线条,采用比背景略深一些的颜色
            if (drawDisturbLine)
            {
                int lines = 3;
                System.Drawing.Pen pen;
                if (!pureBlackBackGround)
                {
                    pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(red - 17, green - 17, blue - 17), 1);
                }
                else
                {
                    pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(12, 12, 12), 1);
                }
                for (int a = 0; a < lines; a++)
                {
                    int x1 = rd.Next() % bmpWidth;
                    int y1 = rd.Next() % bmpHeight;
                    int x2 = rd.Next() % bmpWidth;
                    int y2 = rd.Next() % bmpHeight;
                    graph.DrawLine(pen, x1, y1, x2, y2);
                }
            }

            // 采用的字符集,可以随即拓展,并可以控制字符出现的几率
            string codeScop = "ABCDEFGHJKLMNPRSTUVWXYZ23456789";

            // 4. 循环取得字符,并绘制
            string result = "";

            for (int i = 0; i < keyLength; i++)
            {
                int coordinateX = (i * 26 + rd.Next(3));
                int coordinateY = rd.Next(2) + 1;

                // 确定字体
                System.Drawing.Font font = new System.Drawing.Font("Courier New",
                                                                   13 + rd.Next() % 4,
                                                                   System.Drawing.FontStyle.Bold);
                char currentChar = codeScop[rd.Next(codeScop.Length)];  // 随机获取字符
                result += currentChar.ToString();

                // 绘制字符
                if (!pureBlackBackGround)
                {
                    graph.DrawString(currentChar.ToString(),
                                     font,
                                     new SolidBrush(System.Drawing.Color.FromArgb(red - 60 + coordinateY * 3,
                                                                                  green - 60 + coordinateY * 3,
                                                                                  blue - 40 + coordinateY * 3)),
                                     coordinateX,
                                     coordinateY);
                }
                else
                {
                    graph.DrawString(currentChar.ToString(),
                                     font,
                                     new SolidBrush(System.Drawing.Color.FromArgb(0, 0, 0)),
                                     coordinateX,
                                     coordinateY);
                }
            }

            // 5. 输出字节流
            System.IO.MemoryStream bstream = new System.IO.MemoryStream();
            //bmp = TwistImage(bmp, true, 2.0, 2.0);
            bmp.Save(bstream, System.Drawing.Imaging.ImageFormat.Jpeg);
            bmp.Dispose();
            graph.Dispose();

            imageCodeKey = result;
            byte[] byteReturn = bstream.ToArray();
            bstream.Close();

            return(byteReturn);
        }
Пример #45
0
        private void Click_EXCEL_EXPORT_Button()
        {
            try
            {
                DataTable dt = this._dtChartData.Copy();
                if (dt.Columns.Contains(Definition.CHART_COLUMN.TIME2))
                {
                    dt.Columns.Remove(Definition.CHART_COLUMN.TIME2);
                }
                if (dt.Columns.Contains("TIME"))
                {
                    dt.Columns.Remove("TIME");
                }
                if (dt.Columns.Contains(CommonChart.COLUMN_NAME_SEQ_INDEX))
                {
                    dt.Columns.Remove(CommonChart.COLUMN_NAME_SEQ_INDEX);
                }

                this.bSpread1.ActiveSheet.RowCount    = 0;
                this.bSpread1.ActiveSheet.ColumnCount = 0;
                this.bSpread1.ClearHead();
                this.bSpread1.AddHeadComplete();
                this.bSpread1.UseSpreadEdit       = false;
                this.bSpread1.AutoGenerateColumns = true;
                this.bSpread1.DataSource          = dt;
                this.bSpread1_Sheet1.SheetName    = this.bTChrt_RawData.Name;

                string file     = "";
                bool   bProtect = this.bSpread1.ActiveSheet.Protect;

                this.bSpread1.ActiveSheet.Protect = false;

                SaveFileDialog openDlg = new SaveFileDialog();
                openDlg.Filter          = "Excel Files (*.xls)|*.xls";
                openDlg.FileName        = "";
                openDlg.DefaultExt      = ".xls";
                openDlg.CheckFileExists = false;
                openDlg.CheckPathExists = true;

                DialogResult res = openDlg.ShowDialog();

                if (res != DialogResult.OK)
                {
                    return;
                }

                file = openDlg.FileName;

                FarPoint.Win.Spread.SheetView spread_Sheet1 = new FarPoint.Win.Spread.SheetView();
                spread_Sheet1.SheetName = "_ExcelExportSheet";

                FarPoint.Win.Spread.FpSpread spread = new FarPoint.Win.Spread.FpSpread();

                spread.Sheets.Add(spread_Sheet1);
                spread_Sheet1.Visible = true;
                spread.ActiveSheet    = spread_Sheet1;

                byte[] buffer = null;
                System.IO.MemoryStream stream = null;
                this.bSpread1.SetFilterVisible(false);

                try
                {
                    stream = new System.IO.MemoryStream();
                    this.bSpread1.Save(stream, false);
                    buffer = stream.ToArray();
                    stream.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                        stream = null;
                    }
                }

                stream = new System.IO.MemoryStream(buffer);
                spread.Open(stream);

                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }

                for (int i = spread.ActiveSheet.Columns.Count - 1; i >= 0; i--)
                {
                    if (!spread.ActiveSheet.Columns[i].Visible)
                    {
                        spread.ActiveSheet.Columns[i].Remove();
                    }
                }

                spread.SaveExcel(file, FarPoint.Win.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly);
                this.bSpread1.ActiveSheet.Protect = bProtect;

                string strMessage = "It was saved successfully. Do you open saved file?";

                DialogResult result = MessageBox.Show(strMessage, "Open", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Classes\Applications\EXCEL.EXE");

                    if (key == null)
                    {
                        MSGHandler.DisplayMessage(MSGType.Error, "SPC_INFO_NEED_MS_OFFICE", null, null);
                    }
                    else
                    {
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo.FileName = file;
                        process.Start();
                    }
                }
                //this.bSpread1.Export(false);
            }
            catch (Exception ex)
            {
                MSGHandler.DisplayMessage(MSGType.Error, ex.ToString());
                EESUtil.DebugLog("BTeeChart", "ExportDataForExcel", ex);
            }
        }
Пример #46
0
        private void Setup()
        {
            try
            {
                if (BoltNetwork.isRunning)
                {
                    if (entity == null)
                    {
                        entity = transform.root.GetComponentInChildren <BoltEntity>();
                    }
                    if (entity == null)
                    {
                        entity = HealthScript.entity;
                    }
                    if (entity == null)
                    {
                        entity = transform.root.GetComponent <BoltEntity>();
                    }
                    EnemyManager.AddHostEnemy(this);
                }
                if (!EnemyManager.enemyByTransform.ContainsKey(transform))
                {
                    EnemyManager.enemyByTransform.Add(this.transform, this);
                }
            }
            catch (Exception ex)
            {
                ModAPI.Log.Write(ex.ToString());
            }

            //Assiging base health, if new enemy
            if (baseHealth == 0)
            {
                baseHealth = HealthScript.Health;
            }
            else                //reverting health to base health if reused enemy (in case enemies are pooled)
            {
                HealthScript.Health = baseHealth;
            }

            StopAllCoroutines();

            Steadfast          = 100;
            slows              = new Dictionary <int, EnemyDebuff>();
            dmgTakenDebuffs    = new Dictionary <int, EnemyDebuff>();
            dmgDealtDebuffs    = new Dictionary <int, EnemyDebuff>();
            FireDamageDebuffs  = new Dictionary <int, EnemyDebuff>();
            DamageOverTimeList = new List <DoT>();
            abilities          = new List <Abilities>();

            bool isElite = (Random.value < 0.1 || (AIScript.creepy_boss && !AIScript.girlFullyTransformed) || ModSettings.difficulty == ModSettings.Difficulty.Hell) && ModSettings.AllowElites;

            SetType(ref isElite);


            //picking abilities
            if (isElite)
            {
                int abilityAmount = (int)ModSettings.difficulty > (int)ModSettings.Difficulty.Veteran ? Random.Range(3, 7) : 2;
                if (AIScript.creepy_boss)
                {
                    abilityAmount = 10;
                }                   //Megan boss always has abilities, a lot of them.

                int   i            = 0;
                Array abilityArray = Enum.GetValues(typeof(Abilities));

                //Determining if enemy is Elite, Miniboss or Boss type of enemy
                if (abilityAmount > 6 && Random.value < 0.1f)
                {
                    _rarity = EnemyRarity.Boss;
                    abilities.Add(Abilities.BossSteadfast);
                }
                else if (abilityAmount > 4 && Random.value < 0.25f)
                {
                    abilities.Add(Abilities.EliteSteadfast);
                    _rarity = EnemyRarity.Miniboss;
                }
                else
                {
                    _rarity = EnemyRarity.Elite;
                }

                if (AIScript.creepy_boss && !AIScript.girlFullyTransformed)                    //Force adding BossSteadfast to Megan
                {
                    abilities.Clear();
                    _rarity = EnemyRarity.Boss;
                    abilities.Add(Abilities.BossSteadfast);
                }

                //Trial and error method of picking abilities
                while (i < abilityAmount)
                {
                    bool      canAdd = true;
                    Abilities ab     = (Abilities)abilityArray.GetValue(Random.Range(0, abilityArray.Length));
                    if (ab == Abilities.Steadfast || ab == Abilities.EliteSteadfast || ab == Abilities.BossSteadfast)
                    {
                        if (abilities.Contains(Abilities.Steadfast) || abilities.Contains(Abilities.EliteSteadfast) || abilities.Contains(Abilities.BossSteadfast))
                        {
                            canAdd = false;
                        }
                    }
                    else if (ab == Abilities.Tiny || ab == Abilities.Gargantuan)
                    {
                        if (AIScript.creepy_boss && ab == Abilities.Tiny)
                        {
                            canAdd = false;
                        }
                        else if (abilities.Contains(Abilities.Gargantuan) || abilities.Contains(Abilities.Tiny))
                        {
                            canAdd = false;
                        }
                    }
                    else if (ab == Abilities.Undead && !(AIScript.creepy || AIScript.creepy_fat))
                    {
                        canAdd = false;
                    }
                    else if (ab == Abilities.ArcaneCataclysm || ab == Abilities.BlackHole || ab == Abilities.FireCataclysm || ab == Abilities.Meteor)
                    {
                        if ((int)ModSettings.difficulty < (int)ModSettings.Difficulty.Master)
                        {
                            canAdd = false;
                        }
                    }
                    if (abilities.Contains(ab))
                    {
                        canAdd = false;
                    }
                    if (canAdd)
                    {
                        i++;
                        abilities.Add(ab);
                    }
                }
            }
            else
            {
                _rarity = EnemyRarity.Normal;
            }

            SetLevel();
            RollName(isElite);
            setupDifficulty = ModSettings.difficulty;
            //Assigning rest of stats
            int dif = (int)setupDifficulty;

            DamageMult     = level < 67 ? ((31f - 0.286f * (level - 20f)) * (level - 5f) + 3.5f) * (level - 1f) + 11 : Mathf.Pow(level - 60, 2.61f) * 600;
            armor          = Mathf.FloorToInt(Random.Range(Mathf.Pow(level, 2.4f) * 0.36f + 1, Mathf.Pow(level, 2.45f) + 20) * ModSettings.EnemyArmorMultiplier);
            armor         *= dif / 2 + 1;
            armorReduction = 0;
            extraHealth    = (Mathf.Sqrt(HealthScript.Health) + 40) * Mathf.Pow(level, 2.22f) / 6f;
            extraHealth   *= (level / 50) + 0.4f;

            AnimSpeed           = 0.93f + (float)level / 175;
            HealthScript.Health = int.MaxValue;

            extraHealth *= ModSettings.EnemyHealthMultiplier;
            DamageMult  *= ModSettings.EnemyDamageMultiplier;
            AnimSpeed   *= ModSettings.EnemySpeedMultiplier;

            if (_rarity != EnemyRarity.Normal)
            {
                armor *= 2;
            }
            //Extra health for boss type enemies
            switch (_rarity)
            {
            case EnemyRarity.Elite:
                extraHealth *= 5;

                break;

            case EnemyRarity.Miniboss:
                extraHealth *= 10;

                break;

            case EnemyRarity.Boss:
                extraHealth *= 20;
                if (!abilities.Contains(Abilities.Tiny))
                {
                    gameObject.transform.localScale *= 1.1f;
                }

                break;
            }
            if (level > 25)
            {
                extraHealth *= 2.15f;
            }
            if (level > 50)
            {
                extraHealth *= 2f;
            }
            if (level > 100)
            {
                extraHealth *= 3.4f;
            }
            if (level > 200)
            {
                extraHealth *= 2.5f;
            }
            if (level > 300)
            {
                extraHealth *= 3.2f;
            }
            //Applying some abilities
            if (abilities.Contains(Abilities.Gargantuan))
            {
                armor       *= 3;
                extraHealth *= 2.5f;
                DamageMult  *= 2.5f;
                AnimSpeed   /= 1.5f;
                BroadcastMessage("SetTriggerScale", 2.5f, SendMessageOptions.DontRequireReceiver);
            }
            else if (abilities.Contains(Abilities.Tiny))
            {
                AnimSpeed  *= 1.1f;
                DamageMult *= 1.2f;
                BroadcastMessage("SetTriggerScale", 5f, SendMessageOptions.DontRequireReceiver);
            }
            else
            {
                BroadcastMessage("SetTriggerScale", 1.6f, SendMessageOptions.DontRequireReceiver);
            }
            if (abilities.Contains(Abilities.Steadfast))
            {
                Steadfast = 6;
                armor    *= 2;
            }
            if (abilities.Contains(Abilities.EliteSteadfast))
            {
                Steadfast = 4f;
                armor    *= 2;
            }
            if (abilities.Contains(Abilities.BossSteadfast))
            {
                Steadfast = 1f;
                armor    *= 2;
            }
            if (abilities.Contains(Abilities.ExtraHealth))
            {
                extraHealth *= 4;
            }
            if (abilities.Contains(Abilities.ExtraDamage))
            {
                DamageMult *= 5f;
            }
            if (abilities.Contains(Abilities.RainEmpowerment))
            {
                prerainDmg   = DamageMult;
                prerainArmor = armor;
            }
            if (abilities.Contains(Abilities.Juggernaut))
            {
                CCimmune   = true;
                AnimSpeed /= 1.15f;
            }
            if (abilities.Contains(Abilities.Avenger))
            {
                if (avengerability == null)
                {
                    avengerability = gameObject.AddComponent <Avenger>();
                }
                avengerability.progression = this;
                avengerability.Stacks      = 0;
            }
            else if (avengerability != null)
            {
                Destroy(avengerability);
            }
            if (abilities.Contains(Abilities.Radiance))
            {
                float aurDmg = DamageMult / 20;
                FireAura.Cast(gameObject, aurDmg);
                if (BoltNetwork.isRunning)
                {
                    using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                    {
                        using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                        {
                            w.Write(8);
                            w.Write(2);
                            w.Write(entity.networkId.PackedValue);
                            w.Write(aurDmg);
                        }
                        Network.NetworkManager.SendLine(answerStream.ToArray(), Network.NetworkManager.Target.Clients);
                        answerStream.Close();
                    }
                }

                InvokeRepeating("SendFireAura", 20, 30);
            }
            else
            {
                var aura = gameObject.GetComponent <FireAura>();
                if (aura != null)
                {
                    Destroy(aura);
                }
            }
            //Clamping Health
            try
            {
                maxHealth = extraHealth;
                HealthScript.maxHealthFloat = maxHealth;
                HealthScript.Health         = (int)Mathf.Min(maxHealth, int.MaxValue);
                extraHealth = Mathf.Max(0, maxHealth - HealthScript.Health);
                ClampHealth();
                armor = Mathf.Min(armor, int.MaxValue - 5);
                if (armor < 0)
                {
                    armor = int.MaxValue;
                }
                DebuffDmgMult  = 1;
                DualLifeSpend  = false;
                setupComplete  = true;
                OnDieCalled    = false;
                BaseDamageMult = Mathf.Abs(DamageMult);
                BaseAnimSpeed  = AnimSpeed;
                knockbackSpeed = 0;
            }
            catch (Exception e)
            {
                CotfUtils.Log(e.Message);
            }

            AssignBounty();

            steadfastCap = Mathf.Max(Steadfast * 0.01f * maxHealth, 1f);
            if (steadfastCap < 1)             // Making sure the enemy can be killed
            {
                steadfastCap = 1;
            }

            CreationTime = Time.time;

            if (BoltNetwork.isRunning)
            {
                ulong id = entity.networkId.PackedValue;
                color = normalColor;
                SyncAppearance(id);
            }
        }
Пример #47
0
        public static void DoParry(Vector3 parryPos)
        {
            if (Parry)
            {
                BuffDB.AddBuff(6, 61, 1, ParryBuffDuration);
                float dmg = ParryDamage + ModdedPlayer.instance.SpellDamageBonus + ModdedPlayer.instance.MeleeDamageBonus;
                dmg *= ModdedPlayer.instance.SpellDamageAmplifier * 1.2f;

                float heal = ParryHeal + ModdedPlayer.instance.SpellDamageBonus / 6 + ModdedPlayer.instance.LifeRegen + ModdedPlayer.instance.LifeOnHit * 2;
                heal *= ModdedPlayer.instance.HealingMultipier * (1 + ModdedPlayer.instance.HealthRegenPercent);
                LocalPlayer.Stats.HealthTarget += heal;
                ParrySound.Play(parryPos);
                float energy = ParryEnergy * ModdedPlayer.instance.StaminaAndEnergyRegenAmp + ModdedPlayer.instance.EnergyOnHit * 2 + ModdedPlayer.instance.MaxEnergy / 12.5f;
                LocalPlayer.Stats.Energy  += energy;
                LocalPlayer.Stats.Stamina += energy;
                if (ParryDmgBonus > 0)
                {
                    float f = dmg * ParryDmgBonus;
                    ModdedPlayer.instance.ParryCounterStrikeDamage += f;
                    BuffDB.AddBuff(23, 88, f, 20);
                }

                if (GameSetup.IsMpClient)
                {
                    if (BoltNetwork.isRunning)
                    {
                        using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                        {
                            using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                            {
                                w.Write(3);
                                w.Write(13);
                                w.Write(parryPos.x);
                                w.Write(parryPos.y);
                                w.Write(parryPos.z);
                                w.Write(ParryRadius);
                                w.Write(ParryIgnites);
                                w.Write(dmg);
                                w.Close();
                            }
                            ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.OnlyServer);
                            answerStream.Close();
                        }
                    }
                }
                else
                {
                    DamageMath.DamageClamp(dmg, out int d, out int r);
                    var hits = Physics.SphereCastAll(parryPos, ParryRadius, Vector3.one);
                    for (int i = 0; i < hits.Length; i++)
                    {
                        if (hits[i].transform.CompareTag("enemyCollide"))
                        {
                            for (int a = 0; a < r; a++)
                            {
                                hits[i].transform.SendMessageUpwards("Hit", d, SendMessageOptions.DontRequireReceiver);
                                if (ParryIgnites)
                                {
                                    hits[i].transform.SendMessageUpwards("Burn", SendMessageOptions.DontRequireReceiver);
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #48
0
 public bool PickUp()
 {
     if (item.PickUpAll)
     {
         if (!GameSetup.IsMpClient)
         {
             if (Player.Inventory.Instance.AddItem(item, amount))
             {
                 using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                 {
                     using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                     {
                         w.Write(4);
                         w.Write(ID);
                         w.Close();
                     }
                     ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Everyone);
                     answerStream.Close();
                 }
                 PickUpManager.RemovePickup(ID);
                 Destroy(gameObject);
                 return(true);
             }
         }
         else if (Player.Inventory.Instance.HasSpaceFor(item, amount))
         {
             using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
             {
                 using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                 {
                     w.Write(25);
                     w.Write(ID);
                     w.Write(amount);
                     w.Write(ModReferences.ThisPlayerID);
                     w.Close();
                 }
                 ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.OnlyServer);
                 answerStream.Close();
             }
         }
     }
     else
     {
         if (!GameSetup.IsMpClient)
         {
             if (Player.Inventory.Instance.AddItem(item))
             {
                 amount--;
                 if (amount <= 0)
                 {
                     using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                     {
                         using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                         {
                             w.Write(4);
                             w.Write(ID);
                             w.Close();
                         }
                         ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Everyone);
                         answerStream.Close();
                     }
                     PickUpManager.RemovePickup(ID);
                     Destroy(gameObject);
                 }
                 return(true);
             }
         }
         else if (Player.Inventory.Instance.HasSpaceFor(item))
         {
             using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
             {
                 using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                 {
                     w.Write(25);
                     w.Write(ID);
                     w.Write(1);
                     w.Write(ModReferences.ThisPlayerID);
                     w.Close();
                 }
                 ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.OnlyServer);
                 answerStream.Close();
             }
         }
     }
     return(false);
 }
Пример #49
0
        public void ProcessRequest(HttpContext context)
        {
            string nod  = context.Request.Params["node"]; // IPA@123 RUBR@123 IPA@123[1]  RUBR@435653[3]
            tNode  node = new tNode(nod);

            if (node.nodeId == -1 || node.nodeId == 0)
            {
                return;
            }
            string nodeRaw = context.Request.Form["node"];

            if (context.Application[TREE_KEY] == null)
            {
                InitializeTreeStore(node.nodeId.ToString());
            }

            List <SimpleTreeItem> xDoc = (List <SimpleTreeItem>)context.Application[TREE_KEY];

            if (xDoc == null || xDoc.Count == 0)
            {
                throw new InvalidOperationException("Errore nel recupero dell'ente");
            }

            if (xDoc.SingleOrDefault(e => e.Value.Equals(node.nodeId.ToString())) == null)
            {
                InitializeTreeStore(node.nodeId.ToString());
                xDoc = (List <SimpleTreeItem>)context.Application[TREE_KEY];
            }

            IEnumerable <HierarchyNode <SimpleTreeItem> > hl = null;
            IEnumerable <SimpleTreeItem> ll = null;
            Func <List <SimpleTreeItem>, SimpleTreeItem> getRoot = l => l.FirstOrDefault(x => !l.Select(y => y.Value).Contains(x.Padre));

            try
            {
                //provo prima a prendere gli item dalla memoria
                if (node.nodeId > -1)
                {
                    ll = xDoc.Where(e => e.Padre.Equals(node.nodeId.ToString()));
                }
                else
                {
                    ll = xDoc.Where(e => String.IsNullOrEmpty(e.Padre));
                }

                if (node.virtualNode)
                {
                    ll = ll.Skip((node.virtualPager - 1) * PACK_SIZE).Take(PACK_SIZE);
                }

                JSONTreeNode[] nodes = null;
                //se non trova figli prova a caricarli dalla banca dati
                if (ll.Count() == 0)
                {
                    if (nodeRaw == ROOT_NODE)
                    {
                        hl    = xDoc.AsHierarchy(e => e.Value, e => e.Padre, e => e.Text, getRoot(xDoc).Value);
                        nodes = ConvertToJSON(hl);
                    }
                    else
                    {
                        RubricaEntitaService  rubrentitaService = new RubricaEntitaService();
                        List <SimpleTreeItem> tree = (List <SimpleTreeItem>)rubrentitaService.GetRubricaEntitaTreeByIdPadre(node.nodeId);
                        if (tree != null && tree.Count > 0)
                        {
                            AppendChildren(tree);
                        }
                        xDoc  = (List <SimpleTreeItem>)context.Application[TREE_KEY];
                        hl    = xDoc.AsHierarchy(e => e.Value, e => e.Padre, e => e.Text, node.nodeId.ToString());
                        nodes = ConvertToJSON(hl.ElementAt(0).ChildNodes);
                    }
                }
                else
                {
                    if (node.nodeId > -1)
                    {
                        ll = ll.Union(xDoc.Where(x => x.Value.Equals(node.nodeId.ToString())));
                        hl = ll.AsHierarchy(e => e.Value, e => e.Padre, e => e.Text, node.nodeId.ToString()).ToList();
                        if (nodeRaw == ROOT_NODE)
                        {
                            nodes = ConvertToJSON(hl);
                        }
                        else
                        {
                            nodes = ConvertToJSON(hl.ElementAt(0).ChildNodes);
                        }
                    }
                    else
                    {
                        nodes = ConvertToJSON(ll);
                    }
                }

                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(JSONTreeNode[]));
                System.IO.MemoryStream     ms  = new System.IO.MemoryStream();
                ser.WriteObject(ms, nodes);
                string json = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();

                context.Response.ContentType = "application/json";
                context.Response.AppendHeader("Content-type", "text/json");
                context.Response.Write(json);
            }
            catch (Exception e)
            {
                throw new Exception("Retry Please!!");
            }
        }
        /// <summary>
        /// Use this method to write XMP data to a new PDF
        /// </summary>
        /// <param name="writer"></param>
        private void CreateXmpMetadata(iTextSharp.text.pdf.PdfWriter writer)
        {
            // Set up the buffer to hold the XMP metadata
            byte[] buffer             = new byte[65536];
            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer, true);

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

                // Add Dublin Core attributes
                iTextSharp.text.xml.xmp.LangAlt title = new iTextSharp.text.xml.xmp.LangAlt();
                title.Add("x-default", "Corelogic letter");
                dc.SetProperty(iTextSharp.text.xml.xmp.DublinCoreSchema.TITLE, title);

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

                // Multiple subjects are also possible, so another XmpArray is used
                iTextSharp.text.xml.xmp.XmpArray subject = new iTextSharp.text.xml.xmp.XmpArray(iTextSharp.text.xml.xmp.XmpArray.UNORDERED);
                subject.Add("paper airplanes");
                subject.Add("science project");
                dc.SetProperty(iTextSharp.text.xml.xmp.DublinCoreSchema.SUBJECT, subject);

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

                //---------------------------------------------------------------------------------
                // Shrink the buffer to the correct size (discard empty elements of the byte array)
                int bufsize  = buffer.Length;
                int bufcount = 0;
                foreach (byte b in buffer)
                {
                    if (b == 0)
                    {
                        break;
                    }
                    bufcount++;
                }
                System.IO.MemoryStream ms2 = new System.IO.MemoryStream(buffer, 0, bufcount);
                buffer = ms2.ToArray();
                //---------------------------------------------------------------------------------

                // Add all of the XMP metadata to the PDF doc that we're building
                writer.XmpMetadata = buffer;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
                ms.Dispose();
            }
        }
        //Method to export pdf of statistics
        public void ExportPDF()
        {
            //Getting number of ratings per star.
            var AllRatings     = db.Ratings.ToList();
            var OneStarCount   = 0;
            var TwoStarCount   = 0;
            var ThreeStarCount = 0;
            var FourStarCount  = 0;
            var FiveStarCount  = 0;

            foreach (Rating r in AllRatings)
            {
                if (r.RatingGiven == 5)
                {
                    FiveStarCount += 1;
                }
                else if (r.RatingGiven == 4)
                {
                    FourStarCount += 1;
                }
                else if (r.RatingGiven == 3)
                {
                    ThreeStarCount += 1;
                }
                else if (r.RatingGiven == 2)
                {
                    TwoStarCount += 1;
                }
                else if (r.RatingGiven == 1)
                {
                    OneStarCount += 1;
                }
            }

            //Counting number of bookings
            var NoOfBookings = db.Bookings.ToList().Count();

            //Counting number of registered users
            var context   = new ApplicationDbContext();
            var userStore = new UserStore <ApplicationUser>(context);
            var NoOfUsers = userStore.Users.Count();

            //Method to export PDF
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                Document document = new Document(PageSize.A4, 10, 10, 10, 10);

                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                document.Open();

                /*
                 * Chunk chunk = new Chunk("PlayMore");
                 * document.Add(chunk);
                 *
                 *
                 * Phrase phrase = new Phrase("User Bookings Statistics.");
                 * document.Add(phrase);
                 */
                string    text      = "PlayMore";
                Paragraph paragraph = new Paragraph
                {
                    SpacingBefore = 10,
                    SpacingAfter  = 10,
                    Alignment     = Element.ALIGN_LEFT,
                    Font          = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14f, BaseColor.BLUE)
                };
                paragraph.Add(text);
                document.Add(paragraph);



                Paragraph para = new Paragraph("Total number of registered users: " + NoOfUsers);
                document.Add(para);
                para = new Paragraph("Total Number of bookings: " + NoOfBookings);
                document.Add(para);
                para = new Paragraph("Number of 5 Star ratings: " + FiveStarCount);
                document.Add(para);
                para = new Paragraph("Number of 4 Star ratings: " + FourStarCount);
                document.Add(para);
                para = new Paragraph("Number of 3 Star ratings: " + ThreeStarCount);
                document.Add(para);
                para = new Paragraph("Number of 2 Star ratings: " + TwoStarCount);
                document.Add(para);
                para = new Paragraph("Number of 1 Star ratings: " + OneStarCount);
                document.Add(para);

                document.Close();
                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
                Response.ClearHeaders();
                Response.Clear();
                Response.ContentType = "application/pdf";

                string pdfName = "PlayMoreStats";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + pdfName + ".pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer      = true;
                Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
                Response.Close();
            }
        }
Пример #52
0
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="pass">密文</param>
        /// <param name="key">密码</param>
        /// <param name="keyIV">偏移</param>
        /// <param name="padding">填充方式</param>
        /// <param name="mode">加密方式</param>
        /// <param name="sEncode">编码</param>
        /// <returns></returns>
        public static string DESDecrypt(string pass, string key, string keyIV, string cmode = "CFB", string cpadding = "Zeros", Encoding sEncode = null)
        {
            try
            {
                sEncode = null == sEncode ? Encoding.UTF8 : sEncode;
                CipherMode  mode    = (CipherMode)Enum.Parse(typeof(CipherMode), cmode);
                PaddingMode padding = (PaddingMode)Enum.Parse(typeof(PaddingMode), cpadding);
                if (key.Length < 8)
                {
                    for (int i = 0; key.Length < 8; i++)
                    {
                        key += "0";
                    }
                }
                if (key.Length > 8)
                {
                    key = key.Substring(0, 8);
                }
                if (!string.IsNullOrEmpty(keyIV))
                {
                    if (keyIV.Length < 8)
                    {
                        for (int i = 0; keyIV.Length < 8; i++)
                        {
                            keyIV += "0";
                        }
                    }
                    if (keyIV.Length > 8)
                    {
                        keyIV = keyIV.Substring(0, 8);
                    }
                }

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.Mode    = mode;
                des.Padding = padding;
                byte[] orgByte = new byte[pass.Length / 2];
                for (int i = 0; i < pass.Length / 2; i++)
                {
                    orgByte[i] = (byte)(Convert.ToInt32(pass.Substring(i * 2, 2), 16));
                }
                des.Key = sEncode.GetBytes(key);
                if (string.IsNullOrEmpty(keyIV))
                {
                    des.IV = new byte[8];
                }
                else
                {
                    des.IV = sEncode.GetBytes(keyIV);
                }
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream           cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(orgByte, 0, orgByte.Length);
                cs.FlushFinalBlock();
                cs.Close();
                string retstr = sEncode.GetString(ms.ToArray());
                ms.Close();
                ms = null;
                return(retstr);
            }
            catch (Exception)
            {
                throw;
            }
        }
        void OnTriggerEnter(Collider other)
        {
            try
            {
                if (other.CompareTag("enemyCollide") || other.CompareTag("enemyRoot"))
                {
                    if (SpellActions.SeekingArrow_ChangeTargetOnHit)
                    {
                        SpellActions.SetSeekingArrowTarget(other.transform);
                    }

                    var crit      = ModdedPlayer.Stats.RandomCritDamage;
                    var dmgOutput = dmg * crit;

                    ModdedPlayer.instance.OnHit();
                    if (GameSetup.IsMpClient)
                    {
                        var entity = other.GetComponentInParent <BoltEntity>();
                        if (entity != null)
                        {
                            {
                                var hitContext = new COTFEvents.HitOtherParams(dmgOutput, crit != 1, entity, this);
                                COTFEvents.Instance.OnHitSpell.Invoke(hitContext);
                                COTFEvents.Instance.OnHitEnemy.Invoke(hitContext);
                            }
                            var phe = PlayerHitEnemy.Create(GlobalTargets.OnlyServer);
                            phe.Target          = entity;
                            phe.getAttackerType = DamageMath.SILENTattackerTypeMagic;
                            phe.Hit             = DamageMath.GetSendableDamage(dmgOutput);
                            if (crit > 1)
                            {
                                int   myID    = 3000 + ModReferences.Players.IndexOf(LocalPlayer.GameObject);
                                float fireDmg = 1 + ModdedPlayer.Stats.spellFlatDmg / 3;
                                fireDmg *= ModdedPlayer.Stats.TotalMagicDamageMultiplier;
                                fireDmg *= ModdedPlayer.Stats.fireDamage + 1;
                                using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                                {
                                    using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                                    {
                                        w.Write(27);
                                        w.Write(entity.networkId.PackedValue);
                                        w.Write(fireDmg);
                                        w.Write(15);
                                        w.Write(myID);
                                        w.Close();
                                    }
                                    AsyncHit.SendCommandDelayed(2, answerStream.ToArray(), NetworkManager.Target.OnlyServer);
                                    answerStream.Close();
                                }
                                phe.Burn = true;
                            }
                            phe.Send();
                        }
                    }
                    else                            //is singleplayer or host
                    {
                        if (EnemyManager.enemyByTransform.ContainsKey(other.transform.root))
                        {
                            var progression = EnemyManager.enemyByTransform[other.transform.root];
                            {
                                var hitContext = new COTFEvents.HitOtherParams(dmgOutput, crit != 1, progression, this);
                                COTFEvents.Instance.OnHitSpell.Invoke(hitContext);
                                COTFEvents.Instance.OnHitEnemy.Invoke(hitContext);
                            }
                            progression.HitMagic(dmgOutput);
                            if (crit > 1)
                            {
                                if (ModdedPlayer.Stats.perk_fireDmgIncreaseOnHit)
                                {
                                    //int myID = 3000 + ModReferences.Players.IndexOf(LocalPlayer.GameObject);
                                    float fireDmg = 1 + ModdedPlayer.Stats.spellFlatDmg / 3;
                                    fireDmg *= ModdedPlayer.Stats.TotalMagicDamageMultiplier;
                                    fireDmg *= ModdedPlayer.Stats.fireDamage + 1;
                                    progression.FireDebuff(3000, fireDmg, 14);
                                }
                                progression.HealthScript.Burn();
                            }
                        }
                        else
                        {
                            Debug.LogWarning("Enemy not found");
                        }
                    }
                    if (UnityEngine.Random.value < ModdedPlayer.Stats.projectilePierceChance - pierceCount)
                    {
                        pierceCount++;
                    }
                    else
                    {
                        dieTimestamp = 0;
                    }
                }
            }
            catch (Exception exc)
            {
                Debug.LogWarning(exc.ToString());
            }
        }
Пример #54
0
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="txt">原文</param>
        /// <param name="key">密码</param>
        /// <param name="keyIV">偏移</param>
        /// <param name="mode">模式</param>
        /// <param name="padding">填充方式</param>
        /// <param name="sEncode">编码</param>
        /// <returns></returns>
        public static string DESEncrypt(string txt, string key, string keyIV = null, string cmode = "CFB", string cpadding = "Zeros", Encoding sEncode = null)
        {
            try
            {
                sEncode = null == sEncode ? Encoding.UTF8 : sEncode;
                CipherMode  mode    = (CipherMode)Enum.Parse(typeof(CipherMode), cmode);
                PaddingMode padding = (PaddingMode)Enum.Parse(typeof(PaddingMode), cpadding);
                if (key.Length < 8)
                {
                    for (int i = 0; key.Length < 8; i++)
                    {
                        key += "0";
                    }
                }
                if (string.IsNullOrEmpty(keyIV))
                {
                    if (key.Length > 8)
                    {
                        key = key.Substring(0, 8);
                    }

                    if (keyIV.Length < 8)
                    {
                        for (int i = 0; keyIV.Length < 8; i++)
                        {
                            keyIV += "0";
                        }
                    }
                    if (keyIV.Length > 8)
                    {
                        keyIV = keyIV.Substring(0, 8);
                    }
                }

                DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //加解密对象
                des.Mode    = mode;
                des.Padding = padding;
                byte[] orgByte = sEncode.GetBytes(txt); //原文
                des.Key = sEncode.GetBytes(key);        //密钥
                if (string.IsNullOrEmpty(keyIV))        //初始偏移向量
                {
                    des.IV = new byte[8];
                }
                else
                {
                    des.IV = sEncode.GetBytes(keyIV);
                }
                System.IO.MemoryStream ms = new System.IO.MemoryStream();                                        //内存流
                CryptoStream           cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); //加解密流
                cs.Write(orgByte, 0, orgByte.Length);                                                            //加密
                cs.FlushFinalBlock();
                cs.Close();
                StringBuilder sb = new StringBuilder();
                //循环写出16进制文本
                foreach (byte b in ms.ToArray())
                {
                    sb.AppendFormat("{0:X2}", b);
                }
                ms.Close();
                ms = null;
                return(sb.ToString());
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #55
0
        protected override bool Equip(InventoryItemView itemView, bool pickedUpFromWorld)
        {
            if (!ModSettings.IsDedicated)
            {
                if (GreatBow.instance != null)
                {
                    GreatBow.instance.SetActive(false);
                }
                if (ToEquipWeaponType == BaseItem.WeaponModelType.None)
                {
                    foreach (CustomWeapon item in customWeapons.Values)
                    {
                        item.obj.SetActive(false);
                        item.objectToHide?.SetActive(true);
                    }
                }
                if (itemView != null)
                {
                    if (EquippedModel != BaseItem.WeaponModelType.None)
                    {
                        customWeapons[EquippedModel].objectToHide?.SetActive(true);
                    }

                    EquippedModel = BaseItem.WeaponModelType.None;

                    //Send network event to display a custom weapon for other players
                    if (BoltNetwork.isRunning && PlayerInventoryMod.ToEquipWeaponType != BaseItem.WeaponModelType.None)
                    {
                        using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                        {
                            using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                            {
                                w.Write(28);
                                w.Write(ModReferences.ThisPlayerID);
                                w.Write((int)PlayerInventoryMod.ToEquipWeaponType);
                                w.Close();
                            }
                            ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Others);
                            answerStream.Close();
                        }
                    }


                    if (itemView.gameObject.name == "axePlane_Inv")
                    {
                        if (ToEquipWeaponType != BaseItem.WeaponModelType.None)
                        {
                            try
                            {
                                foreach (CustomWeapon item in customWeapons.Values)
                                {
                                    item.obj.SetActive(false);
                                }
                                CustomWeapon cw = customWeapons[ToEquipWeaponType];
                                cw.obj.SetActive(true);
                                itemView._heldWeaponInfo.weaponSpeed          = itemView._heldWeaponInfo.baseWeaponSpeed * cw.swingspeed;
                                itemView._heldWeaponInfo.tiredSpeed           = itemView._heldWeaponInfo.baseTiredSpeed * cw.tiredswingspeed;
                                itemView._heldWeaponInfo.smashDamage          = cw.smashDamage;
                                itemView._heldWeaponInfo.weaponDamage         = cw.damage;
                                itemView._heldWeaponInfo.treeDamage           = cw.treeDamage;
                                itemView._heldWeaponInfo.weaponRange          = cw.ColliderScale * 3;
                                itemView._heldWeaponInfo.staminaDrain         = cw.staminaDrain;
                                itemView._heldWeaponInfo.noTreeCut            = cw.blockTreeCut;
                                itemView._heldWeaponInfo.spear                = cw.spearType;
                                itemView._heldWeaponInfo.transform.localScale = Vector3.one * cw.ColliderScale;
                                cw.objectToHide?.SetActive(false);
                                originalPlaneAxeModel.GetComponent <MeshFilter>().mesh = noMesh;
                            }
                            catch (System.Exception exc)
                            {
                                ModAPI.Log.Write("Error with EQUIPPING custom weaponry " + exc.ToString());
                            }
                            EquippedModel = ToEquipWeaponType;
                        }
                        else
                        //equip the base plane axe
                        {
                            itemView._heldWeaponInfo.transform.parent.GetChild(2).gameObject.SetActive(true);
                            foreach (CustomWeapon item in customWeapons.Values)
                            {
                                item.obj.SetActive(false);
                            }
                            itemView._heldWeaponInfo.weaponSpeed                   = itemView._heldWeaponInfo.baseWeaponSpeed;
                            itemView._heldWeaponInfo.tiredSpeed                    = itemView._heldWeaponInfo.baseTiredSpeed;
                            itemView._heldWeaponInfo.smashDamage                   = itemView._heldWeaponInfo.baseSmashDamage;
                            itemView._heldWeaponInfo.weaponDamage                  = itemView._heldWeaponInfo.baseWeaponDamage;
                            itemView._heldWeaponInfo.treeDamage                    = 1;
                            itemView._heldWeaponInfo.weaponRange                   = itemView._heldWeaponInfo.baseWeaponRange;
                            itemView._heldWeaponInfo.staminaDrain                  = itemView._heldWeaponInfo.baseStaminaDrain;
                            itemView._heldWeaponInfo.noTreeCut                     = false;
                            itemView._heldWeaponInfo.transform.localScale          = Vector3.one * 0.6f;
                            originalPlaneAxeModel.GetComponent <MeshFilter>().mesh = originalMesh;
                        }
                    }
                    else if (itemView == _itemViews[158])                       //spear
                    {
                        if (ToEquipWeaponType == BaseItem.WeaponModelType.Polearm)
                        {
                            EquippedModel = ToEquipWeaponType;
                            try
                            {
                                foreach (CustomWeapon item in customWeapons.Values)
                                {
                                    item.obj.SetActive(false);
                                }
                                CustomWeapon cw = customWeapons[ToEquipWeaponType];
                                cw.obj.SetActive(true);
                                itemView._heldWeaponInfo.weaponSpeed              = itemView._heldWeaponInfo.baseWeaponSpeed * cw.swingspeed;
                                itemView._heldWeaponInfo.tiredSpeed               = itemView._heldWeaponInfo.baseTiredSpeed * cw.tiredswingspeed;
                                itemView._heldWeaponInfo.smashDamage              = cw.smashDamage;
                                itemView._heldWeaponInfo.weaponDamage             = cw.damage;
                                itemView._heldWeaponInfo.treeDamage               = cw.treeDamage;
                                itemView._heldWeaponInfo.weaponRange              = cw.ColliderScale * 3;
                                itemView._heldWeaponInfo.staminaDrain             = cw.staminaDrain;
                                itemView._heldWeaponInfo.noTreeCut                = cw.blockTreeCut;
                                itemView._heldWeaponInfo.spear                    = cw.spearType;
                                cw.objectToHide.GetComponent <Renderer>().enabled = false;
                            }
                            catch (System.Exception exc)
                            {
                                ModAPI.Log.Write("Error with EQUIPPING custom weaponry " + exc.ToString());
                            }
                        }
                        else
                        {
                            foreach (CustomWeapon item in customWeapons.Values)
                            {
                                item.obj.SetActive(false);
                            }
                            itemView._heldWeaponInfo.weaponSpeed  = itemView._heldWeaponInfo.baseWeaponSpeed;
                            itemView._heldWeaponInfo.tiredSpeed   = itemView._heldWeaponInfo.baseTiredSpeed;
                            itemView._heldWeaponInfo.smashDamage  = itemView._heldWeaponInfo.baseSmashDamage;
                            itemView._heldWeaponInfo.weaponDamage = itemView._heldWeaponInfo.baseWeaponDamage;
                            itemView._heldWeaponInfo.weaponRange  = itemView._heldWeaponInfo.baseWeaponRange;
                            itemView._heldWeaponInfo.staminaDrain = itemView._heldWeaponInfo.baseStaminaDrain;
                            itemView._heldWeaponInfo.noTreeCut    = false;
                            itemView._heldWeaponInfo.spear        = true;
                            customWeapons[BaseItem.WeaponModelType.Polearm].objectToHide.GetComponent <Renderer>().enabled = true;
                        }
                    }
                }
            }
            return(base.Equip(itemView, pickedUpFromWorld));
        }
        public static void SaveCanvasAsImage(Canvas _to_save, string _name, double _dpi = 96d)
        {
            if (_to_save == null)
            {
                return;
            }
            string file_name = (string.IsNullOrEmpty(_name)) ? "Canvas_" : _name + "_";

            // get info about the DPI of the displaying device
            var dpiXProperty = typeof(SystemParameters).GetProperty("DpiX", BindingFlags.NonPublic | BindingFlags.Static);
            var dpiYProperty = typeof(SystemParameters).GetProperty("Dpi", BindingFlags.NonPublic | BindingFlags.Static);

            int dpiX = (dpiXProperty == null) ? 96 : (int)dpiXProperty.GetValue(null, null);
            int dpiY = (dpiYProperty == null) ? 96 : (int)dpiYProperty.GetValue(null, null);

            double sc_factX = _dpi / dpiX;
            double sc_factY = _dpi / dpiY;

            // determine position in visual parent to avoid cropping
            Visual visual_parent           = LogicalTreeHelper.GetParent(_to_save) as Visual;
            Point  offset_in_visual_parent = new Point(0, 0);

            if (visual_parent != null)
            {
                // if the visual parent is a scroll viewer, scroll to top left to avoid cropping
                ScrollViewer scrl_viewer = visual_parent as ScrollViewer;
                if (scrl_viewer != null)
                {
                    scrl_viewer.ScrollToTop();
                    scrl_viewer.ScrollToLeftEnd();
                }

                var transf = _to_save.TransformToAncestor(visual_parent);
                offset_in_visual_parent = transf.Transform(new Point(0, 0));
            }
            offset_in_visual_parent.X = Math.Max(0, offset_in_visual_parent.X);
            offset_in_visual_parent.Y = Math.Max(0, offset_in_visual_parent.Y);

            try
            {
                // Configure save file dialog box
                var dlg = new Microsoft.Win32.SaveFileDialog()
                {
                    OverwritePrompt = true,
                    FileName        = file_name + DateTime.Now.ToString("yyyyMMdd"), // Default file name
                    DefaultExt      = ".png",                                        // Default file extension
                    Filter          = "png files|*.png"                              // Filter files by extension
                };

                // Show save file dialog box
                Nullable <bool> result = dlg.ShowDialog();

                // Process save file dialog box results
                if (result.HasValue && result == true)
                {
                    // create the image
                    Rect rect = new Rect(_to_save.RenderSize);
                    RenderTargetBitmap rtb = new RenderTargetBitmap((int)((rect.Right + offset_in_visual_parent.X) * sc_factX),
                                                                    (int)((rect.Bottom + offset_in_visual_parent.Y) * sc_factY), _dpi, _dpi, System.Windows.Media.PixelFormats.Default);
                    rtb.Render(_to_save);

                    //endcode as PNG
                    BitmapEncoder pngEncoder = new PngBitmapEncoder();
                    pngEncoder.Frames.Add(BitmapFrame.Create(rtb));

                    // save
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        pngEncoder.Save(ms);
                        ms.Close();
                        using (System.IO.FileStream fs = System.IO.File.Create(dlg.FileName))
                        {
                            byte[] content_B = ms.ToArray();
                            fs.Write(content_B, 0, content_B.Length);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error Saving Canvas as Image", MessageBoxButton.OK, MessageBoxImage.Error);
                // MessageBox.Show(ex.StackTrace, "Error Saving Canvas as Image", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #57
0
        private void UpdateLevelData()
        {
            if (Players.Count > 1)
            {
                LevelRequestCooldown -= 1;
                if (LevelRequestCooldown < 0)
                {
                    LevelRequestCooldown = 120;
                    using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                    {
                        using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                        {
                            w.Write(18);
                            w.Write("x");
                            w.Close();
                        }
                        ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Clients);
                        answerStream.Close();
                    }
                }
                else if (Players.Count != PlayerLevels.Count + 1)
                {
                    LevelRequestCooldown = 120;
                    PlayerLevels.Clear();
                    //PlayerLevels.Add(ThisPlayerPacked, ModdedPlayer.instance.Level);
                    using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                    {
                        using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                        {
                            w.Write(18);
                            w.Write("x");
                            w.Close();
                        }
                        ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Clients);
                        answerStream.Close();
                    }
                }
                MFindRequestCooldown--;
                if (MFindRequestCooldown <= 0)
                {
                    using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                    {
                        using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                        {
                            w.Write(23);
                            w.Close();
                        }
                        ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Everyone);
                        answerStream.Close();
                    }
                    MFindRequestCooldown = 300;
                }

                if (PlayerHands.ContainsValue(null))
                {
                    PlayerHands.Clear();
                }
            }
            else
            {
                PlayerLevels.Clear();
            }
        }
Пример #58
0
        protected override void Update()
        {
            this.activeWormWalkers.RemoveAll((GameObject o) => o == null);
            this.activeWormTrees.RemoveAll((GameObject o) => o == null);
            this.activeWormSingle.RemoveAll((GameObject o) => o == null);
            this.activeWormAngels.RemoveAll((GameObject o) => o == null);
            if (this.activeWormWalkers.Count > 0 || this.activeWormAngels.Count > 0 || this.activeWormTrees.Count > 0)
            {
                this.anyFormSpawned = true;
            }
            else
            {
                this.anyFormSpawned = false;
            }
            if (this.activeWormSingle.Count == 0 && this.init)
            {
                if (GameSetup.IsMpServer || GameSetup.IsSinglePlayer)
                {
                    long Exp;
                    switch (ModSettings.difficulty)
                    {
                    case ModSettings.Difficulty.Easy:
                        Exp = 5000;
                        break;

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

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

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

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

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

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

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

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

                    default:
                        Exp = 10000000000;
                        break;
                    }
                    if (GameSetup.IsMpServer)
                    {
                        using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
                        {
                            using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
                            {
                                w.Write(10);
                                w.Write(Exp);
                                w.Close();
                            }
                            Network.NetworkManager.SendLine(answerStream.ToArray(), Network.NetworkManager.Target.Everyone);
                            answerStream.Close();
                        }
                    }
                    else
                    {
                        ModdedPlayer.instance.AddKillExperience(Exp);
                    }
                    int itemCount = UnityEngine.Random.Range(15, 26);
                    for (int i = 0; i < itemCount; i++)
                    {
                        Network.NetworkManager.SendItemDrop(ItemDataBase.GetRandomItem(Exp), LocalPlayer.Transform.position + Vector3.up * 2);
                    }
                }
                UnityEngine.Object.Destroy(base.gameObject);
            }
        }
Пример #59
0
        /// <summary>
        /// 生成校验码图片
        /// </summary>
        /// <param name="code">验证码</param>
        /// <returns></returns>
        private void CreateImage(string code)
        {
            int fSize       = FontSize;
            int fWidth      = fSize + Padding;
            int imageWidth  = (int)(code.Length * fWidth) + 6 + Padding * 2 + 1;
            int imageHeight = fSize * 2 + Padding * 2 + 4;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);
            Graphics g = Graphics.FromImage(image);

            g.Clear(BackgroundColor);
            //给背景添加随机生成的燥点
            if (this.Chaos)
            {
                Pen pen = new Pen(ChaosColor, 0);
                int c   = Length * 10;
                for (int i = 0; i < c; i++)
                {
                    int x = rnd.Next(image.Width);
                    int y = rnd.Next(image.Height);
                    g.DrawRectangle(pen, x, y, 1, 1);
                }
            }
            int left = 0, top = 0, top1 = 1, top2 = 1;
            int n1 = (imageHeight - FontSize - Padding * 2);
            int n2 = n1 / 4;

            top1 = n2;
            top2 = n2 * 2;
            Font  f;
            Brush b;
            int   cindex, findex;

            //随机字体和颜色的验证码字符
            for (int i = 0; i < code.Length; i++)
            {
                cindex = rnd.Next(Colors.Length - 1);
                findex = rnd.Next(Fonts.Length - 1);
                f      = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
                b      = new System.Drawing.SolidBrush(Colors[cindex]);
                if (i % 2 == 1)
                {
                    top = top2;
                }
                else
                {
                    top = top1;
                }
                left = i * fWidth;
                g.DrawString(code.Substring(i, 1), f, b, left, top);
            }
            //画一个边框 边框颜色为Color.Gainsboro
            g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
            //产生波形
            image = TwistImage(image, false, 0, 0);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            //将图片保存到二进制流
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            Response.ClearContent();
            Response.ContentType = "image/Png";
            //写入至HTTP流
            Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
            ms.Dispose();
            ms.Close();
            Response.End();
        }
Пример #60
0
        private void GetDataFromServer2(object obj)
        {
            NetSimplifyClient simplifyClient = new HslCommunication.Enthernet.NetSimplifyClient("118.24.36.220", 18467);

            HslCommunication.OperateResult <HslCommunication.NetHandle, string> read = simplifyClient.ReadCustomerFromServer(1000, HslCommunication.BasicFramework.SoftBasic.FrameworkVersion.ToString( ));
            if (!read.IsSuccess)
            {
                return;
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.Unicode.GetBytes(read.Content2));
            System.IO.StreamReader sr = new System.IO.StreamReader(ms, Encoding.Unicode);


            Dictionary <string, long> loginData = new Dictionary <string, long>( );

            while (true)
            {
                string city = sr.ReadLine( );
                if (city == null)
                {
                    break;
                }

                string count = sr.ReadLine( );
                loginData.Add(city, long.Parse(count));
            }
            sr.Close( );
            ms.Close( );


            List <dataMy> list = new List <dataMy>( );

            foreach (var m in loginData)
            {
                list.Add(new dataMy(m.Key, m.Value));
            }
            list.Sort( );
            list.Reverse( );

            // 统计省份功能
            string[] province = new string[]
            {
                "北京",
                "天津",
                "上海",
                "重庆",
                "香港",
                "澳门",
                "湖州",
                "嘉兴",
                "绍兴",
                "宁波",
                "舟山",
                "金华",
                "台州",
                "温州",
                "丽水",
                "衢州",
                "杭州",

                "徐州",
                "连云港",
                "宿迁",
                "淮安",
                "盐城",
                "扬州",
                "泰州",
                "南通",
                "镇江",
                "常州",
                "无锡",
                "苏州",
                "南京",

                "聊城",
                "德州",
                "滨州",
                "东营",
                "淄博",
                "泰安",
                "莱芜",
                "菏泽",
                "济宁",
                "枣庄",
                "临沂",
                "潍坊",
                "日照",
                "青岛",
                "烟台",
                "威海",
                "济南",

                "亳州",
                "淮北",
                "宿州",
                "阜阳",
                "淮南",
                "蚌埠",
                "六安",
                "滁州",
                "安庆",
                "巢湖",
                "马鞍山",
                "铜陵",
                "芜湖",
                "池州",
                "黄山",
                "宣城",
                "合肥",

                "三门峡",
                "济源",
                "焦作",
                "新乡",
                "鹤壁",
                "安阳",
                "濮阳",
                "洛阳",
                "开封",
                "商丘",
                "平顶山",
                "许昌",
                "漯河",
                "周口",
                "南阳",
                "驻马店",
                "信阳",
                "郑州",

                "张家口",
                "承德",
                "秦皇岛",
                "唐山",
                "保定",
                "廊坊",
                "沧州",
                "衡水",
                "邢台",
                "邯郸",
                "石家庄",

                "大同",
                "朔州",
                "忻州",
                "吕梁",
                "晋中",
                "阳泉",
                "临汾",
                "长治",
                "运城",
                "晋城",
                "太原",

                "朝阳",
                "葫芦岛",
                "锦州",
                "阜新",
                "铁岭",
                "抚顺",
                "盘锦",
                "鞍山",
                "辽阳",
                "本溪",
                "营口",
                "丹东",
                "大连",
                "沈阳",

                "白城",
                "松原",
                "四平",
                "吉林",

                "辽源",
                "通化",
                "白山",
                "延吉",
                "长春",
                "黑河",
                "齐齐哈尔",

                "大庆",
                "绥化",
                "伊春",
                "鹤岗",
                "佳木斯",
                "双鸭山",
                "鸡西",
                "七台河",
                "牡丹江",
                "哈尔滨",

                "乌海",
                "巴彦淖尔",
                "包头",
                "鄂尔多斯",
                "乌兰察布",
                "呼伦贝尔",
                "赤峰",
                "通辽",
                "呼和浩特",

                "榆林",
                "延安",
                "铜川",
                "宝鸡",
                "咸阳",
                "渭南",
                "汉中",
                "安康",
                "商洛",
                "西安",

                "十堰",
                "襄樊",
                "神农架",
                "恩施",
                "宜昌",
                "随州",
                "荆门",
                "荆州",
                "孝感",
                "天门",
                "潜江",
                "仙桃",
                "黄冈",
                "鄂州",
                "黄石",
                "咸宁",
                "武汉",

                "湘西土家",
                "张家界",
                "常德",
                "岳阳",
                "益阳",
                "怀化",
                "娄底",
                "湘潭",
                "株洲",
                "邵阳",
                "衡阳",
                "永州",
                "郴州",
                "长沙",

                "九江",
                "景德镇",
                "上饶",
                "萍乡",
                "宜春",
                "新余",
                "鹰潭",
                "抚州",
                "吉安",
                "赣州",
                "南昌",

                "南平",
                "宁德",
                "三明",
                "龙岩",
                "莆田",
                "泉州",
                "厦门",
                "漳州",
                "福州",

                "湛江",
                "茂名",
                "阳江",
                "云浮",
                "江门",
                "肇庆",
                "佛山",
                "中山",
                "珠海",
                "清远",
                "惠州",
                "东莞",
                "深圳",
                "韶关",
                "河源",
                "汕尾",
                "梅州",
                "揭阳",
                "汕头",
                "潮州",
                "广州",

                "百色",
                "河池",
                "柳州",
                "桂林",
                "崇左",
                "防城港",
                "钦州",
                "北海",
                "玉林",
                "来宾",
                "贵港",
                "梧州",
                "贺州",
                "南宁",

                "毕节",
                "遵义",
                "铜仁",
                "六盘水",
                "安顺",
                "黔西南",
                "黔南",
                "黔东南",
                "贵阳",

                "甘孜藏",
                "阿坝藏",
                "凉山彝",
                "攀枝花",
                "雅安",
                "绵阳",
                "德阳",
                "广元",
                "巴中",
                "达州",
                "南充",
                "广安",
                "遂宁",
                "资阳",
                "眉山",
                "内江",
                "乐山",
                "自贡",
                "宜宾",
                "泸州",
                "成都",

                "保山",
                "丽江",
                "昭通",
                "曲靖",
                "玉溪",
                "临沧",
                "普洱",
                "怒江",
                "德宏",
                "红河",
                "楚雄",
                "大理",
                "文山",
                "西双版",
                "迪庆",
                "昆明",

                "三亚",
                "儋州",
                "五指山",
                "文昌",
                "琼海",
                "万宁",
                "东方",
                "白沙黎",
                "昌江黎",
                "乐东黎",
                "陵水黎",
                "保亭黎",
                "琼中黎",
                "海口",

                "基隆",
                "桃园",
                "新竹",
                "宜兰",
                "苗栗",
                "台中",
                "花莲",
                "彰化",
                "南投",
                "云林",
                "嘉义",
                "台南",
                "高雄",
                "屏东",
                "台东",
                "澎湖",
                "台北",

                "日喀则",
                "山南",
                "林芝",
                "昌都",
                "那曲",
                "阿里地",
                "拉萨",

                "海东",
                "西宁",
                "海西",
                "海北",
                "海南藏族",
                "黄南",
                "果洛",
                "玉树",

                "克拉玛依",
                "吐鲁番",
                "哈密",
                "阿克苏",
                "博尔塔拉",
                "巴音",
                "昌吉",
                "孜勒苏柯",
                "伊宁",
                "阿勒泰",
                "和田",
                "石河子",
                "阿拉尔",
                "塔城",
                "喀什",
                "伊犁哈",
                "乌鲁木齐",

                "嘉峪关",
                "酒泉",
                "张掖",
                "金昌",
                "白银",
                "天水",
                "武威",
                "平凉",
                "庆阳",
                "定西",
                "陇南",
                "临夏",
                "甘南",
                "兰州",

                "石嘴山",
                "吴忠",
                "固原",
                "中卫",
                "银川",
            };

            //var selsec = from m in province
            //             group m by m into g
            //             where g.Count( ) > 1
            //             select g.Key;
            //if (selsec.Count( ) > 0)
            //{
            //    throw new Exception( "城市名称发生了重名" );
            //}

            List <dataMy> shengfen = new List <dataMy>( );

            for (int i = 0; i < list.Count; i++)
            {
                string tmp = string.Empty;
                for (int j = 0; j < province.Length; j++)
                {
                    if (list[i].Key.Contains(province[j]))
                    {
                        tmp = province[j];
                    }
                    else
                    {
                        continue;
                    }
                }

                if (string.IsNullOrEmpty(tmp))
                {
                    continue;
                }
                dataMy dataMy = shengfen.Find(m => m.Key == tmp);
                if (dataMy == null)
                {
                    shengfen.Add(new dataMy(tmp, list[i].Value));
                }
                else
                {
                    dataMy.Value += list[i].Value;
                }
            }


            Invoke(new Action(() =>
            {
                for (int i = 0; i < shengfen.Count; i++)
                {
                    if (shengfen[i].Value == 0)
                    {
                        shengfen[i].Value = 0;
                    }
                    else if (shengfen[i].Value <= 10)
                    {
                        shengfen[i].Value = 1;
                    }
                    else if (shengfen[i].Value <= 100)
                    {
                        shengfen[i].Value = 2;
                    }
                    else if (shengfen[i].Value <= 1000)
                    {
                        shengfen[i].Value = 3;
                    }
                    else if (shengfen[i].Value <= 3000)
                    {
                        shengfen[i].Value = 4;
                    }
                    else if (shengfen[i].Value <= 5000)
                    {
                        shengfen[i].Value = 5;
                    }
                    else if (shengfen[i].Value <= 10000)
                    {
                        shengfen[i].Value = 6;
                    }
                    else if (shengfen[i].Value <= 13000)
                    {
                        shengfen[i].Value = 7;
                    }
                    else if (shengfen[i].Value <= 15000)
                    {
                        shengfen[i].Value = 8;
                    }
                    else if (shengfen[i].Value <= 20000)
                    {
                        shengfen[i].Value = 9;
                    }
                    else if (shengfen[i].Value <= 25000)
                    {
                        shengfen[i].Value = 10;
                    }
                    else if (shengfen[i].Value <= 30000)
                    {
                        shengfen[i].Value = 11;
                    }
                    else if (shengfen[i].Value <= 50000)
                    {
                        shengfen[i].Value = 12;
                    }
                    else if (shengfen[i].Value <= 100000)
                    {
                        shengfen[i].Value = 13;
                    }
                    else
                    {
                        shengfen[i].Value = 15;
                    }
                }
                hslChinaMap1.MarkCity(
                    shengfen.Select(m => m.Key).ToArray( ),
                    shengfen.Select(m => (int)m.Value).ToArray( ),
                    shengfen.Select(m => Color.Yellow).ToArray( ));
            }));
        }