public void StringToCharArrayRange() { // 00000000000111111111222222 // 01234567890123456789012345 const string text = "Lorem ipsum dolor sit amet"; char[] expected = "ipsum dolor".ToCharArray(); char[] result = String2.ToCharArray(text, 6, 11); Assert.AreEqual(expected.Length, result.Length); if (!result.SequenceEqual(expected)) { Assert.Fail("String range char array test #1"); } expected = "Lorem ipsum".ToCharArray(); result = String2.ToCharArray(text, 0, 11); Assert.AreEqual(expected.Length, result.Length); if (!result.SequenceEqual(expected)) { Assert.Fail("String range char array test #2"); } expected = "sit amet".ToCharArray(); result = String2.ToCharArray(text, 18, 8); Assert.AreEqual(expected.Length, result.Length); if (!result.SequenceEqual(expected)) { Assert.Fail("String range char array test #3"); } }
public void StringSplitByStringsCount() { const string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Cras convallis, nulla eget faucibus sagittis, dolor."; string[] expected1 = { "Lorem ipsum dolor sit amet", "consectetur adipiscing elit", "Cras convallis, nulla eget faucibus sagittis, dolor.", }; string[] result = String2.Split(text, new string[] { ", ", ". ", ",", "." }, 3, StringSplitOptions2.None); Assert.AreEqual(expected1.Length, result.Length); if (!result.SequenceEqual(expected1)) { Assert.Fail("String split count by string test #1"); } result = String2.Split(text, new string[] { ", ", ". ", ",", "." }, 3, StringSplitOptions2.RemoveEmptyEntries); Assert.AreEqual(expected1.Length, result.Length); if (!result.SequenceEqual(expected1)) { Assert.Fail("String split count by string test #2"); } result = String2.Split(text, new string[] { ", ", ". ", ",", "." }, 1, StringSplitOptions2.None); Assert.AreEqual(1, result.Length); Assert.AreEqual(text, result[0], "String split count by string test #3"); result = String2.Split(text, new string[] { ", ", ". ", ",", "." }, 1, StringSplitOptions2.RemoveEmptyEntries); Assert.AreEqual(1, result.Length); Assert.AreEqual(text, result[0], "String split count by string test #4"); }
public void StringSplitByStrings() { const string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Cras convallis, nulla eget faucibus sagittis, dolor."; string[] expected1 = { "Lorem ipsum dolor sit amet", "consectetur adipiscing elit", "Cras convallis", "nulla eget faucibus sagittis", "dolor", "" }; string[] result = String2.Split(text, new string[] { ", ", ". ", ",", "." }, StringSplitOptions2.None); Assert.AreEqual(expected1.Length, result.Length); if (!result.SequenceEqual(expected1)) { Assert.Fail("String split by string test #1"); } string[] expected2 = new string[expected1.Length - 1]; Array.Copy(expected1, expected2, expected2.Length); result = String2.Split(text, new string[] { ", ", ". ", ",", "." }, StringSplitOptions2.RemoveEmptyEntries); Assert.AreEqual(expected2.Length, result.Length); if (!result.SequenceEqual(expected2)) { Assert.Fail("String split by string test #2"); } }
//TODO: This source should be modified what "try ~ catch" syntax . public MessageNode GetNodeFromJson(String2 json) { try { IDictionary <String, String> buffer = JsonConvert.DeserializeObject <Dictionary <String, String> >(json.ToString()); MessageNode node = new MessageNode(); if (buffer.ContainsKey("TYPE")) { node.MessageType = (MessageType)Int32.Parse(buffer["TYPE"]); } if (buffer.ContainsKey("MESSAGE")) { node.Message = buffer["MESSAGE"]; } if (buffer.ContainsKey("WORKTITLE")) { node.WorkTitle = buffer["WORKTITLE"]; } return(node); } catch (Exception) { return(null); } }
public String2 ReadFile(String filepath) { FileInfo info = new FileInfo(filepath); if (!info.Exists) { State = "403"; StateComment = "Not Found"; return(_body); } if (".JS".Equals(info.Extension.ToUpper())) { ContextType = "text/javascript; charset=UTF-8"; } if (".CSS".Equals(info.Extension.ToUpper())) { ContextType = "text/css; charset=UTF-8"; } using (FileStream stream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read)) { _body = new String2((int)info.Length); stream.Read(_body.ToBytes(), 0, (int)info.Length); } StateOK(); return(_body); }
/// <summary> /// Gets NAT public IP address. /// </summary> /// <returns>Returns NAT public IP address.</returns> public IPAddress GetExternalIPAddress() { /* http://upnp.org GetExternalIPAddress * This action retrieves the value of the external IP address on this connection instance. * * Returns: * NewExternalIPAddress */ string soapBody = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n" + "<s:Body>\r\n" + "<u:GetExternalIPAddress xmlns:u=\"" + m_ServiceType + "\"></u:GetExternalIPAddress>\r\n" + "</s:Body>\r\n" + "</s:Envelope>\r\n"; string soapResponse = SendCommand("GetExternalIPAddress", soapBody); XmlReader reader = XmlReader.Create(new System.IO.StringReader(soapResponse)); while (reader.Read()) { if (String2.Equals("NewExternalIPAddress", reader.Name, StringComparison2.InvariantCultureIgnoreCase)) { return(IPAddress.Parse(reader.ReadString())); } } return(null); }
/// <summary> /// Returns parsed IMAP SEARCH <b>UID (sequence set)</b> key. /// </summary> /// <param name="r">String reader.</param> /// <returns>Returns parsed IMAP SEARCH <b>UID (sequence set)</b> key.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when parsing fails.</exception> internal static IMAP_Search_Key_Uid Parse(StringReader r) { if (r == null) { throw new ArgumentNullException("r"); } string word = r.ReadWord(); if (!String2.Equals(word, "UID", StringComparison2.InvariantCultureIgnoreCase)) { throw new ParseException("Parse error: Not a SEARCH 'UID' key."); } r.ReadToFirstChar(); string value = r.QuotedReadToDelimiter(' '); if (value == null) { throw new ParseException("Parse error: Invalid 'UID' value."); } try { return(new IMAP_Search_Key_Uid(IMAP_t_SeqSet.Parse(value))); } catch { throw new ParseException("Parse error: Invalid 'UID' value."); } }
/// <summary> /// Returns parsed IMAP SEARCH <b>SENTON (string)</b> key. /// </summary> /// <param name="r">String reader.</param> /// <returns>Returns parsed IMAP SEARCH <b>SENTON (string)</b> key.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when parsing fails.</exception> internal static IMAP_Search_Key_SentOn Parse(StringReader r) { if (r == null) { throw new ArgumentNullException("r"); } string word = r.ReadWord(); if (!String2.Equals(word, "SENTON", StringComparison2.InvariantCultureIgnoreCase)) { throw new ParseException("Parse error: Not a SEARCH 'SENTON' key."); } string value = r.ReadWord(); if (value == null) { throw new ParseException("Parse error: Invalid 'SENTON' value."); } DateTime date; try { date = IMAP_Utils.ParseDate(value); } catch { throw new ParseException("Parse error: Invalid 'SENTON' value."); } return(new IMAP_Search_Key_SentOn(date)); }
/// <summary> /// Transforme un nom d'objet ou de fichier de façon à ce qu'il respecte une longueur de 8 caractères maxi et son unicité. /// This transformation is used with 3D meshes, materials, texture names. /// </summary> /// <param name="objectName">nom à convertir, sans chemin s'il s'agit d'un fichier</param> /// <returns>Un nom unique, ou null s'il s'agit d'une chaîne vide ou nulle</returns> public static string NormalizeName(string objectName) { if (string.IsNullOrEmpty(objectName)) { return(null); } // Récupération du nom sans extension string name = File2.GetNameFromFilename(objectName); if (name.Length <= 8) { // Length <= 8: string is filled with 0s for (int i = name.Length; i < 8; i++) { name += "\0"; } // BUG_: name is returned return(name); } // Récupération des caractères dépassant le 8e char[] nameChars = name.Substring(0, 8).ToCharArray(); char[] overFlow = name.Substring(8).ToCharArray(); // Pour chaque caractère dépassant, on va ajouter sa valeur ASCII aux caractères de début de chaîne // EVO_84: found how to manage >16 characters : modulo 8 for (int pos = 0; pos < overFlow.Length; pos++) { nameChars[pos % 8] = (char)(nameChars[pos % 8] + overFlow[pos]); } return(String2.CharArrayToString(nameChars)); }
public void SendBroadcast(MessageType messageType, String2 data) { foreach (IWorkSocketClient client in WorkSocketFactory.GetWorkSocketServer().GetSocketList()) { client.Send((int)messageType, data); } }
public void Send(int opcode, String2 data) { socketlist.AsParallel().ForAll(_client => { _client.Send(opcode, data); }); }
/// <summary> /// Removes specified flags from message flags list. /// </summary> /// <param name="flags">Message flags.</param> /// <param name="flagsToRemove">Message flags to remove.</param> /// <returns>Returns new message flags.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>flags</b> or <b>flagsToRemove</b> is null reference.</exception> public static string[] MessageFlagsRemove(string[] flags, string[] flagsToRemove) { if (flags == null) { throw new ArgumentNullException("flags"); } if (flagsToRemove == null) { throw new ArgumentNullException("flagsToRemove"); } List <string> retVal = new List <string>(); foreach (string flag in flags) { bool remove = false; foreach (string flagToRemove in flagsToRemove) { if (String2.Equals(flag, flagToRemove, StringComparison2.InvariantCultureIgnoreCase)) { remove = true; break; } } if (!remove) { retVal.Add(flag); } } return(retVal.ToArray()); }
/// <summary> /// Parses STATUS response from status-response string. /// </summary> /// <param name="response">Satatus response string.</param> /// <returns>Returns parsed STATUS response.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception> public static IMAP_r_u_Status Parse(string response) { if (response == null) { throw new ArgumentNullException("response"); } /* RFC 3501 7.2.4 STATUS Response. * Contents: name * status parenthesized list * * The STATUS response occurs as a result of an STATUS command. It * returns the mailbox name that matches the STATUS specification and * the requested mailbox status information. * * Example: S: * STATUS blurdybloop (MESSAGES 231 UIDNEXT 44292) */ StringReader r = new StringReader(response); // Eat "*" r.ReadWord(); // Eat "STATUS" r.ReadWord(); int messages = 0; int recent = 0; long uidNext = 0; long folderUid = 0; int unseen = 0; string folder = TextUtils.UnQuoteString(IMAP_Utils.Decode_IMAP_UTF7_String(r.ReadWord())); string[] items = r.ReadParenthesized().Split(' '); for (int i = 0; i < items.Length; i += 2) { if (String2.Equals(items[i], "MESSAGES", StringComparison2.InvariantCultureIgnoreCase)) { messages = Convert.ToInt32(items[i + 1]); } else if (String2.Equals(items[i], "RECENT", StringComparison2.InvariantCultureIgnoreCase)) { recent = Convert.ToInt32(items[i + 1]); } else if (String2.Equals(items[i], "UIDNEXT", StringComparison2.InvariantCultureIgnoreCase)) { uidNext = Convert.ToInt64(items[i + 1]); } else if (String2.Equals(items[i], "UIDVALIDITY", StringComparison2.InvariantCultureIgnoreCase)) { folderUid = Convert.ToInt64(items[i + 1]); } else if (String2.Equals(items[i], "UNSEEN", StringComparison2.InvariantCultureIgnoreCase)) { unseen = Convert.ToInt32(items[i + 1]); } } return(new IMAP_r_u_Status(folder, messages, recent, uidNext, folderUid, unseen)); }
/// <summary> /// Returns parsed IMAP SEARCH <b>SMALLER (string)</b> key. /// </summary> /// <param name="r">String reader.</param> /// <returns>Returns parsed IMAP SEARCH <b>SMALLER (string)</b> key.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when parsing fails.</exception> internal static IMAP_Search_Key_Smaller Parse(StringReader r) { if (r == null) { throw new ArgumentNullException("r"); } string word = r.ReadWord(); if (!String2.Equals(word, "SMALLER", StringComparison2.InvariantCultureIgnoreCase)) { throw new ParseException("Parse error: Not a SEARCH 'SMALLER' key."); } string value = r.ReadWord(); if (value == null) { throw new ParseException("Parse error: Invalid 'SMALLER' value."); } int size = 0; if (!int.TryParse(value, out size)) { throw new ParseException("Parse error: Invalid 'SMALLER' value."); } return(new IMAP_Search_Key_Smaller(size)); }
/// <summary> /// Returns an instruction according to specified type name /// </summary> /// <param name="instructionType">Type of instruction to generate</param> /// <returns>Corresponding instruction</returns> public static PatchInstruction MakeInstruction(string instructionType) { PatchInstruction resultPI = null; if (!string.IsNullOrEmpty(instructionType)) { instructionType = String2.ToPascalCase(instructionType); string fullClassName = string.Format(_FORMAT_INSTRUCTION_CLASS, instructionType); // To solve culture issues ?? ObjectHandle dynamicObject = Activator.CreateInstance(null, fullClassName, false, BindingFlags.CreateInstance, null, null, CultureInfo.InvariantCulture, null, null); if (dynamicObject != null) { resultPI = dynamicObject.Unwrap() as PatchInstruction; if (resultPI != null) { resultPI._Type = (InstructionName)Enum.Parse(typeof(InstructionName), instructionType, true); } } } return(resultPI); }
/// <summary> /// Parses COPYUID optional response from reader. /// </summary> /// <param name="r">COPYUID optional response reader.</param> /// <returns>Returns COPYUID optional response.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception> public new static IMAP_t_orc_CopyUid Parse(StringReader r) { if (r == null) { throw new ArgumentNullException("r"); } /* RFC 4315 3. * COPYUID * Followed by the UIDVALIDITY of the destination mailbox, a UID set * containing the UIDs of the message(s) in the source mailbox that * were copied to the destination mailbox and containing the UIDs * assigned to the copied message(s) in the destination mailbox, * indicates that the message(s) have been copied to the destination * mailbox with the stated UID(s). */ string[] code_mailboxUid_sourceSeqSet_targetSeqSet = r.ReadParenthesized().Split(new char[] { ' ' }, 4); if (!String2.Equals("COPYUID", code_mailboxUid_sourceSeqSet_targetSeqSet[0], StringComparison2.InvariantCultureIgnoreCase)) { throw new ArgumentException("Invalid COPYUID response value.", "r"); } if (code_mailboxUid_sourceSeqSet_targetSeqSet.Length != 4) { throw new ArgumentException("Invalid COPYUID response value.", "r"); } return(new IMAP_t_orc_CopyUid( Convert.ToInt64(code_mailboxUid_sourceSeqSet_targetSeqSet[1]), IMAP_t_SeqSet.Parse(code_mailboxUid_sourceSeqSet_targetSeqSet[2]), IMAP_t_SeqSet.Parse(code_mailboxUid_sourceSeqSet_targetSeqSet[3]) )); }
/// <summary> /// Returns array of bytes for file data section /// </summary> /// <param name="files"></param> /// <returns></returns> private byte[] _MakeFileData(IEnumerable <byte[]> files) { byte[] returnedData = new byte[0]; if (files != null) { // Computing theorical size: current size of each file + up to 16 padding bytes per file int maxSize = 0; foreach (byte[] anotherFileData in files) { maxSize += (anotherFileData.Length + 16); } byte[] tempData = new byte[maxSize]; long realDataSize; // Writing all files Section fileDataSection = _GetSection(SectionType.FileData); using (BinaryWriter writer = new BinaryWriter(new MemoryStream(tempData))) { int index = 0; foreach (byte[] anotherFileData in files) { // Updating packed file information PackedFile correspondingFile = _FileList[index++]; correspondingFile.fileSize = (uint)anotherFileData.Length; correspondingFile.startAddress = (uint)writer.BaseStream.Position + fileDataSection.address; // Data writer.Write(anotherFileData); // Padding... if (index < _FileList.Count) { uint paddingLength = _GetPaddingLength((uint)anotherFileData.Length, _SecondaryBlockSize); byte[] padding = new byte[paddingLength]; byte[] paddingString = String2.ToByteArray(_PADDING_SEQUENCE); Array.Copy(paddingString, padding, paddingLength); writer.Write(padding); } } realDataSize = writer.BaseStream.Position; } // Putting real data into result returnedData = new byte[realDataSize]; Array.Copy(tempData, 0, returnedData, 0, realDataSize); // Updating usableSize fileDataSection.usableSize = (uint)realDataSize; } return(returnedData); }
/// <summary> /// Returns parsed IMAP SEARCH <b>HEADER (field-name) (string)</b> key. /// </summary> /// <param name="r">String reader.</param> /// <returns>Returns parsed IMAP SEARCH <b>HEADER (field-name) (string)</b> key.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when parsing fails.</exception> internal static IMAP_Search_Key_Header Parse(StringReader r) { if (r == null) { throw new ArgumentNullException("r"); } string word = r.ReadWord(); if (!String2.Equals(word, "HEADER", StringComparison2.InvariantCultureIgnoreCase)) { throw new ParseException("Parse error: Not a SEARCH 'HEADER' key."); } string fieldName = IMAP_Utils.ReadString(r); if (fieldName == null) { throw new ParseException("Parse error: Invalid 'HEADER' field-name value."); } string value = IMAP_Utils.ReadString(r); if (value == null) { throw new ParseException("Parse error: Invalid 'HEADER' string value."); } return(new IMAP_Search_Key_Header(fieldName, value)); }
/// <summary> /// Reads and decodes word from reader. /// </summary> /// <param name="r">String reader.</param> /// <returns>Returns decoded word.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception> private static string ReadAndDecodeWord(StringReader r) { if (r == null) { throw new ArgumentNullException("r"); } r.ReadToFirstChar(); // We have string-literal. if (r.SourceString.StartsWith("{")) { int literalSize = Convert.ToInt32(r.ReadParenthesized()); // Literal has CRLF ending, skip it. r.ReadSpecifiedLength(2); return(MIME_Encoding_EncodedWord.DecodeTextS(r.ReadSpecifiedLength(literalSize))); } else { string word = r.ReadWord(); if (word == null) { throw new ParseException("Excpetcted quoted-string or string-literal, but non available."); } else if (String2.Equals(word, "NIL", StringComparison2.InvariantCultureIgnoreCase)) { return(""); } else { return(MIME_Encoding_EncodedWord.DecodeTextS(word)); } } }
private void SendFileList(IWorkSocketClient client, FileMessageType type) { WebSocketMessageBuilder builder = WebSocketMessageBuilder.GetMessage(MessageType.FILELIST); DirectoryInfo info = new DirectoryInfo(Program.FILE_STORE_PATH); FileInfo[] files = info.GetFiles(); builder.SetFileList(from f in info.GetFiles() select f.Name); String2 message = builder.Build(); if (type == FileMessageType.FileSearch) { client.Send((int)Opcode.BINARY, message); /*if (!clientlist.Contains(this)) * { * clientlist.Add(this); * }*/ } else if (type == FileMessageType.FileListNotice) { /*foreach (WebSocketServer client in clientlist) * { * client.Send((int)OPCODE.BINARY, message); * }*/ } }
/// <summary> /// Met à jour l'entrée correspondante /// </summary> /// <param name="editedEntry">Entrée modifiée</param> /// <returns>entry after update. Contents may be modified for compatibility reasons</returns> public Entry UpdateEntry(Entry editedEntry) { Entry newEntry = new Entry(); // Parcours des entrées for (int i = 0; i < _Entries.Count; i++) { newEntry = _Entries[i]; if (newEntry.index == editedEntry.index) { ResourceIdentifier oldId = newEntry.id; // Process value to replace forbidden characters Couple <char> couple1 = new Couple <char>(DB._CHAR_START_TEXT, '('); Couple <char> couple2 = new Couple <char>(DB._CHAR_END_TEXT, ')'); newEntry.id = editedEntry.id.Clone() as ResourceIdentifier; if (newEntry.id != null) { newEntry.value = String2.ReplaceChars(editedEntry.value, couple1, couple2); _Entries[i] = newEntry; // Accelerator update ! entriesById.Remove(oldId); entriesById.Add(newEntry.id, newEntry); } break; } } return(newEntry); }
/// <summary> /// Checks if signature is valid and data not altered. /// </summary> /// <returns>Returns true if signature is valid, otherwise false.</returns> /// <remarks>This method is valid only if <b>Content-Type</b> parameter <b>smime-type=signed-data</b>.</remarks> /// <exception cref="InvalidOperationException">Is raised when <b>smime-type != signed-data</b>.</exception> public bool VerifySignature() { if (!String2.Equals(this.Entity.ContentType.Parameters["smime-type"], "signed-data", StringComparison2.InvariantCultureIgnoreCase)) { throw new InvalidOperationException("The VerifySignature method is only valid if Content-Type parameter smime-type=signed-data."); } // Check this.Data exists. if (this.Data == null) { return(false); } try { SignedCms signedCms = new SignedCms(); signedCms.Decode(this.Data); signedCms.CheckSignature(true); return(true); } catch { } return(false); }
/// <summary> /// Sets body encoded data from specified stream. /// </summary> /// <param name="contentTransferEncoding">Content-Transfer-Encoding in what encoding <b>stream</b> data is.</param> /// <param name="stream">Stream data to add.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentTransferEncoding</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="InvalidOperationException">Is raised when this method is accessed and this body is not bounded to any entity.</exception> public void SetEncodedData(string contentTransferEncoding, Stream stream) { if (contentTransferEncoding == null) { throw new ArgumentNullException("contentTransferEncoding"); } if (contentTransferEncoding == string.Empty) { throw new ArgumentException("Argument 'contentTransferEncoding' value must be specified."); } if (stream == null) { throw new ArgumentNullException("stream"); } if (this.Entity == null) { throw new InvalidOperationException("Body must be bounded to some entity first."); } // Owner entity has no content-type or has different content-type, just add/overwrite it. if (this.Entity.ContentType == null || !String2.Equals(this.Entity.ContentType.TypeWithSubtype, this.MediaType, StringComparison2.InvariantCultureIgnoreCase)) { this.Entity.ContentType = new MIME_h_ContentType(this.MediaType); } this.Entity.ContentTransferEncoding = contentTransferEncoding; m_pEncodedDataStream.SetLength(0); Net_Utils.StreamCopy(stream, m_pEncodedDataStream, 84000); m_IsModified = true; }
/// <summary> /// Parses APPENDUID optional response from reader. /// </summary> /// <param name="r">APPENDUID optional response reader.</param> /// <returns>Returns APPENDUID optional response.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception> public new static IMAP_t_orc_AppendUid Parse(StringReader r) { if (r == null) { throw new ArgumentNullException("r"); } /* RFC 4315 3. * APPENDUID * Followed by the UIDVALIDITY of the destination mailbox and the UID * assigned to the appended message in the destination mailbox, * indicates that the message has been appended to the destination * mailbox with that UID. */ string[] code_mailboxUid_msgUid = r.ReadParenthesized().Split(new char[] { ' ' }, 3); if (!String2.Equals("APPENDUID", code_mailboxUid_msgUid[0], StringComparison2.InvariantCultureIgnoreCase)) { throw new ArgumentException("Invalid APPENDUID response value.", "r"); } if (code_mailboxUid_msgUid.Length != 3) { throw new ArgumentException("Invalid APPENDUID response value.", "r"); } return(new IMAP_t_orc_AppendUid(Convert.ToInt64(code_mailboxUid_msgUid[1]), Convert.ToInt32(code_mailboxUid_msgUid[2]))); }
/// <summary> /// Adds specified flags to flags list. /// </summary> /// <param name="flags">Current message flags.</param> /// <param name="flagsToAdd">Flags to add.</param> /// <returns>Returns new flags.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>flags</b> or <b>flagsToAdd</b> is null reference.</exception> public static string[] MessageFlagsAdd(string[] flags, string[] flagsToAdd) { if (flags == null) { throw new ArgumentNullException("flags"); } if (flagsToAdd == null) { throw new ArgumentNullException("flagsToAdd"); } List <string> retVal = new List <string>(); retVal.AddRange(flags); foreach (string flagToAdd in flagsToAdd) { bool contains = false; foreach (string flag in flags) { if (String2.Equals(flag, flagToAdd, StringComparison2.InvariantCultureIgnoreCase)) { contains = true; break; } } if (!contains) { retVal.Add(flagToAdd); } } return(retVal.ToArray()); }
private String ComputeHash(String2 key) { String buffer = key.Trim().ToString() + GUID; byte[] hash = SHA.ComputeHash(Encoding.ASCII.GetBytes(buffer)); return(Convert.ToBase64String(hash)); }
protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken) { // Inputs var string1 = String1.Get(context); var string2 = String2.Get(context); double in_percent = new double(); string a = string1; string b = string2; char[] turkishChars = { 'ý', 'ð', 'Ý', 'Ð', 'ç', 'Ç', 'þ', 'Þ', 'ö', 'Ö', 'ü', 'Ü' }; char[] englishChars = { 'i', 'g', 'I', 'G', 'c', 'C', 's', 'S', 'o', 'O', 'u', 'U' }; // Match char for (int i = 0; i < turkishChars.Length; i++) { a = a.Replace(turkishChars[i], englishChars[i]); b = b.Replace(turkishChars[i], englishChars[i]); } a = a.ToLower().ToUpper(); b = b.ToLower().ToUpper(); if (string.IsNullOrEmpty(a)) { in_percent = b.Length; } if (string.IsNullOrEmpty(b)) { in_percent = a.Length; } int lengthA = a.Length; int lengthB = b.Length; var distances = new int[lengthA + 1, lengthB + 1]; for (int i = 0; i <= lengthA; distances[i, 0] = i++) { ; } for (int j = 0; j <= lengthB; distances[0, j] = j++) { ; } for (int i = 1; i <= lengthA; i++) { for (int j = 1; j <= lengthB; j++) { int cost = b[j - 1] == a[i - 1] ? 0 : 1; distances[i, j] = Math.Min(Math.Min(distances[i - 1, j] + 1, distances[i, j - 1] + 1), distances[i - 1, j - 1] + cost); } in_percent = distances[lengthA, lengthB]; in_percent = (1.0 - ((double)in_percent / (double)Math.Max(a.Length, b.Length))) * 100; } // Outputs return((ctx) => { Percentage.Set(ctx, in_percent); }); }
/// <summary> /// Reads RFC 2047 (section 5) 'phrase' from source stream. /// </summary> /// <returns>Returns RFC 2047 (section 5) 'phrase' or null if end of stream reached.</returns> public string Phrase() { /* RFC 2047 5. * phrase = 1*( encoded-word / word ) * word = atom / quoted-string */ int peek = Peek(true); if (peek == -1) { return(null); } else if (peek == '"') { return("\"" + QuotedString() + "\""); } else if (peek == '=') { return(EncodedWord()); } else { string word = Atom(); if (word == null) { return(null); } // Try to encode invalid encoded-words if any mixed in text. word = encodedword_regex.Replace(word, delegate(Match m) { string encodedWord = m.Value; try { if (String2.Equals(m.Groups["encoding"].Value, "Q", StringComparison2.InvariantCultureIgnoreCase)) { return(MIME_Utils.QDecode(Encoding.GetEncoding(m.Groups["charset"].Value), m.Groups["value"].Value)); } else if (String2.Equals(m.Groups["encoding"].Value, "B", StringComparison2.InvariantCultureIgnoreCase)) { return(Encoding.GetEncoding(m.Groups["charset"].Value).GetString(Net_Utils.FromBase64(Encoding2.Default.GetBytes(m.Groups["value"].Value)))); } // Failed to parse encoded-word, leave it as is. RFC 2047 6.3. else { return(encodedWord); } } catch { // Failed to parse encoded-word, leave it as is. RFC 2047 6.3. return(encodedWord); } }); return(word); } }
public void ServerStart() { ThreadPool.QueueUserWorkItem((c) => { while (true) { Socket client = null; try { client = Accept(); ThreadPool.QueueUserWorkItem((temp_client) => { var _client = temp_client as Socket; String2 buffer = new String2(Define.BUFFER_SIZE); _client.Receive(buffer.ToBytes(), buffer.Length, SocketFlags.None); if (buffer.IsEmpty()) { logger.Debug("not Byte data.."); //TODO : Bug?? _client.Close(); return; } Request req = new Request(buffer); Console.WriteLine(req.Uri); if (req.IsWebSocket()) { socketlist.Add(new WebSocket(client, this, req, _websocket_method_list)); return; } Response res = new Response(); Console.WriteLine(req.Uri); if (_method_list.ContainsKey(req.Uri)) { _method_list[req.Uri](req, res); } else if (_rootpath != null) { string filepath = _rootpath + req.Uri.ToString(); if (File.Exists(filepath)) { res.ReadFile(filepath); } } String2 sendbuffer = TransResponse(res); client.Send(sendbuffer.ToBytes(), sendbuffer.Length, SocketFlags.None); _client.Close(); }, client); } catch (Exception e) { if (client != null) { client.Dispose(); } throw e; } } }); }
/// <summary> /// Convertit un fichier DDS en fichier 2DB. Utilise l'en-tête du fichier 2DB d'origine. /// </summary> /// <param name="original2DBFile">ancien fichier 2DB</param> /// <param name="sourceDDSFile">fichier DDS à convertir</param> /// <param name="target2DBFile">nouveau fichier 2DB à créer</param> /// <param name="newTextureName">if not null, allows to override texture name</param> /// <param name="mipmapCount">if not -1, forces mipmap count</param> public static void DDSTo2DB(string original2DBFile, string sourceDDSFile, string target2DBFile, string newTextureName, int mipmapCount) { // EVO_37 : 1. Récupérer les dimensions de la texture DDS ddsFile = (DDS)TduFile.GetFile(sourceDDSFile); DDS.TextureHeader ddsHeader = (DDS.TextureHeader)ddsFile.Header; uint ddsWidth = ddsHeader.ddsd.dwWidth; uint ddsHeight = ddsHeader.ddsd.dwHeight; uint ddsMipmapCount = ddsHeader.ddsd.dwMipMapCount; // 2. Prendre l'en-tête du fichier 2DB original _2DB old2DBFile = (_2DB)TduFile.GetFile(original2DBFile); _2DB.TextureHeader old2DBHeader = (_2DB.TextureHeader)old2DBFile.Header; // 3. Mettre à jour les dimensions et nombre de mipmap old2DBHeader.height = (short)ddsHeight; old2DBHeader.width = (short)ddsWidth; // BUG_58 : mipmap count in 2DB takes main texture into account (so always >= 1) // Mipmap count enforcement if (mipmapCount == KEEP_ORIGINAL_MIPMAP_COUNT) { old2DBHeader.bMipMapCount = old2DBHeader.bMipMapCountBis = (byte)(ddsMipmapCount + 1); } else { old2DBHeader.bMipMapCount = old2DBHeader.bMipMapCountBis = (byte)mipmapCount; } // 4. Calcul de bourrage / découpage éventuels long fileSize = _2DB.HEADER_SIZE + (ddsFile.Size - DDS.HEADER_SIZE) + _2DB.FINALIZATION_STRING.LongLength; // 5. Création du nouveau fichier et assemblage using (BinaryWriter writer = new BinaryWriter(new FileStream(target2DBFile, FileMode.Create, FileAccess.Write))) { // Mettre à jour la taille du fichier dans l'entete old2DBHeader.dwSize = (uint)fileSize; old2DBHeader.dwSize2 = old2DBHeader.dwSize2Bis = (uint)(fileSize - 32); // Override texture name ? if (newTextureName != null) { old2DBHeader.strName = String2.ToByteArray(Tools.NormalizeName(newTextureName)); } // Ecriture de l'en-tête old2DBFile.Header = old2DBHeader; writer.Write(old2DBFile.HeaderData); // Data writing byte[] imageData = ddsFile.ImageData; writer.Write(imageData); // Finalization: REAL (??) writer.Write(_2DB.FINALIZATION_STRING); } }