Esempio n. 1
0
        internal static string EncodePassword(string password, string hash)
        {
            byte[] hash_byte = new byte[hash.Length / 2];
            for (int i = 0; i <= hash.Length - 2; i += 2)
            {
                hash_byte[i / 2] = Byte.Parse(hash.Substring(i, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture);
            }
            byte[] heslo = new byte[1 + password.Length + hash_byte.Length];
            heslo[0] = 0;
            Encoding.ASCII.GetBytes(password.ToCharArray()).CopyTo(heslo, 1);
            hash_byte.CopyTo(heslo, 1 + password.Length);

            Byte[] hotovo;
            System.Security.Cryptography.MD5 md5;

            md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

            hotovo = md5.ComputeHash(heslo);

            //Convert encoded bytes back to a 'readable' string
            string result = "";
            foreach (byte h in hotovo)
            {
                result += h.ToString("x2", CultureInfo.InvariantCulture);
            }
            return result;
        }
Esempio n. 2
0
        public static string GetMD5Hash(byte[] data)
        {
            string strResult = "";
            string strHashData = "";

            byte[] arrbytHashValue;

            System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher =
                       new System.Security.Cryptography.MD5CryptoServiceProvider();

            try
            {

                arrbytHashValue = oMD5Hasher.ComputeHash(data);

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
            }
            catch
            {
            }

            return (strResult);
        }
Esempio n. 3
0
 public static string GetMd5(string str)
 {
     System.Security.Cryptography.MD5CryptoServiceProvider Md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] src = System.Text.Encoding.ASCII.GetBytes(str);
     byte[] md5out=Md5.ComputeHash(src);
     return Convert.ToBase64String(md5out);
 }
 public static string ToMd5Pass(this string value)
 {
     byte[] hash = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(ToByteArray(value));
     string result = System.BitConverter.ToString(hash);
     result = result.Replace("-", "");
     return result;
 }
 static void Main(string[] args)
 {
     string test = "admin";
     System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] test_encrypt = System.Text.Encoding.ASCII.GetBytes(test);
     byte[] result = md5.ComputeHash(test_encrypt);
 }
        public static byte[] ToMD5Bytes(this byte[] buffer)
        {
            var x = new System.Security.Cryptography.MD5CryptoServiceProvider();


            return x.ComputeHash(buffer);
        }
Esempio n. 7
0
 public string MD5(string str)
 {
     var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
     var bs = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));
     md5.Clear();
     return bs.Aggregate("", (current, b) => current + (b.ToString("x2")));
 }
Esempio n. 8
0
        /// <summary>
        /// 获得字节数组MD5值
        /// </summary>
        /// <param name="data">字节数组</param>
        /// <returns>返回MD5值</returns>
        public static string GetMD5Hash(byte[] data)
        {
            string strResult = "";
                string strHashData = "";

                byte[] arrbytHashValue;

                System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher =
                           new System.Security.Cryptography.MD5CryptoServiceProvider();

                try
                {

                    arrbytHashValue = oMD5Hasher.ComputeHash(data);

                    strHashData = System.BitConverter.ToString(arrbytHashValue);
                    strHashData = strHashData.Replace("-", "");
                    strResult = strHashData;
                }
                catch
                {
                    //System.Windows.Forms.MessageBox.Show(ex.Message, "Error!",System.Exception ex
                    //           System.Windows.Forms.MessageBoxButtons.OK,
                    //           System.Windows.Forms.MessageBoxIcon.Error,
                    //           System.Windows.Forms.MessageBoxDefaultButton.Button1);
                }

                return (strResult);
        }
 public string MaHoaMatKhau(string Password)
 {
     System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] hashedDataBytes = md5Hasher.ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(Password));
     string EncryptPass = Convert.ToBase64String(hashedDataBytes);
     return EncryptPass;
 }
Esempio n. 10
0
        public static string GetMD5Hash(string pathName)
        {
            string strResult = "";
            string strHashData = "";

            byte[] arrbytHashValue;
            System.IO.FileStream oFileStream = null;

            System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher =
                       new System.Security.Cryptography.MD5CryptoServiceProvider();

            try
            {
                oFileStream = GetFileStream(pathName);
                arrbytHashValue = oMD5Hasher.ComputeHash(oFileStream);
                oFileStream.Close();

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
                oMD5Hasher.Clear();
            }
            catch (System.Exception)
            {
                oMD5Hasher.Clear();
            }
            return (strResult);
        }
Esempio n. 11
0
 private static string MD5(string theEmail)
 {
     var md5Obj = new System.Security.Cryptography.MD5CryptoServiceProvider();
     var bytesToHash = Encoding.ASCII.GetBytes(theEmail);
     bytesToHash = md5Obj.ComputeHash(bytesToHash);
     return bytesToHash.Aggregate("", (current, b) => current + b.ToString("x2"));
 }
Esempio n. 12
0
        public static void init()
        {
            reqIndex = 1;

              unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);

              string bundle = DeviceInfo.bundleID();
              string deviceId = DeviceInfo.deviceID();
              string hashSrc;

              if(bundle.Length > 0 && deviceId.Length > 0) {
            reqIdBase = "a-";
            hashSrc = bundle + "-" + deviceId;
              } else {
            System.Random rng = new System.Random();
            reqIdBase = "b-";
            hashSrc = (int)((System.DateTime.UtcNow - unixEpoch).TotalMilliseconds) + "-" + rng.Next();
              }

              byte[] srcBytes = System.Text.Encoding.UTF8.GetBytes(hashSrc);

              System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
              byte[] destBytes = md5.ComputeHash(srcBytes);

              string finalHash = System.BitConverter.ToString(destBytes).Replace("-", string.Empty);

              reqIdBase += finalHash + "-";
        }
Esempio n. 13
0
 /// <summary>
 /// Hashes the entry string
 /// </summary>
 /// <param name="unhashed">The string not empty instance</param>
 /// <returns>Hashed string</returns>
 public static string CreateHash(this string unhashed)
 {
     if (string.IsNullOrWhiteSpace(unhashed))
         return string.Empty;
     System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
     return System.Text.Encoding.ASCII.GetString(md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(unhashed)));
 }
Esempio n. 14
0
 public static string ComputeXCode(object o, string token)
 {
     var strs = ComputeSourceKey(o, token);
     var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
     var bys = md5.ComputeHash(Encoding.Unicode.GetBytes(strs));
     return BitConverter.ToString(bys);
 }
Esempio n. 15
0
 /// <summary>
 /// MD5 16位加密 加密后密码为大写
 /// </summary>
 /// <param name="ConvertString"></param>
 /// <returns></returns>
 public static string GetMd5Str(string ConvertString)
 {
     System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
     string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
     t2 = t2.Replace("-", "");
     return t2;
 }
Esempio n. 16
0
      /// <summary>
      /// Gets a string which represents a unique signature of this machine based on MAC addresses of interfaces.
      /// The signature has a form of: [intf.count]-[CRC32 of all MACs]-[convoluted MD5 of all MACs]
      /// </summary>
      public static string GetMachineUniqueMACSignature()
      {
          var nics = NetworkInterface.GetAllNetworkInterfaces();
          var buf = new byte[6 * 32];
          var ibuf = 0;
          var cnt=0;
          var csum = new NFX.IO.ErrorHandling.CRC32();
          foreach(var nic in nics.Where(a => a.NetworkInterfaceType!=NetworkInterfaceType.Loopback))
          {                       
            var mac = nic.GetPhysicalAddress().GetAddressBytes();
            csum.Add( mac );
            for(var i=0; i<mac.Length; i++)
            {
              buf[ibuf] = mac[i];
              ibuf++;
              if(ibuf==buf.Length) ibuf = 0;
            }
            cnt++;
          }

          var md5s = new StringBuilder();
          using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
          {
               var hash = md5.ComputeHash(buf);
               for(var i=0 ; i<hash.Length ; i+=2)
                md5s.Append( (hash[i]^hash[i+1]).ToString("X2"));
          }
          
          return "{0}-{1}-{2}".Args( cnt, csum.Value.ToString("X8"),  md5s );
      }
Esempio n. 17
0
 public void ProcessRequest(HttpContext context)
 {
     context.Response.ContentType = "text/plain";
     string md5Code = "NoUpdate";
     try
     {
         string fileName = context.Request.QueryString["FileName"];
         string filePath = context.Server.MapPath("App/Update/"+fileName);
         if (File.Exists(filePath))
         {
             FileStream file = new FileStream(filePath, FileMode.Open);
             System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
             byte[] retVal = md5.ComputeHash(file);
             file.Close();
             StringBuilder sb = new StringBuilder();
             for (int i = 0; i < retVal.Length; i++)
             {
                 sb.Append(retVal[i].ToString("x2"));
             }
             md5Code = sb.ToString();
         }
     }
     catch { }
     context.Response.Write(md5Code);
 }
 internal byte[] HashPassword(string password)
 {
     var cryptoServiceProvider = new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] dataToHash = _nonce1.Concat(Encoding.UTF8.GetBytes(password)).Concat(_nonce2).ToArray();
     var hash = cryptoServiceProvider.ComputeHash(dataToHash);
     return hash;
 }
Esempio n. 19
0
        public static string GetMD5Hash( string pathName )
        {
            string strResult = "";
            string strHashData = "";

            byte[] arrbytHashValue;
            System.IO.FileStream oFileStream = null;

            System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher =
                       new System.Security.Cryptography.MD5CryptoServiceProvider( );

            try
            {
                oFileStream = GetFileStream( pathName );
                arrbytHashValue = oMD5Hasher.ComputeHash( oFileStream );
                oFileStream.Close( );

                strHashData = System.BitConverter.ToString( arrbytHashValue );
                strHashData = strHashData.Replace( "-" , "" );
                strResult = strHashData;
            }
            catch ( System.Exception ex )
            {
                System.Windows.Forms.MessageBox.Show( ex.Message , "Error!" ,
                           System.Windows.Forms.MessageBoxButtons.OK ,
                           System.Windows.Forms.MessageBoxIcon.Error ,
                           System.Windows.Forms.MessageBoxDefaultButton.Button1 );
            }

            return ( strResult );
        }
Esempio n. 20
0
        public static string GetMD5(string filePath)
        {
            string strResult = "";
            string strHashData = "";

            byte[] arrbytHashValue;
            System.IO.FileStream oFileStream = null;

            System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher =
                       new System.Security.Cryptography.MD5CryptoServiceProvider();

            try
            {
                oFileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open,
                      System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                arrbytHashValue = oMD5Hasher.ComputeHash(oFileStream);//计算指定Stream 对象的哈希值
                oFileStream.Close();
                //由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A”
                strHashData = System.BitConverter.ToString(arrbytHashValue);
                //替换-
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
            }
            catch (System.Exception ex)
            {

            }

            return strResult;
        }
 public static string CreateHash(string unHashed)
 {
     System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] data = System.Text.Encoding.ASCII.GetBytes(unHashed);
     data = x.ComputeHash(data);
     return System.Text.Encoding.ASCII.GetString(data);
 }
Esempio n. 22
0
        //MD5によるハッシュ作成
        public static string Hash(string passStr,string timestampStr)
        {
            const int range = 64;
            var pass = Encoding.ASCII.GetBytes(passStr);
            var timestamp = Encoding.ASCII.GetBytes(timestampStr);
            var h = new System.Security.Cryptography.MD5CryptoServiceProvider();
            var k = new byte[range];
            if (range < pass.Length)
                throw new InvalidOperationException("key length is too long");
            var ipad = new byte[range];
            var opad = new byte[range];
            pass.CopyTo(k,0);
            for (var i = pass.Length; i < range; i++) {
                k[i] = 0x00;
            }
            for (var i = 0; i < range; i++) {
                ipad[i] = (byte)(k[i] ^ 0x36);
                opad[i] = (byte)(k[i] ^ 0x5c);
            }
            var hi = new byte[ipad.Length + timestamp.Length];
            ipad.CopyTo(hi,0);
            timestamp.CopyTo(hi,ipad.Length);
            var hash = h.ComputeHash(hi);
            var ho = new byte[opad.Length + hash.Length];
            opad.CopyTo(ho,0);
            hash.CopyTo(ho,opad.Length);
            h.Initialize();
            var tmp = h.ComputeHash(ho);

            var sb = new StringBuilder();
            foreach (var b in tmp) {
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }
Esempio n. 23
0
 public static string GetEncondeMD5(string password)
 {
     System.Security.Cryptography.MD5 md5;
     md5 = new System.Security.Cryptography.MD5CryptoServiceProvider ();
     Byte[] encodedBytes = md5.ComputeHash (ASCIIEncoding.Default.GetBytes (password));
     return System.Text.RegularExpressions.Regex.Replace (BitConverter.ToString (encodedBytes).ToLower (), @"-", "");
 }
Esempio n. 24
0
 public static byte[] EncryptData(string data)
 {
     System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] hashedBytes;
     System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
     hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(data));
     return hashedBytes;
 }
Esempio n. 25
0
        // Calculates a MD5 hash from the given string and uses the given encoding.
        public static string CalculateMd5(string input, Encoding useEncoding)
        {
            var cryptoService = new System.Security.Cryptography.MD5CryptoServiceProvider();

            var inputBytes = useEncoding.GetBytes(input);
            inputBytes = cryptoService.ComputeHash(inputBytes);
            return BitConverter.ToString(inputBytes).Replace("-", string.Empty);
        }
Esempio n. 26
0
        /// <summary>
        /// 获取MD5得值,转换成BASE64
        /// </summary>
        /// <param name="Sourcein"></param>
        /// <returns></returns>
        public static string MD5(string Sourcein)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] MD5Source = System.Text.Encoding.UTF8.GetBytes(Sourcein);
            byte[] MD5Out = MD5CSP.ComputeHash(MD5Source);

            return Convert.ToBase64String(MD5Out);
        }
Esempio n. 27
0
        public static byte[] ComputeHashBytes(byte[] clearText)
        {
            if (clearText == null) return null;

            System.Security.Cryptography.MD5CryptoServiceProvider MD5;
            MD5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            return MD5.ComputeHash(clearText);
        }
Esempio n. 28
0
 public string Get(Request request)
 {
     using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
     {
         var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(request.Url.ToString()));
         return Convert.ToBase64String(hash);
     }
 }
Esempio n. 29
0
 public static string MD5(string srcContent)
 {
     System.Security.Cryptography.MD5CryptoServiceProvider md5Provider =
         new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] contentCrypt = System.Text.Encoding.Unicode.GetBytes(srcContent);
     byte[] resultContent = md5Provider.ComputeHash(contentCrypt);
     return System.Text.Encoding.Unicode.GetString(resultContent);
 }
Esempio n. 30
0
 public static string HashPassword(string clearTextPassword)
 {
     var crypto = new System.Security.Cryptography.MD5CryptoServiceProvider();
     var data = System.Text.Encoding.ASCII.GetBytes(clearTextPassword);
     data = crypto.ComputeHash(data);
     var md5Hash = System.Text.Encoding.ASCII.GetString(data);
     return md5Hash;
 }
Esempio n. 31
0
 /// <summary>
 /// 计算32位2重MD5码
 /// </summary>
 /// <param name="word">字符串</param>
 /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
 /// <returns></returns>
 public static string Hash_2_MD5_32(string word, bool toUpper = false)
 {
     try
     {
         System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP
             = new System.Security.Cryptography.MD5CryptoServiceProvider();
         byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
         byte[] bytHash  = MD5CSP.ComputeHash(bytValue);
         //根据计算得到的Hash码翻译为MD5码
         string sHash = "", sTemp = "";
         for (int counter = 0; counter < bytHash.Count(); counter++)
         {
             long i = bytHash[counter] / 16;
             if (i > 9)
             {
                 sTemp = ((char)(i - 10 + 0x41)).ToString();
             }
             else
             {
                 sTemp = ((char)(i + 0x30)).ToString();
             }
             i = bytHash[counter] % 16;
             if (i > 9)
             {
                 sTemp += ((char)(i - 10 + 0x41)).ToString();
             }
             else
             {
                 sTemp += ((char)(i + 0x30)).ToString();
             }
             sHash += sTemp;
         }
         bytValue = System.Text.Encoding.UTF8.GetBytes(sHash);
         bytHash  = MD5CSP.ComputeHash(bytValue);
         MD5CSP.Clear();
         sHash = "";
         //根据计算得到的Hash码翻译为MD5码
         for (int counter = 0; counter < bytHash.Count(); counter++)
         {
             long i = bytHash[counter] / 16;
             if (i > 9)
             {
                 sTemp = ((char)(i - 10 + 0x41)).ToString();
             }
             else
             {
                 sTemp = ((char)(i + 0x30)).ToString();
             }
             i = bytHash[counter] % 16;
             if (i > 9)
             {
                 sTemp += ((char)(i - 10 + 0x41)).ToString();
             }
             else
             {
                 sTemp += ((char)(i + 0x30)).ToString();
             }
             sHash += sTemp;
         }
         //根据大小写规则决定返回的字符串
         return(toUpper ? sHash : sHash.ToLower());
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Esempio n. 32
0
        public static int IntUnicodeString([MarshalAs(UnmanagedType.LPWStr)] string str)
        {
            var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

            return(BitConverter.ToInt32(md5.ComputeHash(Encoding.UTF8.GetBytes(str)), 0));
        }
Esempio n. 33
0
 /// <summary>
 /// Digests the given string using the MD5 algorithm.
 /// </summary>
 /// <param name="data">The data to be digested.</param>
 /// <remarks>This method is used for APOP authentication.</remarks>
 /// <returns>A 16 bytes digest representing the data.</returns>
 /// <example>
 /// The example below illustrates the use of this method.
 ///
 /// <code>
 /// C#
 ///
 /// string data = "ActiveMail rocks ! Let's see how this string is digested...";
 /// string digest = Crypto.MD5Digest(data);
 /// </code>
 ///
 /// digest returns 3ff3501885f8602c4d8bf7edcd2ceca1
 ///
 /// Digesting is used to check data equivalence.
 /// Different data result in different digests.
 /// </example>
 public static string MD5Digest(string data)
 {
     System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] bufe = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(data));
     return(System.BitConverter.ToString(bufe).ToLower().Replace("-", ""));
 }
Esempio n. 34
0
        public static void TestPCS_API(BaiduPCS api)
        {
            var trace = Tracer.GlobalTracer;

            trace.TraceInfo("Testing PCS API...");

            try { api.DeletePath("/pcsapi_testbench"); } catch { }

            trace.TraceInfo("[1/88] Creating Directory (general test)");
            try
            {
                var temp_dir = api.CreateDirectory("/pcsapi_testbench"); //meta: /pcsapi_testbench
            }
            catch (Exception ex)
            {
                trace.TraceError(ex);
                return;
            }

            trace.TraceInfo("[2/88] Creating Directory (conflict test)");
            try
            {
                var temp_dir = api.CreateDirectory("/pcsapi_testbench/conflict_test"); //meta: /pcsapi_testbench/conflict_test
                temp_dir = api.CreateDirectory("/pcsapi_testbench/conflict_test");     //meta: /pcsapi_testbench_conflict_test(1)
            }
            catch { }

            trace.TraceInfo("[3/88] Creating Directory (special character test)");
            try
            {
                var temp_dir = api.CreateDirectory("/pcsapi_testbench/this<is>a-D!I:R!"); //errno = -7
            }
            catch { }

            var rnd = new Random();

            trace.TraceInfo("[4/88] Upload Test (100 Bytes)");
            var data = new byte[100];

            rnd.NextBytes(data);
            var ms = new MemoryStream(data);

            try
            {
                var temp_file = api.UploadRaw(ms, 100, "/pcsapi_testbench/100b_file.dat", BaiduPCS.ondup.overwrite); //meta: /pcsapi_testbench/100b_file.dat
            }
            catch { }

            trace.TraceInfo("[5/88] Upload Test (5 MB)");
            data = new byte[5242880];
            rnd.NextBytes(data);
            var ms2      = new MemoryStream(data);
            var filedata = new ObjectMetadata();

            try
            {
                var temp_file = api.UploadRaw(ms2, (ulong)data.Length, "/pcsapi_testbench/5mb_file.dat", BaiduPCS.ondup.overwrite); //meta: /pcsapi_testbench/5mb_file.dat
                filedata = temp_file;
            }
            catch { }
            //calculating data
            var md5cp = new System.Security.Cryptography.MD5CryptoServiceProvider();

            md5cp.TransformFinalBlock(data, 0, data.Length);
            var content_md5 = util.Hex(md5cp.Hash);

            md5cp.Initialize();
            md5cp.TransformFinalBlock(data, 0, (int)BaiduPCS.VALIDATE_SIZE);
            var slice_md5 = util.Hex(md5cp.Hash);
            var crccp     = new Crc32();

            crccp.TransformBlock(data, 0, data.Length);
            var content_crc32 = crccp.Hash.ToString("X2").ToLower();

            trace.TraceInfo("[6/88] Upload Test (overwrite test)");
            data = new byte[300];
            rnd.NextBytes(data);
            ms = new MemoryStream(data);
            try
            {
                var temp_file = api.UploadRaw(ms, 300, "/pcsapi_testbench/100b_file.dat", BaiduPCS.ondup.overwrite); //meta: /pcsapi_testbench/100b_file.dat
            }
            catch { }

            trace.TraceInfo("[7/88] Upload Test (newcopy test)");
            data = new byte[400];
            rnd.NextBytes(data);
            ms = new MemoryStream(data);
            try
            {
                var temp_file = api.UploadRaw(ms, 400, "/pcsapi_testbench/100b_file.dat", BaiduPCS.ondup.newcopy); //meta: /pcsapi_testbench/100b_file_yyyyMMddHHmmss.dat
            }
            catch { }

            trace.TraceInfo("[8/88] Upload Test (path invalid test)");
            ms.Seek(0, SeekOrigin.Begin);
            try
            {
                var temp_file = api.UploadRaw(ms, 400, "/pcsapi_testbench/100b_file<:nonono:>.dat", BaiduPCS.ondup.newcopy); //HTTP 400 with errno 31062 "file name is invalid"
            }
            catch { }

            trace.TraceInfo("[9/88] Upload Test (zero length file test)");
            ms.Seek(0, SeekOrigin.Begin);
            try
            {
                var temp_file = api.UploadRaw(ms, 0, "/pcsapi_testbench/zero_file.dat"); //meta: /pcsapi_testbench/zero_file.dat (with 0 size)
            }
            catch { }

            trace.TraceInfo("[10/88] Download Test (API, http)");
            try
            {
                var download_data = api.GetDownloadLink_API("/pcsapi_testbench/5mb_file.dat", false); //http://pcs.baidu.com/rest/2.0/pcs/file?method=download&app_id=250528&path=%2Fpcsapi_testbench%2F5mb_file.dat
            }
            catch { }

            trace.TraceInfo("[11/88] Download Test (API, https)");
            try
            {
                var download_data = api.GetDownloadLink_API("/pcsapi_testbench/5mb_file.dat", true); //https://pcs.baidu.com/rest/2.0/pcs/file?method=download&app_id=250528&path=%2Fpcsapi_testbench%2F5mb_file.dat
            }
            catch { }

            trace.TraceInfo("[12/88] Download Test (API, null path)");
            try
            {
                var download_data = api.GetDownloadLink_API(""); //https://pcs.baidu.com/rest/2.0/pcs/file?method=download&app_id=250528&path=
            }
            catch { }

            trace.TraceInfo("[13/88] Download Test (API, invalid path)");
            try
            {
                var download_data = api.GetDownloadLink_API("/pcsapi_testbench/<><><>aaaaa"); //https://pcs.baidu.com/rest/2.0/pcs/file?method=download&app_id=250528&path=%2Fpcsapi_testbench%2F%3C%3E%3C%3E%3C%3Eaaaaa
            }
            catch { }

            trace.TraceInfo("[14/88] Get File List Test (general test)");
            try
            {
                var files = api.GetFileList("/pcsapi_testbench"); //meta: { count=6 }
            }
            catch { }

            trace.TraceInfo("[15/88] Get File List Test (non exist path test)");
            try
            {
                var files = api.GetFileList("/pcsapi_testbench/non_exist_path"); //errno -9
            }
            catch { }

            trace.TraceInfo("[16/88] Get File List Test (invalid path test)");
            try
            {
                var files = api.GetFileList("/pcsapi_testbench/aaa:"); //errno -7
            }
            catch { }

            trace.TraceInfo("[17/88] Get File List Test (path is file test)");
            try
            {
                var files = api.GetFileList("/pcsapi_testbench/100b_file.dat"); //meta: { count = 0 }
            }
            catch { }

            trace.TraceInfo("[18/88] Get File List Test (desc order test)");
            try
            {
                var files = api.GetFileList("/pcsapi_testbench", asc: false); //meta: { count=6 }
            }
            catch { }

            trace.TraceInfo("[19/88] Get File List Test (order by size test)");
            try
            {
                var files = api.GetFileList("/pcsapi_testbench", BaiduPCS.FileOrder.size); //meta: { count=6 }
            }
            catch { }

            trace.TraceInfo("[20/88] Get File List Test (max size test)");
            try
            {
                var files = api.GetFileList("/pcsapi_testbench", count: 2); //meta: { count=2 }
            }
            catch { }

            trace.TraceInfo("[21/88] Get File List Test (page test)");
            try
            {
                var files = api.GetFileList("/pcsapi_testbench", page: 2, count: 2); //meta: { count=2 }
            }
            catch { }

            trace.TraceInfo("[22/88] File Diff Test (null cursor)");
            string next_cursor = null;
            bool   noused1, noused2;

            try
            {
                var files = api.GetFileDiff(out next_cursor, out noused1, out noused2); //meta: { count=399 }
            }
            catch { }

            trace.TraceInfo("[23/88] File Diff Test (general cursor)");
            try
            {
                var files = api.GetFileDiff(out next_cursor, out noused1, out noused2, next_cursor); //meta: { count=400 }
            }
            catch { }

            trace.TraceInfo("[24/88] File Diff Test (invalid cursor)");
            try
            {
                var files = api.GetFileDiff(out next_cursor, out noused1, out noused2, "haha"); //errno 2
            }
            catch { }

            trace.TraceInfo("[25/88] Pre Create File Test (general test)");
            string uploadid = null;

            try
            {
                uploadid = api.PreCreateFile("/pcsapi_testbench/slice_upload.dat", 2).UploadId; //P1-XXXXX
            }
            catch { }

            trace.TraceInfo("[26/88] Pre Create File Test (invalid path test)");
            try
            {
                api.PreCreateFile("/pcsapi_testbench/slice:invalid path", 1); //errno -7
            }
            catch { }

            trace.TraceInfo("[27/88] Pre Create File Test (invalid block size)");
            try
            {
                api.PreCreateFile("/pcsapi_testbench/slice_invalid.dat", 0); //errno 2
            }
            catch { }

            trace.TraceInfo("[28/88] Slice Upload Test (general test)");
            data = new byte[BaiduPCS.UPLOAD_SLICE_SIZE + 1];
            var ms3 = new MemoryStream(data);

            rnd.NextBytes(data);
            string slice1 = null, slice2 = null;

            try
            {
                slice1 = api.UploadSliceRaw(ms3, "/pcsapi_testbench/tmp", uploadid, 0, (a, b, c, d) => { });  //file md5
                slice2 = api.UploadSliceRaw(ms3, "/pcsapi_testbench/tmp2", uploadid, 1, (a, b, c, d) => { }); //file md5
            }
            catch { }

            trace.TraceInfo("[29/88] Slice Upload Test (invalid path test)");
            ms.Seek(-1, SeekOrigin.End);
            var id = api.PreCreateFile("/pcsapi_testbench/test_slice_upload.dat", 1);

            try
            {
                api.UploadSliceRaw(ms, "/pcsapi_testbench/:XD", id.UploadId, 1, (a, b, c, d) => { }); //file md5
            }
            catch { }

            trace.TraceInfo("[30/88] Slice Upload Test (invalid uploadid test)");
            ms.Seek(-1, SeekOrigin.End);
            try
            {
                api.UploadSliceRaw(ms, "/pcsapi_testbench/test_slice_upload2.dat", "haha", 1, (a, b, c, d) => { }); //error_code 31299 : Invalid param poms key
            }
            catch { }

            trace.TraceInfo("[31/88] Upload Test (invalid input stream test)");
            try
            {
                var s = new MemoryStream(new byte[] { 1 });
                s.Close();
                s.Dispose();
                api.UploadRaw(s, 1, "/pcsapi_testbench/new_upload.dat"); //empty meta
            }
            catch { }

            trace.TraceInfo("[32/88] Slice Upload Test (invalid input stream test)");
            try
            {
                var s = new MemoryStream(new byte[] { 2 });
                s.Close();
                s.Dispose();
                api.UploadSliceRaw(s, "/pcsapi_testbench/new_slice_upload._dat", id.UploadId, 1, (a, b, c, d) => { }); //ObjectDisposedException
            }
            catch { }

            trace.TraceInfo("[33/88] Slice Upload Test (seq out of range test)");
            ms.Seek(-1, SeekOrigin.End);
            try
            {
                api.UploadSliceRaw(ms, "/pcsapi_testbench/test_slice_upload3.dat", id.UploadId, 2, (a, b, c, d) => { }); //file md5
            }
            catch { }

            trace.TraceInfo("[34/88] Quota Test");
            try
            {
                api.GetQuota(); //Quota
            }
            catch { }

            trace.TraceInfo("[35/88] Locate Download Test (general test)");
            try
            {
                api.GetLocateDownloadLink("/pcsapi_testbench/5mb_file.dat"); //string[5]
            }
            catch { }

            trace.TraceInfo("[36/88] Locate Download Test (non existing path)");
            try
            {
                api.GetLocateDownloadLink("/pcsapi_testbench/nothing"); //error_code 31066 : file does not exist
            }
            catch { }

            trace.TraceInfo("[37/88] Locate Download Test (invalid path)");
            try
            {
                api.GetLocateDownloadLink("/pcsapi_testbench/:data"); //error_code 31066 : file does not exist
            }
            catch { }

            trace.TraceInfo("[38/88] Locate Download Test (empty path)");
            try
            {
                api.GetLocateDownloadLink(""); //ArgumentNullException
            }
            catch { }

            trace.TraceInfo("[39/88] PCS Download Test (general test, https)");
            try
            {
                api.GetDownloadLink(filedata.FS_ID); //https url
            }
            catch { }

            trace.TraceInfo("[40/88] PCS Download Test (general test, http)");
            try
            {
                api.GetDownloadLink(filedata.FS_ID, false); //http url
            }
            catch { }

            trace.TraceInfo("[41/88] PCS Download Test (invalid fs_id test)");
            try
            {
                api.GetDownloadLink(filedata.FS_ID + (ulong)rnd.Next(500)); //empty string
            }
            catch { }

            trace.TraceInfo("[42/88] PCS Download Test (zero fs_id test)");
            try
            {
                api.GetDownloadLink(0); //ArgumentNullException
            }
            catch { }

            trace.TraceInfo("[43/88] Rapid Upload Test (general test)");
            try
            {
                api.RapidUploadRaw("/pcsapi_testbench/rapid_upload_test.dat", (ulong)ms2.Length, content_md5, content_crc32, slice_md5); //meta: /pcsapi_testbench/rapid_upload_test.dat
            }
            catch { }

            trace.TraceInfo("[44/88] Rapid Upload Test (invalid slice md5)");
            try
            {
                api.RapidUploadRaw("/pcsapi_testbench/rapid_upload_test2.dat", (ulong)ms2.Length, content_md5, content_crc32, "abababababababababababababababab"); //meta: /pcsapi_testbench/rapid_upload_test2.dat
            }
            catch { }

            trace.TraceInfo("[45/88] Rapid Upload Test (empty slice md5)");
            try
            {
                api.RapidUploadRaw("/pcsapi_testbench/rapid_upload_test2.dat", (ulong)ms2.Length, content_md5, content_crc32, ""); //error_code 31023 : param error
            }
            catch { }

            trace.TraceInfo("[46/88] Rapid Upload Test (invalid md5)");
            try
            {
                api.RapidUploadRaw("/pcsapi_testbench/rapid_upload_test3.dat", (ulong)ms2.Length, "abababababababababababababababab", content_crc32, slice_md5); //error_code 31079 : file md5 not found, you should use upload api to upload the whole file
            }
            catch { }

            trace.TraceInfo("[47/88] Rapid Upload Test (empty md5)");
            try
            {
                api.RapidUploadRaw("/pcsapi_testbench/rapid_upload_test3.dat", (ulong)ms2.Length, "", content_crc32, slice_md5); //error_code 31023 : param error
            }
            catch { }

            trace.TraceInfo("[48/88] Rapid Upload Test (invalid crc32)");
            try
            {
                api.RapidUploadRaw("/pcsapi_testbench/rapid_upload_test4.dat", (ulong)ms2.Length, content_md5, "abcdef89", slice_md5); //meta: /pcsapi_testbench/rapid_upload_test4.dat
            }
            catch { }

            trace.TraceInfo("[49/88] Rapid Upload Test (empty crc32)");
            try
            {
                api.RapidUploadRaw("/pcsapi_testbench/rapid_upload_test4.dat", (ulong)ms2.Length, content_md5, "", slice_md5); //meta: /pcsapi_testbench/rapid_upload_test4.dat
            }
            catch { }

            trace.TraceInfo("[50/88] Rapid Upload Test (invalid length)");
            try
            {
                api.RapidUploadRaw("/pcsapi_testbench/rapid_upload_test5.dat", 0, content_md5, content_crc32, slice_md5); //meta: /pcsapi_testbench/rapid_upload_test4.dat (with size 0)
            }
            catch { }

            trace.TraceInfo("[51/88] Rapid Upload Test (overwrite test)");
            try
            {
                api.RapidUploadRaw("/pcsapi_testbench/100b_file.dat", (ulong)ms2.Length, content_md5, content_crc32, slice_md5, BaiduPCS.ondup.overwrite);//meta: /pcsapi_testbench/100b_file.dat
            }
            catch { }

            trace.TraceInfo("[52/88] Rapid Upload Test (newcopy test)");
            try
            {
                api.RapidUploadRaw("/pcsapi_testbench/rapid_upload_test.dat", (ulong)ms2.Length, content_md5, content_crc32, slice_md5, BaiduPCS.ondup.newcopy); //meta: /pcsapi_testbench/rapid_upload_test_yyyyMMddHHmmss.dat
            }
            catch { }

            trace.TraceInfo("[53/88] Rapid Upload Test (invalid path)");
            try
            {
                api.RapidUploadRaw("/pcsapi_testbench/rapid_:nodata", (ulong)ms2.Length, content_md5, content_crc32, slice_md5); //error_code 31062 : file name is invalid
            }
            catch { }

            trace.TraceInfo("[54/88] Copy Test (general test, single file)");
            try
            {
                api.CopyPath("/pcsapi_testbench/100b_file.dat", "/pcsapi_testbench/100b_file.dat2"); //true
            }
            catch { }

            trace.TraceInfo("[55/88] Copy Test (general test, single directory)");
            try
            {
                api.CopyPath("/pcsapi_testbench/conflict_test", "/pcsapi_testbench/new_dir"); //true
            }
            catch { }

            trace.TraceInfo("[56/88] Copy Test (general test, mixed multi data)");
            try
            {
                api.CopyPath(new string[] { "/pcsapi_testbench/100b_file.dat2", "/pcsapi_testbench/new_dir" }, new string[] { "/pcsapi_testbench/new_file.dat", "/pcsapi_testbench/new_dir2" }); //true
            }
            catch { }

            trace.TraceInfo("[57/88] Copy Test (invalid src path test)");
            try
            {
                api.CopyPath("/pcsapi_testbench/haha:D", "/pcsapi_testbench/test_copy_invalid.dat"); //errno 12
            }
            catch { }

            trace.TraceInfo("[58/88] Copy Test (invalid dst path test)");
            try
            {
                api.CopyPath("/pcsapi_testbench/new_file.dat", "/pcsapi_testbench/new_dir/haha:D"); //errno 12
            }
            catch { }

            trace.TraceInfo("[59/88] Copy Test (overwriting same type)");
            try
            {
                api.CopyPath("/pcsapi_testbench/100b_file.dat", "/pcsapi_testbench/the_new_file.dat"); //true
                api.CopyPath("/pcsapi_testbench/new_file.dat", "/pcsapi_testbench/the_new_file.dat");  //errno 12
            }
            catch { }

            trace.TraceInfo("[60/88] Copy Test (overwriting diff type)");
            try
            {
                api.CopyPath("/pcsapi_testbench/new_file.dat", "/pcsapi_testbench/new_dir"); //errno 12
            }
            catch { }

            trace.TraceInfo("[61/88] Copy Test (newcopying same type)");
            try
            {
                api.CopyPath("/pcsapi_testbench/new_file.dat", "/pcsapi_testbench/rapid_upload_test.dat", BaiduPCS.ondup.newcopy); //true : /pcsapi_testbench/rapid_upload_test(1).dat
            }
            catch { }

            trace.TraceInfo("[62/88] Copy Test (newcopying diff type)");
            try
            {
                api.CopyPath("/pcsapi_testbench/new_file.dat", "/pcsapi_testbench/new_dir", BaiduPCS.ondup.newcopy); //true: /pcsapi_testbench/new_dir(1) (file)
            }
            catch { }

            trace.TraceInfo("[63/88] Copy Test (src length differs from dst length)");
            try
            {
                api.CopyPath(new string[] { "/pcsapi_testbench/new_file.dat" }, new string[] { "/pcsapi_testbench/new_file2.dat", "/pcsapi_testbench/new_file3.dat" }); //InvalidOperationException
            }
            catch { }

            trace.TraceInfo("[64/88] Copy Test (src not exist)");
            try
            {
                api.CopyPath("/pcsapi_testbench/new_non_exist.dat", "/pcsapi_testbench/new_non_exist2.dat"); //errno 12
            }
            catch { }

            trace.TraceInfo("[65/88] Move Test (general test, single file)");
            try
            {
                api.MovePath("/pcsapi_testbench/100b_file.dat", "/pcsapi_testbench/move/100b_file.dat2"); //true
            }
            catch { }

            trace.TraceInfo("[66/88] Move Test (general test, single directory)");
            try
            {
                api.MovePath("/pcsapi_testbench/conflict_test", "/pcsapi_testbench/move/new_dir"); //true
            }
            catch { }

            trace.TraceInfo("[67/88] Move Test (general test, mixed multi data)");
            try
            {
                api.MovePath(new string[] { "/pcsapi_testbench/100b_file.dat2", "/pcsapi_testbench/new_dir" }, new string[] { "/pcsapi_testbench/move/new_file.dat", "/pcsapi_testbench/move/new_dir2" }); //true
            }
            catch { }

            trace.TraceInfo("[68/88] Move Test (invalid src path test)");
            try
            {
                api.MovePath("/pcsapi_testbench/haha:D", "/pcsapi_testbench/move/test_copy_invalid.dat"); //errno 12
            }
            catch { }

            trace.TraceInfo("[69/88] Move Test (invalid dst path test)");
            try
            {
                api.MovePath("/pcsapi_testbench/new_file.dat", "/pcsapi_testbench/move/new_dir/haha:D"); //errno 12
            }
            catch { }

            trace.TraceInfo("[70/88] Move Test (overwriting same type)");
            try
            {
                api.MovePath("/pcsapi_testbench/move/new_file.dat", "/pcsapi_testbench/move/rapid_upload_test.dat"); //true
            }
            catch { }

            trace.TraceInfo("[71/88] Move Test (overwriting diff type)");
            try
            {
                api.MovePath("/pcsapi_testbench/move/new_file.dat", "/pcsapi_testbench/move/new_dir"); //errno 12
            }
            catch { }

            trace.TraceInfo("[72/88] Move Test (newcopying same type)");
            try
            {
                api.CopyPath("/pcsapi_testbench/move/rapid_upload_test.dat", "/pcsapi_testbench/move/new_file.dat", BaiduPCS.ondup.newcopy); //true
                api.MovePath("/pcsapi_testbench/move/rapid_upload_test.dat", "/pcsapi_testbench/move/new_file.dat", BaiduPCS.ondup.newcopy); //true: /pcsapi_testbench/move/new_file(1).dat
            }
            catch { }

            trace.TraceInfo("[73/88] Move Test (newcopying diff type)");
            try
            {
                api.MovePath("/pcsapi_testbench/move/new_file.dat", "/pcsapi_testbench/move/new_dir", BaiduPCS.ondup.newcopy); //true: /pcsapi_testbench/move/new_dir(1) (file)
            }
            catch { }

            trace.TraceInfo("[74/88] Move Test (src length differs from dst length)");
            try
            {
                api.MovePath(new string[] { "/pcsapi_testbench/move/new_file.dat" }, new string[] { "/pcsapi_testbench/move/new_file2.dat", "/pcsapi_testbench/move/new_file3.dat" }); //InvalidOperationException
            }
            catch { }

            trace.TraceInfo("[75/88] Move Test (src not exist)");
            try
            {
                api.MovePath("/pcsapi_testbench/move/new_non_exist.dat", "/pcsapi_testbench/move/new_non_exist2.dat"); //errno 12
            }
            catch { }

            trace.TraceInfo("[76/88] Create Super File Test (general test)");
            ms2.Seek(0, SeekOrigin.Begin);
            try
            {
                api.CreateSuperFile("/pcsapi_testbench/super.dat", uploadid, new string[] { slice1, slice2 }, (ulong)ms3.Length); //meta: /pcsapi_testbench/super.dat
            }
            catch { }

            trace.TraceInfo("[77/88] Create Super File Test (invalid upload id)");
            try
            {
                api.CreateSuperFile("/pcsapi_testbench/super2.dat", "qwert", new string[] { slice1, slice2 }, (ulong)ms3.Length); //errno 31353
            }
            catch { }

            trace.TraceInfo("[78/88] Create Super File Test (missing slice)");
            try
            {
                api.CreateSuperFile("/pcsapi_testbench/super3.dat", uploadid, new string[] { slice1 }, (ulong)ms3.Length - 1); //errno 2
            }
            catch { }

            trace.TraceInfo("[79/88] Create Super File Test (invalid slice md5)");
            try
            {
                api.CreateSuperFile("/pcsapi_testbench/super4.dat", uploadid, new string[] { "abababababababababababababababab", slice2 }, (ulong)ms3.Length); //errno 2
            }
            catch { }

            trace.TraceInfo("[80/88] Create Super File Test (invalid file size)");
            try
            {
                api.CreateSuperFile("/pcsapi_testbench/super5.dat", uploadid, new string[] { slice1, slice2 }, (ulong)ms3.Length + 2); //errno 2
            }
            catch { }

            trace.TraceInfo("[81/88] Create Super File Test (invalid path)");
            try
            {
                api.CreateSuperFile("/pcsapi_testbench/:<>haha", uploadid, new string[] { slice1, slice2 }, (ulong)ms3.Length); //errno -7
            }
            catch { }

            trace.TraceInfo("[82/88] Create Super File Test (empty path)");
            try
            {
                api.CreateSuperFile("", uploadid, new string[] { slice1, slice2 }, (ulong)ms3.Length); //ArgumentNullException
            }
            catch { }

            trace.TraceInfo("[83/88] Delete Test (general test, single)");
            try
            {
                api.DeletePath("/pcsapi_testbench/move"); //true
            }
            catch { }

            trace.TraceInfo("[84/88] Delete Test (gemeral test, multi)");
            try
            {
                api.DeletePath(new string[] { "/pcsapi_testbench/super.dat", "/pcsapi_testbench/rapid_upload_test.dat" }); //true
            }
            catch { }

            trace.TraceInfo("[85/88] Delete Test (path invalid)");
            try
            {
                api.DeletePath("/pcsapi_testbench/haha:D"); //errno 12
            }
            catch { }

            trace.TraceInfo("[86/88] Delete Test (non existing path)");
            try
            {
                api.DeletePath("/pcsapi_testbench/helloworld"); //true
            }
            catch { }

            trace.TraceInfo("[87/88] Delete Test (empty path)");
            try
            {
                api.DeletePath(""); //ArgumentNullException
            }
            catch { }

            trace.TraceInfo("[88/88] Delete Test (half non exist)");
            try
            {
                api.DeletePath(new string[] { "/pcsapi_testbench/5mb_file.dat", "/pcsapi_testbench/non_existing" }); //errno 12
            }
            catch { }

            trace.TraceInfo("Test finished, deleting temporary remote directory");
            try
            {
                api.DeletePath("/pcsapi_testbench");
            }
            catch { }
        }
Esempio n. 35
0
            public IEnumerator beginToLoad(string sAssetPath, eLoadResPath eloadrespath, string sInputPath, System.Type type, string tag, string sResGroupkey, string md5, bool basyn, bool bNoUseCatching, bool bautoReleaseBundle, bool bOnlyDownload, bool bloadfromfile)
            {
                //请求时候的bundle路径
                //请求时候的asset路径
                string assetsbundlepath;
                string assetname;
                string sinputbundlename;
                string sinputbundlenamewithoutpostfix;

                if (sAssetPath.Contains("|"))
                {
                    assetsbundlepath = sAssetPath.Split('|')[0];
                    assetname        = sAssetPath.Split('|')[1];
                    sinputbundlenamewithoutpostfix = Path.GetDirectoryName(sInputPath);
                    sinputbundlename = sinputbundlenamewithoutpostfix + ResourceLoadManager.msBundlePostfix;
                }
                else
                {//没有'|',表示只是加载assetbundle,不加载里面的资源(例如场景Level对象,依赖assetbundle)
                    assetsbundlepath = sAssetPath;
                    assetname        = string.Empty;
                    sinputbundlenamewithoutpostfix = sInputPath;
                    sinputbundlename = sInputPath + ResourceLoadManager.msBundlePostfix;
                }
                //CLog.Log("start to load===" + assetname);


                //资源标示
                string sReskey = (sAssetPath + ":" + type.ToString());

                //包路径Hash

                //记录此bundle被要求加载的协程次数,外部可能在一个资源加载挂起时多次调用同一资源的加载协程
                string sAssetbundlepath = assetsbundlepath;



                if (_mDicAssetNum.ContainsKey(sReskey))
                {
                    _mDicAssetNum[sReskey]++;
                }
                else
                {
                    _mDicAssetNum.Add(sReskey, 1);
                }
                //while (ListLoadingBundle.Count > 5)
                //{
                //    yield return 1;
                //}


                AssetBundle nowAssetBundle         = null;
                bool        bdownloadbundlesuccess = true;
                Dictionary <string, AssetBundle> DicLoadedBundle = ResourceLoadManager._mDicLoadedBundle;
                List <string> ListLoadingBundle = ResourceLoadManager._mListLoadingBundle;

                if (DicLoadedBundle.ContainsKey(sAssetbundlepath))
                {//如果加载好的bundle,直接取
                    nowAssetBundle = DicLoadedBundle[sAssetbundlepath];
                    if (nowAssetBundle == null)
                    {
                        DLoger.LogError("loaded bundle== " + sAssetbundlepath + "is null");
                    }
                }
                else if (ListLoadingBundle.Contains(sAssetbundlepath))
                {
                    while (!DicLoadedBundle.ContainsKey(sAssetbundlepath))
                    {//这里挂起所有非第一次加载bundl的请求
                        yield return(1);
                    }
                    nowAssetBundle = DicLoadedBundle[sAssetbundlepath];
                    if (nowAssetBundle == null)
                    {
                        DLoger.LogError("loaded bundle== " + sAssetbundlepath + "is null");
                    }
                }
                else
                {//这里是第一次加载该bundle
                    //将该bundle加入正在加载列表
                    ListLoadingBundle.Add(sAssetbundlepath);
                    string finalloadbundlepath = "";



                    AssetBundleCreateRequest abcr = null;

                    //如果是从远程下载
                    if (eloadrespath == eLoadResPath.RP_URL)
                    {
                        if (ResourceLoadManager._mbNotDownLoad == true)
                        {     //如果设置了不下载资源
                            if (CacheBundleInfo.hasBundle(sinputbundlenamewithoutpostfix))
                            { //如果caching有同名文件,从caching里直接读取
                             //下载路径
                                finalloadbundlepath = Application.persistentDataPath + "/bundles/" + ResourceLoadManager.msCachingPath + "/" + sinputbundlename;
                            }
                            else
                            {//否则从包里读取
                                finalloadbundlepath = sAssetbundlepath;
                            }
                        }
                        //检查cache配置,如果还没有,或者不使用caching,则从资源服务器下载该bundle
                        else if (!CacheBundleInfo.isCaching(sinputbundlenamewithoutpostfix, md5.ToString()) || bNoUseCatching)
                        {
                            DLoger.Log("WebRquest开始下载bundle:=" + sAssetbundlepath);
                            UnityWebRequest            webrequest    = UnityWebRequest.Get(sAssetbundlepath);
                            AsyncOperation             asop          = webrequest.Send();
                            Dictionary <string, ulong> dicdownbundle = ResourceLoadManager.mDicDownloadingBundleBytes;
                            if (!dicdownbundle.ContainsKey(sinputbundlename))
                            {
                                dicdownbundle.Add(sinputbundlename, 0);
                            }
                            else
                            {
                                DLoger.LogError("重复下载bundle:" + sAssetbundlepath);
                                dicdownbundle[sinputbundlename] = 0;
                            }
                            float fnospeeddownloadtime = 0;
                            bool  bloadoutoftime       = false;
                            while (!asop.isDone)
                            {
                                if (webrequest.isError)
                                {
                                    break;
                                }
                                if (dicdownbundle[sinputbundlename] == webrequest.downloadedBytes && webrequest.downloadedBytes != 0)
                                {//如果下载字节数一直没变,则开始计时
                                    fnospeeddownloadtime += Time.unscaledDeltaTime;
                                    //DLoger.Log("WebRequest下载速度为0 =" + sAssetbundlepath);
                                }
                                else
                                {
                                    //DLoger.Log("WebRequest下载速度正常 =" + sAssetbundlepath);
                                    fnospeeddownloadtime = 0;
                                }
                                //if (fnospeeddownloadtime != 0)
                                //{
                                //    DLoger.LogError("WebRequest下载超时时间=" + fnospeeddownloadtime);
                                //}

                                if (fnospeeddownloadtime > 15.0f)
                                {//如果下载字节数没变超时
                                    DLoger.LogError("WebRequest下载=" + sAssetbundlepath + "=超时!下载失败!");
                                    bloadoutoftime = true;
                                    break;
                                }
                                //DLoger.Log("WebRequest下载速度为0持续时间 =" + fnospeeddownloadtime);
                                dicdownbundle[sinputbundlename] = webrequest.downloadedBytes;
                                //DLoger.Log("downloadbundle data bytes:" + sAssetbundlepath + ":" + dicdownbundle[sinputbundlename], "down");
                                yield return(null);
                            }
                            dicdownbundle[sinputbundlename] = webrequest.downloadedBytes;
                            DLoger.Log("downloadbundle data bytes:" + sAssetbundlepath + ":" + dicdownbundle[sinputbundlename], "down");
                            //下载完毕,存入缓存路径
                            if (webrequest.isError || bloadoutoftime)
                            {
                                bdownloadbundlesuccess = false;
                                DLoger.LogError("WebRquest下载失败bundle:=" + sAssetbundlepath + "=failed!=" + webrequest.error);
                                //下载失败
                                ResourceLoadManager._removeLoadingResFromList(sReskey);
                                ResourceLoadManager._removePathInResGroup(sResGroupkey, sReskey, sAssetPath, sInputPath, false);
                            }
                            else
                            {
                                DLoger.Log("WebRquest下载成功bundle:=" + sAssetbundlepath);
                                if (!bNoUseCatching)
                                {//如果使用caching,则将下载的bundle写入指定路径
                                    if (ResourceLoadManager._mURLAssetBundleManifest.getBundleSize(sinputbundlenamewithoutpostfix) == webrequest.downloadHandler.data.Length)
                                    {
                                        //下载路径
                                        finalloadbundlepath = Application.persistentDataPath + "/bundles/" + ResourceLoadManager.msCachingPath + "/" + sinputbundlename;
                                        DLoger.Log("开始写入Caching:bundle:=" + finalloadbundlepath);
                                        string dir = Path.GetDirectoryName(finalloadbundlepath);
                                        if (!Directory.Exists(dir))
                                        {
                                            Directory.CreateDirectory(dir);
                                        }
                                        if (File.Exists(finalloadbundlepath))
                                        {
                                            File.Delete(finalloadbundlepath);
                                        }

                                        FileStream fs = new FileStream(finalloadbundlepath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, webrequest.downloadHandler.data.Length);
                                        fs.Write(webrequest.downloadHandler.data, 0, webrequest.downloadHandler.data.Length);
                                        fs.Flush();
                                        fs.Close();
                                        fs.Dispose();

                                        FileStream fscheck = new FileStream(finalloadbundlepath, FileMode.Open);
                                        System.Security.Cryptography.MD5CryptoServiceProvider md5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider();
                                        byte[] resultEncrypt = md5CSP.ComputeHash(fscheck);
                                        fscheck.Close();
                                        fscheck.Dispose();

                                        string sdownloadmd5 = System.BitConverter.ToString(resultEncrypt);
                                        if (sdownloadmd5 == md5)
                                        {
                                            //写入caching配置
                                            CacheBundleInfo.updateBundleInfo(sinputbundlenamewithoutpostfix, md5.ToString());
                                            CacheBundleInfo.saveBundleInfo();
                                            DLoger.Log("成功写入Caching:bundle:=" + finalloadbundlepath);
                                        }
                                        else
                                        {
                                            DLoger.LogError("WebRquest成功下载bundle的MD5和配置大小不一样!WebRquest:" + sdownloadmd5 + "=vs=" + "配置:" + md5);
                                            bdownloadbundlesuccess = false;
                                            finalloadbundlepath    = "";
                                            ResourceLoadManager._removeLoadingResFromList(sReskey);
                                            ResourceLoadManager._removePathInResGroup(sResGroupkey, sReskey, sAssetPath, sInputPath, false);
                                        }
                                    }
                                    else
                                    {
                                        DLoger.LogError("WebRquest成功下载bundle大小和配置大小不一样!WebRquest:" + webrequest.downloadHandler.data.Length + "=vs=" + "配置:" + ResourceLoadManager._mURLAssetBundleManifest.getBundleSize(sinputbundlenamewithoutpostfix));
                                        bdownloadbundlesuccess = false;
                                        finalloadbundlepath    = "";
                                        ResourceLoadManager._removeLoadingResFromList(sReskey);
                                        ResourceLoadManager._removePathInResGroup(sResGroupkey, sReskey, sAssetPath, sInputPath, false);
                                    }
                                }
                                else
                                {
                                    if (!bOnlyDownload)
                                    {
                                        DLoger.Log("LoadFromMemoryAsync:" + sAssetbundlepath);
                                        abcr = AssetBundle.LoadFromMemoryAsync(webrequest.downloadHandler.data);
                                        yield return(abcr);

                                        if (abcr.isDone)
                                        {
                                            nowAssetBundle = abcr.assetBundle;
                                        }
                                        else
                                        {
                                            bdownloadbundlesuccess = false;
                                            DLoger.LogError("LoadFromMemoryAsync=" + sAssetbundlepath + "=failed!=");
                                            //下载失败
                                            ResourceLoadManager._removeLoadingResFromList(sReskey);
                                            ResourceLoadManager._removePathInResGroup(sResGroupkey, sReskey, sAssetPath, sInputPath, false);
                                        }
                                        abcr = null;
                                    }
                                }
                            }
                            //下载完毕释放webrequest
                            if (webrequest != null)
                            {
                                webrequest.Dispose();
                                webrequest = null;
                            }
                        }
                        else if (CacheBundleInfo.isCaching(sinputbundlenamewithoutpostfix, md5.ToString()))
                        {
                            //下载路径
                            finalloadbundlepath = Application.persistentDataPath + "/bundles/" + ResourceLoadManager.msCachingPath + "/" + sinputbundlename;
                        }
                    }
                    else if (eloadrespath == eLoadResPath.RP_Caching)
                    {
                        if (CacheBundleInfo.hasBundle(sinputbundlenamewithoutpostfix))
                        {//如果caching有同名文件,从caching里直接读取
                            //下载路径
                            finalloadbundlepath = Application.persistentDataPath + "/bundles/" + ResourceLoadManager.msCachingPath + "/" + sinputbundlename;
                        }
                        else
                        {//否则从包里读取
                            finalloadbundlepath = ResourceLoadManager.mResourceStreamingAssets + "/" + sinputbundlename;
                        }
                    }
                    else
                    {//否则就是读取包中的路径
                        finalloadbundlepath = sAssetbundlepath;
                    }


                    if (nowAssetBundle == null && finalloadbundlepath != "")
                    {//如果bundle没有创建(如果没创建,则说明是下载下来并且caching,或者直接读app包;如果创建了,则是url读取并且不caching这种情况)
                        if (!bOnlyDownload)
                        {
                            if (bloadfromfile)
                            {
                                DLoger.Log("开始加载bundle:AssetBundle.LoadFromFile= " + finalloadbundlepath);
                                //nowAssetBundle = AssetBundle.LoadFromFile(finalloadbundlepath);
                                abcr = AssetBundle.LoadFromFileAsync(finalloadbundlepath);
                                yield return(abcr);

                                if (abcr.isDone)
                                {
                                    nowAssetBundle = abcr.assetBundle;
                                }
                                else
                                {
                                    bdownloadbundlesuccess = false;
                                    DLoger.LogError("LoadFromFileAsync=" + sAssetbundlepath + "=failed!=");
                                    //下载失败
                                    ResourceLoadManager._removeLoadingResFromList(sReskey);
                                    ResourceLoadManager._removePathInResGroup(sResGroupkey, sReskey, sAssetPath, sInputPath, false);
                                }
                                abcr = null;
                            }
                            else
                            {//从memery加载,对于小而多的Object的加载这个IO更少,但是内存会更大
                                DLoger.Log("开始加载bundle:AssetBundle.LoadFromMemery= " + finalloadbundlepath);
                                byte[] bts = null;
                                WWW    www = null;
                                if (eloadrespath == eLoadResPath.RP_URL || eloadrespath == eLoadResPath.RP_Caching)
                                {//从caching加载
                                    bts = File.ReadAllBytes(finalloadbundlepath);
                                }
                                else
                                {
                                    string wwwpath = ResourceLoadManager.mResourceStreamingAssetsForWWW + sinputbundlename;
                                    DLoger.Log("开始www= " + wwwpath);
                                    www = new WWW(wwwpath);
                                    yield return(www);

                                    if (www.isDone && www.error == null)
                                    {
                                        bts = www.bytes;
                                    }
                                    else
                                    {
                                        DLoger.LogError(www.error);
                                    }
                                }
                                if (bts != null)
                                {
                                    //nowAssetBundle = AssetBundle.LoadFromMemory(bts);
                                    abcr = AssetBundle.LoadFromMemoryAsync(bts);
                                    yield return(abcr);

                                    if (abcr.isDone)
                                    {
                                        nowAssetBundle = abcr.assetBundle;
                                    }
                                    else
                                    {
                                        bdownloadbundlesuccess = false;
                                        DLoger.LogError("LoadFromMemoryAsync=" + sAssetbundlepath + "=failed!=");
                                        //下载失败
                                        ResourceLoadManager._removeLoadingResFromList(sReskey);
                                        ResourceLoadManager._removePathInResGroup(sResGroupkey, sReskey, sAssetPath, sInputPath, false);
                                    }
                                }

                                abcr = null;
                                if (www != null)
                                {
                                    www.Dispose();
                                    www = null;
                                }
                            }
                        }
                    }
                    ListLoadingBundle.Remove(sAssetbundlepath);
                    if (nowAssetBundle != null)
                    {
                        DicLoadedBundle.Add(sAssetbundlepath, nowAssetBundle);
                    }
                }

                if (nowAssetBundle != null)
                {//加载assetsbundle成功
                 /*注释掉秒删,会造成资源重复加载
                  * //缓存中不用的的资源,秒删
                  * //Caching.expirationDelay = 1;
                  */
                 //DLoger.Log("成功加载bundle : " + assetsbundlepath + "===successful!");


                    AssetBundle assetbundle = nowAssetBundle;
                    //AssetBundle assetbundle = mywww.assetBundle;
                    //AssetBundle assetbundle = mDicLoadedBundle[sAssetbundlepath];

                    if (assetname != string.Empty)
                    {
                        //DLoger.Log("开始读取= " + assetname + "= in =" + assetsbundlepath);

                        Object t = null;
                        //开始加载asset
                        if (basyn)
                        {     //如果是异步加载
                            if (_mDicLoadingAssets.ContainsKey(sReskey))
                            { //如果正在加载,则返回等待
                                //yield return _mDicLoadingAssets[sReskey];
                                while (!_mDicLoadingAssets[sReskey].isDone)
                                {
                                    yield return(1);
                                }
                            }
                            else
                            {//否则,开始加载
                                //文件对象名称
                                //CLog.Log("begin to load asset ==" + assetname);
                                if (!_mDicLoadingAssetstime.ContainsKey(sReskey))
                                {
                                    _mDicLoadingAssetstime.Add(sReskey, Time.realtimeSinceStartup);
                                }
                                AssetBundleRequest request = assetbundle.LoadAssetAsync(assetname, type);
                                _mDicLoadingAssets.Add(sReskey, request);

                                //第一个要求加载此资源的在这挂起
                                yield return(request);
                            }
                            //加载完毕
                            //                    CLog.Log("load asset ==" + assetname + "===successful!");
                            AssetBundleRequest myrequest = _mDicLoadingAssets[sReskey];
                            t         = myrequest.asset as Object;
                            myrequest = null;

                            //处理完此资源的加载协程,对请求此资源的加载协程计数减一
                            _mDicAssetNum[sReskey]--;

                            if (_mDicAssetNum[sReskey] == 0)
                            {//如果所有加载此资源的协程都处理完毕,释放资源
                                _mDicLoadingAssets.Remove(sReskey);
                                _mDicAssetNum.Remove(sReskey);
                            }
                        }
                        else
                        {
                            //CLog.Log("begin to load asset ==" + assetname);
                            if (!_mDicLoadingAssetstime.ContainsKey(sReskey))
                            {
                                _mDicLoadingAssetstime.Add(sReskey, Time.realtimeSinceStartup);
                            }

                            t = assetbundle.LoadAsset(assetname, type) as Object;

                            //处理完此资源的加载协程,对请求此资源的加载协程计数减一
                            _mDicAssetNum[sReskey]--;

                            if (_mDicAssetNum[sReskey] == 0)
                            {//如果所有加载此资源的协程都处理完毕,释放资源
                                _mDicLoadingAssets.Remove(sReskey);
                                _mDicAssetNum.Remove(sReskey);
                            }
                        }
                        if (ResourceLoadManager.mbLoadAssetWait)
                        {
                            yield return(1);
                        }
                        _miloadingAssetNum--;
                        //DLoger.Log("加载=" + sAssetPath + "=完毕当前_miloadingAssetNum - 1:" + _miloadingAssetNum);
                        if (t != null)
                        {//加载成功,加入资源管理器,执行回调
                            float fusetime = -1.0f;
                            if (_mDicLoadingAssetstime.ContainsKey(sReskey))
                            {
                                fusetime = (Time.realtimeSinceStartup - _mDicLoadingAssetstime[sReskey]);
                            }
                            DLoger.Log("assetbundle.LoadAsset:成功读取= " + assetname + "= in =" + sAssetbundlepath + "===successful!time :" + fusetime);

                            ResourceLoadManager._addResAndRemoveInLoadingList(sReskey, t, tag, sInputPath);
                            ResourceLoadManager._removePathInResGroup(sResGroupkey, sReskey, sAssetPath, sInputPath, true);
                        }
                        else
                        {
                            ResourceLoadManager._removeLoadingResFromList(sReskey);
                            ResourceLoadManager._removePathInResGroup(sResGroupkey, sReskey, sAssetPath, sInputPath, false);
                            DLoger.LogError("Load===" + sAssetPath + "===Failed");
                        }
                        _mDicLoadingAssetstime.Remove(sReskey);
                    }
                    else
                    {//只加载assetbundle的资源,不加载asset的时候的操作
                        if (ResourceLoadManager.mbLoadAssetWait)
                        {
                            yield return(1);
                        }
                        _miloadingAssetNum--;
                        //DLoger.Log("加载=" + sAssetPath + "=完毕当前_miloadingAssetNum - 1:" + _miloadingAssetNum);
                        if (bautoReleaseBundle)
                        {
                            ResourceLoadManager._removeLoadingResFromList(sReskey);
                        }
                        else
                        {
                            ResourceLoadManager._addResAndRemoveInLoadingList(sReskey, assetbundle, tag);
                        }


                        ResourceLoadManager._removePathInResGroup(sResGroupkey, sReskey, sAssetPath, sInputPath, true);
                    }
                }
                else if (assetname == string.Empty)
                {//如果不加载asset,说明只是下载bundle,并不加载
                    if (ResourceLoadManager.mbLoadAssetWait)
                    {
                        yield return(1);
                    }
                    _miloadingAssetNum--;
                    //DLoger.Log("加载=" + sAssetPath + "=完毕当前_miloadingAssetNum - 1:" + _miloadingAssetNum);
                    if (bdownloadbundlesuccess)
                    {
                        ResourceLoadManager._removeLoadingResFromList(sReskey);
                        ResourceLoadManager._removePathInResGroup(sResGroupkey, sReskey, sAssetPath, sInputPath, true);
                    }
                }
                else
                {//bundle下载出错,依赖其的assetname加载也算出错
                    if (ResourceLoadManager.mbLoadAssetWait)
                    {
                        yield return(1);
                    }
                    _miloadingAssetNum--;
                    //DLoger.Log("加载=" + sAssetPath + "=完毕当前_miloadingAssetNum - 1:" + _miloadingAssetNum);
                    ResourceLoadManager._removeLoadingResFromList(sReskey);
                    ResourceLoadManager._removePathInResGroup(sResGroupkey, sReskey, sAssetPath, sInputPath, false);
                }
            }
Esempio n. 36
0
 public static byte[] MD5hash(byte[] data)
 {
     System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] result = md5.ComputeHash(data);
     return(result);
 }
Esempio n. 37
0
        /// Returns MD5 hash computed via blocking read of entire file.
        public static byte[] GetMd5(string path)
        {
            var hashAlg = new System.Security.Cryptography.MD5CryptoServiceProvider();

            return(hashAlg.ComputeHash(new FileStream(path, FileMode.Open, FileAccess.Read)));
        }
Esempio n. 38
0
        public Guid CleanAndGetCheckSum()
        {
            // Make sure to update checksums in database if you are changing this method.
            var list = new List <string>();

            // GamePad.
            AddValue(ref list, x => x.PassThrough);
            AddValue(ref list, x => x.GamePadType);
            // Force Feedback.
            AddValue(ref list, x => x.ForceEnable);
            AddValue(ref list, x => x.ForceType);
            AddValue(ref list, x => x.ForceSwapMotor);
            AddValue(ref list, x => x.ForceOverall, "100");
            AddValue(ref list, x => x.LeftMotorPeriod);
            AddValue(ref list, x => x.LeftMotorDirection);
            AddValue(ref list, x => x.LeftMotorStrength, "100");
            AddValue(ref list, x => x.RightMotorPeriod);
            AddValue(ref list, x => x.RightMotorDirection);
            AddValue(ref list, x => x.RightMotorStrength, "100");
            // D-PAD
            AddValue(ref list, x => x.AxisToDPadDeadZone, "256");
            AddValue(ref list, x => x.AxisToDPadEnabled);
            AddValue(ref list, x => x.AxisToDPadOffset);
            // Buttons.
            AddValue(ref list, x => x.ButtonA);
            AddValue(ref list, x => x.ButtonB);
            AddValue(ref list, x => x.ButtonGuide);
            AddValue(ref list, x => x.ButtonBack);
            AddValue(ref list, x => x.ButtonStart);
            AddValue(ref list, x => x.ButtonX);
            AddValue(ref list, x => x.ButtonY);
            AddValue(ref list, x => x.DPad);
            AddValue(ref list, x => x.DPadDown);
            AddValue(ref list, x => x.DPadLeft);
            AddValue(ref list, x => x.DPadRight);
            AddValue(ref list, x => x.DPadUp);
            AddValue(ref list, x => x.LeftShoulder);
            AddValue(ref list, x => x.LeftThumbButton);
            AddValue(ref list, x => x.RightShoulder);
            AddValue(ref list, x => x.RightThumbButton);
            // Right Trigger.
            AddValue(ref list, x => x.RightTrigger);
            AddValue(ref list, x => x.RightTriggerDeadZone);
            AddValue(ref list, x => x.RightTriggerAntiDeadZone);
            AddValue(ref list, x => x.RightTriggerLinear);
            // Left Thumb Virtual Buttons.
            AddValue(ref list, x => x.LeftThumbUp);
            AddValue(ref list, x => x.LeftThumbRight);
            AddValue(ref list, x => x.LeftThumbDown);
            AddValue(ref list, x => x.LeftThumbLeft);
            // Left Thumb Axis X
            AddValue(ref list, x => x.LeftThumbAxisX);
            AddValue(ref list, x => x.LeftThumbDeadZoneX);
            AddValue(ref list, x => x.LeftThumbAntiDeadZoneX);
            AddValue(ref list, x => x.LeftThumbLinearX);
            // Left Thumb Axis Y
            AddValue(ref list, x => x.LeftThumbAxisY);
            AddValue(ref list, x => x.LeftThumbDeadZoneY);
            AddValue(ref list, x => x.LeftThumbAntiDeadZoneY);
            AddValue(ref list, x => x.LeftThumbLinearY);
            // Left Trigger.
            AddValue(ref list, x => x.LeftTrigger);
            AddValue(ref list, x => x.LeftTriggerDeadZone);
            AddValue(ref list, x => x.LeftTriggerAntiDeadZone);
            AddValue(ref list, x => x.LeftTriggerLinear);
            // Right Thumb Virtual Buttons.
            AddValue(ref list, x => x.RightThumbUp);
            AddValue(ref list, x => x.RightThumbRight);
            AddValue(ref list, x => x.RightThumbDown);
            AddValue(ref list, x => x.RightThumbLeft);
            // Right Thumb Axis X
            AddValue(ref list, x => x.RightThumbAxisX);
            AddValue(ref list, x => x.RightThumbDeadZoneX);
            AddValue(ref list, x => x.RightThumbAntiDeadZoneX);
            AddValue(ref list, x => x.RightThumbLinearX);
            // Right Thumb Axis Y
            AddValue(ref list, x => x.RightThumbAxisY);
            AddValue(ref list, x => x.RightThumbDeadZoneY);
            AddValue(ref list, x => x.RightThumbAntiDeadZoneY);
            AddValue(ref list, x => x.RightThumbLinearY);
            // Axis to Button dead-zones.
            AddValue(ref list, x => x.ButtonADeadZone);
            AddValue(ref list, x => x.ButtonBDeadZone);
            AddValue(ref list, x => x.ButtonBackDeadZone);
            AddValue(ref list, x => x.ButtonStartDeadZone);
            AddValue(ref list, x => x.ButtonXDeadZone);
            AddValue(ref list, x => x.ButtonYDeadZone);
            AddValue(ref list, x => x.LeftThumbButtonDeadZone);
            AddValue(ref list, x => x.RightThumbButtonDeadZone);
            AddValue(ref list, x => x.LeftShoulderDeadZone);
            AddValue(ref list, x => x.RightShoulderDeadZone);
            AddValue(ref list, x => x.DPadDownDeadZone);
            AddValue(ref list, x => x.DPadLeftDeadZone);
            AddValue(ref list, x => x.DPadRightDeadZone);
            AddValue(ref list, x => x.DPadUpDeadZone);
            // If all values are empty or default then...
            if (list.Count == 0)
            {
                return(Guid.Empty);
            }
            // Sort list to make sure that categorized order above doesn't matter.
            var sorted = list.OrderBy(x => x).ToArray();
            // Prepare list for checksum.
            var s     = string.Join("\r\n", sorted);
            var bytes = System.Text.Encoding.ASCII.GetBytes(s);
            var md5   = new System.Security.Cryptography.MD5CryptoServiceProvider();

            return(new Guid(md5.ComputeHash(bytes)));
        }
Esempio n. 39
0
 static public string GenMD5String(string str)
 {
     System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
     str = System.BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str)), 4, 8);
     return(str.Replace("-", ""));
 }
Esempio n. 40
0
        private static void GenerateSolution(string outputFile, string platform, string inputFile)
        {
            if (outputFile == null)
            {
                throw new OptionException("Expect one output file", "o");
            }

            if (platform == null)
            {
                throw new OptionException("Platform not specified", "p");
            }

            string projectSuffix = platform;

            // Read .sln
            var solution = Solution.FromFile(inputFile);

            var processors = new List <IProjectProcessor>();

            ProjectType projectType;

            if (Enum.TryParse(platform, out projectType))
            {
                processors.Add(new SynchronizeProjectProcessor(projectType));
            }

            var projectProcessorContexts = new List <ProjectProcessorContext>();

            var removedProjects = new List <Project>();

            // Select active projects
            SelectActiveProjects(solution, platform, projectProcessorContexts, removedProjects);

            // Remove unnecessary project dependencies
            CleanProjectDependencies(projectProcessorContexts, removedProjects);

            // Process projects
            foreach (var context in projectProcessorContexts)
            {
                foreach (var processor in processors)
                {
                    processor.Process(context);
                }
            }

            // Update project references
            UpdateProjectReferences(projectProcessorContexts, projectSuffix);

            // Update solution with project that were recreated differently
            UpdateSolutionWithModifiedProjects(projectProcessorContexts, projectSuffix);

            // Rebuild solution configurations
            UpdateSolutionBuildConfigurations(platform, solution, projectProcessorContexts);

            // Remove empty solution folders
            RemoveEmptySolutionFolders(solution);

            // Save .sln
            solution.SaveAs(outputFile);

            // If there is a DotSettings (Resharper team shared file), create one that also reuse this one
            // Note: For now, it assumes input and output solutions are in the same folder (when constructing relative path to DotSetting file)
            var dotSettingsFile = inputFile + ".DotSettings";

            if (File.Exists(dotSettingsFile))
            {
                // Generate a deterministic GUID based on output file
                var cryptoProvider    = new System.Security.Cryptography.MD5CryptoServiceProvider();
                var inputBytes        = Encoding.Default.GetBytes(Path.GetFileName(outputFile));
                var deterministicGuid = new Guid(cryptoProvider.ComputeHash(inputBytes));

                var resharperDotSettingsGenerator = new ResharperDotSettings
                {
                    SharedSolutionDotSettings = new FileInfo(dotSettingsFile),
                    FileInjectedGuid          = deterministicGuid,
                };

                var outputDotSettingsFile = resharperDotSettingsGenerator.TransformText();
                File.WriteAllText(outputFile + ".DotSettings", outputDotSettingsFile);
            }
        }
Esempio n. 41
0
 public static string ComputeHash(string val)
 {
     System.Security.Cryptography.MD5 myHash = new System.Security.Cryptography.MD5CryptoServiceProvider();
     myHash.ComputeHash(System.Text.Encoding.Default.GetBytes(val));
     return(Convert.ToBase64String(myHash.Hash));
 }
Esempio n. 42
0
        public static byte[] Md5(byte[] data)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();

            return(x.ComputeHash(data));
        }
Esempio n. 43
0
        /// <summary>手持登录</summary>
        public AscmUserInfo MobileLogin(string userId, string userPwd, string connString, ref string errorMsg)
        {
            AscmUserInfo ascmUserInfo = null;

            errorMsg = string.Empty;
            using (Oracle.DataAccess.Client.OracleConnection conn = new Oracle.DataAccess.Client.OracleConnection(connString))
            {
                if (conn.State != System.Data.ConnectionState.Open)
                {
                    conn.Open();
                }

                Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand();
                cmd.Connection  = conn;
                cmd.CommandText = "SELECT userId,userName,password,employeeId,extExpandType,extExpandId FROM ynUser WHERE extExpandId = :extExpandId";
                cmd.CommandType = System.Data.CommandType.Text;

                Oracle.DataAccess.Client.OracleParameter parm = new Oracle.DataAccess.Client.OracleParameter();
                parm.ParameterName = ":extExpandId";
                parm.OracleDbType  = Oracle.DataAccess.Client.OracleDbType.NVarchar2;
                parm.Size          = 20;
                parm.Value         = userId;
                parm.Direction     = System.Data.ParameterDirection.Input;
                cmd.Parameters.Add(parm);

                using (Oracle.DataAccess.Client.OracleDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
                {
                    cmd.Parameters.Clear();

                    if (reader.Read())
                    {
                        ascmUserInfo          = new AscmUserInfo();
                        ascmUserInfo.userId   = reader["userId"].ToString();
                        ascmUserInfo.userName = reader["userName"].ToString();
                        ascmUserInfo.password = reader["password"].ToString();
                        int employeeId = 0;
                        int.TryParse(reader["employeeId"].ToString(), out employeeId);
                        ascmUserInfo.employeeId    = employeeId;
                        ascmUserInfo.extExpandType = reader["extExpandType"].ToString();
                        ascmUserInfo.extExpandId   = reader["extExpandId"].ToString();

                        if (ascmUserInfo.extExpandType == "erp")
                        {
                            byte[] result = Encoding.Default.GetBytes(userPwd);
                            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                            userPwd = BitConverter.ToString(md5.ComputeHash(result)).Replace("-", "");
                            if (ascmUserInfo.password != userPwd)
                            {
                                errorMsg = "密码不正确";
                            }
                            else if (!string.IsNullOrEmpty(ascmUserInfo.userName))
                            {
                                Oracle.DataAccess.Client.OracleCommand cmd2 = new Oracle.DataAccess.Client.OracleCommand();
                                cmd2.Connection  = conn;
                                cmd2.CommandText = "SELECT id,name FROM ascm_supplier WHERE docNumber = :docNumber";
                                cmd2.CommandType = System.Data.CommandType.Text;
                                cmd2.Parameters.Add(new Oracle.DataAccess.Client.OracleParameter {
                                    ParameterName = ":docNumber",
                                    OracleDbType  = Oracle.DataAccess.Client.OracleDbType.NVarchar2,
                                    Size          = 20,
                                    Value         = ascmUserInfo.userName,
                                    Direction     = System.Data.ParameterDirection.Input
                                });

                                using (Oracle.DataAccess.Client.OracleDataReader reader2 = cmd2.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
                                {
                                    cmd2.Parameters.Clear();
                                    if (reader2.Read())
                                    {
                                        int id = 0;
                                        if (int.TryParse(reader2["id"].ToString(), out id))
                                        {
                                            AscmSupplier ascmSupplier = new AscmSupplier();
                                            ascmSupplier.id           = id;
                                            ascmSupplier.name         = reader2["name"].ToString();
                                            ascmUserInfo.ascmSupplier = ascmSupplier;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(ascmUserInfo);
        }
 string GetHashString(string s)
 {
     System.Security.Cryptography.MD5CryptoServiceProvider hashProvider = new System.Security.Cryptography.MD5CryptoServiceProvider( );
     byte[] hash = hashProvider.ComputeHash(System.Text.Encoding.UTF8.GetBytes(s));
     return(new Guid(hash).ToString( ));
 }
        public void __startMovie(string pathName)
        {
            var f = new FileInfo(pathName);

            // let zmovies know we started a video. could we stream it to chrome?
            Console.WriteLine("startMovie " + new { f.Name });

            // lets shell and do a ls to figure out we do have the thumbnail there...
            var mp4_jpg = (
                from pf in new DirectoryInfo("/sdcard/oculus/360Photos/").GetFiles()
                //where pf.Extension.ToLower() == ".jpg"
                //  Z:\jsc.svn\examples\rewrite\GearVR360VideoPush\GearVR360VideoPush\Program.cs
                where pf.Name == System.IO.Path.ChangeExtension(f.Name, ".jpg")
                select pf

                // if we change it. can we hotswap the code already rnning in vr?
                ).FirstOrDefault();

            ///System.Console(30077): 757d:0001 startMovie { Name = 360 3D Towering Hoodoos in Bryce Canyon in 3d,  -degree video. by Visit_Utah.mp3._TB.mp4 }
            ///System.Console(30077): 757d:0001 startMovie { mp4_jpg = ScriptCoreLib.Shared.BCLImplementation.System.Linq.__Enumerable__WhereIterator_d__0_1@6d1507a }

            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20160103/x360videoui
            Console.WriteLine("startMovie " + new { mp4_jpg });


            // upstream it!

            #region udp
            if (mp4_jpg != null)
            {
                Task.Run(
                    delegate
                {
                    //args.filesize = mp4_jpg.Length;

                    // we are not on ui thread.
                    // HUD thread can freeze...
                    // mmap?
                    var sw    = System.Diagnostics.Stopwatch.StartNew();
                    var bytes = File.ReadAllBytes(mp4_jpg.FullName);

                    // why slo slow???
                    // can jsc do it in NDK?
                    // http://stackoverflow.com/questions/32269305/android-play-pcm-byte-array-from-converted-from-base64-string-slow-sounds
                    var md5       = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(bytes);
                    var md5string = md5.ToHexString();

                    Console.WriteLine("startMovie " + new { f.Name, md5string, sw.ElapsedMilliseconds });


                    //I/System.Console( 4098): 1002:0001 startMovie { Name = 360 3D [3D  VR] __________(HAC) ______ __(Dance) A_ by _____________Verest__360_VR.mp3._TB.mp4 }
                    //I/System.Console( 4098): 1002:0001 startMovie { mp4_jpg = { FullName = /storage/emulated/legacy/oculus/360Photos/360 3D [3D  VR] __________(HAC) ______ __(Dance) A_ by _____________Verest__360_VR.mp3._TB.jpg, Exists = true } }
                    //I/System.Console( 4098): 1002:06a2 startMovie { Name = 360 3D [3D  VR] __________(HAC) ______ __(Dance) A_ by _____________Verest__360_VR.mp3._TB.mp4, md5string = 8bebab806331b078b385e33e5e069393, ElapsedMilliseconds = 6579 }


                    if (startMovieLookup.ContainsKey(md5string))
                    {
                        // already uploaded.

                        return;
                    }

                    startMovieLookup[md5string] = pathName;

                    // await for callback. lookup. transaction



                    // now broadcast. at 500KBps in segments.
                    // 8MB is 16 segments then.

                    if (bytes.Length > 0)
                    {
                        NetworkInterface.GetAllNetworkInterfaces().WithEach(
                            n =>
                        {
                            // X:\jsc.svn\examples\java\android\forms\FormsUDPJoinGroup\FormsUDPJoinGroup\ApplicationControl.cs
                            // X:\jsc.svn\core\ScriptCoreLibJava\BCLImplementation\System\Net\NetworkInformation\NetworkInterface.cs

                            var IPProperties    = n.GetIPProperties();
                            var PhysicalAddress = n.GetPhysicalAddress();



                            foreach (var ip in IPProperties.UnicastAddresses)
                            {
                                // ipv4
                                if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                {
                                    if (!IPAddress.IsLoopback(ip.Address))
                                    {
                                        if (n.SupportsMulticast)
                                        {
                                            //fWASDC(ip.Address);
                                            //fParallax(ip.Address);
                                            //fvertexTransform(ip.Address);
                                            //sendTracking(ip.Address);

                                            var port = new Random().Next(16000, 40000);

                                            //new IHTMLPre { "about to bind... " + new { port } }.AttachToDocument();

                                            // where is bind async?
                                            var socket = new UdpClient(
                                                new IPEndPoint(ip.Address, port)
                                                );


                                            //// who is on the other end?
                                            //var nmessage = args.x + ":" + args.y + ":" + args.z + ":0:" + args.filename;

                                            //var data = Encoding.UTF8.GetBytes(nmessage);      //creates a variable b of type byte

                                            // http://stackoverflow.com/questions/25841/maximum-buffer-length-for-sendto

                                            new { }.With(
                                                async delegate
                                            {
                                                // reached too far?
                                                if (bytes.Length == 0)
                                                {
                                                    return;
                                                }

                                                //var current0 = current;

                                                var r            = new MemoryStream(bytes);
                                                var uploadLength = r.Length;

                                                var data = new byte[65507];

                                                next:

                                                //if (current0 != current)
                                                //    return;

                                                var cc = r.Read(data, 0, data.Length);

                                                var uploadPosition = r.Position;

                                                if (cc <= 0)
                                                {
                                                    return;
                                                }

                                                //new IHTMLPre { "about to send... " + new { data.Length } }.AttachToDocument();

                                                // X:\jsc.svn\examples\javascript\chrome\apps\ChromeUDPNotification\ChromeUDPNotification\Application.cs
                                                //Console.WriteLine("about to Send");
                                                // X:\jsc.svn\examples\javascript\chrome\apps\WebGL\ChromeEquirectangularPanorama\ChromeEquirectangularPanorama\Application.cs
                                                await socket.SendAsync(
                                                    data,
                                                    cc,
                                                    hostname: "239.1.2.3",
                                                    port: 49000
                                                    );

                                                //await Task.Delay(1000 / 15);
                                                //await Task.Delay(1000 / 30);

                                                // no corruption
                                                await Task.Delay(1000 / 20);

                                                goto next;
                                            }
                                                );

                                            //socket.Close();
                                        }
                                    }
                                }
                            }
                        }
                            );
                    }
                }
                    );
            }
            #endregion



            // Request audio focus
            requestAudioFocus();

            // Have native code pause any playing movie,
            // allocate a new external texture,
            // and create a surfaceTexture with it.
            movieTexture = com.oculus.oculus360videossdk.MainActivity.nativePrepareNewVideo(base_getAppPtr());
            movieTexture.setOnFrameAvailableListener(this);
            movieSurface = new Surface(movieTexture);

            if (mediaPlayer != null)
            {
                mediaPlayer.release();
            }

            //Log.v(TAG, "MediaPlayer.create");

            //synchronized (this) {
            mediaPlayer = new MediaPlayer();
            //}


            mediaPlayer.setOnVideoSizeChangedListener(this);
            mediaPlayer.setOnCompletionListener(this);

            // if only webview had setSurface method?
            mediaPlayer.setSurface(movieSurface);

            try
            {
                //Log.v(TAG, "mediaPlayer.setDataSource()");
                mediaPlayer.setDataSource(pathName);
            }
            catch //(IOException t)
            {
                //Log.e(TAG, "mediaPlayer.setDataSource failed");
            }

            try
            {
                //Log.v(TAG, "mediaPlayer.prepare");
                mediaPlayer.prepare();
            }
            catch //(IOException t)
            {
                //Log.e(TAG, "mediaPlayer.prepare failed:" + t.getMessage());
            }
            //Log.v(TAG, "mediaPlayer.start");

            // If this movie has a saved position, seek there before starting
            // This seems to make movie switching crashier.
            int seekPos = getPreferences(MODE_PRIVATE).getInt(pathName + "_pos", 0);
            if (seekPos > 0)
            {
                try
                {
                    mediaPlayer.seekTo(seekPos);
                }
                catch //( IllegalStateException ise )
                {
                    //Log.d( TAG, "mediaPlayer.seekTo(): Caught illegalStateException: " + ise.toString() );
                }
            }

            mediaPlayer.setLooping(false);

            try
            {
                mediaPlayer.start();
            }
            catch //( IllegalStateException ise )
            {
                //Log.d( TAG, "mediaPlayer.start(): Caught illegalStateException: " + ise.toString() );
            }

            mediaPlayer.setVolume(1.0f, 1.0f);

            // Save the current movie now that it was successfully started
            var edit = getPreferences(MODE_PRIVATE).edit();
            edit.putString("currentMovie", pathName);
            edit.commit();

            //Log.v(TAG, "returning");



            Console.WriteLine("getTrackInfo");
            var tracks = mediaPlayer.getTrackInfo();

            Console.WriteLine("getTrackInfo " + new { tracks.Length });
            // https://groups.google.com/forum/#!topic/android-platform/lvR6InJf6J0
            foreach (var track in tracks)
            {
                var TrackType = track.getTrackType();

                Console.WriteLine("getTrackInfo " + new { TrackType });
            }

            // do we have any multitrack videos?

            // http://stackoverflow.com/questions/15911135/android-select-audio-track-in-video
            //I/System.Console(11033): 2b19:0001 getTrackInfo
            //I/System.Console(11033): 2b19:0001 getTrackInfo { Length = 2 }
            //I/System.Console(11033): 2b19:0001 getTrackInfo { TrackType = 1 }
            //I/System.Console(11033): 2b19:0001 getTrackInfo { TrackType = 2 }
        }
Esempio n. 46
0
        /// <summary>
        /// Checks if specified message matches to specified criteria.
        /// </summary>
        /// <param name="syntaxCheckOnly">Specifies if syntax check is only done. If true no matching is done.</param>
        /// <param name="r">Match expression reader what contains match expression.</param>
        /// <param name="mailFrom">SMTP MAIL FROM: command email value.</param>
        /// <param name="rcptTo">SMTP RCPT TO: command email values.</param>
        /// <param name="smtpSession">SMTP current session.</param>
        /// <param name="mime">Message to match.</param>
        /// <param name="messageSize">Message size in bytes.</param>
        /// <returns>Returns true if message matches to specified criteria.</returns>
        private bool Match(bool syntaxCheckOnly, LumiSoft.Net.StringReader r, string mailFrom, string[] rcptTo, SMTP_Session smtpSession, Mail_Message mime, int messageSize)
        {
            /* Possible keywords order
             *  At first there can be NOT,parethesized or matcher
             *      After NOT, parethesized or matcher
             *      After matcher, AND or OR
             *      After OR, NOT,parethesized or matcher
             *      After AND, NOT,parethesized or matcher
             *      After parethesized, NOT or matcher
             */

            PossibleClauseItem possibleClauseItems = PossibleClauseItem.Parenthesizes | PossibleClauseItem.NOT | PossibleClauseItem.Matcher;
            bool lastMatchValue = false;

            // Empty string passed
            r.ReadToFirstChar();
            if (r.Available == 0)
            {
                throw new Exception("Invalid syntax: '" + ClauseItemsToString(possibleClauseItems) + "' expected !");
            }

            // Parse while there are expressions or get error
            while (r.Available > 0)
            {
                r.ReadToFirstChar();

                // Syntax check must consider that there is alwas match !!!
                if (syntaxCheckOnly)
                {
                    lastMatchValue = true;
                }

                #region () Groupped matchers

                // () Groupped matchers
                if (r.StartsWith("("))
                {
                    lastMatchValue = Match(syntaxCheckOnly, new LumiSoft.Net.StringReader(r.ReadParenthesized()), mailFrom, rcptTo, smtpSession, mime, messageSize);

                    possibleClauseItems = PossibleClauseItem.Parenthesizes | PossibleClauseItem.Matcher | PossibleClauseItem.NOT;
                }

                #endregion

                #region AND clause

                // AND clause
                else if (r.StartsWith("and", false))
                {
                    // See if AND allowed
                    if ((possibleClauseItems & PossibleClauseItem.AND) == 0)
                    {
                        throw new Exception("Invalid syntax: '" + ClauseItemsToString(possibleClauseItems) + "' expected !");
                    }

                    // Last match value is false, no need to check next conditions
                    if (!lastMatchValue)
                    {
                        return(false);
                    }

                    // Remove AND
                    r.ReadWord();
                    r.ReadToFirstChar();

                    lastMatchValue = Match(syntaxCheckOnly, r, mailFrom, rcptTo, smtpSession, mime, messageSize);

                    possibleClauseItems = PossibleClauseItem.Parenthesizes | PossibleClauseItem.Matcher | PossibleClauseItem.NOT;
                }

                #endregion

                #region OR clause

                // OR clause
                else if (r.StartsWith("or", false))
                {
                    // See if OR allowed
                    if ((possibleClauseItems & PossibleClauseItem.OR) == 0)
                    {
                        throw new Exception("Invalid syntax: '" + ClauseItemsToString(possibleClauseItems) + "' expected !");
                    }

                    // Remove OR
                    r.ReadWord();
                    r.ReadToFirstChar();

                    // Last match value is false, then we need to check next condition.
                    // Otherwise OR is matched already, just eat next matcher.
                    if (lastMatchValue)
                    {
                        // Skip next clause
                        Match(syntaxCheckOnly, r, mailFrom, rcptTo, smtpSession, mime, messageSize);
                    }
                    else
                    {
                        lastMatchValue = Match(syntaxCheckOnly, r, mailFrom, rcptTo, smtpSession, mime, messageSize);
                    }

                    possibleClauseItems = PossibleClauseItem.Parenthesizes | PossibleClauseItem.Matcher | PossibleClauseItem.NOT;
                }

                #endregion

                #region NOT clause

                // NOT clause
                else if (r.StartsWith("not", false))
                {
                    // See if NOT allowed
                    if ((possibleClauseItems & PossibleClauseItem.NOT) == 0)
                    {
                        throw new Exception("Invalid syntax: '" + ClauseItemsToString(possibleClauseItems) + "' expected !");
                    }

                    // Remove NOT
                    r.ReadWord();
                    r.ReadToFirstChar();

                    // Just reverse match result value
                    lastMatchValue = !Match(syntaxCheckOnly, r, mailFrom, rcptTo, smtpSession, mime, messageSize);

                    possibleClauseItems = PossibleClauseItem.Parenthesizes | PossibleClauseItem.Matcher;
                }

                #endregion

                else
                {
                    // See if matcher allowed
                    if ((possibleClauseItems & PossibleClauseItem.Matcher) == 0)
                    {
                        throw new Exception("Invalid syntax: '" + ClauseItemsToString(possibleClauseItems) + "' expected ! \r\n\r\n Near: '" + r.OriginalString.Substring(0, r.Position) + "'");
                    }

                    // 1) matchsource
                    // 2) keyword

                    // Read match source
                    string word = r.ReadWord();
                    if (word == null)
                    {
                        throw new Exception("Invalid syntax: matcher is missing !");
                    }
                    word = word.ToLower();
                    string[] matchSourceValues = new string[] {};


                    #region smtp.mail_from

                    // SMTP command MAIL FROM: value.
                    //  smtp.mail_from
                    if (word == "smtp.mail_from")
                    {
                        if (!syntaxCheckOnly)
                        {
                            matchSourceValues = new string[] { mailFrom };
                        }
                    }

                    #endregion

                    #region smtp.rcpt_to

                    // SMTP command RCPT TO: values.
                    //  smtp.mail_to
                    else if (word == "smtp.rcpt_to")
                    {
                        if (!syntaxCheckOnly)
                        {
                            matchSourceValues = rcptTo;
                        }
                    }

                    #endregion

                    #region smtp.ehlo

                    // SMTP command EHLO/HELO: value.
                    //  smtp.ehlo
                    else if (word == "smtp.ehlo")
                    {
                        if (!syntaxCheckOnly)
                        {
                            matchSourceValues = new string[] { smtpSession.EhloHost };
                        }
                    }

                    #endregion

                    #region smtp.authenticated

                    // Specifies if SMTP session is authenticated.
                    //  smtp.authenticated
                    else if (word == "smtp.authenticated")
                    {
                        if (!syntaxCheckOnly)
                        {
                            if (smtpSession != null)
                            {
                                matchSourceValues = new string[] { smtpSession.IsAuthenticated.ToString() };
                            }
                        }
                    }

                    #endregion

                    #region smtp.user

                    // SMTP authenticated user name. Empy string "" if not authenticated.
                    //  smtp.user
                    else if (word == "smtp.user")
                    {
                        if (!syntaxCheckOnly)
                        {
                            if (smtpSession != null && smtpSession.AuthenticatedUserIdentity != null)
                            {
                                matchSourceValues = new string[] { smtpSession.AuthenticatedUserIdentity.Name };
                            }
                        }
                    }

                    #endregion

                    #region smtp.remote_ip

                    // SMTP session connected client IP address.
                    //  smtp.remote_ip
                    else if (word == "smtp.remote_ip")
                    {
                        if (!syntaxCheckOnly)
                        {
                            if (smtpSession != null)
                            {
                                matchSourceValues = new string[] { smtpSession.RemoteEndPoint.Address.ToString() };
                            }
                        }
                    }

                    #endregion


                    #region message.size

                    // Message size in bytes.
                    //  message.size
                    else if (word == "message.size")
                    {
                        if (!syntaxCheckOnly)
                        {
                            matchSourceValues = new string[] { messageSize.ToString() };
                        }
                    }

                    #endregion

                    #region message.header <SP> "HeaderFieldName:"

                    // Message main header header field. If multiple header fields, then all are checked.
                    //  message.header <SP> "HeaderFieldName:"
                    else if (word == "message.header")
                    {
                        string headerFieldName = r.ReadWord();
                        if (headerFieldName == null)
                        {
                            throw new Exception("Match source MainHeaderField HeaderFieldName is missing ! Syntax:{MainHeaderField <SP> \"HeaderFieldName:\"}");
                        }

                        if (!syntaxCheckOnly)
                        {
                            if (mime.Header.Contains(headerFieldName))
                            {
                                MIME_h[] fields = mime.Header[headerFieldName];
                                matchSourceValues = new string[fields.Length];
                                for (int i = 0; i < matchSourceValues.Length; i++)
                                {
                                    matchSourceValues[i] = fields[i].ValueToString();
                                }
                            }
                        }
                    }

                    #endregion

                    #region message.all_headers <SP> "HeaderFieldName:"

                    // Any mime entity header header field. If multiple header fields, then all are checked.
                    //  message.all_headers <SP> "HeaderFieldName:"
                    else if (word == "message.all_headers")
                    {
                        string headerFieldName = r.ReadWord();
                        if (headerFieldName == null)
                        {
                            throw new Exception("Match source MainHeaderField HeaderFieldName is missing ! Syntax:{MainHeaderField <SP> \"HeaderFieldName:\"}");
                        }

                        if (!syntaxCheckOnly)
                        {
                            List <string> values = new List <string>();
                            foreach (MIME_Entity entity in mime.AllEntities)
                            {
                                if (entity.Header.Contains(headerFieldName))
                                {
                                    MIME_h[] fields = entity.Header[headerFieldName];
                                    for (int i = 0; i < fields.Length; i++)
                                    {
                                        values.Add(fields[i].ValueToString());
                                    }
                                }
                            }
                            matchSourceValues = values.ToArray();
                        }
                    }

                    #endregion

                    #region message.body_text

                    // Message body text.
                    //  message.body_text
                    else if (word == "message.body_text")
                    {
                        if (!syntaxCheckOnly)
                        {
                            matchSourceValues = new string[] { mime.BodyText };
                        }
                    }

                    #endregion

                    #region message.body_html

                    // Message body html.
                    //  message.body_html
                    else if (word == "message.body_html")
                    {
                        if (!syntaxCheckOnly)
                        {
                            matchSourceValues = new string[] { mime.BodyHtmlText };
                        }
                    }

                    #endregion

                    #region message.content_md5

                    // Message any mime entity decoded data MD5 hash.
                    //  message.content_md5
                    else if (word == "message.content_md5")
                    {
                        if (!syntaxCheckOnly)
                        {
                            List <string> values = new List <string>();
                            foreach (MIME_Entity entity in mime.AllEntities)
                            {
                                try{
                                    if (entity.Body is MIME_b_SinglepartBase)
                                    {
                                        byte[] data = ((MIME_b_SinglepartBase)entity.Body).Data;
                                        if (data != null)
                                        {
                                            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                                            values.Add(System.Text.Encoding.Default.GetString(md5.ComputeHash(data)));
                                        }
                                    }
                                }
                                catch {
                                    // Message data parsing failed, just skip that entity md5
                                }
                            }
                            matchSourceValues = values.ToArray();
                        }
                    }

                    #endregion


                    #region sys.date_time

                    // System current date time. Format: yyyy.MM.dd HH:mm:ss.
                    //  sys.date_time
                    else if (word == "sys.date_time")
                    {
                        if (!syntaxCheckOnly)
                        {
                            matchSourceValues = new string[] { DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") };
                        }
                    }

                    #endregion

                    #region sys.date

                    // System current date. Format: yyyy.MM.dd.
                    //  sys.date
                    else if (word == "sys.date")
                    {
                        if (!syntaxCheckOnly)
                        {
                            matchSourceValues = new string[] { DateTime.Today.ToString("dd.MM.yyyy") };
                        }
                    }

                    #endregion

                    #region sys.time

                    // System current time. Format: HH:mm:ss.
                    //  sys.time
                    else if (word == "sys.time")
                    {
                        if (!syntaxCheckOnly)
                        {
                            matchSourceValues = new string[] { DateTime.Now.ToString("HH:mm:ss") };
                        }
                    }

                    #endregion

                    #region sys.day_of_week

                    // Day of week. Days: sunday,monday,tuesday,wednesday,thursday,friday,saturday.
                    //  sys.day_of_week
                    else if (word == "sys.day_of_week")
                    {
                        if (!syntaxCheckOnly)
                        {
                            matchSourceValues = new string[] { DateTime.Today.DayOfWeek.ToString() };
                        }
                    }

                    #endregion

                    /*
                     * // Day of month. Format: 1 - 31. If no so much days in month, then replaced with month max days.
                     * // sys.day_of_month
                     * else if(word == "sys.day_of_month"){
                     * }
                     */
                    #region sys.day_of_year

                    // Month of year. Format: 1 - 12.
                    // sys.day_of_year
                    else if (word == "sys.day_of_year")
                    {
                        if (!syntaxCheckOnly)
                        {
                            matchSourceValues = new string[] { DateTime.Today.ToString("M") };
                        }
                    }

                    #endregion

                    #region Unknown

                    // Unknown
                    else
                    {
                        throw new Exception("Unknown match source '" + word + "' !");
                    }

                    #endregion


                    /* If we reach so far, then we have valid match sorce and compare value.
                     * Just do compare.
                     */

                    // Reset lastMatch result
                    lastMatchValue = false;

                    // Read matcher
                    word = r.ReadWord(true, new char[] { ' ' }, true);
                    if (word == null)
                    {
                        throw new Exception("Invalid syntax: operator is missing ! \r\n\r\n Near: '" + r.OriginalString.Substring(0, r.Position) + "'");
                    }
                    word = word.ToLower();

                    #region * <SP> "astericPattern"

                    // * <SP> "astericPattern"
                    if (word == "*")
                    {
                        string val = r.ReadWord();
                        if (val == null)
                        {
                            throw new Exception("Invalid syntax: <SP> \"value\" is missing !");
                        }
                        val = val.ToLower();

                        if (!syntaxCheckOnly)
                        {
                            // We check matchSourceValues when first is found
                            foreach (string matchSourceValue in matchSourceValues)
                            {
                                if (SCore.IsAstericMatch(val, matchSourceValue.ToLower()))
                                {
                                    lastMatchValue = true;
                                    break;
                                }
                            }
                        }
                    }

                    #endregion

                    #region !* <SP> "astericPattern"

                    // !* <SP> "astericPattern"
                    else if (word == "!*")
                    {
                        string val = r.ReadWord();
                        if (val == null)
                        {
                            throw new Exception("Invalid syntax: <SP> \"value\" is missing !");
                        }
                        val = val.ToLower();

                        if (!syntaxCheckOnly)
                        {
                            // We check matchSourceValues when first is found
                            foreach (string matchSourceValue in matchSourceValues)
                            {
                                if (SCore.IsAstericMatch(val, matchSourceValue.ToLower()))
                                {
                                    lastMatchValue = false;
                                    break;
                                }
                            }
                        }
                    }

                    #endregion

                    #region == <SP> "value"

                    // == <SP> "value"
                    else if (word == "==")
                    {
                        string val = r.ReadWord();
                        if (val == null)
                        {
                            throw new Exception("Invalid syntax: <SP> \"value\" is missing !");
                        }
                        val = val.ToLower();

                        if (!syntaxCheckOnly)
                        {
                            // We check matchSourceValues when first is found
                            foreach (string matchSourceValue in matchSourceValues)
                            {
                                if (val == matchSourceValue.ToLower())
                                {
                                    lastMatchValue = true;
                                    break;
                                }
                            }
                        }
                    }

                    #endregion

                    #region != <SP> "value"

                    // != <SP> "value"
                    else if (word == "!=")
                    {
                        string val = r.ReadWord();
                        if (val == null)
                        {
                            throw new Exception("Invalid syntax: <SP> \"value\" is missing !");
                        }
                        val = val.ToLower();

                        if (!syntaxCheckOnly)
                        {
                            // We check matchSourceValues when first is found, then already value equals
                            foreach (string matchSourceValue in matchSourceValues)
                            {
                                if (val == matchSourceValue.ToLower())
                                {
                                    lastMatchValue = false;
                                    break;
                                }
                                lastMatchValue = true;
                            }
                        }
                    }

                    #endregion

                    #region >= <SP> "value"

                    // >= <SP> "value"
                    else if (word == ">=")
                    {
                        string val = r.ReadWord();
                        if (val == null)
                        {
                            throw new Exception("Invalid syntax: <SP> \"value\" is missing !");
                        }
                        val = val.ToLower();

                        if (!syntaxCheckOnly)
                        {
                            // We check matchSourceValues when first is found
                            foreach (string matchSourceValue in matchSourceValues)
                            {
                                if (matchSourceValue.ToLower().CompareTo(val) >= 0)
                                {
                                    lastMatchValue = true;
                                    break;
                                }
                            }
                        }
                    }

                    #endregion

                    #region <= <SP> "value"

                    // <= <SP> "value"
                    else if (word == "<=")
                    {
                        string val = r.ReadWord();
                        if (val == null)
                        {
                            throw new Exception("Invalid syntax: <SP> \"value\" is missing !");
                        }
                        val = val.ToLower();

                        if (!syntaxCheckOnly)
                        {
                            // We check matchSourceValues when first is found
                            foreach (string matchSourceValue in matchSourceValues)
                            {
                                if (matchSourceValue.ToLower().CompareTo(val) <= 0)
                                {
                                    lastMatchValue = true;
                                    break;
                                }
                            }
                        }
                    }

                    #endregion

                    #region > <SP> "value"

                    // > <SP> "value"
                    else if (word == ">")
                    {
                        string val = r.ReadWord();
                        if (val == null)
                        {
                            throw new Exception("Invalid syntax: <SP> \"value\" is missing !");
                        }
                        val = val.ToLower();

                        if (!syntaxCheckOnly)
                        {
                            // We check matchSourceValues when first is found
                            foreach (string matchSourceValue in matchSourceValues)
                            {
                                if (matchSourceValue.ToLower().CompareTo(val) > 0)
                                {
                                    lastMatchValue = true;
                                    break;
                                }
                            }
                        }
                    }

                    #endregion

                    #region < <SP> "value"

                    // < <SP> "value"
                    else if (word == "<")
                    {
                        string val = r.ReadWord();
                        if (val == null)
                        {
                            throw new Exception("Invalid syntax: <SP> \"value\" is missing !");
                        }
                        val = val.ToLower();

                        if (!syntaxCheckOnly)
                        {
                            // We check matchSourceValues when first is found
                            foreach (string matchSourceValue in matchSourceValues)
                            {
                                if (matchSourceValue.ToLower().CompareTo(val) < 0)
                                {
                                    lastMatchValue = true;
                                    break;
                                }
                            }
                        }
                    }

                    #endregion

                    #region regex <SP> "value"

                    // Regex <SP> "value"
                    else if (word == "regex")
                    {
                        string val = r.ReadWord();
                        if (val == null)
                        {
                            throw new Exception("Invalid syntax: <SP> \"value\" is missing !");
                        }
                        val = val.ToLower();

                        if (!syntaxCheckOnly)
                        {
                            // We check matchSourceValues when first is found
                            foreach (string matchSourceValue in matchSourceValues)
                            {
                                if (Regex.IsMatch(val, matchSourceValue.ToLower()))
                                {
                                    lastMatchValue = true;
                                    break;
                                }
                            }
                        }
                    }

                    #endregion

                    #region Unknown

                    // Unknown
                    else
                    {
                        throw new Exception("Unknown keword '" + word + "' !");
                    }

                    #endregion

                    possibleClauseItems = PossibleClauseItem.AND | PossibleClauseItem.OR;
                }
            }

            return(lastMatchValue);
        }
Esempio n. 47
0
        /// <summary>
        /// Computes MD5 hash.
        /// </summary>
        /// <param name="value">Value to process.</param>
        /// <returns>Return MD5 hash.</returns>
        private byte[] h(byte[] value)
        {
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

            return(md5.ComputeHash(value));
        }
        internal static string DownloadRemoteSettings(string managerID, BuildTarget platform, CASInitSettings settings, DependencyManager deps)
        {
            const string title = "Update CAS remote settings";

            var editorSettings = CASEditorSettings.Load();

            #region Create request URL
            #region Hash
            var managerIdBytes = new UTF8Encoding().GetBytes(managerID);
            var suffix         = new byte[] { 48, 77, 101, 68, 105, 65, 116, 73, 111, 78, 104, 65, 115, 72 };
            if (platform == BuildTarget.iOS)
            {
                suffix[0] = 49;
            }
            var sourceBytes = new byte[managerID.Length + suffix.Length];
            Array.Copy(managerIdBytes, 0, sourceBytes, 0, managerIdBytes.Length);
            Array.Copy(suffix, 0, sourceBytes, managerIdBytes.Length, suffix.Length);

            var           hashBytes   = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(sourceBytes);
            StringBuilder hashBuilder = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashBuilder.Append(Convert.ToString(hashBytes[i], 16).PadLeft(2, '0'));
            }
            var hash = hashBuilder.ToString().PadLeft(32, '0');
            #endregion

            var urlBuilder = new StringBuilder("https://psvpromo.psvgamestudio.com/Scr/cas.php?platform=")
                             .Append(platform == BuildTarget.Android ? 0 : 1)
                             .Append("&bundle=").Append(UnityWebRequest.EscapeURL(managerID))
                             .Append("&hash=").Append(hash)
                             .Append("&lang=").Append(SystemLanguage.English)
                             .Append("&appDev=2")
                             .Append("&appV=").Append(PlayerSettings.bundleVersion)
                             .Append("&coppa=").Append(( int )settings.defaultAudienceTagged)
                             .Append("&adTypes=").Append(( int )settings.allowedAdFlags)
                             .Append("&nets=").Append(DependencyManager.GetActiveMediationPattern(deps))
                             .Append("&orient=").Append(Utils.GetOrientationId())
                             .Append("&framework=Unity_").Append(Application.unityVersion);
            if (deps != null)
            {
                var buildCode = deps.GetInstalledBuildCode();
                if (buildCode > 0)
                {
                    urlBuilder.Append("&sdk=").Append(buildCode);
                }
            }
            if (string.IsNullOrEmpty(editorSettings.mostPopularCountryOfUsers))
            {
                urlBuilder.Append("&country=").Append("US");
            }
            else
            {
                urlBuilder.Append("&country=").Append(editorSettings.mostPopularCountryOfUsers);
            }
            if (platform == BuildTarget.Android)
            {
                urlBuilder.Append("&appVC=").Append(PlayerSettings.Android.bundleVersionCode);
            }

            #endregion

            using (var loader = UnityWebRequest.Get(urlBuilder.ToString()))
            {
                try
                {
                    loader.SendWebRequest();
                    while (!loader.isDone)
                    {
                        if (EditorUtility.DisplayCancelableProgressBar(title, managerID,
                                                                       Mathf.Repeat(( float )EditorApplication.timeSinceStartup * 0.2f, 1.0f)))
                        {
                            loader.Dispose();
                            throw new Exception("Update CAS Settings canceled");
                        }
                    }
                    if (string.IsNullOrEmpty(loader.error))
                    {
                        var content = loader.downloadHandler.text.Trim();
                        if (string.IsNullOrEmpty(content))
                        {
                            throw new Exception("ManagerID [" + managerID + "] is not registered in CAS.");
                        }

                        EditorUtility.DisplayProgressBar(title, "Write CAS settings", 0.7f);
                        var data = JsonUtility.FromJson <AdmobAppIdData>(content);
                        Utils.WriteToFile(content, Utils.GetNativeSettingsPath(platform, managerID));
                        return(data.admob_app_id);
                    }
                    throw new Exception("Server response " + loader.responseCode + ": " + loader.error);
                }
                finally
                {
                    EditorUtility.ClearProgressBar();
                }
            }
        }
        protected void btn_passwd_Click(object sender, EventArgs e)
        {
            int flag = 0;

            if (txt_password.Text == "")
            {
                lbl_invaldpass.Text = "Required"; flag++;
            }
            else if (txt_password.Text.Length < 8)
            {
                lbl_invaldpass.Text = "Minimum Length is 8"; flag++;
            }
            else
            {
                lbl_invaldpass.Text = "<br><br>";
            }

            if (!txt_password.Text.Equals(txt_confirmpass.Text))
            {
                lbl_invalidconfi.Text = "Password doesn't Match"; flag++;
            }
            else
            {
                lbl_invalidconfi.Text = "<br><br>";
            }

            if (otp.Equals(txt_cus_OTP.Text))
            {
                lbl_invalidotp.Text = "Invalid OTP";
            }
            else
            {
                String pwd = txt_password.Text;
                System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] bs = System.Text.Encoding.UTF8.GetBytes(pwd);
                bs = x.ComputeHash(bs);
                System.Text.StringBuilder s = new System.Text.StringBuilder();
                foreach (byte b in bs)
                {
                    s.Append(b.ToString("x2").ToLower());
                }
                lbl_invalidotp.Text = "";
                try
                {
                    SqlCommand cmd = new SqlCommand("update UserData set password=@pwd where email=@email", con);;
                    cmd.Parameters.Add("@email", SqlDbType.VarChar).Value = txt_email.Text;
                    cmd.Parameters.Add("@pwd", SqlDbType.VarChar).Value   = s.ToString();
                    con.Open();
                    int status = cmd.ExecuteNonQuery();
                    con.Close();
                    if (status != 0)
                    {
                        SqlCommand com = new SqlCommand("select name from UserData where email='" + txt_email.Text + "'", con);
                        con.Open();
                        SqlDataReader dr = com.ExecuteReader(); // for taking single value
                        dr.Read();
                        string      uname        = dr[0].ToString();
                        String      ToEmail      = txt_email.Text;
                        MailMessage passrectmail = new MailMessage("*****@*****.**", ToEmail);
                        String      UserName     = uname;
                        String      EmailBody    = "<html><body><h2>Hi <b>" + UserName + "</b>,</h2><br/>" + "You have successfully changed your Password on : <b>" + DateTime.Now.ToString() + "</b></body></html>";
                        passrectmail.Body       = EmailBody;
                        passrectmail.IsBodyHtml = true;
                        passrectmail.Subject    = "MY Services";
                        SmtpClient SMTP = new SmtpClient("smtp.gmail.com", 587);
                        SMTP.Credentials = new NetworkCredential("*****@*****.**", "tingtotong");
                        SMTP.EnableSsl   = true;
                        SMTP.Send(passrectmail);
                        Response.Redirect("LogIn.aspx");
                        Response.Write(@"<script language='text/javascript'>alert(' PASSWORD SUCCESSFULLY CHANGED. ')</script>");
                    }
                    else
                    {
                        Response.Write(@"<script language='javascript'>alert(' FAILED TO CHANGE PASSWORD ')</script>");
                    }
                }
                catch (Exception)
                {
                    Response.Write(@"<script language='javascript'>alert(' FAILED TO CHANGE PASSWORD ')</script>");
                }
            }
        }
Esempio n. 50
0
        /// <summary>
        /// 计算指定文件的MD5值
        /// </summary>
        /// <param name="file">文件名</param>
        /// <returns>文件的MD5值(若出现异常则返回null)</returns>
        private byte[] _Get_File_MD5(string file)
        {
            byte[] ret = null;

            var csp = new System.Security.Cryptography.MD5CryptoServiceProvider();

            byte[] buffer = new byte[STREAM_BUFFER_SIZE];

            csp.Initialize();

            FileInfo   fi = new FileInfo(file);
            FileStream fs = null;

            try
            {
                fs = fi.OpenRead();
            }
            catch (Exception)
            {
                return(ret);
            }
            //构造MD5计算事件的参数
            File_MD5_Calculate_Event_Arg e = new File_MD5_Calculate_Event_Arg();

            e.Current_Position = 0;
            e.File_Extension   = fi.Extension;
            e.Full_File_Name   = fi.FullName;
            e.File_Length      = fi.Length;
            e.File_Name        = fi.Name;

            if (File_MD5_Begin_Calculate_Event != null)
            {
                File_MD5_Begin_Calculate_Event(e);
            }

            //读取文件计算MD5
            try
            {
                fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);

                int nRead = 0;
                do
                {
                    nRead = fs.Read(buffer, 0, STREAM_BUFFER_SIZE);
                    csp.TransformBlock(buffer, 0, nRead, buffer, 0);

                    e.Current_Position += nRead;

                    if (File_MD5_Calculating_Event != null)
                    {
                        File_MD5_Calculating_Event(e);
                    }
                } while (nRead != 0);

                csp.TransformFinalBlock(buffer, 0, 0);

                ret = csp.Hash;
            }
            finally
            {
                try
                {
                    fs.Close();
                }
                catch (Exception)
                {
                }
                csp.Clear();
            }

            if (File_MD5_End_Calculate_Event != null)
            {
                File_MD5_End_Calculate_Event(e);
            }

            return(ret);
        }
Esempio n. 51
0
        static bool ExtractFromMinidump(string filename, string symPath, ref List <sCallstack> callstack, out byte[] callstackUid)
        {
            callstackUid = new byte[16];

            string output = GetCallstackFromMinidump(filename, symPath);

            string[] lines    = output.Split('\n');
            int      depth    = 0;
            string   haystack = "";

            foreach (string line in lines)
            {
                if (depth > 0)
                {
                    depth++;
                }

                int rearPos = line.IndexOf('[');
                if (rearPos != -1)
                {
                    sCallstack stack = new sCallstack();

                    if (depth == 0)
                    {
                        depth = 1;
                    }

                    stack.depth    = depth;
                    stack.funcname = line.Substring(45, rearPos - 45 - 1);
                    stack.fileline = line.Substring(rearPos);

                    haystack += stack.funcname;

                    callstack.Add(stack);
                }
            }

            if (haystack.Length <= 0)
            {
                lines = output.Split('\n');
                depth = 0;
                foreach (string line in lines)
                {
                    if (depth > 0)
                    {
                        depth++;
                    }

                    sCallstack stack = new sCallstack();

                    if (depth == 0)
                    {
                        depth = 1;
                    }

                    stack.depth    = depth;
                    stack.funcname = line;
                    stack.fileline = "";

                    haystack += stack.funcname;

                    callstack.Add(stack);
                }
            }

            System.Security.Cryptography.MD5CryptoServiceProvider hashGen = new System.Security.Cryptography.MD5CryptoServiceProvider();
            callstackUid = hashGen.ComputeHash(Encoding.ASCII.GetBytes(haystack));

            return(true);
        }
Esempio n. 52
0
        /// <summary>
        /// 获取文件的MD5值
        /// </summary>
        /// <param name="_PathValue"></param>
        /// <returns></returns>
        public static string GetFileMD5(string _PathValue)
        {
            //判断是否为本地资源   因为本地文件里有文件名称 但是在资源名称又不能重复  于是需要去掉名称 来检测md5值
            Object _ObejctValue = AssetDatabase.LoadAssetAtPath <Object>(_PathValue);
            bool   _isNative    = AssetDatabase.IsNativeAsset(_ObejctValue);
            string _FileMD5     = "";
            string _TemPath     = Application.dataPath.Replace("Assets", "");

            if (_isNative)
            {
                string _TempFileText = File.ReadAllText(_TemPath + _PathValue).Replace("m_Name: " + _ObejctValue.name, "");

                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                //将字符串转换为字节数组
                byte[] fromData = System.Text.Encoding.Unicode.GetBytes(_TempFileText);
                //计算字节数组的哈希值
                byte[] toData = md5.ComputeHash(fromData);
                _FileMD5 = "";
                for (int i = 0; i < toData.Length; i++)
                {
                    _FileMD5 += toData[i].ToString("x2");
                }
            }
            else
            {
                _FileMD5 = "";
                //外部文件的MD5值
                try
                {
                    FileStream fs = new FileStream(_TemPath + _PathValue, FileMode.Open);

                    System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                    byte[] retVal = md5.ComputeHash(fs);
                    fs.Close();
                    for (int i = 0; i < retVal.Length; i++)
                    {
                        _FileMD5 += retVal[i].ToString("x2");
                    }
                }
                catch (System.Exception ex)
                {
                    Debug.Log(ex);
                }
                //因为外部文件还存在不同的设置问题,还需要检测一下外部资源的.meta文件
                if (_FileMD5 != "")
                {
                    string _MetaPath   = AssetDatabase.GetTextMetaFilePathFromAssetPath(_PathValue);
                    string _ObjectGUID = AssetDatabase.AssetPathToGUID(_PathValue);
                    //去掉guid来检测
                    string _TempFileText = File.ReadAllText(_TemPath + _MetaPath).Replace("guid: " + _ObjectGUID, "");

                    System.Security.Cryptography.MD5 _MetaMd5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                    //将字符串转换为字节数组
                    byte[] fromData = System.Text.Encoding.Unicode.GetBytes(_TempFileText);
                    //计算字节数组的哈希值
                    byte[] toData = _MetaMd5.ComputeHash(fromData);
                    for (int i = 0; i < toData.Length; i++)
                    {
                        _FileMD5 += toData[i].ToString("x2");
                    }
                }
            }
            return(_FileMD5);
        }
        protected string HashString(string Value)
        {
            var provider = new System.Security.Cryptography.MD5CryptoServiceProvider();

            return(System.Convert.ToBase64String(provider.ComputeHash(System.Text.Encoding.ASCII.GetBytes(Value))).Replace("/", "_"));
        }
Esempio n. 54
0
        public Tesws()
        {
            InitializeComponent();
            //if (true)
            //{

            //}
            if (File.Exists(Environment.CurrentDirectory + "\\tesws.json"))
            {
                OutPut($"检测到位于{Environment.CurrentDirectory}\\tesws.json的配置文件");
                try
                {
                    foreach (JObject item in JObject.Parse(File.ReadAllText(Environment.CurrentDirectory + "\\tesws.json"))["Servers"])
                    {
                        WebSocket webSocket = new WebSocket(item["Address"].ToString());
                        webSocket.OnOpen += (senderClient, ClientE) =>
                        {
                            OutPut((senderClient as WebSocket).Url, $"已连接");
                        };
                        webSocket.OnError += (senderClient, ClientE) =>
                        {
                            OutPutErr((senderClient as WebSocket).Url, $"出错啦{ClientE.Message}");
                        };
                        webSocket.OnMessage += WebSocket_OnMessage;
                        webSocket.OnClose   += (senderClient, ClientE) =>
                        {
                            OutPutErr((senderClient as WebSocket).Url, $"连接已关闭\t{ClientE.Code}=>{ClientE.Reason}");
                        };
                        SelectServer.Items.Add(new ComboBoxItem()
                        {
                            Content = item["Address"].ToString(), Tag = new WS()
                            {
                                client = webSocket, info = item
                            }
                        });
                    }
                    OutPut("配置文件读取成功");
                }
                catch (Exception err)
                { OutPutErr("配置文件读取失败" + err.Message); }
            }
#if false
//test
            try
            {
                string GetMD5(string sDataIn)
                {
                    var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

                    byte[] bytValue, bytHash;
                    bytValue = Encoding.UTF8.GetBytes(sDataIn);
                    bytHash  = md5.ComputeHash(bytValue);
                    md5.Clear();
                    string sTemp = "";

                    for (int i = 0, loopTo = bytHash.Length - 1; i <= loopTo; i++)
                    {
                        sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
                    }
                    return(sTemp.ToUpper());
                }
                {
                    string text     = "操";
                    string password = "******";
                    string md5      = GetMD5(password);
                    //byte[] md5bytes = Encoding.UTF8.GetBytes(md5);
                    OutPut("raw\t\t" + text);
                    OutPut("password\t" + password);
                    OutPut("passwordMd5\t" + md5);
                    #region AES_CBC
                    {
                        //byte[] keyRaw = new byte[16];
                        //byte[] ivRaw = new byte[16];
                        //for (int i = 0; i < keyRaw.Length; i++)
                        //    keyRaw[i] = md5bytes[i];
                        //for (int i = 0; i < ivRaw.Length; i++)
                        //    ivRaw[i] = md5bytes[i];
                        //string iv = Encoding.UTF8.GetString(ivRaw);
                        //string key = Encoding.UTF8.GetString(keyRaw);
                        string iv  = md5.Substring(16);
                        string key = md5.Remove(16);
                        OutPut("key\t" + key);
                        OutPut("iv\t" + iv);
                        var encryptString = EasyEncryption.AES.Encrypt(text, key, iv);
                        OutPut("encrypted\t" + encryptString);
                        var result = EasyEncryption.AES.Decrypt(encryptString, key, iv);
                        OutPut("result\t" + result);
                    }
                    #endregion
                }
            }
            catch (Exception e)
            {
                OutPutErr(e);
            }
#endif
        }
Esempio n. 55
0
        /** Called by our worker thread, this function handles a single item in the queue. */
        protected void WorkerCompute(QueueItem item)
        {
            // is it a directory?
            if (Directory.Exists(item.fullpath))
            {
                string[] files = Directory.GetFileSystemEntries(item.fullpath);
                foreach (string f in files)
                {
                    //QueueItem(f,item.partialpath+"\\"+JustTheFileName(f));
                    Enqueue(new QueueItem(f, item.partialpath + "\\" + JustTheFileName(f)));
                    this.Invoke(new UpdateEnqueuedLabelDelegate(UpdateEnqueuedLabel), new object[1] {
                        queue.Count()
                    });
                }
                return;
            }

            //	Console.WriteLine(item.partialpath);

            // it's not a directory. Is it a md5 file?
            if (IsMD5File(item.fullpath))
            {
                //Console.WriteLine("caught md5 file");
                StreamReader sr = new StreamReader(item.fullpath);
                string       s;

                // read each lkine. If the line looks like an md5 hash, add it
                // to the database.
                while ((s = sr.ReadLine()) != null)
                {
                    Match m = Regex.Match(s, @"^([0-9a-fA-F]{32})\s+(.+)$", RegexOptions.None);
                    if (m.Success && m.Groups.Count == 3)
                    {
                        string p    = m.Groups[2].Value.Trim();
                        string path = p.Replace("/", "\\");
                        string hash = m.Groups[1].Value.Trim().ToLower();
                        kb.AddRecord(path, hash);
                    }
                }

                sr.Close();
                listView.Invoke(new EventHandler(this.ReverifyAllItems));

                // don't return; we also compute the hash of the md5sum file. (why not?)
            }

            // compute the md5 hash
            FileStream fsr = null;

            try
            {
                currentlyProcessingLabel.Invoke(new SetCurrentlyProcessingDelegate(SetCurrentlyProcessing), new object[] { item.partialpath });

                fsr       = new FileStream(item.fullpath, FileMode.Open, FileAccess.Read);
                item.size = fsr.Length;

                // wrap the file system's stream in our progress stream. The progress stream
                // updates the thermometer/progress bar as the file is read.
                progStream = new ProgressStream(fsr, progressBar);

                // compute the hash
                // Is it just me, or is this MD5 routine slow?
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                md5.Initialize();
                byte[] hash = md5.ComputeHash(progStream);
                progStream = null;

                // we're done. Add the data to the screen
                listView.Invoke(new AddFileToGridDelegate(AddFileToGrid), new object[] { item, ByteArrayToHexadecimalString(hash) });

                md5.Clear();
            }
            catch (Exception e)
            {
                // did they click the abort button?
                if (e.Message.Equals("aborted"))
                {
                    queue.Clear();
                    this.Invoke(new UpdateEnqueuedLabelDelegate(UpdateEnqueuedLabel), new object[1] {
                        queue.Count()
                    });
                }
                else if (!quitting)
                {
                    ReportError("Couldn't process " + item.fullpath + "\r\n\r\nIs it open by another application?");
                }
                return;
            }
            finally
            {
                currentlyProcessingLabel.Invoke(new SetCurrentlyProcessingDelegate(SetCurrentlyProcessing), new object[] { "(idle)" });
                if (fsr != null)
                {
                    fsr.Close();
                }
            }
        }
Esempio n. 56
0
        private void DownloadFile(HttpContext context, Fe fe)
        {
            var fileEntity = this.dbcontext.FileEntity.Where(x => x.UploadStepValue == Model.UploadStep.完成).Where(x => x.Id == fe.id).FirstOrDefault();

            if (fileEntity == null)
            {
                throw new ArgumentException("指定的文件数据库记录不存在,文件id:" + fe.id);
            }
            context.Response.ContentType = "application/octet-stream";
            //这涉及RFC标准
            context.Response.AddHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + context.Server.UrlEncode(System.IO.Path.GetFileName(fileEntity.FullName)));
            long start     = 0;
            long end       = fileEntity.Size - 1;
            var  range     = context.Request.Headers["Range"] ?? string.Empty;
            var  rangeFlag = "bytes=";

            if (range.StartsWith(rangeFlag))
            {
                var lstRange = range.Substring(rangeFlag.Length).Split(new char[] { '-', ',', ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                if (lstRange.Count == 1)
                {
                    start = long.Parse(lstRange.First());
                }
                else if (lstRange.Count == 2)
                {
                    start = long.Parse(lstRange.First());
                    end   = long.Parse(lstRange.Last());
                }
                else if (lstRange.Count > 2)
                {
                    throw new ArgumentException("服务端不支持多个range范围的下载请求");
                }
                //如果请求头range具有值,0-2777,或者122-,或者134-1221112,则是浏览器恢复下载的断点续传请求。
                //响应码206,响应头content-range,包含本次下载的数据范围 134-1221111/1221112
                context.Response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent;
            }
            context.Response.Headers.Add("Content-Range", $"bytes {start}-{end}/{fileEntity.Size}");
            //响应头增加accept-ranges,向浏览器声明服务端支持断点续传
            //相关必须的响应头,content-length,last-modified,etag,响应码200
            //浏览器需要的GMT的时间,用于last-modified,
            var gmtDateString = new DateTime(2021, 1, 1).ToString("r");

            //etag使用文件相关的特征值,例如把文件最后修改时间进行md5
            context.Response.Headers.Add("Accept-Ranges", "bytes");
            context.Response.Headers.Add("Content-Length", (end - start + 1).ToString());
            context.Response.Headers.Add("Last-Modified", gmtDateString);
            var md5buffer = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(fileEntity.FullName));
            var etag      = System.BitConverter.ToString(md5buffer).Replace("-", string.Empty).ToLower();

            context.Response.Headers.Add("ETag", etag);
            int bufferSize = 1 * 1024 / 2;
            var rootFolder = this.GetRootFolder(context);

            using (var fs = new System.IO.FileStream(System.IO.Path.Combine(rootFolder, fileEntity.FullName), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
            {
                fs.Position = start;
                var buffer     = new byte[bufferSize];
                var datalength = 0;
                while ((datalength = fs.Read(buffer, 0, bufferSize)) > 0)
                {
                    context.Response.OutputStream.Write(buffer, 0, datalength);
                    context.Response.Flush();
                }
            }
            //firefox,ie,经典edge支持关闭浏览器,重新打开后,在中断位置继续下载
            //高版本chrome不支持关闭浏览器后在中断位置继续下载。
            //但如果下载过程发生错误,比如网络中断,可以恢复在中断位置继续下载下载(chrome不关闭);
        }
Esempio n. 57
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="resource"></param>
        /// <returns></returns>
        public static bool InstallMEX(ImageResource resource)
        {
            // patch dol
            using (var src = new MemoryStream(resource.GetDOL()))
                using (System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
                {
                    byte[] vanillaFullHash = new byte[] { 39, 123, 108, 9, 132, 118, 2, 32, 152, 149, 208, 17, 197, 163, 163, 139 };
                    byte[] vanillaDolHash  = new byte[] { 135, 241, 17, 254, 252, 165, 45, 39, 50, 80, 104, 65, 216, 32, 142, 212 };
                    byte[] patchedHash     = new byte[] { 220, 216, 224, 150, 88, 53, 129, 175, 54, 201, 175, 176, 53, 71, 167, 40 };

                    var hash = md5.ComputeHash(src);

                    if (!hash.SequenceEqual(vanillaDolHash) && !hash.SequenceEqual(vanillaFullHash) && !hash.SequenceEqual(patchedHash))
                    {
                        return(false);
                    }

                    if (!hash.SequenceEqual(patchedHash))
                    {
                        using (var dest = new MemoryStream())
                        {
                            src.Position = 0;
                            GCILib.BZip2.BinaryPatchUtility.Apply(src, () => new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lib/dol.patch"), FileMode.Open, FileAccess.Read, FileShare.Read), dest);

                            dest.Position = 0;
                            hash          = md5.ComputeHash(dest);

                            if (!hash.SequenceEqual(patchedHash))
                            {
                                return(false);
                            }

                            System.Diagnostics.Debug.WriteLine(string.Join(", ", patchedHash) + " " + hash.SequenceEqual(vanillaDolHash));

                            resource.SetDOL(dest.ToArray());
                        }
                    }
                }

            // generate mex files
            using (MEXDOLScrubber dol = new MEXDOLScrubber(resource.GetDOL()))
            {
                var resourceFile = new HSDRawFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lib\\resource.dat"));

                // generate mxdt
                MEX_Data data = new MEX_Data();

                // generate meta data
                data.MetaData = new MEX_Meta()
                {
                    NumOfInternalIDs   = 33,
                    NumOfExternalIDs   = 33,
                    NumOfCSSIcons      = 26,
                    NumOfInternalStage = 0,
                    NumOfExternalStage = 285,
                    NumOfSSSIcons      = 30,
                    NumOfSSMs          = 55,
                    NumOfMusic         = 98,
                    NumOfEffects       = 51,
                    EnterScene         = 2,
                    LastMajor          = 45, //?
                    LastMinor          = 45,
                };
                // Version
                data.MetaData._s.SetInt16(0x00, 0x0100);


                // fighter table
                InstallFighters(dol, data, resourceFile);


                // kirby table
                InstallKirby(dol, data, resourceFile);


                // sound table
                InstallSounds(dol, data, resourceFile);


                // item table
                InstallItems(dol, data, resourceFile);



                // effect table
                data.EffectTable             = new MEX_EffectData();
                data.EffectTable.EffectFiles = new HSDArrayAccessor <MEX_EffectFiles>()
                {
                    _s = new HSDFixedLengthPointerArrayAccessor <HSD_String>()
                    {
                        Array = dol.ReadStringTable(EffectStringOffset, data.MetaData.NumOfEffects * 3)
                    }._s
                };
                // note: this really isn't needed here because saving will regenerate anyway
                data.EffectTable.RuntimeUnk1 = new HSDAccessor()
                {
                    _s = new HSDStruct(0x60)
                };
                data.EffectTable.RuntimeUnk3 = new HSDAccessor()
                {
                    _s = new HSDStruct(0xCC)
                };
                data.EffectTable.RuntimeTexGrNum = new HSDAccessor()
                {
                    _s = new HSDStruct(0xCC)
                };
                data.EffectTable.RuntimeTexGrData = new HSDAccessor()
                {
                    _s = new HSDStruct(0xCC)
                };
                data.EffectTable.RuntimeUnk4 = new HSDAccessor()
                {
                    _s = new HSDStruct(0xCC)
                };
                data.EffectTable.RuntimePtclLast = new HSDAccessor()
                {
                    _s = new HSDStruct(0xCC)
                };
                data.EffectTable.RuntimePtclData = new HSDAccessor()
                {
                    _s = new HSDStruct(0xCC)
                };
                data.EffectTable.RuntimeLookup = new HSDAccessor()
                {
                    _s = new HSDStruct(0xCC)
                };

                // stage table
                InstallStages(dol, data, resourceFile);


                // scene table
                InstallScenes(dol, data, resourceFile);


                // misc table
                InstallMisc(dol, data, resourceFile);


                // generate sss and css symbols
                GetIconFromDOL(dol, data);
                var cssFile   = new HSDRawFile(resource.GetFile("MnSlChr.usd"));
                var sssFile   = new HSDRawFile(resource.GetFile("MnSlMap.usd"));
                var ifallFile = new HSDRawFile(resource.GetFile("IfAll.usd"));


                // mexSelectChr
                var mexMenuSymbol = GenerateMexSelectChrSymbol(cssFile.Roots[0].Data as SBM_SelectChrDataTable, data.MenuTable.CSSIconData.Icons);
                cssFile.Roots.RemoveAll(e => e.Name == "mexSelectChr");
                cssFile.Roots.Add(new HSDRootNode()
                {
                    Name = "mexSelectChr", Data = mexMenuSymbol
                });


                // mexMapData
                var mexMapSymbol = LoadIconDataFromVanilla(sssFile.Roots[0].Data as SBM_MnSelectStageDataTable);
                sssFile.Roots.RemoveAll(e => e.Name == "mexMapData");
                sssFile.Roots.Add(new HSDRootNode()
                {
                    Name = "mexMapData", Data = mexMapSymbol
                });


                // ifall data
                // load this from resources; don't generate
                if (ifallFile["bgm"] == null)
                {
                    ifallFile.Roots.Add(new HSDRootNode()
                    {
                        Name = "bgm",
                        Data = resourceFile["bgm"].Data
                    });
                }
                if (ifallFile["Eblm_matanim_joint"] == null)
                {
                    ifallFile.Roots.Add(new HSDRootNode()
                    {
                        Name = "Eblm_matanim_joint",
                        Data = resourceFile["Eblm_matanim_joint"].Data
                    });
                }
                if (ifallFile["Stc_icns"] == null)
                {
                    ifallFile.Roots.Add(new HSDRootNode()
                    {
                        Name = "Stc_icns",
                        Data = resourceFile["Stc_icns"].Data
                    });
                }



#if DEBUG
                /*var mexfile2 = new HSDRawFile();
                 * mexfile2.Roots.Add(new HSDRootNode() { Name = "mexData", Data = data });
                 * mexfile2.Save("test_Mxdt.dat");
                 * cssFile.Save("test_CSS.dat");
                 * sssFile.Save("test_SSS.dat");
                 * ifallFile.Save("test_IfAll.dat");
                 * return false;*/
#endif

                // add  files to resource
                resource.AddFile("codes.gct", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lib\\codes.gct"));

                // null ssm file
                resource.AddFile("audio/us/null.ssm", resource.GetFile("audio/us/end.ssm"));

                using (MemoryStream dat = new MemoryStream())
                {
                    ifallFile.Save(dat);
                    resource.AddFile("IfAll.usd", dat.ToArray());
                }
                using (MemoryStream dat = new MemoryStream())
                {
                    cssFile.Save(dat);
                    resource.AddFile("MnSlChr.usd", dat.ToArray());
                }
                using (MemoryStream dat = new MemoryStream())
                {
                    sssFile.Save(dat);
                    resource.AddFile("MnSlMap.usd", dat.ToArray());
                }
                using (MemoryStream dat = new MemoryStream())
                {
                    var mexfile = new HSDRawFile();
                    mexfile.Roots.Add(new HSDRootNode()
                    {
                        Name = "mexData", Data = data
                    });
                    mexfile.Save(dat);
                    resource.AddFile("MxDt.dat", dat.ToArray());
                }
            }



            // success
            return(true);
        }
Esempio n. 58
0
        public static int IntAnsiString(string str)
        {
            var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

            return(BitConverter.ToInt32(md5.ComputeHash(Encoding.ASCII.GetBytes(str)), 0));
        }
Esempio n. 59
0
 /// <summary>
 /// Generates GUID based on a string MD5 hash
 /// </summary>
 public static Guid ToGUID(this string input)
 {
     using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
         return(new Guid(md5.ComputeHash(Encoding.Default.GetBytes(input))));
 }
Esempio n. 60
0
        //Required for creating CRC

        /// <summary>
        /// Creates a new Zip writer, used to write a zip archive.
        /// </summary>
        /// <param name="fileStream">
        /// the output stream to which the zip archive is written.
        /// </param>
        public XyzEntryWriter(System.IO.Stream fileStream)
        {
            baseStream = fileStream;
            md5        = new System.Security.Cryptography.MD5CryptoServiceProvider();
        }