public void RunThread(object Obj) { object[] ObjArray = (object[])Obj; Uri url = (Uri)ObjArray[0]; string requestString = (string)ObjArray[1]; string responseString = (string)ObjArray[2]; WebHeaderCollection headerCollection = (WebHeaderCollection)ObjArray[3]; var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Headers = headerCollection; request.BeginGetRequestStream((s) => { var req = (HttpWebRequest)s.AsyncState; var str = req.EndGetRequestStream(s); System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); Byte[] bytes = encoding.GetBytes(responseString); str.Write(bytes, 0, bytes.Length); str.Close(); req.BeginGetResponse((k) => { var req2 = (HttpWebRequest)k.AsyncState; var resp = (HttpWebResponse)req2.EndGetResponse(k); byte[] bytes2 = ReadFully(resp.GetResponseStream()); string res = System.Text.Encoding.Unicode.GetString(bytes2); }, req); }, null); if (RunComleted != null) { RunCompleted(res); } }
private static void Main(string[] args) { List <string> keys = new List <string>(); var path = Path.GetFullPath("SEGA_MatisseN v2-B.ttf"); foreach (FontFamily fontFamily in Fonts.GetFontFamilies(path)) { var typefaces = fontFamily.GetTypefaces(); int index = 0; foreach (Typeface typeface in typefaces) { index++; Dictionary <object, object> result = new Dictionary <object, object>(); if (typeface.TryGetGlyphTypeface(out GlyphTypeface glyphTypeface)) { foreach (var item in glyphTypeface.CharacterToGlyphMap) { var key = item.Key.ToString("x8"); byte[] arr = HexStringToByteArray(key); System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding(); string str = converter.GetString(arr); result[str] = item.Value; } } File.WriteAllText("test" + index + ".json", JsonHelper.ToJson(result, indentLevel: 2, isUnicode: false)); } } File.WriteAllLines("test.txt", keys.ToArray()); }
/// <summary>This version of EncryptData takes the message, password /// and IV as strings and encrypts the message, returning the encrypted text as a string. /// </summary> /// <param name="message">The plain text message</param> /// <param name="password">The password/key to encrypt the message with</param> /// <param name="initialisationVector">The IV as a string</param> /// <param name="blockSize">The block size used to encrypt the message</param> /// <param name="keySize">The key size used to encrypt the message</param> /// <param name="cryptMode">The encryption mode, CBC or ECB, used to encrypt the message</param> /// <param name="returnAsHex">Whether the encrypted message is to be returned as Hex</param> public static string EncryptData(string message, string password, string initialisationVector, BlockSize blockSize, KeySize keySize, EncryptionMode cryptMode, bool returnAsHex) { byte[] messageData, passwordData, vectorData; // If message is empty dont bother doing any work if (message.Length <= 0) { return(""); } System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding(); // Convert message, key and IV to byte arrays messageData = encoderUnicode.GetBytes(message); passwordData = encoderUnicode.GetBytes(password); vectorData = encoderUnicode.GetBytes(initialisationVector); // Return encrypted message as string (hex version of bytes if required) if (returnAsHex) { return(BytesToHex(EncryptData(messageData, passwordData, vectorData, blockSize, keySize, cryptMode))); } else { return(encoderUnicode.GetString(EncryptData(messageData, passwordData, vectorData, blockSize, keySize, cryptMode))); } }
/// <summary> /// A function that is called when pressing "Save txt" button. /// It starts an new windows object of type SaveFileDialog. /// It saves a list of Points in format: "Point: (x, F(x)) \n" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TextSaveGraph(object sender, EventArgs e) { System.Text.UnicodeEncoding uniEncoding = new System.Text.UnicodeEncoding(); Stream streamToSaveText = new MemoryStream(); SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; saveDialog.FilterIndex = 1; saveDialog.RestoreDirectory = true; String points = ""; for (float x = xMin; x <= xMax; x = x + counter) { points += "Point: (" + Math.Round(x, 2) + ", " + Math.Round(F(x), 2) + ")\n"; } byte[] messageBytes = uniEncoding.GetBytes(points); if (saveDialog.ShowDialog() == DialogResult.OK) { if ((streamToSaveText = saveDialog.OpenFile()) != null) { streamToSaveText.Write(messageBytes, 0, messageBytes.Length); streamToSaveText.Position = 0; streamToSaveText.Close(); } } }
public ActionResult BatchUpload(DateTime date, HttpPostedFileBase file, int? fundid, string text) { string s; if (file != null) { byte[] buffer = new byte[file.ContentLength]; file.InputStream.Read(buffer, 0, file.ContentLength); System.Text.Encoding enc = null; if (buffer[0] == 0xFF && buffer[1] == 0xFE) { enc = new System.Text.UnicodeEncoding(); s = enc.GetString(buffer, 2, buffer.Length - 2); } else { enc = new System.Text.ASCIIEncoding(); s = enc.GetString(buffer); } } else s = text; var id = PostBundleModel.BatchProcess(s, date, fundid); if (id.HasValue) return Redirect("/PostBundle/Index/" + id); return RedirectToAction("Batch"); }
/// <summary>This version of DecryptData takes the encrypted message, password /// and IV as strings and decrypts the message, returning the plain text as a string. /// </summary> /// <param name="message">The encrypted message</param> /// <param name="password">The password/key that was used to encrypt the message</param> /// <param name="initialisationVector">The IV as a string</param> /// <param name="blockSize">The block size used in encrypting the message</param> /// <param name="keySize">The key size used in encrypting the message</param> /// <param name="cryptMode">The encryption mode, CBC or ECB, used in encrypting the message</param> /// <param name="messageAsHex">Whether the encrypted message was returned as Hex</param> public static string DecryptData(string message, string password, string initialisationVector, BlockSize blockSize, KeySize keySize, EncryptionMode cryptMode, bool messageAsHex) { byte[] messageData, passwordData, vectorData; // Dont do any work is the message is empty if (message.Length <= 0) { return(""); } System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding(); // Was message supplied in Hex or as simple string if (messageAsHex) { messageData = HexToBytes(message); } else { messageData = encoderUnicode.GetBytes(message); } // Convert key and IV to byte arrays passwordData = encoderUnicode.GetBytes(password); vectorData = encoderUnicode.GetBytes(initialisationVector); // Return the decrypted plain test as a string return(encoderUnicode.GetString(DecryptData(messageData, passwordData, vectorData, blockSize, keySize, cryptMode))); }
private string convertUnicodeToASCII(string value) { System.Text.ASCIIEncoding encodingASCII = new System.Text.ASCIIEncoding(); System.Text.UnicodeEncoding encodingUNICODE = new System.Text.UnicodeEncoding(); byte[] sampleTextEncoded = encodingUNICODE.GetBytes(value); return(HttpUtility.UrlEncode(encodingASCII.GetString(sampleTextEncoded))); }
/// <summary> /// Allocates a string on the uWebKit memory paging system /// </summary> public static int AllocateString(string value, ref int size) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); Byte[] bytes = encoding.GetBytes(value); Byte[] nbytes = new Byte[bytes.Length + 2]; Array.Copy(bytes, nbytes, bytes.Length); nbytes[bytes.Length] = 0; nbytes[bytes.Length + 1] = 0; GCHandle pinned = GCHandle.Alloc(nbytes, GCHandleType.Pinned); int i = UWK_AllocateAndCopy(pinned.AddrOfPinnedObject(), nbytes.Length); pinned.Free(); size = nbytes.Length; if (i < 0) { throw new Exception("Error Allocating String"); } return(i); }
internal void GetPersisitedNames(IntPtr storePtr, List <string> persistedNames) { buffer = new Buffer(); NativeApi.UnityWindowsMR_refPoints_GetPersistedNames(storePtr, out buffer); if (buffer.size == 0) { return; } byte[] byteBuffer = new byte[buffer.size]; Marshal.Copy(buffer.buffer, byteBuffer, 0, buffer.size); using (MemoryStream stream = new MemoryStream(byteBuffer)) { using (BinaryReader reader = new BinaryReader(stream)) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); int countStrings = reader.ReadInt32(); for (int i = 0; i < countStrings; i++) { int strByteLen = reader.ReadInt32() * 2; byte[] bytes = reader.ReadBytes(strByteLen); string name = encoding.GetString(bytes, 0, strByteLen); persistedNames.Add(name); } } } }
public void AddTo (CodeGen code_gen, PEAPI.MetaDataElement elem) { System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding (); foreach (DictionaryEntry entry in permissionset_table) { PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction) entry.Key; SSPermissionSet ps = (SSPermissionSet) entry.Value; code_gen.PEFile.AddDeclSecurity (sec_action, ue.GetBytes (ps.ToXml ().ToString ()), elem); } if (permissionset20_table == null) return; foreach (DictionaryEntry entry in permissionset20_table) { PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction) entry.Key; MIPermissionSet ps = (MIPermissionSet) entry.Value; code_gen.PEFile.AddDeclSecurity (sec_action, ps.Resolve (code_gen), elem); } }
internal static void GetFilesContent(PythonModel pe) { var files = HttpContext.Current.Request.Files; var a = files.AllKeys; for (var i = 0; i < a.Length; i++) { var file = files[i]; var buffer = new byte[file.ContentLength]; file.InputStream.Read(buffer, 0, file.ContentLength); System.Text.Encoding enc; string s = null; if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) { enc = new System.Text.ASCIIEncoding(); s = enc.GetString(buffer, 3, buffer.Length - 3); } else if (buffer[0] == 0xFF && buffer[1] == 0xFE) { enc = new System.Text.UnicodeEncoding(); s = enc.GetString(buffer, 2, buffer.Length - 2); } else { enc = new System.Text.ASCIIEncoding(); s = enc.GetString(buffer); } pe.DictionaryAdd(a[i], s); } }
public ActionResult LoginSubmit(String email, String password) { if (Session["user"] == null) { var unicodeCoder = new System.Text.UnicodeEncoding(); var byteEncodedPassword = unicodeCoder.GetBytes(password); var byteHashPassword = new System.Security.Cryptography.SHA256Managed().ComputeHash(byteEncodedPassword); password = Convert.ToBase64String(byteHashPassword); User user = db.Users.SingleOrDefault(s => s.Email == email && s.Password == password && s.Status == true); if (user != null) { Session["user"] = user; Session["role"] = user.Role; Session["email"] = user.Email; Session["userId"] = user.Id; Session["username"] = user.FirstName; } else { return(RedirectToAction("Login")); } } return(RedirectToAction("Index")); }
/** * Constructor * * @param pw the password */ public PasswordRecord(string pw) : base(Type.PASSWORD) { password = pw; if (pw == null) { data = new byte[2]; IntegerHelper.getTwoBytes(0, data, 0); } else { // System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding(); System.Text.UnicodeEncoding encoder = new System.Text.UnicodeEncoding(); byte[] passwordBytes = encoder.GetBytes(pw); int passwordHash = 0; for (int a = 0; a < passwordBytes.Length; a++) { int shifted = rotLeft15Bit(passwordBytes[a], a + 1); passwordHash ^= shifted; } passwordHash ^= passwordBytes.Length; passwordHash ^= 0xCE4B; data = new byte[2]; IntegerHelper.getTwoBytes(passwordHash, data, 0); } }
public void AddTo(CodeGen code_gen, PEAPI.MetaDataElement elem) { System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding(); foreach (DictionaryEntry entry in permissionset_table) { PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction)entry.Key; SSPermissionSet ps = (SSPermissionSet)entry.Value; code_gen.PEFile.AddDeclSecurity(sec_action, ue.GetBytes(ps.ToXml().ToString()), elem); } if (permissionset20_table == null) { return; } foreach (DictionaryEntry entry in permissionset20_table) { PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction)entry.Key; MIPermissionSet ps = (MIPermissionSet)entry.Value; code_gen.PEFile.AddDeclSecurity(sec_action, ps.Resolve(code_gen), elem); } }
public override bool setContentsString(string str, string encoding) { onError(null); if (object.Equals(str, null)) { return(false); } System.Text.Encoding ee; if (encoding == null || encoding.Equals("UTF-8") || encoding.Equals("UTF8")) { ee = new System.Text.UTF8Encoding(false); } else if (encoding.Equals("ASCII")) { ee = System.Text.Encoding.ASCII; } else if (encoding.Equals("UCS-2") || encoding.Equals("UCS2")) { ee = new System.Text.UnicodeEncoding(false, false); } else { return(false); } try { System.IO.File.WriteAllText(completePath, str, ee); } catch (System.Exception e) { onError(e.ToString()); return(false); } return(true); }
internal static string Serialize <T>(IList <T> info) { // serialize data var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }); var serializer = new XmlSerializer(info.GetType(), new XmlRootAttribute("ROOT")); var settings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true }; try { using (var stream = new StringWriter()) { using (var writer = XmlWriter.Create(stream, settings)) { serializer.Serialize(writer, info, emptyNamepsaces); var encoding = new System.Text.UnicodeEncoding(); byte[] bytestosend = encoding.GetBytes(stream.ToString()); string sText = encoding.GetString(bytestosend); return(sText); } } } catch (Exception ex) { Logger.Error(ex); throw; } }
private static string convertToUnicode(char ch) { System.Text.UnicodeEncoding class1 = new System.Text.UnicodeEncoding(); byte[] msg = class1.GetBytes(System.Convert.ToString(ch)); return(fourDigits(msg[1] + msg[0].ToString("X"))); }
public ActionResult BatchUpload(DateTime date, HttpPostedFileBase file, int?fundid, string text) { string s; if (file != null) { byte[] buffer = new byte[file.ContentLength]; file.InputStream.Read(buffer, 0, file.ContentLength); System.Text.Encoding enc = null; if (buffer[0] == 0xFF && buffer[1] == 0xFE) { enc = new System.Text.UnicodeEncoding(); s = enc.GetString(buffer, 2, buffer.Length - 2); } else { enc = new System.Text.ASCIIEncoding(); s = enc.GetString(buffer); } } else { s = text; } var id = PostBundleModel.BatchProcess(s, date, fundid); if (id.HasValue) { return(Redirect("/PostBundle/Index/" + id)); } return(RedirectToAction("Batch")); }
public mfString(byte[] data, uint offset) { this.uni = new System.Text.UnicodeEncoding(); uint i = (uint)(new mwgDword(data, offset)); this.dat = uni.GetString(data, (int)(offset + 4), (int)i); //※問題点 intの文字数分までしか読み取る事が出来ない。 }
private static byte[] ToByteArray(object value) { var result = new byte[] { }; var val = value as string; if (val != null) result = new System.Text.UnicodeEncoding().GetBytes(val); return result; }
static bool GetSiteNameFromISAPI() { Debug.Trace("config_loc", "GetSiteNameFromISAPI()"); HttpContext context = HttpContext.Current; if (context != null) { string metabaseAppKey = context.Request.ServerVariables["INSTANCE_META_PATH"]; const string KEY_LMW3SVC = "/LM/W3SVC/"; Debug.Assert(metabaseAppKey.StartsWith(KEY_LMW3SVC)); string appNumber = metabaseAppKey.Substring(KEY_LMW3SVC.Length - 1); //string appServerComment = "/" + appNumber + "/ServerComment"; Debug.Trace("config_loc", "appNumber:" + appNumber + " INSTANCE_META_PATH:" + metabaseAppKey); UnicodeEncoding encoding = new UnicodeEncoding(); // null-terminate appNumber and convert to byte array byte [] byteAppNumber = encoding.GetBytes(appNumber + "\0"); int retVal = 2; byte [] outBytes = new byte[64]; while (retVal == 2) { retVal = context.CallISAPI(UnsafeNativeMethods.CallISAPIFunc.GetSiteServerComment, byteAppNumber, outBytes); if (retVal == 2) { if (outBytes.Length > 1024) // should never happen { throw new ConfigurationException(HttpRuntime.FormatResourceString( SR.Config_site_name_too_long, metabaseAppKey)); } outBytes = new byte[outBytes.Length * 2]; } } // find WCHAR null terminator in byte array int i = 0; while (i + 1 < outBytes.Length && (outBytes[i] != 0 || outBytes[i + 1] != 0)) { i += 2; } // decode up to null terminator s_siteName = encoding.GetString(outBytes, 0, i); Debug.Trace("config_loc", "i: " + i + " site name:" + s_siteName); return(true); } else { Debug.Trace("config_loc", "could not query site name. No Context."); } return(false); // keep trying to evaluate }
public static string Encrypt(string pData) { System.Text.UnicodeEncoding parser = new System.Text.UnicodeEncoding(); byte[] _original = parser.GetBytes(pData); MD5CryptoServiceProvider Hash = new MD5CryptoServiceProvider(); byte[] _encrypt = Hash.ComputeHash(_original); return(Convert.ToBase64String(_encrypt)); }
/// <summary> /// Retrieves a string allocated on the uWebKit memory paging system /// </summary> public static string GetString(int page, int sz) { byte[] bytes = new byte[sz]; GetBytes(page, sz, bytes); System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); return(encoding.GetString(bytes)); }
public ArrayList CreateNewCharContainer(bool lowerCaseLetters, bool capitals, bool peculiar, bool numbers, bool ownCharacters, string myCharacters) { if (lowerCaseLetters) { for (int i = 97; i < 123; i++) { charContainer.Add((char)i); } } if (capitals) { for (int i = 65; i < 91; i++) { charContainer.Add((char)i); } } if (peculiar) { for (int i = 32; i < 48; i++) { charContainer.Add((char)i); } for (int i = 58; i < 65; i++) { charContainer.Add((char)i); } for (int i = 91; i < 97; i++) { charContainer.Add((char)i); } charContainer.Add((char)123); charContainer.Add((char)124); charContainer.Add((char)125); charContainer.Add((char)126); } if (numbers) { for (int i = 48; i < 58; i++) { charContainer.Add((char)i); } } if (ownCharacters) { System.Text.UnicodeEncoding unicode = new System.Text.UnicodeEncoding(); char[] characters = unicode.GetChars(unicode.GetBytes(myCharacters)); for (int i = 0; i < characters.Length; i++) { if (!charContainer.Contains(characters[i])) { charContainer.Add(characters[i]); } } } return(charContainer); }
public void GetStringFromUnicodeArrayTest() { string expected = "Test!"; System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); var self = encoding.GetBytes(expected); var actual = self.GetStringFromArray(EncodingType.Unicode); Assert.AreEqual(expected, actual); }
/// <summary>Utility function to convert a byte array to a string</summary> public static string BytesToString(byte[] message) { if (message.Length <= 0) { return(""); } System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding(); return(encoderUnicode.GetString(message)); }
/// <summary>Utility function to convert a string to a byte array</summary> public static byte[] StringToBytes(string message) { if (message.Length <= 0) { return(new byte[0]); } System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding(); return(encoderUnicode.GetBytes(message)); }
/// <summary> /// Sets the commands index parameter to the specified string /// </summary> public void SetSParam(int index, string value) { int startIndex = index * 256 * 2; System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); Byte[] bytes = encoding.GetBytes(value); Array.Copy(bytes, 0, sParams, startIndex, bytes.Length); sParams[startIndex + bytes.Length] = 0; sParams[startIndex + bytes.Length + 1] = 0; }
public ActionResult BatchUpload(DateTime?date, HttpPostedFileBase file, int?fundid, string text) { if (!date.HasValue) { ModelState.AddModelError("date", "Date is required"); return(View("Batch")); } var fromFile = false; string s; if (file != null) { var buffer = new byte[file.ContentLength]; file.InputStream.Read(buffer, 0, file.ContentLength); System.Text.Encoding enc; if (buffer[0] == 0xFF && buffer[1] == 0xFE) { enc = new System.Text.UnicodeEncoding(); s = enc.GetString(buffer, 2, buffer.Length - 2); } else { enc = new System.Text.ASCIIEncoding(); s = enc.GetString(buffer); } fromFile = true; } else { if (String.IsNullOrWhiteSpace(text)) { ModelState.AddModelError("textarea", "Text is required when no file is uploaded."); return(View("Batch")); } s = text; } try { var id = BatchImportContributions.BatchProcess(s, date.Value, fundid, fromFile); if (id.HasValue) { return(Redirect("/PostBundle/" + id)); } return(RedirectToAction("Batch")); } catch (Exception ex) { return(PageMessage(ViewExtensions2.Markdown(ex.Message).ToString())); } }
/// <summary> /// Renames the replays' internal name /// </summary> /// <param name="newName">New name to use for the replay</param> public bool RenameReplay(Replay replay, string newName) { try { //load the replay data FileStream fsreader = File.OpenRead(replay.Filename); byte[] data = new byte[fsreader.Length]; fsreader.Read(data, 0, data.Length); fsreader.Close(); //create a buffer for the adjusted file int new_replaysize = replay.FileSize + ((newName.Length - replay.Name.Length) * 2); byte[] buffer = new byte[new_replaysize]; System.IO.MemoryStream writer = new MemoryStream(buffer); //calculate the new db & foldinfo len int database_len = replay.DATABASE + ((newName.Length - replay.Name.Length) * 2); int foldinfo_len = replay.FOLDINFO + ((newName.Length - replay.Name.Length) * 2); //write everything into the new buffer up to the foldinfo len writer.Write(data, 0, replay.FOLDINFOPOS); byte[] foldinfo_byte = BitConverter.GetBytes(foldinfo_len); writer.Write(foldinfo_byte, 0, foldinfo_byte.Length); writer.Write(data, replay.FOLDINFOPOS + 4, (replay.DATABASEPOS - replay.FOLDINFOPOS - 4)); byte[] database_byte = BitConverter.GetBytes(database_len); writer.Write(database_byte, 0, database_byte.Length); writer.Write(data, replay.DATABASEPOS + 4, (replay.REPLAYLENPOS - replay.DATABASEPOS - 4)); byte[] replay_byte = BitConverter.GetBytes(newName.Length); writer.Write(replay_byte, 0, replay_byte.Length); //get the new name in bytes System.Text.UnicodeEncoding encoder = new System.Text.UnicodeEncoding(); byte[] byte_name = encoder.GetBytes(newName); writer.Write(byte_name, 0, byte_name.Length); writer.Write(data, (replay.REPLAYLENPOS + 4 + (replay.Name.Length * 2)), (replay.FileSize - ((replay.REPLAYLENPOS + 4) + replay.Name.Length * 2))); writer.Close(); BinaryWriter binwriter = new BinaryWriter(File.Create(replay.Filename)); binwriter.Write(buffer); binwriter.Close(); return(true); } catch { return(false); } }
/// <summary> /// Mã hóa password /// </summary> protected string EncryptPassword(string Password) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); byte[] hashBytes = encoding.GetBytes(Password); //Compute the SHA-1 hash SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] cryptPassword = sha1.ComputeHash(hashBytes); return(BitConverter.ToString(cryptPassword)); }
public void ReferenceGenerator_InitializesNamesAndReference() { System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding(); _referenceGenerator = new MethodReferenceGenerator( "Remotion.Interfaces, Version=1.13.73.1026, Culture=neutral, PublicKeyToken=fee00910d6e5f53b", "Factory.ObjectFactory", "Param.ParamList"); Assert.That(_referenceGenerator.ObjectFactoryName == "ObjectFactory"); Assert.That(_referenceGenerator.ObjectFactoryNamespace == "Factory"); Assert.That(_referenceGenerator.ParamListName == "ParamList"); Assert.That(_referenceGenerator.ParamListNamespace == "Param"); }
public string StreamToBytes(System.IO.Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, System.IO.SeekOrigin.Begin); System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding(); String d = converter.GetString(bytes); return(d); }
public byte[] KeyGenerator(string AndroidKey) { SecureRandom sr = SecureRandom.GetInstance("SHA1PRNG"); var encoder = new System.Text.UnicodeEncoding(); var b = encoder.GetBytes (AndroidKey); // use key sr.SetSeed(encoder.GetBytes(AndroidKey)); return encoder.GetBytes (AndroidKey); // Cipher c = Cipher.GetInstance("AES"); // c.Init(CipherMode.EncryptMode, // KeyGenerator kg = KeyGenerator.GetInstance("AES"); // kg.Init(128, sr); // return new SecretKeySpec (kg.GenerateKey ().GetEncoded (), "AES").GetEncoded (); }
public ActionResult BatchUpload(DateTime date, HttpPostedFileBase file, int? fundid, string text) { var fromFile = false; string s; if (file != null) { var buffer = new byte[file.ContentLength]; file.InputStream.Read(buffer, 0, file.ContentLength); System.Text.Encoding enc; if (buffer[0] == 0xFF && buffer[1] == 0xFE) { enc = new System.Text.UnicodeEncoding(); s = enc.GetString(buffer, 2, buffer.Length - 2); } else { enc = new System.Text.ASCIIEncoding(); s = enc.GetString(buffer); } fromFile = true; } else s = text; try { var id = BatchImportContributions.BatchProcess(s, date, fundid, fromFile); if (id.HasValue) return Redirect("/PostBundle/" + id); return RedirectToAction("Batch"); } catch (Exception ex) { return PageMessage(ViewExtensions2.Markdown(ex.Message).ToString()); } }
/// <summary> /// Allocates a string on the uWebKit memory paging system /// </summary> public static int AllocateString(string value, ref int size) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding (); Byte[] bytes = encoding.GetBytes (value); Byte[] nbytes = new Byte[bytes.Length + 2]; Array.Copy (bytes, nbytes, bytes.Length); nbytes[bytes.Length] = 0; nbytes[bytes.Length + 1] = 0; GCHandle pinned = GCHandle.Alloc (nbytes, GCHandleType.Pinned); int i = UWK_AllocateAndCopy (pinned.AddrOfPinnedObject (), nbytes.Length); pinned.Free (); size = nbytes.Length; if (i < 0) throw new Exception ("Error Allocating String"); return i; }
public bool setFileName( string sFileName ) { bool bResult = true; System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding(); if( ue.GetByteCount( sFileName ) != 6 ) { bResult = false; throw new ArrayTypeMismatchException( "FileName is should have a length of 6 characters." ); } m_FileName = ue.GetBytes( sFileName ); return bResult; }
public void DoTestLocalMessageBroadcastDotNet() { bool repeat = false; do { Console.Write("What's your name: "); string name = Console.ReadLine(); Console.WriteLine("Welcome " + name + ". You can say something by typing 's', type 'S' for a message to only 1 partner, q to quit."); localMessageBroadcastPartner = new LocalMessageBroadcastPartner(name, "TESTCHANNEL"); localMessageBroadcastPartner.OnPartnerJoined += PartnerJoinedHandler; localMessageBroadcastPartner.OnPartnerLeft += PartnerLeftHandler; localMessageBroadcastPartner.OnMessage += delegate(UInt32 sendingPartnerId, IntPtr msgData, UInt32 msgLength) { Console.Out.WriteLine( localMessageBroadcastPartner.GetPartnerName(sendingPartnerId) + " says: " + Marshal.PtrToStringUni(msgData, (int)msgLength / 2) ); }; if ( localMessageBroadcastPartner != null ) { try { Console.WriteLine("We have ID = " + localMessageBroadcastPartner.PartnerId.ToString()); char input = Console.ReadKey(true).KeyChar;//.ReadLine(); while ( input != 'q' ) { if ( input == 's' ) { Console.Write("" + name + " says: "); string msg = Console.ReadLine(); byte[] stringBytes = new System.Text.UnicodeEncoding().GetBytes(msg); localMessageBroadcastPartner.BroadcastMessage(stringBytes); } else if ( input == 'S' ) { UInt32 partnerId; Console.Write("To which partner ID do you want to speak: "); while ( ! UInt32.TryParse( Console.ReadLine(), out partnerId) ) { Console.Write("Error, you need to give an integer: "); } Console.Write("" + name + " says: "); string msg = Console.ReadLine(); byte[] stringBytes = new System.Text.UnicodeEncoding().GetBytes(msg); localMessageBroadcastPartner.SendMessageToSinglePartner(partnerId, stringBytes); } input = Console.ReadKey(true).KeyChar; } } finally { localMessageBroadcastPartner.Dispose(); } } else { Console.WriteLine( "new LocalMessageBroadcastPartner(...) FAILED!!!" ); } Console.WriteLine( "\nPress 'q' again to really quit or 'r' to restart..." ); repeat = false; char input2 = Console.ReadKey(true).KeyChar;//.ReadLine(); while ( input2 != 'q' && input2 != 'r' ) { input2 = Console.ReadKey(true).KeyChar; } if (input2 == 'r') { repeat = true; Console.WriteLine(); } } while (repeat); //Thread.Sleep(8000); }
/// <summary> /// Retrieves a string allocated on the uWebKit memory paging system /// </summary> public static string GetString(int page, int sz) { byte[] bytes = new byte[sz]; GetBytes (page, sz, bytes); System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding (); return encoding.GetString (bytes); }
public UserComment (byte [] raw_data, bool little) { if (raw_data.Length == 8 || raw_data.Length == 0) { Charset = null; Value = String.Empty; return; } else if (raw_data.Length < 8) { throw new Exception ("Invalid UserComment value, no charset found"); } string charset = System.Text.Encoding.ASCII.GetString (raw_data, 0, 8); System.Text.Encoding enc; switch (charset) { case "ASCII\0\0\0": enc = System.Text.Encoding.ASCII; break; case "UNICODE\0": case "Unicode\0": enc = new System.Text.UnicodeEncoding (! little, true); break; case "JIS\0\0\0\0\0": // FIXME this requires mono locale extras try { enc = System.Text.Encoding.GetEncoding ("euc-jp"); } catch { System.Console.WriteLine ("missing jis0208 encoding"); enc = System.Text.Encoding.Default; } break; case "\0\0\0\0\0\0\0\0": // FIXME the spec says to use the local encoding in this case, we could probably // do something smarter, but whatever. enc = System.Text.Encoding.Default; break; default: enc = null; throw new ParseException (System.String.Format ("Invalid charset name: {0}", charset)); } Charset = charset; // for (int i = 0; i < raw_data.Length; i++) // System.Console.WriteLine ("{0} - \"{1}\"", raw_data [i].ToString ("x"), raw_data [i]); Value = enc.GetString (raw_data, 8, raw_data.Length - 8); }
public byte [] GetBytes (bool is_little) { bool ascii = true; string description = Value; System.Text.Encoding enc; string heading; for (int i = 0; i < description.Length; i++) { if (description [i] > 127) { ascii = false; break; } } if (ascii) { heading = "ASCII\0\0\0"; enc = new System.Text.ASCIIEncoding (); } else { heading = "Unicode\0"; enc = new System.Text.UnicodeEncoding (! is_little, true); } int len = enc.GetByteCount (description); byte [] data = new byte [len + heading.Length]; System.Text.Encoding.ASCII.GetBytes (heading, 0, heading.Length, data, 0); enc.GetBytes (Value, 0, Value.Length, data, heading.Length); UserComment c = new UserComment (data, is_little); System.Console.WriteLine ("old = \"{0}\" new = \"{1}\" heading = \"{2}\"", c.Value, description, heading); return data; }
/// <summary> /// Sets the commands index parameter to the specified string /// </summary> public void SetSParam(int index, string value) { int startIndex = index * 256 * 2; System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding (); Byte[] bytes = encoding.GetBytes (value); Array.Copy (bytes, 0, sParams, startIndex, bytes.Length); sParams[startIndex + bytes.Length] = 0; sParams[startIndex + bytes.Length + 1] = 0; }
public static void sqlite3_result_blob(SqliteContextHandle context, byte[] data, int dataLength, object callback) { var value = new System.Text.UnicodeEncoding().GetString(data, 0, data.Length); Community.CsharpSqlite.Sqlite3.sqlite3_result_blob(context.Handle, value, dataLength, null); }
public void ReferenceGenerator_InitializesNamesAndReference() { System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding(); _referenceGenerator = new MethodReferenceGenerator ( "Remotion.Interfaces, Version=1.13.73.1026, Culture=neutral, PublicKeyToken=fee00910d6e5f53b", "Factory.ObjectFactory", "Param.ParamList"); Assert.That (_referenceGenerator.ObjectFactoryName == "ObjectFactory"); Assert.That (_referenceGenerator.ObjectFactoryNamespace == "Factory"); Assert.That (_referenceGenerator.ParamListName == "ParamList"); Assert.That (_referenceGenerator.ParamListNamespace == "Param"); }
/// <summary> /// Malforms the bytes by removing the last byte from whichever encoding you specify. /// </summary> /// <param name="encoding">The encoding you want a byte representation in. Specify utf-8, utf-16le, or utf16-be</param> /// <param name="character">A single character sent as a string.</param> /// <returns></returns> public byte[] GetCharacterBytesMalformed(string encoding, string character) { System.Text.Encoding enc; if (encoding == "utf-16le") { enc = new System.Text.UnicodeEncoding(); } else if (encoding == "utf-16be") { enc = new System.Text.UnicodeEncoding(true, false); } else { enc = new System.Text.UTF8Encoding(); } byte[] characterBytes = enc.GetBytes(character); // now we have a byte array byte[] shorter; // Check that there's more than one byte before malforming it by removing the last byte. // Otherwise we'd end up with no bytes in the array. This can make test cases pretty useless. if (enc.GetByteCount(character) > 1) { shorter = new byte[characterBytes.Length - 1]; Array.Copy(characterBytes, shorter, shorter.Length); } // just return the one byte array rather than removing the one byte else { shorter = new byte[characterBytes.Length]; Array.Copy(characterBytes, shorter, shorter.Length); } return shorter; }
public bool setCharacterComplement( string sCharacterComplement ) { bool bResult = true; System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding(); if( ue.GetByteCount( sCharacterComplement ) != 8 ) { bResult = false; throw new ArrayTypeMismatchException( "CharacterComplement should have a length of 8 characters." ); } m_CharacterComplement = ue.GetBytes( sCharacterComplement ); return bResult; }
public static string Contrasenia_Cryp_MD5(string texto) { byte[] resultadomd5; byte[] qsstrbytearray; int indice; System.Text.UnicodeEncoding codificacion = new System.Text.UnicodeEncoding(); System.Security.Cryptography.MD5CryptoServiceProvider varmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); string codstr = ""; string ret = ""; if (texto == "") ret = ""; else { qsstrbytearray = codificacion.GetBytes(texto); resultadomd5 = varmd5.ComputeHash(qsstrbytearray); for (indice = 0; indice < resultadomd5.Length; indice++) { string tmp = resultadomd5[indice].ToString("X"); if (tmp.Length == 1) codstr += "0"; codstr += tmp; } ret = codstr; } return ret; }
/// <summary> /// Processes v4 of the .rec file (patch 1.4 / 1.41) /// </summary> private void readv4(BinaryReader reader) { int index = 0; //skip reader.BaseStream.Position += 85; replay.Duration = CalculateDuration(reader.ReadInt32()); reader.BaseStream.Position += 36; //FOLDINFO tag is in here replay.FOLDINFOPOS = (int)reader.BaseStream.Position; replay.FOLDINFO = reader.ReadInt32(); //skip reader.BaseStream.Position += 61; //will use the number of players a bit later int numplayers = reader.ReadInt32(); replay.MapSize = reader.ReadInt32(); //len of map module int mapmodulelen = reader.ReadInt32(); reader.BaseStream.Position += mapmodulelen; //internal map name eg: $1 0 0 3 (dont need this now) int internalmaplen = reader.ReadInt32(); reader.BaseStream.Position += internalmaplen * 2; //map name replay.Map = new String(reader.ReadChars(reader.ReadInt32())); replay.Map = replay.Map.Replace("_", " "); replay.Map = replay.Map.Remove(0, replay.Map.LastIndexOf(@"\") + 4); //skip if (replay.Version > 1) reader.BaseStream.Position += 16; else { //FOLDMODI and DATADMOD tags reader.BaseStream.Position += 33; //skip int foldmodilen = reader.ReadInt32(); reader.BaseStream.Position += foldmodilen + 4; } reader.BaseStream.Position += 12; replay.DATABASEPOS = (int)reader.BaseStream.Position; replay.DATABASE = reader.ReadInt32(); //DATABASE tag is just before here reader.BaseStream.Position += 16; //game options replay.GameOptions = new GameOptionsType(); int numgameopts = reader.ReadInt32(); for (index = 0; index < numgameopts; index++) { int optvalue = reader.ReadInt32(); string option = new String(reader.ReadChars(4)); switch (option) { case GameOptionsType.AIDifficultyName: //AI Difficulty replay.GameOptions.AIDifficulty = (GameOptionsType.AIDifficultyType)optvalue; break; case GameOptionsType.StartingResourcesName: //Starting Resources replay.GameOptions.StartingResources = (GameOptionsType.StartingResourcesType)optvalue; break; case GameOptionsType.LockTeamsName: //Lock Teams replay.GameOptions.LockTeams = (GameOptionsType.LockTeamsType)optvalue; break; case GameOptionsType.CheatsEnabledName: //Cheats enabled replay.GameOptions.CheatsEnabled = (GameOptionsType.CheatsEnabledType)optvalue; break; case GameOptionsType.StartingLocationName: //Starting Location replay.GameOptions.StartingLocation = (GameOptionsType.StartingLocationType)optvalue; break; case GameOptionsType.GameSpeedName: //Game Speed replay.GameOptions.GameSpeed = (GameOptionsType.GameSpeedType)optvalue; break; case GameOptionsType.ResourceSharingName: //Resource Sharing replay.GameOptions.ResourceSharing = (GameOptionsType.ResourceSharingType)optvalue; break; case GameOptionsType.ResourceRateName: //Resource Rate replay.GameOptions.ResourceRate = (GameOptionsType.ResourceRateType)optvalue; break; default: break; } } //skip 1 byte reader.BaseStream.Position++; //internal replay name replay.REPLAYLENPOS = (int)reader.BaseStream.Position; int replaylen = reader.ReadInt32(); System.Text.UnicodeEncoding unicode = new System.Text.UnicodeEncoding(); replay.Name = unicode.GetString(reader.ReadBytes(replaylen * 2)); //skip reader.BaseStream.Position += 4; //win conditions replay.WinConditions = new WinConditionsType(); int numwinconditions = reader.ReadInt32(); for(index = 0; index < numwinconditions; index++) { int win_condition = reader.ReadInt32(); switch(win_condition) { case WinConditionsType.AnnihilateValue: //Annihilate replay.WinConditions.Annihilate = true; break; case WinConditionsType.AssassinateValue://Assassinate replay.WinConditions.Assassinate = true; break; case WinConditionsType.ControlAreaValue://Control Area replay.WinConditions.ControlArea = true; break; case WinConditionsType.DestroyHQValue: //Destroy HQ replay.WinConditions.DestroyHQ = true; break; case WinConditionsType.EconomicVictoryValue: //Economic Victory replay.WinConditions.EconomicVictory = true; break; case WinConditionsType.TakeAndHoldValue: //Take and Hold replay.WinConditions.TakeAndHold = true; break; case WinConditionsType.SuddenDeathValue: //Sudden Death replay.WinConditions.SuddenDeath = true; break; default: break; } } //Players replay.Players = new PlayerCollection(); for (index = 0; index < numplayers; index++) { //skip reader.BaseStream.Position += 12; //player len int playerlen = reader.ReadInt32(); if (playerlen != 44) //this is not really needed now.... handled by the observer skip { replay.Players.Add(new Player()); //skip has DATAINFO tag reader.BaseStream.Position += 12; //skip reader.BaseStream.Position += 12; //current players name int playernamelen = reader.ReadInt32(); replay.Players[index].Name = unicode.GetString(reader.ReadBytes(playernamelen * 2)); //skip reader.BaseStream.Position += 4; //players team number replay.Players[index].Team = reader.ReadInt32() + 1; //+1 for the 0 base if (replay.NumTeams < replay.Players[index].Team) replay.NumTeams = replay.Players[index].Team; int playerracelen = reader.ReadInt32(); replay.Players[index].Race = new string(reader.ReadChars(playerracelen)); //new addition in v1.41 for skirmish check reader.BaseStream.Position += 4; if (replay.Version >= 4) reader.BaseStream.Position += reader.ReadInt32() + 4; //FOLDTCUC skip reader.BaseStream.Position += 32; int datalcinlen = reader.ReadInt32(); reader.BaseStream.Position += datalcinlen + 4; reader.BaseStream.Position += 20; int armynamelen = reader.ReadInt32(); replay.Players[index].Army = unicode.GetString(reader.ReadBytes(armynamelen * 2)); replay.Players[index].ArmyColours = new System.Drawing.Color[5]; for (int i = 0; i < 5; i++) { byte[] rawcolours = reader.ReadBytes(4); replay.Players[index].ArmyColours[i] = System.Drawing.Color.FromArgb(rawcolours[3], rawcolours[2], rawcolours[1], rawcolours[0]); } for (int i = 0; i < 2; i++) //badge and banner images { string tagname = new String(reader.ReadChars(8)); if (tagname == "FOLDTCBD" || tagname == "FOLDTCBN") { //skip reader.BaseStream.Position += 28; int imagenamelen = reader.ReadInt32(); if (tagname == "FOLDTCBD") { replay.Players[index].BadgeName = new string(reader.ReadChars(imagenamelen)); } else { replay.Players[index].BannerName = new string(reader.ReadChars(imagenamelen)); } //skip reader.BaseStream.Position += 24; //get the size of the image we're about to read int xsize = reader.ReadInt32(); int ysize = reader.ReadInt32(); //skip reader.BaseStream.Position += 24; if (tagname == "FOLDTCBD") replay.Players[index].Badge = new System.Drawing.Bitmap(xsize, ysize); else replay.Players[index].Banner = new System.Drawing.Bitmap(xsize, ysize); for (int y = 0; y < ysize; y++) { for (int x = 0; x < xsize; x++) { byte[] rawcolor = reader.ReadBytes(4); if (tagname == "FOLDTCBD") replay.Players[index].Badge.SetPixel(x, y, System.Drawing.Color.FromArgb(rawcolor[3], rawcolor[2], rawcolor[1], rawcolor[0])); else replay.Players[index].Banner.SetPixel(x, y, System.Drawing.Color.FromArgb(rawcolor[3], rawcolor[2], rawcolor[1], rawcolor[0])); } } if (tagname == "FOLDTCBD") replay.Players[index].Badge.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY); else replay.Players[index].Banner.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY); } else { reader.BaseStream.Position -= 8; } } } else { reader.BaseStream.Position += playerlen + 4; } } //convert from zero based index //replay.NumTeams++; //just skip over the observers for the time being string tag = new String(reader.ReadChars(8)); while (tag == "FOLDGPLY") { reader.BaseStream.Position += 4; int observerlen = reader.ReadInt32(); reader.BaseStream.Position += observerlen + 4; tag = new String(reader.ReadChars(8)); if (tag != "FOLDGPLY") reader.BaseStream.Position -= 8; } //process the chat replay.Chat = new ChatType(); int ticks = 0; while (reader.BaseStream.Position < reader.BaseStream.Length) { int type = reader.ReadInt32(); int len = reader.ReadInt32(); if (len == 0) //nothing left... get out break; switch (type) { case 1: int chattype = reader.ReadInt32(); if (chattype == 1) { reader.BaseStream.Position += 5; int senderlen = reader.ReadInt32(); string sender = unicode.GetString(reader.ReadBytes(senderlen*2)); reader.BaseStream.Position += 12; int msg_len = reader.ReadInt32(); //Message Length byte[] msg_bytes = reader.ReadBytes(msg_len*2); string msg = unicode.GetString(msg_bytes); reader.BaseStream.Position = reader.BaseStream.Position; replay.Chat.AddMessage(sender, msg, ticks); } break; default: //skip reader.BaseStream.Position += 2; ticks = reader.ReadInt32(); //skip - what we're already read reader.BaseStream.Position += len - 6; break; } } }
/// <summary> /// Reads the entire backup file and returns a root catalog node. /// The root node contains backup sets/volumes/directories/files /// as child nodes. /// </summary> public CCatalogNode ReadCatalog() { Logger.Info("Reading backup"); // Set to true to cancel reading mCancel = false; // Read the media header var tapeHeaderDescriptorBlock = (CTapeHeaderDescriptorBlock)mStream.ReadDBLK(); // Read soft file mark var filemarkDescriptorBlock = (CSoftFilemarkDescriptorBlock)mStream.ReadDBLK(); // Create the root catalog node var node = new CCatalogNode(tapeHeaderDescriptorBlock, tapeHeaderDescriptorBlock.MediaName, ENodeType.Root); CCatalogNode lastSetNode = null; CCatalogNode lastVolumeNode = null; CCatalogNode lastFolderNode = null; // Get next block type var blockType = mStream.PeekNextBlockType(); while ((blockType != EBlockType.MTF_EOTM) && (blockType != 0) && (mCancel == false)) { // Read next block var block = mStream.ReadDBLK(); // Add to catalog if (blockType == EBlockType.MTF_SSET) { var dataSetDescriptorBlock = (CStartOfDataSetDescriptorBlock)block; var cnode = node.AddSet(dataSetDescriptorBlock); lastSetNode = cnode; } else if (blockType == EBlockType.MTF_VOLB) { var volumeDescriptorBlock = (CVolumeDescriptorBlock)block; var cnode = lastSetNode.AddVolume(volumeDescriptorBlock); lastVolumeNode = cnode; } else if (blockType == EBlockType.MTF_DIRB) { var directoryDescriptorBlock = (CDirectoryDescriptorBlock)block; // Check if the directory name is contained in a data stream CCatalogNode cnode = null; if ((directoryDescriptorBlock.DIRBAttributes & EDIRBAttributes.DIRB_PATH_IN_STREAM_BIT) != 0) { foreach (CDataStream data in directoryDescriptorBlock.Streams) { if (data.Header.StreamID == "PNAM") { if (directoryDescriptorBlock.StringType == EStringType.ANSI) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); var folderName = encoding.GetString(data.Data); folderName = folderName.Substring(0, folderName.Length - 1); cnode = lastVolumeNode.AddFolder(directoryDescriptorBlock, folderName); } else if (directoryDescriptorBlock.StringType == EStringType.Unicode) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); var folderName = encoding.GetString(data.Data); folderName = folderName.Substring(0, folderName.Length - 1); cnode = lastVolumeNode.AddFolder(directoryDescriptorBlock, folderName); } } } } else { var folderName = directoryDescriptorBlock.DirectoryName.Substring(0, directoryDescriptorBlock.DirectoryName.Length - 1); cnode = lastVolumeNode.AddFolder(directoryDescriptorBlock, folderName); } if (cnode != null) lastFolderNode = cnode; } else if (blockType == EBlockType.MTF_FILE) { var fileDescriptorBlock = (CFileDescriptorBlock)block; // Check if the file name is contained in a data stream CCatalogNode cnode = null; if ((fileDescriptorBlock.FileAttributes & EFileAttributes.FILE_NAME_IN_STREAM_BIT) != 0) { foreach (CDataStream data in fileDescriptorBlock.Streams) { if (data.Header.StreamID == "FNAM") { if (fileDescriptorBlock.StringType == EStringType.ANSI) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); var fileName = encoding.GetString(data.Data); lastFolderNode.AddFile(fileDescriptorBlock, fileName); } else if (fileDescriptorBlock.StringType == EStringType.Unicode) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); var fileName = encoding.GetString(data.Data); lastFolderNode.AddFile(fileDescriptorBlock, fileName); } } } } else { lastFolderNode.AddFile(fileDescriptorBlock, fileDescriptorBlock.FileName); } } // Get next block type blockType = mStream.PeekNextBlockType(); // Check progress if (mStream.BaseStream.Position > mLastPos + mIncrement) { mLastPos = mStream.BaseStream.Position; OnProgressChange((int)((float)mLastPos / (float)mStream.BaseStream.Length * 100.0f)); } } return node; }
public Encrypt Encode(EncryptType type, string value) { var result = new Encrypt (); result.Value = null; result.Type = type; if (type == EncryptType.OK) { try { var key = AES; if (key != null) { result.Key = key; Cipher c = Cipher.GetInstance("AES"); c.Init(CipherMode.EncryptMode, key as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal(encoder.GetBytes(value)); return result; } } catch (Exception) { return null; } } else if (type == EncryptType.STRONG) { try { var keys = RSA; if (keys != null) { result.PublicKey = keys[1]; result.PrivateKey = keys[0]; Cipher c = Cipher.GetInstance ("RSA"); c.Init(Javax.Crypto.CipherMode.EncryptMode, result.PublicKey as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal (encoder.GetBytes(value)); return result; } } catch (Exception) { return null; } } return null; }
/// <summary> /// Gets the requested byte representation of the current Unicode character codepoint /// </summary> /// <param name="encoding">The encoding you want a byte representation in. Specify utf-8, utf-16le, or utf16-be</param> /// <param name="character">A single character sent as a string.</param> /// <returns>Returns a byte array</returns> public byte[] GetCharacterBytes(string encoding, string character) { System.Text.Encoding enc; if (encoding == "utf-16le") { enc = new System.Text.UnicodeEncoding(); } else if (encoding == "utf-16be") { enc = new System.Text.UnicodeEncoding(true, false); } else { enc = new System.Text.UTF8Encoding(); } return enc.GetBytes(character); }
/// <summary> /// Renames the replays' internal name /// </summary> /// <param name="newName">New name to use for the replay</param> public bool RenameReplay(Replay replay, string newName) { try { //load the replay data FileStream fsreader = File.OpenRead(replay.Filename); byte[] data = new byte[fsreader.Length]; fsreader.Read(data, 0, data.Length); fsreader.Close(); //create a buffer for the adjusted file int new_replaysize = replay.FileSize + ((newName.Length - replay.Name.Length) * 2); byte[] buffer = new byte[new_replaysize]; System.IO.MemoryStream writer = new MemoryStream(buffer); //calculate the new db & foldinfo len int database_len = replay.DATABASE + ((newName.Length - replay.Name.Length) * 2); int foldinfo_len = replay.FOLDINFO + ((newName.Length - replay.Name.Length) * 2); //write everything into the new buffer up to the foldinfo len writer.Write(data, 0, replay.FOLDINFOPOS); byte[] foldinfo_byte = BitConverter.GetBytes(foldinfo_len); writer.Write(foldinfo_byte, 0, foldinfo_byte.Length); writer.Write(data, replay.FOLDINFOPOS + 4, (replay.DATABASEPOS - replay.FOLDINFOPOS - 4)); byte[] database_byte = BitConverter.GetBytes(database_len); writer.Write(database_byte, 0, database_byte.Length); writer.Write(data, replay.DATABASEPOS + 4, (replay.REPLAYLENPOS - replay.DATABASEPOS - 4)); byte[] replay_byte = BitConverter.GetBytes(newName.Length); writer.Write(replay_byte, 0, replay_byte.Length); //get the new name in bytes System.Text.UnicodeEncoding encoder = new System.Text.UnicodeEncoding(); byte[] byte_name = encoder.GetBytes(newName); writer.Write(byte_name, 0, byte_name.Length); writer.Write(data, (replay.REPLAYLENPOS + 4 + (replay.Name.Length * 2)), (replay.FileSize - ((replay.REPLAYLENPOS + 4) + replay.Name.Length * 2))); writer.Close(); BinaryWriter binwriter = new BinaryWriter(File.Create(replay.Filename)); binwriter.Write(buffer); binwriter.Close(); return true; } catch { return false; } }
/// <summary> /// This function is deprecated in favor of Plugin.GetString and Plugin.AllocateString /// </summary> public void SpanSParams(int startIndex, string s) { numSParams = startIndex; for (int i = 0; i < s.Length;) { string ss = s.Substring (i, s.Length - i < 250 ? s.Length - i : 250); System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding (); Byte[] bytes = encoding.GetBytes (ss); int idx = numSParams * 256 * 2; Array.Copy (bytes, 0, sParams, idx, bytes.Length); sParams[idx + bytes.Length] = 0; sParams[idx + bytes.Length + 1] = 0; numSParams++; i += 250; } }
/// <summary> /// Reads the entire backup file and returns a root catalog node. /// The root node contains backup sets/volumes/directories/files /// as child nodes. /// </summary> public CCatalogNode ReadCatalog() { // Set to true to cancel reading mCancel = false; // Read the media header CTapeHeaderDescriptorBlock tape = (CTapeHeaderDescriptorBlock)mStream.ReadDBLK(); // Read soft file mark CSoftFilemarkDescriptorBlock file = (CSoftFilemarkDescriptorBlock)mStream.ReadDBLK(); // Create the root catalog node CCatalogNode node = new CCatalogNode(tape.MediaName, ENodeType.Root, 0); CCatalogNode nLastSet = null; CCatalogNode nLastVolume = null; CCatalogNode nLastDir = null; // Get next block type EBlockType bt = mStream.PeekNextBlockType(); while ((bt != EBlockType.MTF_EOTM) && (bt != 0) && (mCancel == false)) { // Read next block CDescriptorBlock block = mStream.ReadDBLK(); // Add to catalog if (bt == EBlockType.MTF_SSET) { CStartOfDataSetDescriptorBlock sset = (CStartOfDataSetDescriptorBlock)block; CCatalogNode cnode = node.AddSet("Set: " + sset.DataSetNumber + " - " + sset.DataSetName, block.StartPosition); nLastSet = cnode; } else if (bt == EBlockType.MTF_VOLB) { CVolumeDescriptorBlock vol = (CVolumeDescriptorBlock)block; CCatalogNode cnode = nLastSet.AddVolume(vol.DeviceName, block.StartPosition); nLastVolume = cnode; } else if (bt == EBlockType.MTF_DIRB) { CDirectoryDescriptorBlock dir = (CDirectoryDescriptorBlock)block; // Check if the directory name is contained in a data stream CCatalogNode cnode = null; if ((dir.DIRBAttributes & EDIRBAttributes.DIRB_PATH_IN_STREAM_BIT) != 0) { foreach (CDataStream data in dir.Streams) { if (data.Header.StreamID == "PNAM") { if (dir.StringType == EStringType.ANSI) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); string str = encoding.GetString(data.Data); str = str.Substring(0, str.Length - 1); cnode = nLastVolume.AddFolder(str, block.StartPosition); } else if (dir.StringType == EStringType.Unicode) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); string str = encoding.GetString(data.Data); str = str.Substring(0, str.Length - 1); cnode = nLastVolume.AddFolder(str, block.StartPosition); } } } } else cnode = nLastVolume.AddFolder(dir.DirectoryName.Substring(0, dir.DirectoryName.Length - 1), block.StartPosition); if (cnode != null) nLastDir = cnode; } else if (bt == EBlockType.MTF_FILE) { CFileDescriptorBlock fil = (CFileDescriptorBlock)block; // Check if the file name is contained in a data stream CCatalogNode cnode = null; if ((fil.FileAttributes & EFileAttributes.FILE_NAME_IN_STREAM_BIT) != 0) { foreach (CDataStream data in fil.Streams) { if (data.Header.StreamID == "FNAM") { if (fil.StringType == EStringType.ANSI) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); string str = encoding.GetString(data.Data); cnode = nLastDir.AddFile(str, block.StartPosition); } else if (fil.StringType == EStringType.Unicode) { System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); string str = encoding.GetString(data.Data); cnode = nLastDir.AddFile(str, block.StartPosition); } } } } else cnode = nLastDir.AddFile(fil.FileName, block.StartPosition); } // Get next block type bt = mStream.PeekNextBlockType(); // Check progress if (mStream.BaseStream.Position > mLastPos + mIncrement) { mLastPos = mStream.BaseStream.Position; OnProgressChange((int)((float)mLastPos / (float)mStream.BaseStream.Length * 100.0f)); } } return node; }
/// <summary> /// Retrieve the commands string parameter at the specified index /// </summary> public string GetSParam(int index) { int startIndex = index * 256 * 2; int length = 0; while ((sParams[startIndex + length] != 0 || sParams[startIndex + length + 1] != 0) && length < 256) length += 2; if (length == 256) throw new Exception ("sParam is unterminated"); System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding (); return encoding.GetString (sParams, startIndex, length); }
private UInt32 Update( string FullPathToFile ) { unchecked { // Creates an encoder that will map each Unicode character to 2 bytes System.Text.UnicodeEncoding myEncoder = new System.Text.UnicodeEncoding(); // Include file name only, strip off path information // This is done so we get the same CRC no matter if the CD is in drive G // on one machine and drive F on another, kappish? int index = FullPathToFile.LastIndexOf( '\\' ); string strFileName = FullPathToFile.Substring( index + 1 ); // Convert file name to byte array int count = myEncoder.GetByteCount( strFileName ); byte[] buffer = new byte[count]; buffer = myEncoder.GetBytes(strFileName); UInt32 crc = HighBitMask; //ProcessBuffer( ref buffer, ref crc ); for (int i = 0; i < count; i++) crc = ((crc) >> 8) ^ CRCTable[(buffer[i]) ^ ((crc) & 0x000000FF)]; crc = ~crc; LifetimeCRC ^= crc; return crc; } }
/// <summary> /// Runs an instance of this job /// </summary> public void Execute(IJobExecutionContext context) { log.Debug(MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name + "()"); // Pull up the job context JobKey key = context.JobDetail.Key; JobDataMap dataMap = context.JobDetail.JobDataMap; string XMLTaskJSON = dataMap.GetString("XMLTask"); //log.Debug("Running with raw parameters: " + XMLTaskJSON); XMLTask _XMLTask = JsonConvert.DeserializeObject<XMLTask>(XMLTaskJSON); //log.Debug("Running with parsed parameters: \n" + _XMLTask.DebugDump()); // Make sure the directory exists if (!Directory.Exists(_XMLTask.DestinationPath)) { log.Error("Could not access " + _XMLTask.DestinationPath + "! (Does the folder exist?)"); return; } // Make sure the queue exists MessageQueue messageQueue = null; if (MessageQueue.Exists(_XMLTask.SourcePath)) { messageQueue = new MessageQueue(_XMLTask.SourcePath); messageQueue.Formatter = new ActiveXMessageFormatter(); // This allows the direct export of XML from files } else { // DO NOT Create the Queue - Complain! //MessageQueue.Create(@".\Private$\SomeTestName"); log.Error("Could not access " + _XMLTask.SourcePath + "! (Does the queue exist? Do you have permissions to it?)"); return; } // While there are any entries in the queue, pull them off and shove them onto the filesystem try { int iMessageCount = 0; string sMessageFilename = ""; string sMessagePath = ""; int iMessageLength = 0; byte[] bytes = new byte[MaxMessageSize]; DateTime dt = DateTime.Now; messageQueue = new MessageQueue(_XMLTask.SourcePath); Message[] messages = messageQueue.GetAllMessages(); Message toss = null; // Used to delete individual messages if (messages.Length == 0) { log.DebugFormat("Found no messages in {0}", _XMLTask.SourcePath); return; } foreach (Message message in messages) { log.DebugFormat("Attempting to post and then delete message #{0}...", message.Id); // Try to post the message to an XML file //sMessageCount = iMessageCount.ToString().PadLeft(4, '0'); //sMessageFilename = "msg-" + dt.ToString("yyyyMMdd-HHmmss-fff-") + sMessageCount + ".xml"; _XMLTask.PopulateName(dt, iMessageCount, message.Label); sMessageFilename = _XMLTask.DestinationName; sMessagePath = _XMLTask.DestinationPath + "\\" + sMessageFilename; // Get the content // sMessageContent = message.Label; iMessageLength = Int32.Parse(message.BodyStream.Length.ToString()); if (iMessageLength > MaxMessageSize) { log.WarnFormat("Ignored (and did not post) too-long message {0}.", message.Id, sMessagePath); } else { //log.InfoFormat("Message.Id={0}", message.Id); // e.g., 11b4ce53-f956-4397-8dc6-18bd9db255ed\2082 //log.InfoFormat("Message.Label={0}", message.Label); // e.g., 6af137c4-a1fa-47d4-a675-98201ea3eaf0 or whatever the Folder2MSMQ process set as the label // TODO: Figure out ASCII/Unicode thing message.BodyStream.Read(bytes, 0, iMessageLength); switch (_XMLTask.SourceEncoding) { case "ASCII": System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding(); File.WriteAllText(sMessagePath, ascii.GetString(bytes, 0, iMessageLength)); log.InfoFormat("Posted message {0} to {1} (with ASCII) OK.", _XMLTask.SourcePath + "::" + message.Id, sMessagePath); break; case "Unicode": System.Text.UnicodeEncoding unicode = new System.Text.UnicodeEncoding(); File.WriteAllText(sMessagePath, unicode.GetString(bytes, 0, iMessageLength)); log.InfoFormat("Posted message {0} to {1} (with Unicode) OK.", _XMLTask.SourcePath + "::" + message.Id, sMessagePath); break; } } toss = messageQueue.ReceiveById(message.Id); log.DebugFormat("Removed message \"{0}\" (ID:{1}) OK.", message.Label, message.Id); iMessageCount++; } // after all processing, delete all the messages //messageQueue.Purge(); //log.DebugFormat("Purged {0} OK.", _XMLTask.SourcePath); } catch (Exception e) { log.Error("Could not work with folder or queue."); log.Debug("Exception details: " + e.ToString()); } }