//Metoda szyfrujaca ciag znaków na podstawie klucz publicznego public String encryption(byte[] plainTextBytes) { try { encryptedTextBytes = rsaCSP.Encrypt(plainTextBytes, false); String encryptedString = byteConverter.GetString(encryptedTextBytes); return(encryptedString); } catch (CryptographicException e) { Console.WriteLine(e.Message); return(null); } }
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); } } } }
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))); } }
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; } }
/// <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))); }
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 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 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"); }
private string convertASCIIToUnicode(string value) { System.Text.ASCIIEncoding encodingASCII = new System.Text.ASCIIEncoding(); System.Text.UnicodeEncoding encodingUNICODE = new System.Text.UnicodeEncoding(); byte[] sampleTextEncoded = encodingASCII.GetBytes(HttpUtility.UrlDecode(value)); return(encodingUNICODE.GetString(sampleTextEncoded)); }
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の文字数分までしか読み取る事が出来ない。 }
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 }
/// <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)); }
/// <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)); }
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())); } }
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); }
/// <summary> /// Decrypt /// </summary> public static string DecryptString(string cipherTextB64, string passPhrase = null) { byte[] input = StringUtil.DecodeFrom64ToByteArray(cipherTextB64); byte[] output = new byte[input.Length]; for (int i = 0; i < input.Length; i++) { output[i] = (byte)(input[i] ^ key); } System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding(); return(encoding.GetString(output)); }
public mbString(byte[] data) { System.Text.UnicodeEncoding uni = new System.Text.UnicodeEncoding(); uint x = (uint)(new mwg.File.mbUInt32(data)); if (x > System.Int32.MaxValue) { throw new System.Exception("文字列の大きさが、既定の限界を超えています。"); } if (x == 0) { this.dat = ""; return; } this.dat = uni.GetString(data, 4, (int)x); }
/// <summary> /// Decode encrypted data provided as Base64 string /// </summary> /// <param name="cypherText">The encoded data</param> /// <returns>The original string</returns> public string DecryptBase64AsString(string cypherText) { byte [] theBytes = System.Convert.FromBase64String(cypherText); string decryptedString = null; try { decryptedString = unienc.GetString(Decrypt(theBytes, null)); } catch (System.Exception caught) { Log.Write(caught); } return(decryptedString); }
public static ElementHeader Parse(byte[] buf) { var serializedCreationDate = BitConverter.ToUInt64(buf, 0); var serializedModificationDate = BitConverter.ToUInt64(buf, 8); // 4 байта на Reserved var enc = new System.Text.UnicodeEncoding(bigEndian: false, byteOrderMark: false); var NameOffset = 8 + 8 + 4; var name = enc.GetString(buf, NameOffset, buf.Length - NameOffset).TrimEnd('\0'); // TODO: Разобраться, как правильно сериализовать дату var creationDate = DateTime.FromBinary((long)serializedCreationDate); var modificationDate = DateTime.FromBinary((long)serializedModificationDate); return(new ElementHeader(name, creationDate, modificationDate)); }
private string ExtractPropertyValueByte(ref ExtractedValueType formattedValueType) { formattedValueType = ExtractedValueType.String; if (this._propItem.Value == null) { return(String.Empty); } if (this._propItem.Value.Length == 1) { return(this._propItem.Value[0].ToString(CultureInfo.InvariantCulture)); } else { return(_unicodeEncoding.GetString(this._propItem.Value)); } }
/// <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)); }
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(Content(ex.Message)); } }
internal void PrepareHttpPost() { var request = HttpContextFactory.Current.Request; var files = request.Files; var a = files.AllKeys; for (var i = 0; i < a.Length; i++) { var file = files[i]; if (file == null) { continue; } 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); } pythonModel.DictionaryAdd(a[i], s); } foreach (var key in request.Form.AllKeys) { pythonModel.DictionaryAdd(key, request.Form[key]); } pythonModel.HttpMethod = "post"; }
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()); } }
public static string strDecifraString(string strTextoASerDecifrado) { string strRetorno = ""; try { byte[] byTextoASerDeCifrado, byTextoDeCifrado; byte[] byKey = new byte[] { 255, 241, 3, 17, 206, 69, 56, 167, 94, 220, 219, 76, 112, 179, 12, 97, 178, 233, 14, 172, 238, 20, 54, 232, 212, 54, 50, 151, 138, 32, 26, 122 }; byte[] byIV = new byte[] { 207, 100, 146, 104, 139, 60, 94, 109, 109, 195, 236, 213, 235, 234, 233, 114 }; System.Text.UnicodeEncoding conversorTexto = new System.Text.UnicodeEncoding(); System.Security.Cryptography.RijndaelManaged clsSecCrypRijndael = new System.Security.Cryptography.RijndaelManaged(); clsSecCrypRijndael.Padding = System.Security.Cryptography.PaddingMode.Zeros; //Get an encryptor. System.Security.Cryptography.ICryptoTransform decifrador = clsSecCrypRijndael.CreateDecryptor(byKey, byIV); byTextoASerDeCifrado = System.Convert.FromBase64String(strTextoASerDecifrado); // Cria os Streams System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(byTextoASerDeCifrado); System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decifrador, System.Security.Cryptography.CryptoStreamMode.Read); byTextoDeCifrado = new byte[byTextoASerDeCifrado.Length]; // Read all data to the crypto stream and flush it. cryptoStream.Read(byTextoDeCifrado, 0, byTextoDeCifrado.Length); strRetorno = conversorTexto.GetString(byTextoDeCifrado).Replace("\0", ""); } catch (Exception err) { m_errException = err; return(strRetorno); } return(strRetorno); }
/// <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); }
//constructor public mbString(mwg.File.mwgBinary mbin) { System.Text.UnicodeEncoding uni = new System.Text.UnicodeEncoding(); this.dat = uni.GetString(mbin.readBytes((uint)(new mwg.File.mbUInt32(mbin)))); }
/// <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() { // 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 (var 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); } } else if (blockType == EBlockType.MTF_DBDB) { var databaseDescriptorBlock = (CDatabaseDescriptorBlock)block; var cnode = lastVolumeNode.AddDatabase(databaseDescriptorBlock); //lastVolumeNode = cnode; } // Get next block type blockType = mStream.PeekNextBlockType(); // Check progress if (mStream.BaseStream.Position > mLastPos + mIncrement) { mLastPos = mStream.BaseStream.Position; OnProgressChange((int)(mLastPos / (float)mStream.BaseStream.Length * 100.0f)); } } return(node); }
/// <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); }
/// <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()); } }
//constructor public mfString(ref mwg.File.mwgBinary mbin) { this.uni = new System.Text.UnicodeEncoding(); this.dat = uni.GetString(mbin.readBytes((uint)(new mwg.File.mwgDword(ref mbin)))); }
/// <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; }
/// <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> /// 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); }
/// <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> /// byte数组转换为string /// </summary> /// <param name="bytes">byte数组</param> /// <returns></returns> public static string ConvertToString(this byte[] bytes) { System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding(); return(converter.GetString(bytes)); }