// Token: 0x06000EF8 RID: 3832 RVA: 0x00045384 File Offset: 0x00043584 public static string Decrypt(string encrypted) { RijndaelManaged rijndaelManaged = new RijndaelManaged(); ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(SimpleAES.key, SimpleAES.vector); UTF8Encoding uTF8Encoding = new UTF8Encoding(); return uTF8Encoding.GetString(SimpleAES.Decrypt(Convert.FromBase64String(encrypted), decryptor)); }
public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: "); try { Byte[] bytes = new Byte[] { 85, 84, 70, 56, 32, 69, 110, 99, 111, 100, 105, 110, 103, 32, 69, 120, 97, 109, 112, 108, 101}; UTF8Encoding utf8 = new UTF8Encoding(); string str = utf8.GetString(bytes, 0, bytes.Length); } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown when bytes is a null reference"); try { Byte[] bytes = null; UTF8Encoding utf8 = new UTF8Encoding(); string str = utf8.GetString(bytes, 0, 2); TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown when bytes is a null reference."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
public static string DecryptRijndael(string encryptedString) { byte[] encrypted; byte[] fromEncrypted; UTF8Encoding utf8Converter = new UTF8Encoding(); encrypted = Convert.FromBase64String(encryptedString); RijndaelManaged myRijndael = new RijndaelManaged(); ICryptoTransform decryptor = myRijndael.CreateDecryptor(Key, IV); MemoryStream ms = new MemoryStream(encrypted); CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); fromEncrypted = new byte[encrypted.Length]; cs.Read(fromEncrypted, 0, fromEncrypted.Length); string decryptedString = utf8Converter.GetString(fromEncrypted); int indexNull = decryptedString.IndexOf("\0"); if (indexNull > 0) { decryptedString = decryptedString.Substring(0, indexNull); } return decryptedString; }
public static string get_uft8(string unicodeString) { UTF8Encoding utf8 = new UTF8Encoding(); byte[] encodedBytes = utf8.GetBytes(unicodeString); string decodedString = utf8.GetString(encodedBytes); return decodedString; }
static bool RunTest (ThreadStart tstart, bool delete) { locker = 0; Thread t = new Thread (tstart); t.Start (); using (FileStream fs = File.Open (path, FileMode.Create, FileAccess.Write, FileShare.Delete)) { Byte [] info = new UTF8Encoding (true).GetBytes ("This is some text in the file.\r\n"); fs.Write (info, 0, info.Length); fs.Write (info, 0, info.Length); fs.Write (info, 0, info.Length); fs.Write (info, 0, info.Length); fs.Write (info, 0, info.Length); } using (FileStream fs = File.Open (path, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete)) { locker = 1; byte [] b = new byte [10]; UTF8Encoding temp = new UTF8Encoding (true); while (fs.Read (b, 0, b.Length) > 0) { temp.GetString (b); Thread.Sleep (1000); } if (delete && !File.Exists (path)) throw new Exception ("File should continue to exist until FileStream is closed."); } t.Join (); return (!File.Exists (path)); }
public void NegTest1() { Byte[] bytes = null; UTF8Encoding utf8 = new UTF8Encoding(); Assert.Throws<ArgumentNullException>(() => { string str = utf8.GetString(bytes, 0, 2); }); }
public static string DecryptRSA(string privateKeyAsPem, byte[] payload, string passphrase = null) { var encoder = new UTF8Encoding(); byte[] byte_payload = payload; CryptoKey d = CryptoKey.FromPrivateKey(privateKeyAsPem, passphrase); OpenSSL.Crypto.RSA rsa = d.GetRSA(); byte[] result = rsa.PrivateDecrypt(byte_payload, OpenSSL.Crypto.RSA.Padding.PKCS1); rsa.Dispose(); return encoder.GetString(result); }
public void PosTest1() { Byte[] bytes = new Byte[] { 85, 84, 70, 56, 32, 69, 110, 99, 111, 100, 105, 110, 103, 32, 69, 120, 97, 109, 112, 108, 101}; UTF8Encoding utf8 = new UTF8Encoding(); string str = utf8.GetString(bytes, 0, bytes.Length); }
public void readfile(object obj) { Monitor.Enter(this); FileStream fs = File.OpenRead(@"d:\temp\myfile.txt"); byte [] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while(fs.Read(b, 0, b.Length) > 0) { Console.WriteLine(temp.GetString(b)); } Monitor.Exit(this); Thread.Sleep(400); }
private string RunTally(string input) { var encoding = new UTF8Encoding(); using (var inStream = new MemoryStream(encoding.GetBytes(input))) { using (var outStream = new MemoryStream()) { Tournament.Tally(inStream, outStream); return encoding.GetString(outStream.GetBuffer()); } } }
public static string UTF8ToString(MemoryStream ms) { var utf = new UTF8Encoding(false); var result = utf.GetString( ms.GetBuffer(), 0, (int)ms.Length ); // F*****g UTF8 if (result[0] == 0xFEFF) result = result.Substring(1); return result; }
public void NegTest4() { Byte[] bytes = new Byte[] { 85, 84, 70, 56, 32, 69, 110, 99, 111, 100, 105, 110, 103, 32, 69, 120, 97, 109, 112, 108, 101}; UTF8Encoding utf8 = new UTF8Encoding(); Assert.Throws<ArgumentOutOfRangeException>(() => { string str = utf8.GetString(bytes, 1, bytes.Length); }); }
// Use this for initialization void Start() { TcpClient tcpClient = new TcpClient(); tcpClient.Connect("127.0.0.1", 10000); clientStream = tcpClient.GetStream(); byte[] message = new byte[4096]; int bytesRead; bytesRead = 0; bytesRead = clientStream.Read(message, 0, 4096); UTF8Encoding encoder = new UTF8Encoding(); MonoBehaviour.print(encoder.GetString(message, 0, bytesRead)); }
protected void Install_Click(object sender, EventArgs e) { bool success = false; try { switch (_catalogType) { case CatalogType.Plugins: case CatalogType.Widgets: string fileName = Item.FileName; if (fileName.EndsWith(".zip")) fileName = fileName.Replace(".zip", ".dll"); if (!fileName.EndsWith(".dll")) fileName = fileName + ".dll"; new WebClient().DownloadFile(Item.DownloadUrl, Path.Combine(Server.MapPath("~/bin"), fileName)); break; case CatalogType.Themes: string themeFilename = Path.Combine(Server.MapPath("~/files/themes"), Item.FileName); new WebClient().DownloadFile(Item.DownloadUrl, themeFilename); UTF8Encoding utf = new UTF8Encoding(); string encodedFile = utf.GetString(File.ReadAllBytes(themeFilename)); ThemeConverter.ToDisk(encodedFile, Server.MapPath("~/files/themes/"), true, Item.Name); File.Delete(themeFilename); break; } success = true; } catch { } if (success) { InstallButton.Enabled = false; CancelButton.Enabled = false; Message.Type = StatusType.Success; Message.Text = string.Format("This {0} has been successfully installed.", _itemTypeName); } else { InstallButton.Text = "Try Again"; Message.Type = StatusType.Error; Message.Text = string.Format("An error has occurred during the downloading of this {0}.", _itemTypeName); } }
public string loadFromHtml(string FileAddr) { string path = System.Web.HttpContext.Current.Server.MapPath(FileAddr);//"~/htmlfrm/html_CarInfoWindow_Point.htm"); string str; System.IO.FileStream fs = File.Open(path, FileMode.Open); //HttpContext.Current.Session["UnitID"] = PointID.ToString(); byte[] b = new byte[fs.Length]; UTF8Encoding temp = new UTF8Encoding(true); str = ""; while (fs.Read(b, 0, b.Length) > 0) { str = str + (temp.GetString(b)); } fs.Close(); return str; }
public static void Main() { string path = "MyTest.txt"; // Delete the file if it exists. if (File.Exists(path)) { File.Delete(path); } //Create the file. FileStream fs = File.Create(path); AddText(fs, "This is some text"); AddText(fs, "This is some more text,"); AddText(fs, "\r\nand this is on a new line"); AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n"); for (int i = 100; i < 220; i++) { AddText(fs, Convert.ToChar(i).ToString()); //Split the output at every 10th character. if (i % 10 == 0) { AddText(fs, "\r\n"); } } fs.Close(); //Open the stream and read it back. fs = File.OpenRead(path); byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(); while (fs.Read(b, 0, b.Length) > 0) { String s = temp.GetString(b); Console.WriteLine(s); } }
public static String DecryptToString(Byte[] data, Byte[] key) { return(utf8.GetString(Decrypt(data, key))); }
public static string AStyleDirectory(string dir, bool writeChanges, out bool changesMade) { var pattern = Settings.Default.Pattern; var options = Settings.Default.Options; var license = Settings.Default.License.Replace("\r", "").Replace("\n", "\r\n"); var ignore = Settings.Default.Ignore.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); changesMade = false; // Get a list of source files string[] sources = GitLsFiles(dir, pattern); if (sources.Length <= 0) { return("No source files found!"); } // Format the files var output = new StringBuilder(); var AStyle = new AStyleInterface(); var encoding = new UTF8Encoding(false); foreach (string file in sources) { try { if (ignore.Any(p => Regex.IsMatch(file, p))) { continue; } var fileText = encoding.GetString(File.ReadAllBytes(file)); var formatText = AStyle.FormatSource(fileText, options) .Replace("\r\n", "\n") .Replace("\n", "\r\n") .Trim('\uFEFF', '\u200B'); if (license.Length > 0 && !formatText.StartsWith(license)) { formatText = license + fileText; } if (formatText == String.Empty) { output.AppendLine("Cannot format " + file); continue; } if (!fileText.Equals(formatText)) { changesMade = true; if (writeChanges) { File.WriteAllText(file, formatText, encoding); } else { output.AppendLine(file); } } } catch { // Ignored. Any files that can't be read or written will be skipped. } } return(output.ToString()); }
protected void Page_Load(object sender, EventArgs e) { //StreamWriter stw = new StreamWriter(Server.MapPath("/Log/IPNstatus.txt"), true); //stw.WriteLine("INSTANT PAYPAL NOTIFICATION STARTED " + DateTime.Now.ToString()); try { //Post back to either sandbox or live HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PayPal.GetPaypalServiceURL()); //Set values for the request back req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength); string strRequest = Encoding.ASCII.GetString(param); strRequest += "&cmd=_notify-validate"; req.ContentLength = strRequest.Length; //for proxy //WebProxy proxy = new WebProxy(new Uri("http://*****:*****@"/site/Activation.aspx?vc=" + user.Confirmation_Code; sendmail(user, link); } //stw.WriteLine("END OF SIGNUP"); } // FOR PAYMENT SECOND TIME //else if (Users.Any(u => u.Paypal_Buyer_ID == PayPal_payer_id))// else if (Users.Any(u => u.Paypal_Email_Address == PayPal_buyer_email)) { // THIS BLOCK OF CODE WILL BE HIT WHEN THE USER'S RECURRING PAYMEN OCCURS OR THE USER RE SUBSCRIBES //stw.WriteLine("RECURING SUBSCRIPTION " + DateTime.Now.ToString()); //stw.WriteLine(Request.Params.ToString()); //User user = Users.Single(u => u.Paypal_Buyer_ID == PayPal_payer_id); User user = Users.Single(u => u.Paypal_Email_Address == PayPal_buyer_email); user.Is_Paypal_Paid = true; user.Is_Active = true; user.Is_Locked = false; //==== INSERT SUBSCRIPTION DETAIL Subscription sub = new Subscription(); sub.User_Code = user.User_Code; sub.PayPal_Email_Address = PayPal_buyer_email; //stw.WriteLine("RECURRING PAYMENT"); try { //Paypal_mc_gross = decimal.Parse(Request["mc_amount3"].ToString()); Paypal_mc_gross = decimal.Parse(Request["mc_gross"].ToString()); } catch { } // PACKAGE UPDATION sub.Package_Id = int.Parse(paypal_item_id); sub.Amount = Paypal_mc_gross; sub.Transaction_Id = Paypal_txn_id.ToString(); sub.Subscription_Date = DateTime.Now; sub.Paypal_Buyer_ID = PayPal_payer_id; // ConvertFromPayPalDate(Paypal_subscr_date, 0); sub.Expiry_Date = DateTime.Now.AddMonths(1); entites.Subscriptions.AddObject(sub); entites.SaveChanges(); } } else if (Paypal_txn_type == "subscr-failed") { // THIS BLOCK OF CODE WILL BE HIT WHEN THE USER'S RECURRING PAYMENT WILL BE FAILED DUE TO INSUFFICIENT BALANCE //stw.WriteLine("RECURRING FAILED SUBSCRIPTION " + DateTime.Now.ToString()); //User user = Users.Single(u => u.Paypal_Buyer_ID == PayPal_payer_id); User user = Users.Single(u => u.Paypal_Email_Address == PayPal_buyer_email); user.Is_Paypal_Paid = false; user.Is_Locked = true; ////==== DELETE SUBSCRIPTION DETAILsu //List<Subscription> subs = entites.Subscriptions.ToList(); //entites.Subscriptions.Where(w => w.Paypal_Buyer_ID == PayPal_payer_id) //.ToList().ForEach(entites.Subscriptions.DeleteObject); entites.SaveChanges(); //stw.WriteLine("CANCEL FAILED CoMNPLETED" + DateTime.Now.ToString()); //==== SEND ACTIVATION EMAIL TO THE USER AFTER PAYMENT PROCESSING sendmailFailure(user.Full_Name, user.Email_Address, user.Full_Name, user.Password, user.Confirmation_Code); } else if (Paypal_txn_type == "subscr_cancel") { // THIS BLOCK OF CODE WILL BE HIT WHEN THE USER'S CANCEL THE SUBSCRIPTION //stw.WriteLine("CANCEL SUBSCRIPTION " + DateTime.Now.ToString()); //User user = Users.Single(u => u.Paypal_Buyer_ID == PayPal_payer_id); User user = Users.Single(u => u.Paypal_Email_Address == PayPal_buyer_email); user.Is_Paypal_Paid = false; user.Is_Active = false; entites.SaveChanges(); sendmailCancelSubscription(user.Full_Name, user.Email_Address, user.Full_Name, user.Password, user.Confirmation_Code); //stw.WriteLine("CANCEL SUBSCRIPTION CoMNPLETED" + DateTime.Now.ToString()); } //} //else //{ //} } catch (Exception ex) { //stw.WriteLine(ex.Message); //stw.Dispose(); Email.SendMail("*****@*****.**", "Test IPN", ex.ToString(), null); } //stw.Dispose(); } else if (strResponse == "INVALID") { // THIS BLOCK OF CODE WILL BE HIT WHEN THE USER'S PAYPAL PROCESS IS INVALID UTF8Encoding en = new UTF8Encoding(); string input = en.GetString(param); //StreamWriter stw = new StreamWriter(Server.MapPath("status.txt"), true); //stw.WriteLine("Invalid " + DateTime.Now.ToString()); // CANCEL SUBSCTIPION AS USER DONT HAVE FUNDS if (Users.Any(u => u.Paypal_Buyer_ID == PayPal_payer_id && u.Is_Active == true)) { //stw.WriteLine("invalid SUBSCRIPTION " + DateTime.Now.ToString()); User user = Users.Single(u => u.Paypal_Email_Address == PayPal_buyer_email); user.Is_Paypal_Paid = false; user.Is_Locked = true; entites.SaveChanges(); //==== SEND ACTIVATION EMAIL TO THE USER AFTER PAYMENT PROCESSING } //stw.Dispose(); } else { //log response/ipn data for manual investigation } //stw.Dispose(); } catch (Exception ee) { ////stw.WriteLine(DateTime.Now.ToString()); ////stw.WriteLine(ee.ToString()); //stw.Dispose(); //Logging.WriteLog(LogType.Critical, ee.ToString()); Email.SendMail("*****@*****.**", "Test IPN", ee.ToString(), null); } }
public static List <byte[]> ExtractParams(byte[] source) { int num = 0; EFetchResponseParserState state = EFetchResponseParserState.Base; int start = 0; int end = 0; uint num4 = 0; List <byte[]> list = new List <byte[]>(); uint num5 = 0; for (int i = 0; i < source.Length; i++) { EFetchResponseParserState inParanthesis = state; switch (state) { case EFetchResponseParserState.Base: if (source[i] != 40) { break; } num++; inParanthesis = EFetchResponseParserState.InParanthesis; start = i + 1; goto Label_0197; case EFetchResponseParserState.InQuotes: if (source[i] == 0x5c) { inParanthesis = EFetchResponseParserState.AfterSlash; } if (source[i] == 0x22) { inParanthesis = EFetchResponseParserState.Base; end = i; } goto Label_0197; case EFetchResponseParserState.InParanthesis: if (source[i] == 40) { num++; } if (source[i] == 0x29) { num--; if (num == 0) { inParanthesis = EFetchResponseParserState.Base; end = i; } } goto Label_0197; case EFetchResponseParserState.InWord: if (source[i] != 0x20) { goto Label_0120; } inParanthesis = EFetchResponseParserState.Base; end = i; goto Label_0197; case EFetchResponseParserState.InMultilineHeader: if (source[i] == 0x7d) { inParanthesis = EFetchResponseParserState.AfterMultilineHeader; end = i; byte[] bytes = ExtractSubarray(source, start, end); num4 = uint.Parse(DefaultEncoding.GetString(bytes, 0, bytes.Length)); } goto Label_0197; case EFetchResponseParserState.InMultilineBlock: num5++; if (num5 >= num4) { inParanthesis = EFetchResponseParserState.Base; end = i + 1; } goto Label_0197; case EFetchResponseParserState.AfterMultilineHeader: if (source[i] == 10) { inParanthesis = EFetchResponseParserState.InMultilineBlock; start = i + 1; } goto Label_0197; case EFetchResponseParserState.AfterSlash: inParanthesis = EFetchResponseParserState.InQuotes; goto Label_0197; default: goto Label_0197; } if (source[i] == 0x22) { inParanthesis = EFetchResponseParserState.InQuotes; start = i + 1; } else if (source[i] == 0x7b) { inParanthesis = EFetchResponseParserState.InMultilineHeader; start = i + 1; } else { if ((source[i] == 0x7d) || (source[i] == 0x29)) { throw new FormatException("The source string was not in a correct format"); } if (source[i] != 0x20) { inParanthesis = EFetchResponseParserState.InWord; start = i; } } goto Label_0197; Label_0120: if (((source[i] == 0x22) || (source[i] == 40)) || (source[i] == 0x29)) { throw new FormatException("The source string was not in a correct format"); } Label_0197: if ((state != inParanthesis) && (inParanthesis == EFetchResponseParserState.Base)) { list.Add(ExtractSubarray(source, start, end)); } state = inParanthesis; } if (state == EFetchResponseParserState.InWord) { list.Add(ExtractSubarray(source, start, source.Length)); return(list); } if (state != EFetchResponseParserState.Base) { throw new FormatException("The source string was not in a correct format"); } return(list); }
// loads input from a file public bool loadFile() { string fileString = ""; UTF8Encoding utf8 = new UTF8Encoding(); try { Console.Write("> Input File: "); fileString = Console.ReadLine(); byte[] bytes = File.ReadAllBytes(fileString); this.inputText_ = utf8.GetString(bytes); Console.WriteLine(this.inputText_+"\n"); return true; } catch (Exception) { Console.WriteLine("> File not found. Try again."); loadFile(); return false; } }
protected void Page_PreRenderComplete(object sender, EventArgs e) { HotelSearchRS objHotelSearchRS = (HotelSearchRS)Session["AreaListHotelSearchRS"]; AreaList objAreaList = new AreaList(); objAreaList.Area = new WBS_Area[0]; if (objHotelSearchRS.ResponseHeader.Success) { List<WBS_Area> lAreas = new List<WBS_Area>(); if (objHotelSearchRS.HotelListItems != null) { List<string> lCountryCodes = new List<string>(); for (int i = 0; i < objHotelSearchRS.AreaListItems.Length; i++) { if (!lCountryCodes.Contains(objHotelSearchRS.AreaListItems[i].CountryCode)) lCountryCodes.Add(objHotelSearchRS.AreaListItems[i].CountryCode); } lCountryCodes.Sort(); for (int i = 0; i < lCountryCodes.Count; i++) { for (int j = 0; j < objHotelSearchRS.AreaListItems.Length; j++) { if (objHotelSearchRS.AreaListItems[j].CountryCode == lCountryCodes[i]) { WBS_Area objArea = new WBS_Area(); lAreas.Add(objArea); objArea.AreaID = objHotelSearchRS.AreaListItems[j].AreaID; objArea.AreaName = objHotelSearchRS.AreaListItems[j].AreaName; objArea.CountryCode = objHotelSearchRS.AreaListItems[j].CountryCode; } } } } objAreaList.Area = lAreas.ToArray(); } XmlSerializer ser = new XmlSerializer(objAreaList.GetType()); MemoryStream ms = new MemoryStream(); ser.Serialize(ms, objAreaList); UTF8Encoding utf8 = new UTF8Encoding(); string strAreaListXML = utf8.GetString(ms.ToArray()); ms.Close(); try { HttpContext.Current.Response.ContentType = "text/xml"; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Write(strAreaListXML); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } catch (System.Threading.ThreadAbortException) { // Ignore -- html output always terminated since the xml // response document only is to go out to client. return; } Session.Abandon(); return; }
public static string ByteArrToString(byte[] bytes) { UTF8Encoding encoding = new UTF8Encoding(); return(encoding.GetString(bytes)); }
public void Test() { //读取文件.txt //读取内容流 //新建文件.html //yptoopman.html using (FileStream fs = File.Create(@"E:\yptoopman.html")) { AddText(fs, "<<!DOCTYPE html>>"); AddText(fs, "<html>"); AddText(fs, "<head>"); AddText(fs, " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"); AddText(fs, "<meta charset=\"utf-8\" />"); AddText(fs, "<title>YPTopMan"); AddText(fs, "</title>"); AddText(fs, "</head>"); AddText(fs, "<body>"); AddText(fs, "<table>"); using (FileStream fs2 = File.OpenRead(@"E:\EV5y8xmj.txt")) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs2.Read(b, 0, b.Length) > 0) { var val = temp.GetString(b); var vals = val.Split('h'); //int startIndex = 0; //for (int i = 0; i < 15; i++) //{ // AddText(fs, "<tr>"); // //长度 // int len = val.IndexOf('h', startIndex); // string title = val.Substring(startIndex, len); // startIndex = len; // string url = val.Substring(startIndex, 50); // AddText(fs, "<td>"); // AddText(fs, title); // AddText(fs, "</td>"); // AddText(fs, "<td>"); // AddText(fs, "<a href=\"" + url + "\">" + title + "</a>"); // AddText(fs, "</td>"); // AddText(fs, "</tr>"); //} } } AddText(fs, "</table>"); AddText(fs, "</body>"); AddText(fs, "</html>"); } //输出文件保存 }
private async void BackgroundCheck() { //`! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //`! !!! !!! //`! !!! Turn off Debug Visualizer before stepping through this method live on the stream!!! !!! //`! !!! !!! //`! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! webRequest = WebRequest.Create(string.Format("https://widgets.streamloots.com/alerts/{0}/media-stream", streamlootsID.GetStr())); ((HttpWebRequest)webRequest).AllowReadStreamBuffering = false; WebResponse response = webRequest.GetResponse(); responseStream = response.GetResponseStream(); UTF8Encoding encoder = new UTF8Encoding(); string cardStr = string.Empty; var buffer = new byte[100000]; while (true) { try { while (responseStream.CanRead) { int len = await responseStream.ReadAsync(buffer, 0, 100000); if (len <= 10) { continue; } string text = encoder.GetString(buffer, 0, len); if (string.IsNullOrEmpty(text)) { continue; } cardStr += text; try { JObject cardObject = JObject.Parse("{ " + cardStr + " }"); if (cardObject == null) { continue; } if (!cardObject.ContainsKey("data")) { continue; } cardStr = string.Empty; JObject cardData = cardObject.Value <JObject>("data"); if (!cardData.ContainsKey("data")) { continue; } JObject cardDataData = cardData.Value <JObject>("data"); if (!cardDataData.ContainsKey("type")) { continue; } string type = cardDataData.Value <string>("type"); switch (type.ToLower()) { case "purchase": ProcessChestPurchase(cardObject); break; case "redemption": ProcessCardRedemption(cardObject); break; default: Console.WriteLine($"Unknown Streamloots packet type: {type}"); break; } } catch (Exception) { } // To handle the case where partial packet data is received } } catch (Exception ex) { //System.Diagnostics.Debugger.Break(); Console.WriteLine(ex.ToString()); webRequest = WebRequest.Create(string.Format("https://widgets.streamloots.com/alerts/{0}/media-stream", streamlootsID.GetStr())); ((HttpWebRequest)webRequest).AllowReadStreamBuffering = false; response = webRequest.GetResponse(); responseStream = response.GetResponseStream(); encoder = new UTF8Encoding(); cardStr = string.Empty; buffer = new byte[100000]; } } }
public static string ToStringFromByteArray(this byte[] value) { var enc = new UTF8Encoding(); return(enc.GetString(value)); }
protected void Page_Load(object sender, EventArgs e) { txtPassword.Attributes["type"] = "password"; rdoNormalLogin.Checked = true; // Read encrypted password from cookie if (!IsPostBack && Request.Cookies["LoginCookie"] != null) { HttpCookie myCookie = Request.Cookies["LoginCookie"]; //txtEmail.Text = myCookie.Values["Email"]; //txtPassword.Text = myCookie.Values["Password"]; String encryptedEmail = myCookie.Values["Email"]; String encryptedPassword = myCookie.Values["Password"]; Byte[] encryptedEmailBytes = Convert.FromBase64String(encryptedEmail); Byte[] emailBytes; String plainTextEmail; UTF8Encoding encoder = new UTF8Encoding(); RijndaelManaged rmEncryption = new RijndaelManaged(); MemoryStream memStream = new MemoryStream(); CryptoStream decryptionStream = new CryptoStream(memStream, rmEncryption.CreateDecryptor(key, vector), CryptoStreamMode.Write); //Email decryptionStream.Write(encryptedEmailBytes, 0, encryptedEmailBytes.Length); decryptionStream.FlushFinalBlock(); memStream.Position = 0; emailBytes = new Byte[memStream.Length]; memStream.Read(emailBytes, 0, emailBytes.Length); decryptionStream.Close(); memStream.Close(); plainTextEmail = encoder.GetString(emailBytes); txtEmail.Text = plainTextEmail; //Password if (encryptedPassword != null) { Byte[] encryptedPasswordBytes = Convert.FromBase64String(encryptedPassword); Byte[] passwordBytes; String plainTextPassword; memStream = new MemoryStream(); decryptionStream = new CryptoStream(memStream, rmEncryption.CreateDecryptor(key, vector), CryptoStreamMode.Write); decryptionStream.Write(encryptedPasswordBytes, 0, encryptedPasswordBytes.Length); decryptionStream.FlushFinalBlock(); memStream.Position = 0; passwordBytes = new Byte[memStream.Length]; memStream.Read(passwordBytes, 0, passwordBytes.Length); decryptionStream.Close(); memStream.Close(); plainTextPassword = encoder.GetString(passwordBytes); txtPassword.Text = plainTextPassword; //lblMessage.Text = "Password: "******"") { rdoAutoLogin.Checked = true; } else { rdoFastLogin.Checked = true; } } }
public void TestDirectoryHierarchy() { var fileSystem = new Repository(); var nodeOne = new LocalFileTree(); var nodeTwo = new LocalFileTree(); var nodeThree = new ZipNodeTree(); string appPath = Path.Combine(TestingUtils.GetTestingBaseFolder(), "testdata"); var tempDir = Path.Combine(Path.Combine(appPath, @"Data2\temp")); if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } Assert.IsTrue(nodeOne.Build(Path.Combine(appPath, @"Data\"))); Assert.IsTrue(nodeTwo.Build(Path.Combine(appPath, @"Data2\"))); Assert.IsTrue(nodeThree.Build(Path.Combine(appPath, @"Data.zip"))); fileSystem.AddSystem("First", nodeOne); fileSystem.AddSystem("Second", nodeTwo); fileSystem.AddSystem("Third", nodeThree); Assert.IsTrue(fileSystem.DirExists(@"subfolder01")); Assert.IsTrue(fileSystem.DirExists(@"subfolder02")); Assert.IsTrue(fileSystem.DirExists(@"alphabetagamma")); Assert.IsTrue(fileSystem.DirExists(@"subfolder02\subfolder_a")); Assert.IsTrue(fileSystem.DirExists(@"subfolder02\subfolder_a\subfolder_a_b")); Assert.IsTrue(fileSystem.DirExists(@"subfolder02\subfolder_a\subfolder_a_c")); Assert.IsTrue(fileSystem.FileExists(@"colours.txt")); Assert.IsTrue(fileSystem.FileExists(@"File01.txt")); Assert.IsTrue(fileSystem.FileExists(@"subfolder02\booga.txt")); Assert.IsTrue(fileSystem.FileExists(@"subfolder02\subfolder_a\geoip.txt")); Assert.IsTrue(fileSystem.FileExists(@"subfolder02\subfolder_a\subfolder_a_b\another_test.folder.txt")); Assert.IsTrue(fileSystem.FileExists(@"subfolder01\map01.txt")); // Get Data from various filesystems // This should be coming from nodeOne using (Stream fs = fileSystem.Open(@"alphabetagamma\db.sample.txt")) { byte[] buffer = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); int amountRead = fs.Read(buffer, 0, buffer.Length); int accumulation = amountRead; while (amountRead > 0) { string contents = temp.GetString(buffer, 0, amountRead); Console.Write(contents); amountRead = fs.Read(buffer, 0, buffer.Length); accumulation += amountRead; } Console.WriteLine(""); Console.WriteLine("Read {0} bytes", accumulation); } // This should be coming from nodeTwo using (Stream fs = fileSystem.Open(@"File01.txt")) { byte[] buffer = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); int amountRead = fs.Read(buffer, 0, buffer.Length); int accumulation = amountRead; while (amountRead > 0) { string contents = temp.GetString(buffer, 0, amountRead); Console.Write(contents); amountRead = fs.Read(buffer, 0, buffer.Length); accumulation += amountRead; } Console.WriteLine(""); Console.WriteLine("Read {0} bytes", accumulation); } // This should be coming from nodeThree using (Stream fs = fileSystem.Open(@"subfolder02\subfolder_a\subfolder_a_c\data.data.data.txt")) { byte[] buffer = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); int amountRead = fs.Read(buffer, 0, buffer.Length); int accumulation = amountRead; while (amountRead > 0) { string contents = temp.GetString(buffer, 0, amountRead); Console.Write(contents); amountRead = fs.Read(buffer, 0, buffer.Length); accumulation += amountRead; } Console.WriteLine(""); Console.WriteLine("Read {0} bytes", accumulation); } // Write a file - this should go into nodeTwo Byte[] info = new UTF8Encoding(true).GetBytes("This is a test of data being written into the FileSystem."); Assert.IsTrue(fileSystem.Write(@"temp\sample_file.txt", info, info.Length)); Assert.IsTrue(fileSystem.FileExists(@"temp\sample_file.txt")); Assert.IsTrue(nodeTwo.FileExists(@"temp\sample_file.txt")); Assert.IsTrue(fileSystem.Delete(@"temp\sample_file.txt")); }
public static string UTF8GetString(byte[] bytes, int offset, int len) { return(utf8.GetString(bytes, offset, len)); }
private static bool HasValueChanged(object newValue, object oldValue) { var valuesChanged = true; if (null != newValue && null != oldValue) { var valueToCompare = newValue as IComparable; if (null == valueToCompare) { try { var serializer = new XmlSerializer(newValue.GetType()); using (var streamNew = new MemoryStream()) { serializer.Serialize(streamNew, newValue); var encoding = new UTF8Encoding(); var oldValueSerialized = encoding.GetString(streamNew.ToArray()); using (var streamOld = new MemoryStream()) { serializer.Serialize(streamOld, oldValue); var newValueSerialized = encoding.GetString(streamOld.ToArray()); valuesChanged = !string.Equals(newValueSerialized, oldValueSerialized); } } } catch { valuesChanged = true; } } else { valuesChanged = valueToCompare.CompareTo(oldValue) != 0; } } else if (null == oldValue && null == newValue) { valuesChanged = false; } return valuesChanged; }
// Decode the character or escape sequence starting at start and appends it to result; returns the index of the // first character following the decoded character or escape sequence. private static int DecodeChar( string s, int start, int end, string special, StringBuilder result, UTF8Encoding utf8Encoding) { Debug.Assert(start >= 0); Debug.Assert(start < end); Debug.Assert(end <= s.Length); if (s[start] != '\\') { result.Append(CheckChar(s, start++)); } else if (start + 1 == end) { ++start; result.Append('\\'); // trailing backslash } else { char c = s[++start]; switch (c) { case '\\': case '\'': case '"': case '?': { ++start; result.Append(c); break; } case 'a': { ++start; result.Append('\a'); break; } case 'b': { ++start; result.Append('\b'); break; } case 'f': { ++start; result.Append('\f'); break; } case 'n': { ++start; result.Append('\n'); break; } case 'r': { ++start; result.Append('\r'); break; } case 't': { ++start; result.Append('\t'); break; } case 'v': { ++start; result.Append('\v'); break; } case 'u': case 'U': { int codePoint = 0; bool inBMP = c == 'u'; int size = inBMP ? 4 : 8; ++start; while (size > 0 && start < end) { c = s[start++]; int charVal; if (c >= '0' && c <= '9') { charVal = c - '0'; } else if (c >= 'a' && c <= 'f') { charVal = 10 + (c - 'a'); } else if (c >= 'A' && c <= 'F') { charVal = 10 + (c - 'A'); } else { break; // while } codePoint = (codePoint * 16) + charVal; --size; } if (size > 0) { throw new System.ArgumentException("Invalid universal character name: too few hex digits"); } if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { throw new System.ArgumentException("A universal character name cannot designate a surrogate"); } if (inBMP || codePoint <= 0xFFFF) { result.Append((char)codePoint); } else { result.Append(char.ConvertFromUtf32(codePoint)); } break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case 'x': { // UTF-8 byte sequence encoded with octal escapes byte[] arr = new byte[end - start]; int i = 0; bool more = true; while (more) { int val = 0; if (c == 'x') { int size = 2; ++start; while (size > 0 && start < end) { c = s[start++]; int charVal; if (c >= '0' && c <= '9') { charVal = c - '0'; } else if (c >= 'a' && c <= 'f') { charVal = 10 + (c - 'a'); } else if (c >= 'A' && c <= 'F') { charVal = 10 + (c - 'A'); } else { --start; // move back break; // while } val = (val * 16) + charVal; --size; } if (size == 2) { throw new System.ArgumentException("Invalid \\x escape sequence: no hex digit"); } } else { for (int j = 0; j < 3 && start < end; ++j) { int charVal = s[start++] - '0'; if (charVal < 0 || charVal > 7) { --start; // move back Debug.Assert(j != 0); // must be at least one digit break; // for } val = (val * 8) + charVal; } if (val > 255) { string msg = "octal value \\" + System.Convert.ToString(val, 8) + " (" + val + ") is out of range"; throw new System.ArgumentException(msg); } } arr[i++] = (byte)val; more = false; if ((start + 1 < end) && s[start] == '\\') { c = s[start + 1]; if (c == 'x' || (c >= '0' && c <= '9')) { start++; more = true; } } } result.Append(utf8Encoding.GetString(arr, 0, i)); // May raise ArgumentException. break; } default: { if (string.IsNullOrEmpty(special) || !special.Contains(c)) { result.Append('\\'); // not in special, so we keep the backslash } result.Append(CheckChar(s, start++)); break; } } } return(start); }
private void CommandInput(RichTextBox textbox) { string[] input = textbox.Text.Split(' '); input[0] = input[0].ToLower(); if (input[0] == "cryptostreambuffer" || input[0] == "csbuffer" || input[0] == "buffer") { if (input.Length > 1 && !string.IsNullOrEmpty(input[1]) && uint.TryParse(input[1], out uint csBufferTmp)) { Logging.Log($"CryptoStream Buffer set to {csBufferTmp} bytes"); FileAES_Utilities.SetCryptoStreamBuffer(csBufferTmp); } else { TooFewArgsError(textbox.Text); } } else if (input[0] == "getcryptostreambuffer" || input[0] == "getcsbuffer" || input[0] == "getbuffer") { Logging.Log($"CryptoStream Buffer is {FileAES_Utilities.GetCryptoStreamBuffer()} bytes"); } else if (input[0] == "getfaestempfolder" || input[0] == "gettemp" || input[0] == "gettempfolder") { Logging.Log($"FAES Temp Folder is: {FileAES_Utilities.GetFaesTempFolder()}"); } else if (input[0] == "getfaesversion" || input[0] == "getfaesver" || input[0] == "faesver") { Logging.Log($"FAES Version: {FileAES_Utilities.GetVersion()}"); } else if (input[0] == "getfaesuiversion" || input[0] == "getfaesguiversion" || input[0] == "getfaesuiver" || input[0] == "getfaesguiver" || input[0] == "ver" || input[0] == "guiver" || input[0] == "faesguiver") { Logging.Log($"FAES_GUI Version: {Program.GetVersion()}"); } else if (input[0] == "getssmversion" || input[0] == "getssmver" || input[0] == "ssmver") { Logging.Log($"SSM Version: {SimpleSettingsManager.SSM.GetVersion()}"); } else if (input[0] == "getlatestversiononbranch" || input[0] == "latestver" || input[0] == "latestversion" || input[0] == "latestvercheck") { Thread updateCheckThread = new Thread(() => { try { string branch = Program.programManager.GetBranch(); if (input.Length > 1 && !string.IsNullOrEmpty(input[1])) { string rawBranchRequest = input[1]; if (rawBranchRequest.ToLower() == "stable" || rawBranchRequest.ToLower() == "beta" || rawBranchRequest.ToLower() == "dev") { branch = rawBranchRequest.ToLower(); } } string verCheck = $"https://api.mullak99.co.uk/FAES/IsUpdate.php?app=faes_gui&ver=latest&branch={branch}&showver=true"; Logging.Log($"Getting the latest FAES_GUI version number on branch '{branch}'."); Logging.Log("This process may take a few seconds..."); WebClient webClient = new WebClient(); string latestVer = webClient.DownloadString(new Uri(verCheck)); if (!string.IsNullOrWhiteSpace(latestVer)) { Logging.Log($"Latest FAES_GUI Version on branch '{branch}' is '{latestVer}'."); } else { Logging.Log($"The branch '{branch}' does not contain any versions!", Severity.WARN); } } catch { Logging.Log("Unable to connect to the update server! Please check your internet connection.", Severity.WARN); } }); updateCheckThread.Start(); } else if (input[0] == "checkupdate" || input[0] == "check" || input[0] == "updatecheck") { try { string latestVer = GetLatestVersion(); string currentVer = ConvertVersionToNonFormatted(Program.GetVersion()); Program.programManager.GetBranch(); string compareVersions = $"https://api.mullak99.co.uk/FAES/CompareVersions.php?app=faes_gui&branch={"dev"}&version1={currentVer}&version2={latestVer}"; WebClient client = new WebClient(); byte[] html = client.DownloadData(compareVersions); UTF8Encoding utf = new UTF8Encoding(); string result = utf.GetString(html).ToLower(); if (string.IsNullOrEmpty(result) || result == "null") { Logging.Log("Unable to connect to the update server! Please check your internet connection.", Severity.WARN); } else if (result.Contains("not exist in the database!") || result == "version1 is newer than version2") { Logging.Log($"You are on a private build. ({currentVer} is newer than {latestVer})."); } else if (result == "version1 is older than version2") { Logging.Log($"You are on an outdated build. ({currentVer} is older than {latestVer})."); } else if (result == "version1 is equal to version2") { Logging.Log($"You are on the latest build. ({currentVer} is equal to {latestVer})."); } else { Logging.Log("Unable to connect to the update server! Please check your internet connection.", Severity.WARN); } } catch { Logging.Log("Unable to connect to the update server! Please check your internet connection.", Severity.WARN); } DoCheckUpdate(); } else if (input[0] == "spoofversion" || input[0] == "spoof") { if (input.Length > 1 && !string.IsNullOrEmpty(input[1])) { string verToSpoof = ""; if (input[1].Contains("\"") || input[1].Contains("\'")) { for (int i = 1; i < input.Length; i++) { verToSpoof += input[i].Replace("\"", "").Replace("\'", ""); verToSpoof += " "; } verToSpoof = verToSpoof.TrimEnd(' '); } else { verToSpoof = input[1]; } if (verToSpoof.ToLower() == "reset" || verToSpoof.ToLower() == "off" || verToSpoof.ToLower() == "false") { Logging.Log("Disabled Version Spoofing."); Program.SetSpoofedVersion(false); } else { Logging.Log($"Enabled Version Spoofing. Spoofing Version: {verToSpoof}"); Program.SetSpoofedVersion(true, verToSpoof); } } else { Logging.Log("Disabled Version Spoofing."); Program.SetSpoofedVersion(false); } } else if (input[0] == "getselectedbranch" || input[0] == "branch" || input[0] == "getbranch") { Logging.Log($"FAES_GUI Branch: {Program.programManager.GetBranch()}"); } else if (input[0] == "setselectedbranch" || input[0] == "setbranch") { if (input.Length > 1 && !string.IsNullOrEmpty(input[1])) { string rawBranchRequest = input[1]; string validBranch; if (rawBranchRequest.ToLower() == "stable" || rawBranchRequest.ToLower() == "beta" || rawBranchRequest.ToLower() == "dev") { validBranch = rawBranchRequest.ToLower(); Program.programManager.SetBranch(validBranch); Logging.Log($"FAES_GUI Branch changed to: {validBranch}"); } else { Logging.Log($"'{rawBranchRequest}' is not a valid branch!", Severity.WARN); } } else { TooFewArgsError(textbox.Text); } } else if (input[0] == "exportlog" || input[0] == "export" || input[0] == "log") { ExportLog_Click(null, null); } else if (input[0] == "setlogpath") { if (input.Length > 1 && !string.IsNullOrEmpty(input[1])) { _overrideLogPath = input[1].Replace("\"", string.Empty).Replace("\'", string.Empty); Program.programManager.SetLogPath(_overrideLogPath); Logging.Log($"Log path changed to: {_overrideLogPath}"); } else { TooFewArgsError(textbox.Text); } } else if (input[0] == "getlogpath" || input[0] == "logpath") { _overrideLogPath = Program.programManager.GetLogPath(); Logging.Log($"Log path set to: {_overrideLogPath}"); } else if (input[0] == "resetlogpath") { Program.programManager.ResetLogPath(); Logging.Log("Log path reset!"); } else if (input[0] == "setdevmode" || input[0] == "setdevelopermode" || input[0] == "setdebugmode" || input[0] == "setdebug" || input[0] == "setdev" || input[0] == "setdeveloper") { if (input.Length > 1 && !string.IsNullOrEmpty(input[1])) { bool dev = false; if (input[1] == "1" || input[1] == "true" || input[1] == "t" || input[1] == "y" || input[1] == "yes") { dev = true; } Program.programManager.SetDevMode(dev); Logging.Log( $"Developer Mode {(dev ? "Enabled" : "Disabled")}! (Setting will be applied next launch)"); } else { TooFewArgsError(textbox.Text); } } else if (input[0] == "getdevmode" || input[0] == "getdevelopermode" || input[0] == "getdebugmode" || input[0] == "getdebug" || input[0] == "getdev" || input[0] == "getdeveloper" || input[0] == "developer" || input[0] == "dev" || input[0] == "debug") { Logging.Log($"Developer Mode is {(Program.programManager.GetDevMode() ? "Enabled" : "Disabled")}!"); } else if (input[0] == "resetdevmode" || input[0] == "resetdevelopermode" || input[0] == "resetdebugmode" || input[0] == "resetdebug" || input[0] == "resetdev" || input[0] == "resetdeveloper") { Program.programManager.ResetDevMode(); Logging.Log("Developer Mode reset!"); } else if (input[0] == "clear" || input[0] == "cls") { clearConsole.PerformClick(); } else { Logging.Log($"Unknown command: {textbox.Text}", Severity.WARN); } textbox.Clear(); }
public string Decrypt(string encrypted) { return(encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)))); }
public void T1_Correct_GreekWord_kosme() { byte[] data = { 0xCE, 0xBA, 0xE1, 0xBD, 0xB9, 0xCF, 0x83, 0xCE, 0xBC, 0xCE, 0xB5 }; string s = utf8.GetString(data); // cute but saving source code in unicode can be problematic // so we just ensure we can re-encode this Assert.AreEqual(BitConverter.ToString(data), BitConverter.ToString(utf8.GetBytes(s)), "Reconverted"); }
public int PortConfigInit(byte[] b) { int buffer_start; int buffer_len; string field_name; UTF8Encoding temp = new UTF8Encoding(true); string content = temp.GetString(b).Replace(" ", " "); m_xmlDoc = new XmlDocument(); string filename = System.Windows.Forms.Application.StartupPath + "\\description.xml"; if (!File.Exists(filename)) { File.WriteAllText(filename, Config.Resource.Resource.Description); } //m_xmlDoc.LoadXml(Config.Resource.Resource.Description); m_xmlDoc.Load(filename); //buffer_start = 0; buffer_start = content.IndexOf(MODULE_HASH); buffer_len = content.IndexOf('[', buffer_start + 1) - buffer_start; m_moduleConfig = content.Substring(buffer_start, buffer_len); //m_moduleConfig = new PortConfig(MODULE_HASH, content.Substring(buffer_start, buffer_len)); for (int i = 0; i < PORT_CFG_NUM; i++) { if (i >= PORT_CFG_NUM / 2) { field_name = "[Modbus G" + (i - PORT_CFG_NUM / 2 + 1) + "B]"; } else { field_name = "[Modbus G" + (i + 1) + "A]"; } buffer_start = content.IndexOf(field_name); if (buffer_start > 0) { buffer_len = content.IndexOf('[', buffer_start + 1) - buffer_start; if (buffer_len < 0) { buffer_len = content.Length - buffer_start; } m_portConfigArray.Add(new PortConfig(field_name, content.Substring(buffer_start, buffer_len), Config.EditType.EDIT_PORT_CONFIG, GetXmlNodeList(Config.EditType.EDIT_PORT_CONFIG))); } } for (int i = 0; i < PORT_CFG_NUM; i++) { if (i >= PORT_CFG_NUM / 2) { field_name = "[Modbus G" + (i - PORT_CFG_NUM / 2 + 1) + "B Commands]"; } else { field_name = "[Modbus G" + (i + 1) + "A Commands]"; } buffer_start = content.IndexOf(field_name); if (buffer_start > 0) { buffer_len = content.IndexOf('[', buffer_start + 1) - buffer_start; if (buffer_len < 0) { buffer_len = content.Length - buffer_start; } m_portCommandsArray.Add(new PortCommands(field_name, content.Substring(buffer_start, buffer_len), Config.EditType.EDIT_PORT_COMMAND, GetXmlNodeList(Config.EditType.EDIT_PORT_COMMAND))); } } for (int i = 0; i < PORT_PC_NUM; i++) { field_name = "[Modbus PC Port " + i + "]"; buffer_start = content.IndexOf(field_name); if (buffer_start > 0) { buffer_len = content.IndexOf('[', buffer_start + 1) - buffer_start; if (buffer_len < 0) { buffer_len = content.Length - buffer_start; } m_pcPortConfigArray.Add(new PortConfig(field_name, content.Substring(buffer_start, buffer_len), Config.EditType.EDIT_PCPORT_CONFIG, GetXmlNodeList(Config.EditType.EDIT_PCPORT_CONFIG))); } } for (int i = 0; i < PORT_PC_NUM; i++) { field_name = "[Modbus PC Port " + i + " Commands]"; buffer_start = content.IndexOf(field_name); if (buffer_start > 0) { buffer_len = content.IndexOf('[', buffer_start + 1) - buffer_start; if (buffer_len < 0) { buffer_len = content.Length - buffer_start; } m_pcPortCommandsArray.Add(new PortCommands(field_name, content.Substring(buffer_start, buffer_len), Config.EditType.EDIT_PCPORT_COMMAND, GetXmlNodeList(Config.EditType.EDIT_PCPORT_COMMAND))); } } for (int i = 0; i < PORT_ETHERNET_NUM; i++) { field_name = "[Ethernet " + i + "]"; buffer_start = content.IndexOf(field_name); if (buffer_start > 0) { buffer_len = content.IndexOf('[', buffer_start + 1) - buffer_start; if (buffer_len < 0) { buffer_len = content.Length - buffer_start; } m_etherNetPortArray.Add(new PortConfig(field_name, content.Substring(buffer_start, buffer_len), Config.EditType.EDIT_ETHERNET_CONFIG, GetXmlNodeList(Config.EditType.EDIT_ETHERNET_CONFIG))); } } for (int i = 0; i < PORT_ETHERNET_NUM; i++) { field_name = "[Ethernet Client " + i + "]"; buffer_start = content.IndexOf(field_name); if (buffer_start > 0) { buffer_len = content.IndexOf('[', buffer_start + 1) - buffer_start; if (buffer_len < 0) { buffer_len = content.Length - buffer_start; } m_etherNetClientConfigArray.Add(new PortConfig(field_name, content.Substring(buffer_start, buffer_len), Config.EditType.EDIT_ETHERNET_CLIENT_CONFIG, GetXmlNodeList(Config.EditType.EDIT_ETHERNET_CLIENT_CONFIG))); } } for (int i = 0; i < PORT_ETHERNET_NUM; i++) { field_name = "[Ethernet Client " + i + " Commands]"; buffer_start = content.IndexOf(field_name); if (buffer_start > 0) { buffer_len = content.IndexOf('[', buffer_start + 1) - buffer_start; if (buffer_len < 0) { buffer_len = content.Length - buffer_start; } m_etherNetClientCommandsArray.Add(new PortCommands(field_name, content.Substring(buffer_start, buffer_len), Config.EditType.EDIT_ETHERNET_CLIENT_COMMAND, GetXmlNodeList(Config.EditType.EDIT_ETHERNET_CLIENT_COMMAND))); } } for (int i = 0; i < PORT_ETHERNET_NUM; i++) { field_name = "[Ethernet Server " + i + "]"; buffer_start = content.IndexOf(field_name); if (buffer_start > 0) { buffer_len = content.IndexOf('[', buffer_start + 1) - buffer_start; if (buffer_len < 0) { buffer_len = content.Length - buffer_start; } m_etherNetServerConfigArray.Add(new PortConfig(field_name, content.Substring(buffer_start, buffer_len), Config.EditType.EDIT_ETHERNET_SERVER_CONFIG, GetXmlNodeList(Config.EditType.EDIT_ETHERNET_SERVER_CONFIG))); } } // for (int i = 0; i < PORT_ETHERNET_NUM; i++) // { // field_name = MODBUS_PORT_ETHERNET_SERVER_CMD.Replace('0', (char)('0' + i)); // buffer_start = content.IndexOf(field_name); // if (buffer_start > 0) // { // // buffer_len = content.IndexOf('[', buffer_start + 1) - buffer_start; // if (buffer_len < 0) // { // buffer_len = content.Length - buffer_start; // } // m_etherNetServerCommandsArray.Add(new PortCommands(field_name, content.Substring(buffer_start, buffer_len))); // } // } // field_name = "[Data Remap]"; buffer_start = content.IndexOf(field_name); if (buffer_start > 0) { buffer_len = content.IndexOf('[', buffer_start + 1) - buffer_start; if (buffer_len < 0) { buffer_len = content.Length - buffer_start; } m_dataRemap = new PortCommands(field_name, content.Substring(buffer_start, buffer_len), Config.EditType.EDIT_DATA_REMAP, GetXmlNodeList(Config.EditType.EDIT_DATA_REMAP)); } PortConfigCheckContent(); return(1); }
public ErrorType Execute() { List <string> scenes; string allContent = ""; //Find template if (!Directory.Exists(m_worldRootPath)) { return(ErrorType.NoSceneRootPath); } DirectoryInfo folder = new DirectoryInfo(m_worldRootPath); FileInfo [] SceneInfos = folder.GetFiles("*.unity", SearchOption.AllDirectories); //FileInfo [] sceneMetaInfos = folder.GetFiles("*.unity.meta"); scenes = new List <string> (); //SceneIds = new List<string>(); foreach (FileInfo info in SceneInfos) { scenes.Add(info.Name.Remove(info.Name.LastIndexOf(".", StringComparison.Ordinal))); } //Check config Path error ErrorType error = CheckFilePath(m_configPath, ErrorType.NoTemplateFile); if (error != ErrorType.NoError) { return(ErrorType.NoTemplateFile); } //Read template using (FileStream fs = File.OpenRead(m_configPath)) { byte [] buffer = new byte [1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(buffer, 0, buffer.Length) > 0) { allContent += temp.GetString(buffer); Array.Clear(buffer, 0, buffer.Length); } } //Generator code for GameRoot config StringBuilder inputContent = new StringBuilder(); inputContent.Append(SCENE_CONFIG_CODE_START); inputContent.Append("\n\n"); for (int i = 0; i < scenes.Count; i++) { inputContent.Append($"[SerializeField]\n"); inputContent.Append($"private string {scenes [i]}Name = \"{ scenes [i]}\"; \n "); inputContent.Append($"public CameraService.SceneCameraType {scenes [i]}CameraType; \n\n"); } int startOfConfig = allContent.IndexOf(SCENE_CONFIG_CODE_START); int endOfConfig = allContent.IndexOf(SCENE_CONFIG_CODE_END); if (startOfConfig < 0 || endOfConfig < 0) { return(ErrorType.NotExistInsertFlag); } allContent = allContent.Remove(startOfConfig, endOfConfig - startOfConfig); allContent = allContent.Insert(startOfConfig, inputContent.ToString()); inputContent.Clear(); // Getter Case Auto Generator inputContent.Append(GETTER_CASE_CODE_START); inputContent.Append("\n\n"); for (int i = 0; i < scenes.Count; i++) { inputContent.Append($"case \"{scenes [i]}\" : \n"); inputContent.Append($" return {scenes [i]}CameraType; \n\n"); } int startOfCase = allContent.IndexOf(GETTER_CASE_CODE_START); int endOfCase = allContent.IndexOf(GETTER_CASE_CODE_END); if (startOfCase < 0 || endOfCase < 0) { return(ErrorType.NotExistInsertFlag); } allContent = allContent.Remove(startOfCase, endOfCase - startOfCase); allContent = allContent.Insert(startOfCase, inputContent.ToString()); inputContent.Clear(); allContent = allContent.Substring(0, allContent.IndexOf('\0')); //Write scene lookup if (File.Exists(m_configPath)) { File.Delete(m_configPath); } // Write the byte array to the other FileStream. using (FileStream fsNew = new FileStream(m_configPath, FileMode.Create, FileAccess.Write)) { Byte [] bs = Encoding.UTF8.GetBytes(allContent); fsNew.Write(bs, 0, bs.Length); } //Auto Generated Code For Game Root Inspector allContent = ""; using (FileStream fs = File.OpenRead(m_InspectorPath)) { byte [] buffer = new byte [1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(buffer, 0, buffer.Length) > 0) { allContent += temp.GetString(buffer); Array.Clear(buffer, 0, buffer.Length); } } // Type Variable inputContent.Append(TYPE_VARIABLE_CODE_START); inputContent.Append("\n"); inputContent.Append("\n"); for (int i = 0; i < scenes.Count; i++) { inputContent.Append($"CameraService.SceneCameraType m_{scenes [i]}CameraType; \n\n "); } int startOfTypeVar = allContent.IndexOf(TYPE_VARIABLE_CODE_START); int endOfTypeVar = allContent.IndexOf(TYPE_VARIABLE_CODE_END); if (startOfTypeVar < 0 || endOfTypeVar < 0) { return(ErrorType.NotExistInsertFlag); } allContent = allContent.Remove(startOfTypeVar, endOfTypeVar - startOfTypeVar); allContent = allContent.Insert(startOfTypeVar, inputContent.ToString()); inputContent.Clear(); //POPUP inputContent.Append(POPUP_CODE_START); inputContent.Append("\n\n"); for (int i = 0; i < scenes.Count; i++) { inputContent.Append($"m_{scenes [i]}CameraType = ConfigRoot.Instance.{scenes [i]}CameraType; \n"); inputContent.Append($"m_{scenes [i]}CameraType = (CameraService.SceneCameraType)EditorGUILayout.EnumPopup(\"{scenes [i]} Camera Type: \", m_{scenes [i]}CameraType); \n"); inputContent.Append($" if (m_{scenes [i]}CameraType != ConfigRoot.Instance.{scenes [i]}CameraType) \n"); inputContent.Append("{ \n"); inputContent.Append($"ConfigRoot.Instance.{scenes [i]}CameraType = m_{scenes [i]}CameraType; \n"); inputContent.Append("} \n\n"); } int startOfPopup = allContent.IndexOf(POPUP_CODE_START); int endOfPopup = allContent.IndexOf(POPUP_CODE_END); if (startOfPopup < 0 || endOfPopup < 0) { return(ErrorType.NotExistInsertFlag); } allContent = allContent.Remove(startOfPopup, endOfPopup - startOfPopup); allContent = allContent.Insert(startOfPopup, inputContent.ToString()); inputContent.Clear(); allContent = allContent.Substring(0, allContent.IndexOf('\0')); //Write scene lookup if (File.Exists(m_InspectorPath)) { File.Delete(m_InspectorPath); } // Write the byte array to the other FileStream. using (FileStream fsNew = new FileStream(m_InspectorPath, FileMode.Create, FileAccess.Write)) { Byte [] bs = Encoding.UTF8.GetBytes(allContent); fsNew.Write(bs, 0, bs.Length); } return(ErrorType.NoError); }
/* converts binary to char */ public char binaryToChar(string _binaryString) { UTF8Encoding utf8 = new UTF8Encoding(); string binary = _binaryString; byte[] bytes = binaryStringToBytes(binary); string output = utf8.GetString(bytes); return output[0]; }
public static string ByteArrayToString(byte[] bytes) { UTF8Encoding charset = new UTF8Encoding(true); return charset.GetString(bytes); }
/// <summary> /// Decrypts a cipher text and returns a plain text /// </summary> public string Decrypt(string text) { byte[] input = Convert.FromBase64String(text); byte[] output = Transform(input, _des.CreateDecryptor(_key, _iv)); return(_utf8.GetString(output)); }
public static string Encrypt(string text) { byte[] input = utf8.GetBytes(text); byte[] output = Transform(input, AESCryptoServiceProvider.CreateEncryptor(Key, IV)); return(utf8.GetString(output)); }
/// <summary> /// Converts bytes in UTF-8 encoding to a regular string. /// </summary> /// <param name="InBytes">The UTF-8 bytes.</param> /// <returns>The input bytes as a string.</returns> public static string Utf8BytesToString(byte[] InBytes) { UTF8Encoding utf8encoder = new UTF8Encoding(false, true); return(utf8encoder.GetString(InBytes)); }
public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException is not thrown when index is less than zero."); try { Byte[] bytes = new Byte[] { 85, 84, 70, 56, 32, 69, 110, 99, 111, 100, 105, 110, 103, 32, 69, 120, 97, 109, 112, 108, 101}; UTF8Encoding utf8 = new UTF8Encoding(); string str = utf8.GetString(bytes, -1, bytes.Length); TestLibrary.TestFramework.LogError("102.1", "ArgumentNullException is not thrown when index is less than zero.."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
internal static object[] TryDecode(string format, byte[] value, out bool decodeSucceeded) { if (format == null) { throw new ArgumentNullException(nameof(format)); } Debug.WriteLine("Begin decoding\n"); UTF8Encoding utf8Encoder = new UTF8Encoding(false, true); berval berValue = new berval(); ArrayList resultList = new ArrayList(); BerSafeHandle berElement = null; object[] decodeResult = null; decodeSucceeded = false; if (value == null) { berValue.bv_len = 0; berValue.bv_val = IntPtr.Zero; } else { berValue.bv_len = value.Length; berValue.bv_val = Marshal.AllocHGlobal(value.Length); Marshal.Copy(value, 0, berValue.bv_val, value.Length); } try { berElement = new BerSafeHandle(berValue); } finally { if (berValue.bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(berValue.bv_val); } } int error = 0; for (int formatCount = 0; formatCount < format.Length; formatCount++) { char fmt = format[formatCount]; if (fmt == '{' || fmt == '}' || fmt == '[' || fmt == ']' || fmt == 'n' || fmt == 'x') { error = Wldap32.ber_scanf(berElement, new string(fmt, 1)); if (error != 0) { Debug.WriteLine("ber_scanf for {, }, [, ], n or x failed"); } } else if (fmt == 'i' || fmt == 'e' || fmt == 'b') { int result = 0; error = Wldap32.ber_scanf_int(berElement, new string(fmt, 1), ref result); if (error == 0) { if (fmt == 'b') { // should return a bool bool boolResult = false; if (result == 0) { boolResult = false; } else { boolResult = true; } resultList.Add(boolResult); } else { resultList.Add(result); } } else { Debug.WriteLine("ber_scanf for format character 'i', 'e' or 'b' failed"); } } else if (fmt == 'a') { // return a string byte[] byteArray = DecodingByteArrayHelper(berElement, 'O', ref error); if (error == 0) { string s = null; if (byteArray != null) { s = utf8Encoder.GetString(byteArray); } resultList.Add(s); } } else if (fmt == 'O') { // return berval byte[] byteArray = DecodingByteArrayHelper(berElement, fmt, ref error); if (error == 0) { // add result to the list resultList.Add(byteArray); } } else if (fmt == 'B') { // return a bitstring and its length IntPtr ptrResult = IntPtr.Zero; int length = 0; error = Wldap32.ber_scanf_bitstring(berElement, "B", ref ptrResult, ref length); if (error == 0) { byte[] byteArray = null; if (ptrResult != IntPtr.Zero) { byteArray = new byte[length]; Marshal.Copy(ptrResult, byteArray, 0, length); } resultList.Add(byteArray); } else { Debug.WriteLine("ber_scanf for format character 'B' failed"); } // no need to free memory as wldap32 returns the original pointer instead of a duplicating memory pointer that // needs to be freed } else if (fmt == 'v') { //null terminate strings byte[][] byteArrayresult = null; string[] stringArray = null; byteArrayresult = DecodingMultiByteArrayHelper(berElement, 'V', ref error); if (error == 0) { if (byteArrayresult != null) { stringArray = new string[byteArrayresult.Length]; for (int i = 0; i < byteArrayresult.Length; i++) { if (byteArrayresult[i] == null) { stringArray[i] = null; } else { stringArray[i] = utf8Encoder.GetString(byteArrayresult[i]); } } } resultList.Add(stringArray); } } else if (fmt == 'V') { byte[][] result = null; result = DecodingMultiByteArrayHelper(berElement, fmt, ref error); if (error == 0) { resultList.Add(result); } } else { Debug.WriteLine("Format string contains undefined character\n"); throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.BerConverterUndefineChar)); } if (error != 0) { // decode failed, just return return(decodeResult); } } decodeResult = new object[resultList.Count]; for (int count = 0; count < resultList.Count; count++) { decodeResult[count] = resultList[count]; } decodeSucceeded = true; return(decodeResult); }
public static string ByteArrayToString(byte[] byteArray, int length) { var enc = new UTF8Encoding(); return(enc.GetString(byteArray, 0, length)); }
/// <summary> /// Private accessor for all GET and POST requests. /// </summary> /// <param name="url">Web url to be accessed.</param> /// <param name="post">Place POST request information here. If a GET request, use null. </param> /// <param name="attempts"># of attemtps before sending back an empty string.</param> /// <returns>Page HTML if access was successful, otherwise will return a blank string. </returns> private String getHtml(String url, String post, int attempts) { WebClient webClient = new WebClient(); UTF8Encoding utfObj = new UTF8Encoding(); byte[] reqHTML; while (attempts > 0)// Will keep trying to access until attempts reach zero. { try { if (post != null) //If post is null, then no post request is required. reqHTML = webClient.UploadData(url, "POST", System.Text.Encoding.ASCII.GetBytes(post)); else reqHTML = webClient.DownloadData(url); String input = utfObj.GetString(reqHTML); return input; } catch (WebException e) { errorLog.WriteMessage("Could not contact to " + url + " - " + e.Message); Thread.Sleep(2000); } catch (ArgumentNullException e) { errorLog.WriteMessage("Could not retrieve data from " + url + " - " + e.Message); Thread.Sleep(2000); } attempts--; } return ""; }
public static string UTF8BytesToString(byte[] data) { UTF8Encoding utf8Encoding = new UTF8Encoding(); return(utf8Encoding.GetString(data)); }
private static void ReceiveData(IAsyncResult asyncResult) { try { int numReceived = _socket.EndReceive(asyncResult); Debug.Assert(numReceived >= 0, "Received negative amount of bytes from surface connection"); var processingOffset = 0; var bufferEnd = _receiveBufferOffset + numReceived; while (processingOffset < bufferEnd) { if (_expectedPacketSize <= 0) { if (HasPacketHeader(processingOffset)) { var header = GetPacketHeader(processingOffset); if (header.IsHeartbeat) { LastHeartbeatTime = DateTimeOffset.Now.ToUnixTimeMilliseconds(); processingOffset += header.PacketSize; } else { processingOffset = header.PacketStartOffset; _expectedPacketSize = header.PacketSize; } } else { Debug.LogWarning("Invalid packet received, skipping ahead!"); while (processingOffset < bufferEnd && !HasPacketHeader(processingOffset)) { processingOffset++; } } } else if (processingOffset + _expectedPacketSize <= bufferEnd) { byte[] rawPacket = new byte[_expectedPacketSize]; Buffer.BlockCopy(_receiveBuffer, processingOffset, rawPacket, 0, rawPacket.Length); var packet = _encoding.GetString(rawPacket); try { // messages have to be handled in main update() thread, to avoid possible threading issues in handlers var incomingPacket = JsonConvert.DeserializeObject <InPacket>(packet); _queuedCommands.Enqueue(incomingPacket); } catch (Exception e) { Debug.LogError(e.Message); Debug.LogError(packet); } processingOffset += _expectedPacketSize; _expectedPacketSize = -1; } else { // neither header nor complete package // -> currently incomplete packet in buffer, wait for rest break; } } if (processingOffset == bufferEnd) { // cleared buffer entirely, no need to rearrange memory due to incomplete packet _receiveBufferOffset = 0; } else { // incomplete packet in buffer, move to front _receiveBufferOffset = Math.Max(0, bufferEnd - processingOffset); Buffer.BlockCopy(_receiveBuffer, processingOffset, _receiveBuffer, 0, _receiveBufferOffset); } if (_receiveBuffer.Length - _receiveBufferOffset < 100) { var error = "Receive buffer getting too small, aborting receive"; Debug.LogError(error); throw new OverflowException(error); } _socket.BeginReceive(_receiveBuffer, _receiveBufferOffset, _receiveBuffer.Length - _receiveBufferOffset, SocketFlags.None, _receiveCallback, null); } catch (Exception) { // ignore } }
public IEnumerator LoadUIAsset(CUILoadState openState, UILoadRequest request) { var name = openState.TemplateName; // 具体加载逻辑 // manifest string manifestPath = ResourceDepUtils.GetBuildPath(string.Format("BundleResources/NGUI/{0}.prefab.manifest{1}", name, AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt))); var manifestLoader = KBytesLoader.Load(manifestPath, KResourceInAppPathType.PersistentAssetsPath, KAssetBundleLoaderMode.PersitentDataPathSync); while (!manifestLoader.IsCompleted) yield return null; var manifestBytes = manifestLoader.Bytes; manifestLoader.Release(); // 释放掉文本字节 var utf8NoBom = new UTF8Encoding(false); var manifestList = utf8NoBom.GetString(manifestBytes).Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); for (var i = 0; i < manifestList.Length; i++) { var depPath = manifestList[i] + AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt); var depLoader = KAssetFileLoader.Load(depPath); while (!depLoader.IsCompleted) { yield return null; } } string path = ResourceDepUtils.GetBuildPath(string.Format("BundleResources/NGUI/{0}.prefab{1}", name, KEngine.AppEngine.GetConfig("AssetBundleExt"))); var assetLoader = KStaticAssetLoader.Load(path); openState.UIResourceLoader = assetLoader; // 基本不用手工释放的 while (!assetLoader.IsCompleted) yield return null; request.Asset = assetLoader.TheAsset; }
/// <summary> /// Convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String. /// </summary> /// <param name="characters">Unicode Byte Array to be converted to String</param> /// <returns>String converted from Unicode Byte Array</returns> private String ConvertByteArrayToString(Byte[] characters) { UTF8Encoding encoding = new UTF8Encoding(); return(encoding.GetString(characters)); }
public static string UTF8ByteArrayToString(byte[] characters) { UTF8Encoding encoding = new UTF8Encoding(); string constructedString = encoding.GetString(characters); return (constructedString); }
private static string DecodeData(byte[] data) { var encoding = new UTF8Encoding(); return(encoding.GetString(data)); }
static bool ExtraUPK(string upkfilepath, string outputpath, ref List <string> pathList, IProgress progress, bool saveToFile, Action <string, byte[]> callback) { m_allFileInfoDic.Clear(); if (!outputpath.EndsWith("/")) { outputpath = outputpath + "/"; } int totalsize = 0; bool success = true; pathList = new List <string>(); FileStream upkFilestream = new FileStream(upkfilepath, FileMode.Open); try { upkFilestream.Seek(0, SeekOrigin.Begin); int offset = 0; //读取文件数量; byte[] totaliddata = new byte[4]; upkFilestream.Read(totaliddata, 0, 4); int filecount = BitConverter.ToInt32(totaliddata, 0); offset += 4; Debug.Log("filecount=" + filecount); //读取所有文件信息; for (int index = 0; index < filecount; index++) { //读取id; byte[] iddata = new byte[4]; upkFilestream.Seek(offset, SeekOrigin.Begin); upkFilestream.Read(iddata, 0, 4); int id = BitConverter.ToInt32(iddata, 0); offset += 4; //读取StartPos; byte[] startposdata = new byte[4]; upkFilestream.Seek(offset, SeekOrigin.Begin); upkFilestream.Read(startposdata, 0, 4); int startpos = BitConverter.ToInt32(startposdata, 0); offset += 4; //读取size; byte[] sizedata = new byte[4]; upkFilestream.Seek(offset, SeekOrigin.Begin); upkFilestream.Read(sizedata, 0, 4); int size = BitConverter.ToInt32(sizedata, 0); offset += 4; //读取pathLength; byte[] pathLengthdata = new byte[4]; upkFilestream.Seek(offset, SeekOrigin.Begin); upkFilestream.Read(pathLengthdata, 0, 4); int pathLength = BitConverter.ToInt32(pathLengthdata, 0); offset += 4; //读取path; byte[] pathdata = new byte[pathLength]; upkFilestream.Seek(offset, SeekOrigin.Begin); upkFilestream.Read(pathdata, 0, pathLength); string path = m_UTF8Encoding.GetString(pathdata); offset += pathLength; //添加到Dic; OneFileInfo info = new OneFileInfo(); info.m_id = id; info.m_Size = size; info.m_PathLength = pathLength; info.m_Path = path; info.m_StartPos = startpos; m_allFileInfoDic.Add(id, info); pathList.Add(path); totalsize += size; // Debug.Log ("id=" + id + " startPos=" + startpos + " size=" + size + " pathLength=" + pathLength + " path=" + path); } //释放文件; int totalprocesssize = 0; foreach (var infopair in m_allFileInfoDic) { OneFileInfo info = infopair.Value; int startPos = info.m_StartPos; int size = info.m_Size; string path = info.m_Path; //创建文件 string dirpath = outputpath + (path.LastIndexOf('/') < 0 ? "" : path.Substring(0, path.LastIndexOf('/'))); string filepath = outputpath + path; if (Directory.Exists(dirpath) == false) { Directory.CreateDirectory(dirpath); } if (File.Exists(filepath)) { File.Delete(filepath); } FileStream fileStream = null; if (saveToFile) { fileStream = new FileStream(filepath, FileMode.Create); } MemoryStream memoryStream = new MemoryStream(); try { byte[] tmpfiledata; int processSize = 0; while (processSize < size) { if (size - processSize < 1024) { tmpfiledata = new byte[size - processSize]; } else { tmpfiledata = new byte[1024]; } //读取; upkFilestream.Seek(startPos + processSize, SeekOrigin.Begin); upkFilestream.Read(tmpfiledata, 0, tmpfiledata.Length); //写入; if (saveToFile) { fileStream.Write(tmpfiledata, 0, tmpfiledata.Length); } memoryStream.Write(tmpfiledata, 0, tmpfiledata.Length); processSize += tmpfiledata.Length; totalprocesssize += tmpfiledata.Length; if (progress != null) { progress.SetProgress((long)totalprocesssize, (long)totalsize); } } if (saveToFile) { fileStream.Flush(); } if (callback != null) { callback(filepath, memoryStream.ToArray()); } } catch (Exception e) { Debug.LogError(e.Message); Debug.LogError(e.StackTrace); success = false; } finally { if (saveToFile) { fileStream.Close(); } memoryStream.Close(); } } } catch (Exception e) { Debug.LogError(e.Message); Debug.LogError(e.StackTrace); success = false; } finally { upkFilestream.Close(); } return(success); }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_GetAniDBTitles"); try { bool process = (ServerSettings.AniDB_Username.Equals("jonbaby", StringComparison.InvariantCultureIgnoreCase) || ServerSettings.AniDB_Username.Equals("jmediamanager", StringComparison.InvariantCultureIgnoreCase)); if (!process) { return; } string url = Constants.AniDBTitlesURL; logger.Trace("Get AniDB Titles: {0}", url); Stream s = Utils.DownloadWebBinary(url); int bytes = 2048; byte[] data = new byte[2048]; StringBuilder b = new StringBuilder(); UTF8Encoding enc = new UTF8Encoding(); ICSharpCode.SharpZipLib.GZip.GZipInputStream zis = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(s); while ((bytes = zis.Read(data, 0, data.Length)) > 0) { b.Append(enc.GetString(data, 0, bytes)); } zis.Close(); AniDB_Anime_TitleRepository repTitles = new AniDB_Anime_TitleRepository(); string[] lines = b.ToString().Split('\n'); Dictionary <int, AnimeIDTitle> titles = new Dictionary <int, AnimeIDTitle>(); foreach (string line in lines) { if (line.Trim().Length == 0 || line.Trim().Substring(0, 1) == "#") { continue; } string[] fields = line.Split('|'); int animeID = 0; int.TryParse(fields[0], out animeID); if (animeID == 0) { continue; } string titleType = fields[1].Trim().ToLower(); //string language = fields[2].Trim().ToLower(); string titleValue = fields[3].Trim(); AnimeIDTitle thisTitle = null; if (titles.ContainsKey(animeID)) { thisTitle = titles[animeID]; } else { thisTitle = new AnimeIDTitle(); thisTitle.AnimeIDTitleId = 0; thisTitle.MainTitle = titleValue; thisTitle.AnimeID = animeID; titles[animeID] = thisTitle; } if (!string.IsNullOrEmpty(thisTitle.Titles)) { thisTitle.Titles += "|"; } if (titleType.Equals("1")) { thisTitle.MainTitle = titleValue; } thisTitle.Titles += titleValue; } foreach (AnimeIDTitle aniTitle in titles.Values) { //AzureWebAPI.Send_AnimeTitle(aniTitle); CommandRequest_Azure_SendAnimeTitle cmdAzure = new CommandRequest_Azure_SendAnimeTitle(aniTitle.AnimeID, aniTitle.MainTitle, aniTitle.Titles); cmdAzure.Save(); } } catch (Exception ex) { logger.Error("Error processing CommandRequest_GetAniDBTitles: {0}", ex.ToString()); return; } }
/* loads input from a file */ public void loadFile() { string fileString = ""; UTF8Encoding utf8 = new UTF8Encoding(); try { Console.Write("\nInput file name: "); fileString = Console.ReadLine(); Console.WriteLine(); string output = ""; byte[] bytes = File.ReadAllBytes(fileString); BitArray bits = new BitArray(bytes); for (int i=0;i!=bits.Length;i+=1) { output += (bits[i] ? '1' : '0'); } String inputText = utf8.GetString(bytes); Console.WriteLine(inputText); this.inputText_ = output; } catch (Exception) { Console.WriteLine("> File not found. Try again."); loadFile(); } }
public async Task <string> EncryptString(string textToEncrypt) { var encryptedBytes = await EncryptBytes(encoding.GetBytes(textToEncrypt)); return(encoding.GetString(encryptedBytes, 0, encryptedBytes.Length)); }
/// <summary> /// Pega um valor previamente criptografado e retorna o valor inicial /// </summary> /// <param name="text">texto criptografado</param> /// <returns>valor descriptografado</returns> public static string Decrypt(string text) { try { // Se a string não está vazia, executa a criptografia if (!string.IsNullOrEmpty(text)) { // Cria instancias de vetores de bytes com as chaves byte[] bKey = Convert.FromBase64String(cryptoKey); byte[] bText = Convert.FromBase64String(text); // Instancia a classe de criptografia Rijndael Rijndael rijndael = new RijndaelManaged(); // Define o tamanho da chave "256 = 8 * 32" // Lembre-se: chaves possíves: // 128 (16 caracteres), 192 (24 caracteres) e 256 (32 caracteres) rijndael.KeySize = 256; // Cria o espaço de memória para guardar o valor DEScriptografado: MemoryStream mStream = new MemoryStream(); // Instancia o Decriptador CryptoStream decryptor = new CryptoStream( mStream, rijndael.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write); // Faz a escrita dos dados criptografados no espaço de memória decryptor.Write(bText, 0, bText.Length); // Despeja toda a memória. decryptor.FlushFinalBlock(); // Instancia a classe de codificação para que a string venha de forma correta UTF8Encoding utf8 = new UTF8Encoding(); // Com o vetor de bytes da memória, gera a string descritografada em UTF8 return utf8.GetString(mStream.ToArray()); } else { // Se a string for vazia retorna nulo return null; } } catch (Exception ex) { // Se algum erro ocorrer, dispara a exceção throw new ApplicationException("Erro ao descriptografar", ex); } }
static void Main() { Console.Write("Enter server name: "); var serverName = Console.ReadLine(); if (serverName.Contains(' ')) { throw new Exception("Server name cannot contain spaces."); } Console.Write("Use (T)ext or (J)son? "); ConsoleKey keyResponse; do { keyResponse = Console.ReadKey().Key; } while (keyResponse != ConsoleKey.T && keyResponse != ConsoleKey.J); var json = keyResponse == ConsoleKey.J; Console.WriteLine(); Console.WriteLine("Initiating..."); Initiator.AutoMapperConfig(); Console.WriteLine("Creating new game..."); var world = new WorldMap(); Console.WriteLine("Starting server..."); Socket listeningSocket = null; var clients = new List <Client>(); var responseQueue = new Queue <Response>(); var unconfirmedConnections = new List <Socket>(); var currentPlayerIndex = 0; //try //{ listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listeningSocket.Bind(localEndPoint); listeningSocket.Listen(LISTENERBACKLOG); Console.WriteLine("Informing master server..."); using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Connect(IPAddress.Loopback, MASTERPORT); NetHelpers.SendString($"WAMP/1.0 ADD {serverName} {PORT}", socket); socket.Shutdown(SocketShutdown.Both); } Console.WriteLine($"WWAServer is listening on {listeningSocket.LocalEndPoint}. Press Q to quit."); while (true) { if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Q) { break; } // Check for dead connections for (int i = 0; i < unconfirmedConnections.Count; i++) { if (IsDisconnected(unconfirmedConnections[i])) { Console.WriteLine($"{unconfirmedConnections[i].RemoteEndPoint} disconnected."); unconfirmedConnections[i].Close(); unconfirmedConnections.RemoveAt(i--); } } for (int i = 0; i < clients.Count; i++) { if (IsDisconnected(clients[i].Socket)) { Console.WriteLine($"{clients[i].Socket.RemoteEndPoint} ({clients[i].Player.Name}) disconnected."); responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.REMOVEPLAYER, IdParam = clients[i].Player.PlayerId }); clients[i].Socket.Close(); clients.RemoveAt(i--); if (clients.Count <= currentPlayerIndex) { currentPlayerIndex = 0; UpdateMap(world, clients, responseQueue, json); } } } // Check for new logins if (clients.Count < 5) { for (int i = 0; i < unconfirmedConnections.Count; i++) { var connection = unconfirmedConnections[i]; if (connection.Available > 0) { var buffer = new byte[BUFFERLENGTH]; var bytesReceived = connection.Receive(buffer); var command = encoding.GetString(buffer, 0, bytesReceived); command = command.TrimEnd(';'); string[] parts; // Ignore any command that is not LOGIN if (command.StartsWith("WAP/1.0 LOGIN") && (parts = command.Split(' ')).Length == 4) { var name = parts[2]; var password = parts[3]; var model = _repository.GetByName(parts[2]); Player player = null; if (model == null) //Finns inte i databasen { responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.WELCOME, Socket = connection }); player = new Player(GetFirstFreeId(clients), name, 100, 10, 0, world.GetRandomFreeCoords(clients)); model = Initiator.Mapper.Map <PlayerModel>(player); model.Password = password; model.LastLogin = DateTime.Now; _repository.Add(model); responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.NEWPLAYER, IdParam = player.PlayerId }); clients.Add(new Client { Player = player, Socket = connection }); unconfirmedConnections.RemoveAt(i--); if (clients.Count == 2) { responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.YOURTURN, IdParam = clients[currentPlayerIndex].Player.PlayerId }); } Console.WriteLine($"{connection.RemoteEndPoint} created player {player.Name}"); } else //Finns i databasen { if (clients.Select(c => c.Player.Name).Contains(model.Name)) { Console.WriteLine($"{connection.RemoteEndPoint} tried to log in with {model.Name} already in game"); responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.DENIED, Socket = connection, StringParam = "LOGIN Player already in game" }); } else if (model.Password == password) { responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.WELCOME, Socket = connection }); model.LastLogin = DateTime.Now; _repository.Update(model); player = Initiator.Mapper.Map <Player>(model); player.Coordinates = world.GetRandomFreeCoords(clients); player.PlayerId = GetFirstFreeId(clients); responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.NEWPLAYER, IdParam = player.PlayerId }); clients.Add(new Client { Player = player, Socket = connection }); unconfirmedConnections.RemoveAt(i--); if (clients.Count == 2) { responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.YOURTURN, IdParam = clients[currentPlayerIndex].Player.PlayerId }); } Console.WriteLine($"{connection.RemoteEndPoint} logged in as {player.Name}"); } else { Console.WriteLine($"{connection.RemoteEndPoint} failed password for {model.Name}"); responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.DENIED, Socket = connection, StringParam = "LOGIN Wrong password" }); } } } } } } // Accept new connections if (unconfirmedConnections.Count < 20 && listeningSocket.Poll(1000, SelectMode.SelectRead)) { var newConnection = listeningSocket.Accept(); Console.WriteLine($"New connection accepted from {newConnection.RemoteEndPoint}"); unconfirmedConnections.Add(newConnection); } // Get player commands foreach (var client in clients) { if (client.Socket.Available > 0) { var buffer = new byte[BUFFERLENGTH]; var bytesReceived = client.Socket.Receive(buffer); var command = encoding.GetString(buffer, 0, bytesReceived); //Console.WriteLine($"{command} <- {client.Socket.RemoteEndPoint}"); command = command.TrimEnd(';'); string[] parts = command.Split(' '); if (parts.Length < 2 || parts[0] != "WAP/1.0") { continue; } switch (parts[1]) { case "MOVE": if (clients.IndexOf(client) != currentPlayerIndex || clients.Count < 2) { responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.DENIED, Socket = client.Socket, StringParam = "MOVE Not your turn" }); } else if (parts.Length < 3) { responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.DENIED, Socket = client.Socket, StringParam = "MOVE invalid direction" }); } else { var result = world.MovePlayer(client.Player, parts[2], clients); switch (result.MoveResult) { case MoveResult.Fail: responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.DENIED, Socket = client.Socket, StringParam = "MOVE You cannot move that way" }); break; case MoveResult.Success: responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.UPDATEPLAYER, IdParam = client.Player.PlayerId }); break; case MoveResult.Gold: case MoveResult.Potion: responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.UPDATETILE, StringParam = EncodeTile(world, client.Player.Coordinates, json) }); responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.UPDATEPLAYER, IdParam = client.Player.PlayerId }); UpdateDbStats(_repository, client.Player); break; case MoveResult.Player: if (result.Player.Health <= 0) { world.GameMap[result.Player.Coordinates.X, result.Player.Coordinates.Y].Gold = result.Player.Gold; result.Player.Gold = 0; result.Player.Coordinates = world.GetRandomFreeCoords(clients); result.Player.Health = 100; result.Player.IsDead = false; } responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.UPDATEPLAYER, IdParam = result.Player.PlayerId }); UpdateDbStats(_repository, result.Player); break; } if (result.MoveResult != MoveResult.Fail) { if (++currentPlayerIndex >= clients.Count) { currentPlayerIndex = 0; UpdateMap(world, clients, responseQueue, json); } responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.YOURTURN, IdParam = clients[currentPlayerIndex].Player.PlayerId }); } } break; case "MESSAGE": if (parts.Length < 3) { responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.DENIED, Socket = client.Socket, StringParam = "MESSAGE Malformed message" }); } else { responseQueue.Enqueue(new Response { ResponseType = Response.MessageType.MESSAGE, IdParam = client.Player.PlayerId, StringParam = command.Substring("WAP/1.0 MESSAGE ".Length) }); } break; } } } // Fire off responses while (responseQueue.Count > 0) { var response = responseQueue.Dequeue(); switch (response.ResponseType) { case Response.MessageType.NEWPLAYER: Response.SendNewPlayerResponses(clients, world, response.IdParam, json); break; case Response.MessageType.DENIED: Response.SendDeniedResponse(clients, response.Socket, response.StringParam); break; case Response.MessageType.REMOVEPLAYER: Response.SendRemovePlayerResponse(clients, response.IdParam); break; case Response.MessageType.UPDATETILE: Response.SendUpdateTile(clients, response.StringParam); break; case Response.MessageType.YOURTURN: Response.SendYourTurn(clients, response.IdParam); break; case Response.MessageType.UPDATEPLAYER: Response.SendUpdatePlayer(clients, response.IdParam, json); break; case Response.MessageType.MESSAGE: Response.SendMessage(clients, response.IdParam, response.StringParam); break; case Response.MessageType.WELCOME: Response.SendWelcome(response.Socket, json); break; } } } // End while //} //catch (Exception exception) //{ // Console.WriteLine(exception.Message); // Console.ReadLine(); //} //finally //{ // listeningSocket?.Close(); //} using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Connect(IPAddress.Loopback, MASTERPORT); NetHelpers.SendString($"WAMP/1.0 REMOVE {PORT}", socket); socket.Shutdown(SocketShutdown.Both); } }
public MatchCollection procuraExpressaoHTML(string expressaoRegular, string url) { byte[] reqHTML; Regex expressao = new Regex(expressaoRegular); WebClient webClient = new WebClient(); reqHTML = webClient.DownloadData(url); UTF8Encoding objUTF8 = new UTF8Encoding(); string webpage = objUTF8.GetString(reqHTML); MatchCollection listaComparacoes = expressao.Matches(webpage); return listaComparacoes; }
public static string ByteArrayToStr(byte[] barr) { UTF8Encoding encoding = new UTF8Encoding(); return(encoding.GetString(barr, 0, barr.Length)); }