public void In( [FriendlyName("Key", "The string to be used to generate the hash from.")] string Key, [FriendlyName("SHA1 Hash", "The SHA1 Hash generated by the Key.")] out string Hash ) { if (Key != "") { UTF8Encoding ue = new UTF8Encoding(); byte[] bytes = ue.GetBytes(Key); // encrypt bytes SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] hashBytes = sha1.ComputeHash(bytes); // Convert the encrypted bytes back to a string (base 16) string tmpHash = ""; for (int i = 0; i < hashBytes.Length; i++) { tmpHash += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0'); } Hash = tmpHash.PadLeft(32, '0'); } else { uScriptDebug.Log("[Generate SHA1 Hash] The Key provided was empty, returning an empty string for the SHA1 Hash.", uScriptDebug.Type.Warning); Hash = ""; } }
public virtual void Post(string url, Dictionary<string, string> data, System.Action<HttpResult> onResult) { this.MakeRequest(url, HttpMethods.POST, onResult, (r) => { JSONObject js = new JSONObject(data); var requestPayload = js.ToString(); UTF8Encoding encoding = new UTF8Encoding(); r.ContentLength = encoding.GetByteCount(requestPayload); r.Credentials = CredentialCache.DefaultCredentials; r.Accept = "application/json"; r.ContentType = "application/json"; //Write the payload to the request body. using ( Stream requestStream = r.GetRequestStream()) { requestStream.Write(encoding.GetBytes(requestPayload), 0, encoding.GetByteCount(requestPayload)); } return false; }); }
public void In( [FriendlyName("Key", "The string to be used to check against the provided SHA1 hash.")] string Key, [FriendlyName("SHA1 Hash", "The SHA1 Hash to check the key against.")] string Hash ) { if (Key != "" && Hash != "") { UTF8Encoding ue = new UTF8Encoding(); byte[] bytes = ue.GetBytes(Key); // encrypt bytes SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] hashBytes = sha1.ComputeHash(bytes); // Convert the encrypted bytes back to a string (base 16) string tmpHash = ""; for (int i = 0; i < hashBytes.Length; i++) { tmpHash += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0'); } string finalHash = tmpHash.PadLeft(32, '0'); if (finalHash == Hash) { m_GoodHash = true; } } }
// Token: 0x06000EF7 RID: 3831 RVA: 0x00045348 File Offset: 0x00043548 public static string Encrypt(string unencrypted) { RijndaelManaged rijndaelManaged = new RijndaelManaged(); ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(SimpleAES.key, SimpleAES.vector); UTF8Encoding uTF8Encoding = new UTF8Encoding(); return Convert.ToBase64String(SimpleAES.Encrypt(uTF8Encoding.GetBytes(unencrypted), encryptor)); }
public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetBytes(Char[],Int32,Int32,Byte[],Int32) with non-null chars"); try { Byte[] bytes; Char[] chars = new Char[] { '\u0023', '\u0025', '\u03a0', '\u03a3' }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 1, 2); bytes = new Byte[byteCount]; int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, 0); } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
public static DataSet ToDataSet(DataSetData dsd) { DataSet ds = new DataSet(); UTF8Encoding encoding = new UTF8Encoding(); Byte[] byteArray = encoding.GetBytes(dsd.DataXML); MemoryStream stream = new MemoryStream(byteArray); XmlReader reader = new XmlTextReader(stream); ds.ReadXml(reader); XDocument xd = XDocument.Parse(dsd.DataXML); foreach (DataTable dt in ds.Tables) { var rs = from row in xd.Descendants(dt.TableName) select row; int i = 0; foreach (var r in rs) { DataRowState state = (DataRowState)Enum.Parse(typeof(DataRowState), r.Attribute("RowState").Value); DataRow dr = dt.Rows[i]; dr.AcceptChanges(); if (state == DataRowState.Deleted) dr.Delete(); else if (state == DataRowState.Added) dr.SetAdded(); else if (state == DataRowState.Modified) dr.SetModified(); i++; } } return ds; }
/// <summary> /// Main constructor of the Tag. This reads information from the given filename and initializes all fields of the tag. /// It's important to know that this constructor has a considerable weight in term of processor time because it calculates two SHA1 hash: /// one for the entire file and one for the relevant tag information. /// </summary> /// <param name="filename">Filename from whom extract the information for the tag</param> public CompleteTag(string filename) { byte[] retVal; SHA1 crypto = new SHA1CryptoServiceProvider(); using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { retVal = crypto.ComputeHash(file); file.Close(); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } this.FileHash= sb.ToString(); this.FillTag(filename); System.Text.UTF8Encoding enc= new UTF8Encoding(); byte[] tHashByte = crypto.ComputeHash(enc.GetBytes(this.contentString())); crypto.ComputeHash(tHashByte); sb.Clear(); for (int i = 0; i < tHashByte.Length; i++) { sb.Append(tHashByte[i].ToString("x2")); } this.TagHash = sb.ToString(); }
public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetBytes(String,Int32,Int32,Byte[],Int32) with null chars"); try { Byte[] bytes; String chars = ""; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = chars.Length; bytes = new Byte[byteCount]; int bytesEncodedCount = utf8.GetBytes(chars, 0, byteCount, bytes, 0); if (bytesEncodedCount != 0) { TestLibrary.TestFramework.LogError("002.1", "Method GetBytes Err."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
public static string get_uft8(string unicodeString) { UTF8Encoding utf8 = new UTF8Encoding(); byte[] encodedBytes = utf8.GetBytes(unicodeString); string decodedString = utf8.GetString(encodedBytes); return decodedString; }
static AesEncryptor() { encoder = new UTF8Encoding(); RijndaelManaged rijndaelManaged = new RijndaelManaged(); rijndaelManaged.Key = encoder.GetBytes(keyString).Take(keySize).ToArray(); rijndael = rijndaelManaged; rijndael.BlockSize = 128; }
public static string HashMD5(string phrase) { if (phrase == null) return null; var encoder = new UTF8Encoding(); var md5Hasher = new MD5CryptoServiceProvider(); var hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(phrase)); return ByteArrayToHexString(hashedDataBytes); }
public void PosTest1() { Byte[] bytes; String chars = "UTF8 Encoding Example"; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = chars.Length; bytes = new Byte[byteCount]; int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, 0); }
public static byte[] EncryptRSA(string publicKeyAsPem, string payload, string passphrase = null) { var encoder = new UTF8Encoding(); byte[] byte_payload = encoder.GetBytes(payload); CryptoKey d = CryptoKey.FromPublicKey(publicKeyAsPem, passphrase); OpenSSL.Crypto.RSA rsa = d.GetRSA(); byte[] result = rsa.PublicEncrypt(byte_payload, OpenSSL.Crypto.RSA.Padding.PKCS1); rsa.Dispose(); return result; }
protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { try { if (txtNewPass.Text!="" && txtNewPassRepeat.Text!="") { Literal1.Text = ""; var query1 = context.ForgotPasswords.Where(v => v.VerificationCode == VCod).FirstOrDefault(); int UserId = query1.UserId; var query = context.Users.Where(u => u.UserId == UserId).SingleOrDefault(); string NewPass = txtNewPass.Text; string RpNewPass = txtNewPassRepeat.Text; MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); Byte[] hashedBytes; UTF8Encoding encoder = new UTF8Encoding(); hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(NewPass)); if (NewPass == RpNewPass) { query.Password = hashedBytes; context.SubmitChanges(); context.ForgotPasswords.DeleteOnSubmit(query1); context.SubmitChanges(); lblsucces.Visible = true; Imageok.Visible = true; } else { Literal1.Text = "<p class='FormValidation'>کلمه عبور و تکرار آن را وارد نمایید!</p>"; } } } catch (Exception) { Response.Redirect("~/Default.aspx"); } }
public void NegTest2() { Byte[] bytes; String chars = "UTF8 Encoding Example"; UTF8Encoding utf8 = new UTF8Encoding(); bytes = null; Assert.Throws<ArgumentNullException>(() => { int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, 0); }); }
public void PosTest2() { Byte[] bytes; String chars = ""; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = chars.Length; bytes = new Byte[byteCount]; int bytesEncodedCount = utf8.GetBytes(chars, 0, byteCount, bytes, 0); Assert.Equal(0, bytesEncodedCount); }
public void NegTest3() { Byte[] bytes; String chars = "UTF8 Encoding Example"; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = chars.Length; bytes = new Byte[byteCount]; Assert.Throws<ArgumentOutOfRangeException>(() => { int bytesEncodedCount = utf8.GetBytes(chars, -1, 2, bytes, 0); }); }
public void PosTest2() { Byte[] bytes; Char[] chars = new Char[] { }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 0, 0); bytes = new Byte[byteCount]; int bytesEncodedCount = utf8.GetBytes(chars, 0, 0, bytes, 0); Assert.Equal(0, bytesEncodedCount); }
protected void Button_Login_Click(object sender, EventArgs e) { var salt = ""; string kode = ""; SqlConnection conn = new SqlConnection(MyConnectionString.ConnectionString); // MyConnectionString.ConnectionString er fra en class som gør det lettere og skrive sin connectionstring. SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; // Standard connection til din database. cmd.CommandText = @" SELECT bruger_id, bruger_navn, bruger_email, bruger_password, bruger_salt, rolle_adgang FROM bruger INNER JOIN rolle ON rolle_id = fk_rolle_id WHERE bruger_email = @bruger_email"; // Din CommandText hvor du fortæller hvad den skal loade fra db. cmd.Parameters.AddWithValue("@bruger_email", TextBox_Email.Text); conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { salt = reader["bruger_salt"].ToString(); // Henter salt fra db. Salt bruges til når man skal krypterer koden så sætter man salt bag ved koden og så kryptere man koden. // Så hvis der er 2 der har koden 123, så er deres kode ikke ens efter den er krypteret. kode = reader["bruger_password"].ToString(); // Henter password fra db så vi kan se om koden er ens. var password = TextBox_Password.Text; // Tager koden som er indtastet i texboxen. UTF8Encoding encoder = new UTF8Encoding(); // Gør klar så vi encoder koden om til UTF8. SHA256Managed sha256hasher = new SHA256Managed(); // Gør klar til at lave kryptering. byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(password + salt)); // Her sætter vi koden (textboxen) og salted (fra db) og laver det til bytes efter, da ComputeHash kun kan bruge bytes. StringBuilder hash = new StringBuilder(""); // Laver en string builder så vi kan samle alle bytes til en string. for (int i = 0; i < hashedDataBytes.Length; i++) // For hver bytes hash.Append(hashedDataBytes[i].ToString("X2")); // Her laver vi bytesne om til Hexadecimal. if (hash.ToString() == kode) // Nu tjekker vi om de koder er ens. Vi blev nød til at kryptere koden (fra texboxen) da koden fra db er kryptere og vi ikke kan dekryptere koden. { Session["bruger_id"] = reader["bruger_id"]; // Hvis koden er ens laver vi en masse sessions, så vi kan bruge dem hvis vi får brug for dem. Session["bruger_navn"] = reader["bruger_navn"]; Session["bruger_email"] = reader["bruger_email"]; Session["rolle_adgang"] = reader["rolle_adgang"]; Session.Remove("besked"); Response.Redirect(ResolveClientUrl("~/Admin/Default.aspx")); } else // Hvis koden ikke er ens. { Label_Errors.Text = "Forkert Email eller Password"; Label_Errors.Visible = true; } } else // Hvis emailen ikke er findes. Af sikkerheds mæssige grunde fortæller vi ikke at det er emailen som er forkert. { Label_Errors.Text = "Forkert Email eller Password"; Label_Errors.Visible = true; } conn.Close(); }
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 void NegTest1() { Byte[] bytes; Char[] chars = null; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = 10; bytes = new Byte[byteCount]; Assert.Throws<ArgumentNullException>(() => { int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, 0); }); }
protected void ImageButtonLogin_Click(object sender, ImageClickEventArgs e) { AccessControl ac = new AccessControl(); if (!ac.getSectionAccess("Login")) { LabelLoginError.Text = "با عرض پوزش ورود به سیستم موقتاً در سایت غیر فعال می باشد."; LabelLoginError.Visible = true; } else { string loginEmail = TextBoxLoginEmail.Text; MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); Byte[] PassByte; UTF8Encoding encoder = new UTF8Encoding(); PassByte = md5Hasher.ComputeHash(encoder.GetBytes(TextBoxLoginPassword.Text)); var query = context.Users.Where(u => u.Email == loginEmail && u.Password == PassByte).SingleOrDefault(); if (query != null) { LabelLoginError.Visible = false; Session["UserId"] = query.UserId; int Hours = 2; string VerificationCode = Convert.ToString(Guid.NewGuid()); if (CheckBoxLoginRemember.Checked) { Hours = 168; } LoginSession ls = new LoginSession(); ls.setLoginSession(Convert.ToInt32(query.UserId), VerificationCode, Hours); HttpCookie _userInfoCookies = new HttpCookie("VC"); _userInfoCookies["VC"] = VerificationCode; _userInfoCookies.Expires = DateTime.Now.AddHours(Hours); Response.Cookies.Add(_userInfoCookies); query.LastLogin = DateTime.Now; context.SubmitChanges(); Response.Redirect("~/Panel.aspx"); } else { LabelLoginError.Visible = true; } } }
private static string ConstructGravatarUrl(string email) { var md5Hasher = MD5.Create(); var utf8 = new UTF8Encoding(); var emailHash = md5Hasher.ComputeHash(utf8.GetBytes(email)); var s = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < emailHash.Length; i++) s.Append(emailHash[i].ToString("x2")); return s.ToString(); }
public static string Md5(string strToEncrypt) { UTF8Encoding ue = new UTF8Encoding(); byte[] bytes = ue.GetBytes(strToEncrypt); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hashBytes = md5.ComputeHash(bytes); string hashString = ""; for (int i = 0; i < hashBytes.Length; i++) { hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0'); } return hashString.PadLeft(32, '0'); }
public void PosTest1() { Byte[] bytes; Char[] chars = new Char[] { '\u0023', '\u0025', '\u03a0', '\u03a3' }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 1, 2); bytes = new Byte[byteCount]; int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, 0); }
public void NegTest2() { Byte[] bytes; Char[] chars = new Char[] { '\u0023', '\u0025', '\u03a0', '\u03a3' }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 1, 2); bytes = null; Assert.Throws<ArgumentNullException>(() => { int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, 0); }); }
public static string MD5FromString(string strToEncrypt) { UTF8Encoding ue = new UTF8Encoding(); byte[] bytes = ue.GetBytes(strToEncrypt); // encrypt bytes MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hashBytes = md5.ComputeHash(bytes); // Convert the encrypted bytes back to a string (base 16) string hashString = ""; for (int i = 0; i < hashBytes.Length; i++) { hashString += Convert.ToString(hashBytes[i], 16).PadLeft(2, '0'); } return hashString.PadLeft(32, '0'); }
/// <summary> /// Tjekker om man har indtastet al infomation og tilføjer en bruger. /// </summary> protected void Button_Save_Click(object sender, EventArgs e) { var fejl = false; if (TextBox_Name.Text == "") // Hvis TexBoxen er tom. { fejl = true; // Fortæller en der er sket en fejl så den ikke prøve og tilføje brugeren. eName.Attributes.Add("class", "form-group has-error"); // Gør TexBoxen rød så man kan se at det er den der er problemet. } if (TextBox_Email.Text == "") // Hvis TexBoxen er tom. { fejl = true; // Fortæller en der er sket en fejl så den ikke prøve og tilføje brugeren. eEmail.Attributes.Add("class", "form-group has-error");// Gør TexBoxen rød så man kan se at det er den der er problemet. } if (!fejl) // Hvis der ikke sker en fejl så skal den udfører dette. { var salt = Guid.NewGuid().ToString(); // Opretter et salt som er unique som bruges til at tilføje efter koden. var password = TextBox_Password.Text; // Tager koden som er indtastet i texboxen. UTF8Encoding encoder = new UTF8Encoding(); // Gør klar så vi encoder koden om til UTF8. SHA256Managed sha256hasher = new SHA256Managed(); // Gør klar til at lave kryptering. byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(password + salt)); // Her sætter vi koden (textboxen) og salted (fra db) og laver det til bytes efter, da ComputeHash kun kan bruge bytes. StringBuilder hash = new StringBuilder(""); // Laver en string builder så vi kan samle alle bytes til en string. for (int i = 0; i < hashedDataBytes.Length; i++) // For hver bytes hash.Append(hashedDataBytes[i].ToString("X2")); // Her laver vi bytesne om til Hexadecimal. var cmd = new SqlCommand(); var conn = new SqlConnection(MyConnectionString.ConnectionString); // MyConnectionString.ConnectionString er fra en class som gør det lettere og skrive sin connectionstring. cmd.Connection = conn; // Standard connection til din database. cmd.CommandText = cmd.CommandText = "INSERT INTO bruger (bruger_navn, bruger_email, bruger_password, bruger_salt, fk_rolle_id, bruger_dato) VALUES (@1, @2, @3, @4, @5, @6)"; // Din CommandText hvor du fortæller hvad den skal loade fra db. cmd.Parameters.AddWithValue("@1", TextBox_Name.Text); // Dit parameter som laver sikkerhed for sql injection. cmd.Parameters.AddWithValue("@2", TextBox_Email.Text); cmd.Parameters.AddWithValue("@3", hash.ToString()); cmd.Parameters.AddWithValue("@4", salt); cmd.Parameters.AddWithValue("@5", DropDownList_Role.SelectedValue); cmd.Parameters.AddWithValue("@6", DateTime.Now); conn.Open(); // Åbner din connection så så du kan Execute og få din data ud. cmd.ExecuteNonQuery(); // Gør hvad du fortæller den skal gøre som står i din CommandText. conn.Close(); // Lukker din connection så den ved at du ikke skal bruge mere data. Response.Redirect("OprerBruger.aspx"); // Sender personen til siden igen så der ikke er daten som lige er blevet sendt. } }
protected void Page_Load(object sender, EventArgs e) { int eventId = QueryHelper.GetInteger("eventid", 0); EventLogInfo ev = EventLogProvider.GetEventLogInfo(eventId); // Set edited object EditedObject = ev; if (ev != null) { UTF8Encoding enc = new UTF8Encoding(); string text = HTMLHelper.StripTags(HttpUtility.HtmlDecode(EventLogHelper.GetEventText(ev))); byte[] file = enc.GetBytes(text); Response.AddHeader("Content-disposition", "attachment; filename=eventdetails.txt"); Response.ContentType = "text/plain"; Response.BinaryWrite(file); RequestHelper.EndResponse(); } }
IEnumerator _Connect(Uri uri) { isDone = false; connected = false; exception = null; //var host = uri.Host + (uri.Port == 80 ? "" : ":" + uri.Port.ToString ()); var req = new Request("GET", uri.ToString()); req.headers.Set("Upgrade", "websocket"); req.headers.Set("Connection", "Upgrade"); var key = WebSocketKey(); req.headers.Set("Sec-WebSocket-Key", key); req.headers.Add("Sec-WebSocket-Protocol", "chat, superchat"); req.headers.Set("Sec-WebSocket-Version", "13"); req.headers.Set("Origin", "null"); req.acceptGzip = false; yield return(req.Send()); if (req.exception != null) { exception = req.exception; } else { if (req.response.headers.Get("Upgrade").ToLower() == "websocket" && req.response.headers.Get("Connection").ToLower() == "upgrade") { var receivedKey = req.response.headers.Get("Sec-Websocket-Accept").ToLower(); #if UNITY_WP8 var keyBytes = enc.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); var sha = new Org.BouncyCastle.Crypto.Digests.Sha1Digest(); sha.BlockUpdate(keyBytes, 0, keyBytes.Length); var hashBytes = new byte[20]; sha.DoFinal(hashBytes, 0); var computedKey = System.Convert.ToBase64String(hashBytes).ToLower(); #else var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider(); sha.ComputeHash(enc.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); var computedKey = System.Convert.ToBase64String(sha.Hash).ToLower(); #endif if (computedKey == receivedKey) { //good to go connected = true; connection = req.upgradedConnection; outgoingWorkerThread = new Thread(OutgoingWorker); outgoingWorkerThread.Start(); incomingWorkerThread = new Thread(IncomingWorker); incomingWorkerThread.Start(); UniWeb.Instance.StartCoroutine(Dispatcher()); UniWeb.Instance.OnQuit(() => { Close(CloseEventCode.CloseEventCodeGoingAway, "Quit"); req.upgradedConnection.Dispose(); }); if (OnConnect != null) { OnConnect(); } } else { //invalid connected = false; } } } isDone = true; }
static void Main(string[] args) { String logName = "Application"; String queryString = "*[System/Level=2]"; UdpClient _udpClient; String host = "192.168.1.28"; UTF8Encoding _encoding = new UTF8Encoding(); EventLogQuery eventsQuery = new EventLogQuery(logName, PathType.LogName, queryString); EventLogReader logReader; Console.WriteLine("Querying the Application channel event log for all events..."); try { // Query the log logReader = new EventLogReader(eventsQuery); } catch (EventLogNotFoundException e) { Console.WriteLine("Failed to query the log!"); Console.WriteLine(e); return; } ////// // This section creates a list of XPath reference strings to select // the properties that we want to display // In this example, we will extract the User, TimeCreated, EventID and EventRecordID ////// // Array of strings containing XPath references String[] xPathRefs = new String[4]; xPathRefs[0] = "Event/System/Security/@UserID"; xPathRefs[1] = "Event/System/TimeCreated/@SystemTime"; xPathRefs[2] = "Event/System/EventID"; xPathRefs[3] = "Event/System/EventRecordID"; // Place those strings in an IEnumberable object IEnumerable <String> xPathEnum = xPathRefs; // Create the property selection context using the XPath reference EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum); _udpClient = new UdpClient(); _udpClient.Connect(host, 5140); int numberOfEvents = 0; // For each event returned from the query for (EventRecord eventInstance = logReader.ReadEvent(); eventInstance != null; eventInstance = logReader.ReadEvent()) { IList <object> logEventProps; try { // Cast the EventRecord into an EventLogRecord to retrieve property values. // This will fetch the event properties we requested through the // context created by the EventLogPropertySelector logEventProps = ((EventLogRecord)eventInstance).GetPropertyValues(logPropertyContext); Console.WriteLine("Event {0} :", ++numberOfEvents); Console.WriteLine("User: {0}", logEventProps[0]); Console.WriteLine("TimeCreated: {0}", logEventProps[1]); Console.WriteLine("EventID: {0}", logEventProps[2]); Console.WriteLine("EventRecordID : {0}", logEventProps[3]); // Event properties can also be retrived through the event instance Console.WriteLine("Event Description:" + eventInstance.FormatDescription()); Console.WriteLine("MachineName: " + eventInstance.MachineName); Console.WriteLine("=================== START ===================="); Console.WriteLine(eventInstance.ToXml()); Console.WriteLine("=============================================="); String xmlString = eventInstance.ToXml(); byte[] data = _encoding.GetBytes(xmlString); _udpClient.Send(data, data.Length); } catch (Exception e) { Console.WriteLine("Couldn't render event!"); Console.WriteLine("Exception: Event {0} may not have an XML representation \n\n", ++numberOfEvents); Console.WriteLine(e); } } }
public void PartReaderBasicTest() { string partText = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">" + "<w:body>" + "<w:p w:rsidP=\"001\"><w:r><w:t>Run Text.</w:t><w:t>Run 2.</w:t></w:r></w:p>" + "<w:p w:rsidP=\"001\"><w:r><w:t>Run Text.</w:t><w:t>Run 2.</w:t></w:r></w:p>" + "</w:body>" + "</w:document>"; UTF8Encoding utf8Encoding = new UTF8Encoding(); Stream stream = new MemoryStream(utf8Encoding.GetBytes(partText), false); OpenXmlReader targetReader = OpenXmlReader.Create(stream); targetReader.Read(); Assert.False(targetReader.EOF); Assert.NotNull(targetReader.Attributes); Assert.Empty(targetReader.Attributes); Assert.False(targetReader.HasAttributes); Assert.True(targetReader.IsStartElement); Assert.False(targetReader.IsEndElement); Assert.False(targetReader.IsMiscNode); Assert.True(string.IsNullOrEmpty(targetReader.GetText())); Assert.Equal(typeof(Document), targetReader.ElementType); targetReader.ReadFirstChild(); // to <w:body> targetReader.Read(); // to <w:p> TestReaderOnParagraph(targetReader); Assert.False(targetReader.EOF); Assert.NotNull(targetReader.Attributes); Assert.Empty(targetReader.Attributes); Assert.False(targetReader.HasAttributes); Assert.False(targetReader.IsStartElement); Assert.True(targetReader.IsEndElement); Assert.False(targetReader.IsMiscNode); Assert.Equal(typeof(Paragraph), targetReader.ElementType); Assert.True(string.IsNullOrEmpty(targetReader.GetText())); targetReader.ReadNextSibling(); // next <w:p> OpenXmlElement element = targetReader.LoadCurrentElement(); // at </w:p> Assert.False(targetReader.EOF); Assert.NotNull(targetReader.Attributes); Assert.Empty(targetReader.Attributes); Assert.False(targetReader.HasAttributes); Assert.False(targetReader.IsStartElement); Assert.True(targetReader.IsEndElement); Assert.False(targetReader.IsMiscNode); Assert.Equal(typeof(Paragraph), targetReader.ElementType); Assert.True(string.IsNullOrEmpty(targetReader.GetText())); // loaded element is Run Assert.NotNull(element); Assert.IsType <Paragraph>(element); Run run = (Run)element.FirstChild; Assert.Equal("Run Text.", (run.FirstChild as Text).Text); Assert.Equal("Run 2.", (run.LastChild as Text).Text); targetReader.Close(); }
/// <summary> /// This function get the access token based on the type parameter type values. /// If type value is 1, access token is fetch for client credential flow /// If type value is 2, access token is fetch for client credential flow based on the exisiting refresh token /// </summary> /// <param name="type">Type as integer</param> /// <param name="panelParam">Panel details</param> /// <returns>Return boolean</returns> private bool GetAccessToken(AccessType type, ref string message) { FileStream fileStream = null; Stream postStream = null; StreamWriter streamWriter = null; // This is client credential flow if (type == AccessType.ClientCredential) { try { DateTime currentServerTime = DateTime.UtcNow.ToLocalTime(); WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.fqdn + "/oauth/v4/token"); accessTokenRequest.Method = "POST"; string oauthParameters = string.Empty; if (type == AccessType.ClientCredential) { oauthParameters = "client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&grant_type=client_credentials&scope=" + this.scope; } else { oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken; } accessTokenRequest.ContentType = "application/x-www-form-urlencoded"; UTF8Encoding encoding = new UTF8Encoding(); byte[] postBytes = encoding.GetBytes(oauthParameters); accessTokenRequest.ContentLength = postBytes.Length; postStream = accessTokenRequest.GetRequestStream(); postStream.Write(postBytes, 0, postBytes.Length); WebResponse accessTokenResponse = accessTokenRequest.GetResponse(); using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream())) { string jsonAccessToken = accessTokenResponseStream.ReadToEnd().ToString(); JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer(); AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(jsonAccessToken, typeof(AccessTokenResponse)); this.accessToken = deserializedJsonObj.access_token; this.accessTokenExpiryTime = currentServerTime.AddSeconds(Convert.ToDouble(deserializedJsonObj.expires_in)).ToString(); this.refreshToken = deserializedJsonObj.refresh_token; DateTime refreshExpiry = currentServerTime.AddHours(this.refreshTokenExpiresIn); if (deserializedJsonObj.expires_in.Equals("0")) { int defaultAccessTokenExpiresIn = 100; // In Yearsint yearsToAdd = 100; this.accessTokenExpiryTime = currentServerTime.AddYears(defaultAccessTokenExpiresIn).ToLongDateString() + " " + currentServerTime.AddYears(defaultAccessTokenExpiresIn).ToLongTimeString(); } this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString(); fileStream = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write); streamWriter = new StreamWriter(fileStream); streamWriter.WriteLine(this.accessToken); streamWriter.WriteLine(this.accessTokenExpiryTime); streamWriter.WriteLine(this.refreshToken); streamWriter.WriteLine(this.refreshTokenExpiryTime); // Close and clean up the StreamReader accessTokenResponseStream.Close(); return(true); } } catch (WebException we) { string errorResponse = string.Empty; try { using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream())) { errorResponse = sr2.ReadToEnd(); sr2.Close(); } } catch { errorResponse = "Unable to get response"; } message = errorResponse + Environment.NewLine + we.ToString(); } catch (Exception ex) { message = ex.Message; return(false); } finally { if (null != postStream) { postStream.Close(); } if (null != streamWriter) { streamWriter.Close(); } if (null != fileStream) { fileStream.Close(); } } } else if (type == AccessType.RefreshToken) { try { DateTime currentServerTime = DateTime.UtcNow.ToLocalTime(); WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.fqdn + "/oauth/v4/token"); accessTokenRequest.Method = "POST"; string oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken; accessTokenRequest.ContentType = "application/x-www-form-urlencoded"; UTF8Encoding encoding = new UTF8Encoding(); byte[] postBytes = encoding.GetBytes(oauthParameters); accessTokenRequest.ContentLength = postBytes.Length; postStream = accessTokenRequest.GetRequestStream(); postStream.Write(postBytes, 0, postBytes.Length); WebResponse accessTokenResponse = accessTokenRequest.GetResponse(); using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream())) { string accessTokenJSon = accessTokenResponseStream.ReadToEnd().ToString(); JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer(); AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(accessTokenJSon, typeof(AccessTokenResponse)); this.accessToken = deserializedJsonObj.access_token.ToString(); DateTime accessTokenExpiryTime = currentServerTime.AddMilliseconds(Convert.ToDouble(deserializedJsonObj.expires_in.ToString())); this.refreshToken = deserializedJsonObj.refresh_token.ToString(); fileStream = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write); streamWriter = new StreamWriter(fileStream); streamWriter.WriteLine(this.accessToken); streamWriter.WriteLine(this.accessTokenExpiryTime); streamWriter.WriteLine(this.refreshToken); // Refresh token valids for 24 hours DateTime refreshExpiry = currentServerTime.AddHours(24); this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString(); streamWriter.WriteLine(refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString()); accessTokenResponseStream.Close(); return(true); } } catch (WebException we) { string errorResponse = string.Empty; try { using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream())) { errorResponse = sr2.ReadToEnd(); sr2.Close(); } } catch { errorResponse = "Unable to get response"; } message = errorResponse + Environment.NewLine + we.ToString(); } catch (Exception ex) { message = ex.Message; return(false); } finally { if (null != postStream) { postStream.Close(); } if (null != streamWriter) { streamWriter.Close(); } if (null != fileStream) { fileStream.Close(); } } } return(false); }
// 인증 버튼 클릭 private void CertificationBtn_Clicked(object sender, EventArgs e) { #region 네트워크 상태 확인 var current_network = Connectivity.NetworkAccess; // 현재 네트워크 상태 if (current_network != NetworkAccess.Internet) // 네트워크 연결 불가 { DisplayAlert("알림", "네트워크에 연결할 수 없습니다. 다시 한번 시도해주세요.", "확인"); return; } #endregion #region 네트워크 연결 가능 else { if (InputPhoneEntry.Text != "") // 변경된 핸드폰 번호가 널이 아닌 경우 { CheckNumGrid.IsVisible = true; string str = @"{"; str += "DATA:'" + Global.ID; //아이디찾기에선 Name으로 str += "',PHONENUM:'" + InputPhoneEntry.Text; // 입력된 핸드폰 번호로 메세지 전송 str += "',TYPE:'" + "5"; //인증 종류( 1: 회원가입, 2: ID찾기, 3: 비밀번호 찾기, 4: 비밀번호 수정, 5: 핸드폰 번호 수정) str += "'}"; //// JSON 문자열을 파싱하여 JObject를 리턴 JObject jo = JObject.Parse(str); UTF8Encoding encoder = new UTF8Encoding(); byte[] data = encoder.GetBytes(jo.ToString()); // a json object, or xml, whatever... HttpWebRequest request = WebRequest.Create(Global.WCFURL + "Certifiaction_Create") as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = data.Length; request.GetRequestStream().Write(data, 0, data.Length); using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode); } using (StreamReader reader = new StreamReader(response.GetResponseStream())) { var readdata = reader.ReadToEnd(); //Stuinfo test = JsonConvert.DeserializeObject<Stuinfo>(readdata); switch (int.Parse(readdata)) { case 0: CertificationBtn.Text = "인증"; CheckNumGrid.IsVisible = false; DisplayAlert("알림", "일치하는 정보가 없습니다.", "확인"); return; case 1: CertificationBtn.Text = "인증번호 재전송"; CheckNumGrid.IsVisible = true; isEntryFocus = true; #region 남은시간 타이머 DisplayAlert("알림", "인증번호가 발송 되었습니다.", "확인"); // 타이머 생성 및 시작 timer_count = 300; if (timer == null) { timer = new MyTimer(TimeSpan.FromSeconds(1), TimerCallback_event); timer.Start(); } else { timer.Stop(); timer.Start(); } #endregion return; default: DisplayAlert("알림", "서버 점검중입니다.", "확인"); Navigation.PopAsync(); return; } } } } } #endregion }
public static IEnumerable fnWebSendXMLDataKFHRM( SqlString PostURL, SqlString Method, SqlString ContentType, SqlXml XMLData, SqlString P12CertPath, SqlString P12CertPass, SqlInt32 Timeout, SqlString SchemaURI, SqlString RootName, SqlString SuccessNode, SqlString SuccessValue, SqlBoolean UniqueNodeValues, SqlString XPathReturnValue ) { // creates a collection to store the row values ( might have to make this a scalar row rather then multi-rowed ) ArrayList resultCollection = new ArrayList(); // logs the time the row had begun processing SqlDateTime _StartedTS = DateTime.Now; // stores the URL of the request and stores any xml input as bytes Uri URL = null; byte[] postBytes = null; // if the required fields post url and method are not provided then... if (PostURL.IsNull || PostURL.Value == "" || Method.IsNull) { resultCollection.Add(new PostResult(null, null, false, true, "The [Post URL] was missing or the [Method] was missing.", STATUS_CODES.FAILED_VALIDATION, null)); return(resultCollection); } // if the methods are not correctly set to the only valid values then... if (Method.Value != "POST" && Method.Value != "GET") { resultCollection.Add(new PostResult(null, null, false, true, "The [Method] provided was not either POST or GET.", STATUS_CODES.FAILED_VALIDATION, null)); return(resultCollection); } // check to see if the url is correctly formed otherwise... if (Uri.TryCreate(PostURL.Value, UriKind.RelativeOrAbsolute, out URL) == false) { resultCollection.Add(new PostResult(null, null, false, true, "The [URL] provided was incorrectly formatted.", STATUS_CODES.FAILED_VALIDATION, null)); return(resultCollection); } // if xml schema has been specified but no xml has been passed then... if (!SchemaURI.IsNull && XMLData.IsNull) { resultCollection.Add(new PostResult(null, null, false, true, "The [Schema URI] was provided but [XML Data] was not.", STATUS_CODES.FAILED_VALIDATION, null)); return(resultCollection); } // check to see if we can access the schema .xsd file otherwise... if (!SchemaURI.IsNull && System.IO.File.Exists(SchemaURI.Value) == false) { resultCollection.Add(new PostResult(null, null, false, true, "The [Schema URI] was provided but could not be loaded because it could not be found.", STATUS_CODES.FAILED_VALIDATION, null)); return(resultCollection); } // if xml specific fields are available but no xml has been passed then... if ((!RootName.IsNull || !SuccessNode.IsNull || !SuccessValue.IsNull) && XMLData.IsNull) { resultCollection.Add(new PostResult(null, null, false, true, "The [Root Name] or [Success Node] or [Success Value] was provided but the [XML Data] was missing.", STATUS_CODES.FAILED_VALIDATION, null)); return(resultCollection); } // if certificate pass is specified but no certificate file has then... if (!P12CertPass.IsNull && P12CertPath.IsNull) { resultCollection.Add(new PostResult(null, null, false, true, "The [P12 Cert Pass] was provided but the [P12 Cert Path] is missing.", STATUS_CODES.FAILED_VALIDATION, null)); return(resultCollection); } // check to see if we can access the certificate file otherwise... if (!P12CertPath.IsNull && System.IO.File.Exists(P12CertPath.Value) == false) { resultCollection.Add(new PostResult(null, null, false, true, "The [P12 Cert Path] was provided but could not be loaded because it could not be found.", STATUS_CODES.FAILED_VALIDATION, null)); return(resultCollection); } // check that the certificate provided can be opened before performing major code... if (!P12CertPath.IsNull) { try { if (!P12CertPass.IsNull) { new X509Certificate2(P12CertPath.Value, P12CertPass.Value); } else { new X509Certificate2(P12CertPath.Value); } } catch (Exception ex) { resultCollection.Add(new PostResult(null, null, false, true, String.Format("Certificate exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace), STATUS_CODES.FAILED_VALIDATION, null)); return(resultCollection); } } // check if any xml data has been passed to the clr using (var stringWriter = new StringWriter()) { if (!XMLData.IsNull) { // prepare xml variable XmlDocument2 xDoc = new XmlDocument2(); try { // rename root node if applicable if (!RootName.IsNull) { XmlDocument2 _xDoc = new XmlDocument2(); _xDoc.LoadXml(XMLData.Value); XmlElement _xDocNewRoot = xDoc.CreateElement(RootName.Value); xDoc.AppendChild(_xDocNewRoot); _xDocNewRoot.InnerXml = _xDoc.DocumentElement.InnerXml; } else { // otherwise just load the xml exactly as provided xDoc.LoadXml(XMLData.Value); } // add the xml declaration if it doesn't exist if (xDoc.FirstChild.NodeType != XmlNodeType.XmlDeclaration) { XmlDeclaration xmlDec = xDoc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = xDoc.DocumentElement; xDoc.InsertBefore(xmlDec, root); } // if the schema file has been specified then validate otherwise skip if (!SchemaURI.IsNull) { System.Xml.Schema.XmlSchemaSet schemas = new System.Xml.Schema.XmlSchemaSet(); schemas.Add("", SchemaURI.Value); xDoc.Schemas.Add(schemas); if (!UniqueNodeValues.IsNull) { xDoc.UniqueNodeValues = UniqueNodeValues.Value; } xDoc.Validate(ValidationEventHandler); } // adds any validation errors to the output rows and stops processing if errors were found if (xDoc.ValidationErrors.Count > 0) { resultCollection.AddRange(xDoc.ValidationErrors); return(resultCollection); } // Save the xml as a string using (var xmlTextWriter = XmlWriter.Create(stringWriter)) { xDoc.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); } // get the bytes for the xml document //postBytes = Encoding.UTF8.GetBytes(xDoc.OuterXml); UTF8Encoding encoding = new UTF8Encoding(); postBytes = encoding.GetBytes(xDoc.InnerXml); } catch (Exception ex) { string errorMsg = String.Format("XML Parse exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace); resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.XML_ERROR, null, _StartedTS)); return(resultCollection); } } if (Timeout.IsNull) { Timeout = 20; } if (ContentType.IsNull) { ContentType = "*/*"; } // Set the SecurityProtocol System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // create the web request object after validation succeeds HttpWebRequest webRequest; try { // create the http request webRequest = (HttpWebRequest)HttpWebRequest.Create(URL); // setup the connection settings webRequest.Method = Method.Value; webRequest.ContentType = ContentType.Value; webRequest.Accept = ContentType.Value; webRequest.Timeout = (Timeout.Value * 1000); webRequest.SendChunked = true; webRequest.KeepAlive = false; } catch (Exception ex) { string errorMsg = String.Format("WebRequest Create exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace); resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE, null, _StartedTS)); return(resultCollection); } try { // add the P12 certificate to the request if specified if (!P12CertPath.IsNull) { // load with password if specified if (!P12CertPass.IsNull) { webRequest.ClientCertificates.Add(new X509Certificate2(P12CertPath.Value, P12CertPass.Value)); } else { webRequest.ClientCertificates.Add(new X509Certificate2(P12CertPath.Value)); } } } catch (Exception ex) { string errorMsg = String.Format("Certificate exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace); resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.CERTIFICATE_ERROR, null, _StartedTS)); return(resultCollection); } // post the request if (Method.Value == "POST") { try { using (StreamWriter postStream = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8)) { try { // post the data as bytes to the request stream if (postBytes != null) { postStream.Write(System.Text.Encoding.UTF8.GetString(postBytes)); postStream.Flush(); //postStream.BaseStream.Write(postBytes, 0, postBytes.Length); } } catch (Exception ex) { string errorMsg = String.Format("StreamWriter exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace); resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.GET_REQUEST_STREAM, null, _StartedTS, DateTime.Now)); return(resultCollection); } finally { postStream.Close(); } } } catch (Exception ex) { string errorMsg = String.Format("Web request exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace); resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.GET_REQUEST_STREAM, null, _StartedTS, DateTime.Now)); return(resultCollection); } } string response = string.Empty; HttpWebResponse objResponse = null; // get the response (also used for GET) try { objResponse = (HttpWebResponse)webRequest.GetResponse(); if (webRequest.HaveResponse == true) { using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream())) { try { // get the result of the post response = responseStream.ReadToEnd(); // see if the response is in xml format or not XmlDocument doc = null; if (response.IndexOf("<", 0) <= 2) { doc = new XmlDocument(); try { doc.LoadXml(response); } catch (Exception) { doc = null; } } // if the response is expected in xml format if (doc != null) { // check for a success value and node if specified... if (!SuccessNode.IsNull && !SuccessValue.IsNull) { try { // use the response xml and get the success node(s) specified in the xpath XmlNodeList nodeSuccess = doc.SelectNodes(SuccessNode.Value); using (XmlNodeReader xnr = new XmlNodeReader(doc)) { if (nodeSuccess.Count == 0) { resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), false, false, null, STATUS_CODES.XML_XPATH_RESULT_NODE_MISSING, ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now)); } else { // loop through each node we need to validate and get the value IEnumerator EN = nodeSuccess.GetEnumerator(); while (EN.MoveNext() == true) { if (((XmlNode)EN.Current).InnerText == SuccessValue.Value) { resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), true, false, null, STATUS_CODES.SUCCESS, ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now)); } else { resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), false, true, null, STATUS_CODES.FAILURE, ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now)); } } } } } catch (Exception ex) { string errorMsg = String.Format("XML reader exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace); resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE, ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now)); return(resultCollection); } } else { // if we're not checking for a success node then just return the xml response using (XmlNodeReader xnr = new XmlNodeReader(doc)) { resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), true, false, null, STATUS_CODES.SUCCESS, ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now)); } } } else { // all other requests return in plain text in the additional info column resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, true, false, response, STATUS_CODES.SUCCESS, ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now)); } } catch (Exception ex) { string errorMsg = String.Format("StreamWriter exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace); resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE, null, _StartedTS, DateTime.Now)); return(resultCollection); } finally { responseStream.Close(); } } } } catch (Exception ex) { string errorMsg = String.Format("Web response exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace); resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE, null, _StartedTS, DateTime.Now)); return(resultCollection); } finally { if (objResponse != null) { objResponse.Close(); } } } return(resultCollection); }
private byte[] StringToUTF8ByteArray(string pXmlString) { UTF8Encoding encoding = new UTF8Encoding(); return(encoding.GetBytes(pXmlString)); }
/// <summary> /// /// </summary> /// <param name="method"></param> /// <param name="url"></param> /// <param name="body"></param> /// <param name="headers"></param> /// <param name="onRequestDelegate"></param> /// <returns></returns> private static async Task <string> ExecuteRequestAsync(string method, string url, string body , StringDictionary headers , Action <WebRequest> onRequestDelegate) { // prepare request HttpWebRequest request = WebRequest.CreateHttp(url); request.Method = method.ToUpper(); request.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; request.KeepAlive = true; request.AllowAutoRedirect = true; request.Timeout = 50000; if (headers != null) { foreach (string key in headers.Keys) { if (key.ToLower() == "content-type") { request.ContentType = headers[key]; } else if (key.ToLower() == "accept") { request.Accept = headers[key]; } else if (key.ToLower() == "content-length") { // nothing continue; } else { request.Headers.Add(key, headers[key]); } } } onRequestDelegate?.Invoke(request); DebugRequest(request); try { if (!string.IsNullOrEmpty(body) && (request.Method == "POST" | request.Method == "PUT" | request.Method == "PATCH")) { // write body as UTF-8 encoding UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes(body); // set content length request.ContentLength = bytes.Length; using (Stream requestStream = await request.GetRequestStreamAsync()) await requestStream.WriteAsync(bytes, 0, bytes.Length); } using (var firstResponse = await request.GetResponseAsync()) { var response = (HttpWebResponse)firstResponse; DebugResponse(response); if (response.StatusCode == HttpStatusCode.OK | response.StatusCode == HttpStatusCode.Accepted | response.StatusCode == HttpStatusCode.Created | response.StatusCode == HttpStatusCode.NoContent) { return(await ReadResponseAsync(response.GetResponseStream())); } else { throw new Exception("Unknown status code"); } } } catch (WebException e) { if (e.Status == WebExceptionStatus.ConnectFailure || e.Status == WebExceptionStatus.ConnectionClosed || e.Status == WebExceptionStatus.Timeout) { throw e; } if (e.Status == WebExceptionStatus.ProtocolError) { var text = await ReadResponseAsync(e.Response.GetResponseStream()); throw new FormClientException(text , (e.Response as HttpWebResponse).StatusCode , (e.Response as HttpWebResponse).StatusDescription); } throw e; } catch (Exception e) { throw e; } }
public void Write(string text) { var bytes = UTF8EncodingWithoutBom.GetBytes(text); OutputStream.Write(bytes, 0, bytes.Length); }
protected void btnSubmit_Click(object sender, EventArgs e) { string SMSTemplate = lstSMSTemplate.SelectedItem.ToString(); int count = 0; foreach (GridViewRow item in grdAttendance.Rows) { DropDownList ddlSelection = item.FindControl("ddlSelection") as DropDownList; if (ddlSelection.SelectedValue == "0") { int attendanceId = Convert.ToInt32(grdAttendance.DataKeys[item.RowIndex].Value.ToString()); AttendanceCL getAttendance = attendanceBLL.viewAttendanceById(attendanceId); Collection <StudentCL> studentCol = studentBLL.viewStudentsByClassId(getAttendance.classId); foreach (StudentCL x in studentCol) { AttendanceCL attendanceCL = attendanceBLL.viewAttendanceByStudentIdandDate(x.id, getAttendance.date); if (attendanceCL.studentLeaveTypeId == getAttendance.studentLeaveTypeId && x.studentCategoryId != 6) { //Your authentication key string authKey = "136481ASa0LIdW5870d589"; //Multiple mobiles numbers separated by comma string mobileNumber = x.fatherMobileNumber; //Sender ID,While using route4 sender id should be 6 characters long. string senderId = "RAINBO"; //Your message to send, Add URL encoding here. string message = SMSTemplate.Replace("<&admNo>", x.admissionNo.ToString()).Replace("<&studentName>", x.studentName).Replace("<&fatherName>", x.fatherName).Replace("<&motherName>", x.motherName).Replace("<&class>", x.classSection).Replace("<&date>", getAttendance.date.ToString("dd MMM yyyy")); //Prepare you post parameters StringBuilder sbPostData = new StringBuilder(); sbPostData.AppendFormat("authkey={0}", authKey); sbPostData.AppendFormat("&mobiles={0}", mobileNumber); sbPostData.AppendFormat("&message={0}", message); sbPostData.AppendFormat("&sender={0}", senderId); sbPostData.AppendFormat("&route={0}", "4"); try { //Call Send SMS API string sendSMSUri = "https://control.msg91.com/api/sendhttp.php"; //Create HTTPWebrequest HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(sendSMSUri); //Prepare and Add URL Encoded data UTF8Encoding encoding = new UTF8Encoding(); byte[] data = encoding.GetBytes(sbPostData.ToString()); //Specify post method httpWReq.Method = "POST"; httpWReq.ContentType = "application/x-www-form-urlencoded"; httpWReq.ContentLength = data.Length; using (Stream stream = httpWReq.GetRequestStream()) { stream.Write(data, 0, data.Length); } //Get the response HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string responseString = reader.ReadToEnd(); //Close the response reader.Close(); response.Close(); attendanceBLL.addSMSEntry(new SMSEntryCL { attendanceId = attendanceCL.id, dateCreated = DateTime.Now, isDeleted = false, smsTemplateId = Convert.ToInt32(lstSMSTemplate.SelectedValue), }); } catch (SystemException ex) { throw (new Exception(ex.Message)); } count++; } } } } if (count == 0) { lblUpdate.Text = "Attendance Not Selected."; } else { lblUpdate.Text = "SMS sent to " + count + "Entries/Columns. The page will redirect in 10 seconds."; Response.AppendHeader("Refresh", "10;url=index.aspx"); } }
public byte[] Encode(string data) { return(_encoding.GetBytes(data)); }
/// <summary> /// Make request method /// </summary> /// <param name="path"></param> /// <param name="method"></param> /// <param name="parameters"></param> /// <returns></returns> /// <exception cref="ArgumentException"></exception> /// <exception cref="WebException"></exception> public Response MakeRequest(string path, string method, Dictionary <string, object> parameters = null) { string[] allowedMethods = { MethodGet, MethodPost }; if (allowedMethods.Contains(method) == false) { throw new ArgumentException($"Method {method} is not valid. Allowed HTTP methods are {string.Join(", ", allowedMethods)}"); } if (parameters == null) { parameters = new Dictionary <string, object>(); } parameters = _defaultParameters.Union(parameters).ToDictionary(k => k.Key, v => v.Value); path = _url + path; string httpQuery = QueryBuilder.BuildQueryString(parameters); if (method.Equals(MethodGet) && parameters.Count > 0) { path += "?" + httpQuery; } Exception exception = null; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path); request.Method = method; if (method.Equals(MethodPost)) { UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes(httpQuery); request.ContentLength = bytes.Length; request.ContentType = ContentType; request.UserAgent = UserAgent; Stream post = request.GetRequestStream(); post.Write(bytes, 0, bytes.Length); post.Flush(); post.Close(); } HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException webException) { response = (HttpWebResponse)webException.Response; exception = webException; } if (request == null || response == null) { throw new WebException(exception.ToString(), exception); } StreamReader reader = new StreamReader(response.GetResponseStream()); string responseBody = reader.ReadToEnd(); int statusCode = (int)response.StatusCode; return(new Response(statusCode, responseBody)); }
public static byte[] StrToByteArray(string str) { var encoding = new UTF8Encoding(); return(encoding.GetBytes(str)); }
static public bool EditNode(IWin32Window parent, Asn1Node aNode, bool enableTagEdit, bool pureHexMode) { byte[] val; byte[] data; FormNodeContentEditor ed = new FormNodeContentEditor(); ed.aNode = aNode; MemoryStream ms = new MemoryStream(); ed.checker = FormNodeContentEditor.DataChecker.None; ed.enableTagEdit = enableTagEdit; ed.pureHexMode = pureHexMode; if ( ((aNode.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.BIT_STRING) && (aNode.ChildNodeCount < 1)) { ed.panelUnusedBits.Visible = true; ed.textBoxUnusedBits.Text = aNode.UnusedBits.ToString(); } else { ed.panelUnusedBits.Visible = false; } if (pureHexMode) { ed.checker = DataChecker.Hex; ed.ShowDialog(parent); if (!ed.isOK) { return(false); } data = Asn1Util.HexStrToBytes(ed.GetValueStr()); aNode.Data = data; } else { byte[] oidVal; switch (aNode.Tag) { case Asn1Tag.OBJECT_IDENTIFIER: ed.checker = DataChecker.Oid; ed.ShowDialog(parent); if (!ed.isOK) { return(false); } Oid xoid = new Oid(); xoid.Encode(ms, ed.GetValueStr()); ms.Position = 0; oidVal = new byte[ms.Length]; ms.Read(oidVal, 0, (int)ms.Length); ms.Close(); aNode.Data = oidVal; break; case Asn1Tag.RELATIVE_OID: ed.checker = DataChecker.Roid; ed.ShowDialog(parent); if (!ed.isOK) { return(false); } RelativeOid roid = new RelativeOid(); roid.Encode(ms, ed.GetValueStr()); ms.Position = 0; oidVal = new byte[ms.Length]; ms.Read(oidVal, 0, (int)ms.Length); ms.Close(); aNode.Data = oidVal; break; case Asn1Tag.PRINTABLE_STRING: case Asn1Tag.IA5_STRING: case Asn1Tag.UNIVERSAL_STRING: case Asn1Tag.VISIBLE_STRING: case Asn1Tag.NUMERIC_STRING: case Asn1Tag.UTC_TIME: case Asn1Tag.GENERAL_STRING: case Asn1Tag.GENERALIZED_TIME: ed.ShowDialog(parent); if (!ed.isOK) { return(false); } val = Asn1Util.StringToBytes(ed.GetValueStr()); aNode.Data = val; break; case Asn1Tag.UTF8_STRING: ed.ShowDialog(parent); if (!ed.isOK) { return(false); } UTF8Encoding u8 = new UTF8Encoding(false); val = u8.GetBytes(ed.GetValueStr()); aNode.Data = val; break; case Asn1Tag.BMPSTRING: ed.ShowDialog(parent); if (!ed.isOK) { return(false); } byte[] tmpval = Asn1Util.StringToBytes(ed.GetValueStr()); val = new byte[tmpval.Length * 2]; for (int i = 0; i < tmpval.Length; i++) { val[i * 2] = 0; val[i * 2 + 1] = tmpval[i]; } aNode.Data = val; break; case Asn1Tag.INTEGER: case Asn1Tag.BIT_STRING: ed.checker = DataChecker.Hex; ed.ShowDialog(parent); if (!ed.isOK) { return(false); } aNode.UnusedBits = (byte)(Convert.ToUInt16(ed.textBoxUnusedBits.Text) % 8); data = Asn1Util.HexStrToBytes(ed.GetValueStr()); aNode.Data = data; break; default: if ((aNode.Tag & Asn1Tag.TAG_MASK) == 6) // Visible string for certificate { ed.ShowDialog(parent); if (!ed.isOK) { return(false); } val = Asn1Util.StringToBytes(ed.GetValueStr()); aNode.Data = val; } else { ed.checker = DataChecker.Hex; ed.ShowDialog(parent); if (!ed.isOK) { return(false); } data = Asn1Util.HexStrToBytes(ed.GetValueStr()); aNode.Data = data; } break; } ; } return(true); }
public string Encrypt(string value) { byte[] Buffer = Transform(UTF8.GetBytes(value), Encryptor); return(Convert.ToBase64String(Buffer)); }
/// <summary> /// 发送相关数据至页面 /// 进行登录操作 /// 并保存cookie /// </summary> /// <param name="postData"></param> /// <param name="postUrl"></param> /// <param name="cookie"></param> /// <returns></returns> public ArrayList PostData(string postUrl, string postData, CookieContainer cookie) { ArrayList list = new ArrayList(); HttpWebRequest request; HttpWebResponse response; UTF8Encoding encoding = new UTF8Encoding(); //WebProxy proxyObject = new WebProxy(IP, PORT);// port为端口号 整数型 request = WebRequest.Create(postUrl) as HttpWebRequest; request.Referer = refererUrl; //webRequest.Proxy = proxyObject; //设置代理 byte[] b = encoding.GetBytes(postData); request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"; request.Method = "POST"; request.Host = host; request.KeepAlive = true; request.Accept = "application/json, text/javascript, */*; q=0.01"; request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9"); request.ContentType = "application/x-www-form-urlencoded"; request.CookieContainer = cookie; request.ContentLength = b.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(b, 0, b.Length); } try { //获取服务器返回的资源 using (response = request.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { if (response.Cookies.Count > 0) { cookie.Add(response.Cookies); } list.Add(cookie); list.Add(reader.ReadToEnd()); } } } catch (WebException wex) { WebResponse wr = wex.Response; using (Stream st = wr.GetResponseStream()) { using (StreamReader sr = new StreamReader(st, System.Text.Encoding.UTF8)) { list.Add(sr.ReadToEnd()); } } } catch (Exception ex) { list.Add("发生异常/n/r" + ex.Message); } return(list); }
/// <summary> /// This function invokes api SpeechToText to convert the given wav amr file and displays the result. /// </summary> private void TextToSpeech(string parEndPoint, string parURI, string parAccessToken, string parXarg, string parContentType, string parContent) { try { HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(string.Empty + parEndPoint + parURI); httpRequest.Headers.Add("Authorization", "Bearer " + parAccessToken); httpRequest.Headers.Add("X-SpeechContext", parXarg); httpRequest.ContentLength = parContent.Length; httpRequest.ContentType = parContentType; httpRequest.Accept = "audio/x-wav"; httpRequest.Method = "POST"; httpRequest.KeepAlive = true; UTF8Encoding encoding = new UTF8Encoding(); byte[] postBytes = encoding.GetBytes(parContent); httpRequest.ContentLength = postBytes.Length; using (Stream writeStream = httpRequest.GetRequestStream()) { writeStream.Write(postBytes, 0, postBytes.Length); writeStream.Close(); } HttpWebResponse speechResponse = (HttpWebResponse)httpRequest.GetResponse(); int offset = 0; int remaining = Convert.ToInt32(speechResponse.ContentLength); using (var stream = speechResponse.GetResponseStream()) { receivedBytes = new byte[speechResponse.ContentLength]; while (remaining > 0) { int read = stream.Read(receivedBytes, offset, remaining); if (read <= 0) { TTSErrorMessage = String.Format("End of stream reached with {0} bytes left to read", remaining); return; } remaining -= read; offset += read; } audioPlay.Attributes.Add("src", "data:audio/wav;base64," + Convert.ToBase64String(receivedBytes, Base64FormattingOptions.None)); TTSSuccessMessage = "Success"; } } catch (WebException we) { string errorResponse = string.Empty; try { using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream())) { errorResponse = sr2.ReadToEnd(); sr2.Close(); } TTSErrorMessage = errorResponse; } catch { errorResponse = "Unable to get response"; TTSErrorMessage = errorResponse; } } catch (Exception ex) { TTSErrorMessage = ex.Message; return; } }
public async Task <IActionResult> LedgerConnection( [ModelBinder(typeof(WalletIdModelBinder))] WalletId walletId, string command, // getinfo // getxpub int account = 0, // sendtoaddress string psbt = null, string hintChange = null ) { if (!HttpContext.WebSockets.IsWebSocketRequest) { return(NotFound()); } var network = NetworkProvider.GetNetwork(walletId.CryptoCode); if (network == null) { throw new FormatException("Invalid value for crypto code"); } var storeData = (await Repository.FindStore(walletId.StoreId, GetUserId())); var derivationSettings = GetDerivationSchemeSettings(walletId, storeData); var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(); using (var normalOperationTimeout = new CancellationTokenSource()) using (var signTimeout = new CancellationTokenSource()) { normalOperationTimeout.CancelAfter(TimeSpan.FromMinutes(30)); var hw = new LedgerHardwareWalletService(webSocket); var model = new WalletSendLedgerModel(); object result = null; try { if (command == "test") { result = await hw.Test(normalOperationTimeout.Token); } if (command == "sendtoaddress") { if (!_dashboard.IsFullySynched(network.CryptoCode, out var summary)) { throw new Exception($"{network.CryptoCode}: not started or fully synched"); } var accountKey = derivationSettings.GetSigningAccountKeySettings(); // Some deployment does not have the AccountKeyPath set, let's fix this... if (accountKey.AccountKeyPath == null) { // If the saved wallet key path is not present or incorrect, let's scan the wallet to see if it can sign strategy var foundKeyPath = await hw.FindKeyPathFromDerivation(network, derivationSettings.AccountDerivation, normalOperationTimeout.Token); accountKey.AccountKeyPath = foundKeyPath ?? throw new HardwareWalletException($"This store is not configured to use this ledger"); storeData.SetSupportedPaymentMethod(derivationSettings); await Repository.UpdateStore(storeData); } // If it has already the AccountKeyPath, we did not looked up for it, so we need to check if we are on the right ledger else { // Checking if ledger is right with the RootFingerprint is faster as it does not need to make a query to the parent xpub, // but some deployment does not have it, so let's use AccountKeyPath instead if (accountKey.RootFingerprint == null) { var actualPubKey = await hw.GetExtPubKey(network, accountKey.AccountKeyPath, normalOperationTimeout.Token); if (!derivationSettings.AccountDerivation.GetExtPubKeys().Any(p => p.GetPublicKey() == actualPubKey.GetPublicKey())) { throw new HardwareWalletException($"This store is not configured to use this ledger"); } } // We have the root fingerprint, we can check the root from it else { var actualPubKey = await hw.GetPubKey(network, new KeyPath(), normalOperationTimeout.Token); if (actualPubKey.GetHDFingerPrint() != accountKey.RootFingerprint.Value) { throw new HardwareWalletException($"This store is not configured to use this ledger"); } } } // Some deployment does not have the RootFingerprint set, let's fix this... if (accountKey.RootFingerprint == null) { accountKey.RootFingerprint = (await hw.GetPubKey(network, new KeyPath(), normalOperationTimeout.Token)).GetHDFingerPrint(); storeData.SetSupportedPaymentMethod(derivationSettings); await Repository.UpdateStore(storeData); } var psbtResponse = new CreatePSBTResponse() { PSBT = PSBT.Parse(psbt, network.NBitcoinNetwork), ChangeAddress = string.IsNullOrEmpty(hintChange) ? null : BitcoinAddress.Create(hintChange, network.NBitcoinNetwork) }; derivationSettings.RebaseKeyPaths(psbtResponse.PSBT); signTimeout.CancelAfter(TimeSpan.FromMinutes(5)); psbtResponse.PSBT = await hw.SignTransactionAsync(psbtResponse.PSBT, accountKey.GetRootedKeyPath(), accountKey.AccountKey, psbtResponse.ChangeAddress?.ScriptPubKey, signTimeout.Token); result = new SendToAddressResult() { PSBT = psbtResponse.PSBT.ToBase64() }; } } catch (OperationCanceledException) { result = new LedgerTestResult() { Success = false, Error = "Timeout" }; } catch (Exception ex) { result = new LedgerTestResult() { Success = false, Error = ex.Message }; } finally { hw.Dispose(); } try { if (result != null) { UTF8Encoding UTF8NOBOM = new UTF8Encoding(false); var bytes = UTF8NOBOM.GetBytes(JsonConvert.SerializeObject(result, _mvcJsonOptions.Value.SerializerSettings)); await webSocket.SendAsync(new ArraySegment <byte>(bytes), WebSocketMessageType.Text, true, new CancellationTokenSource(2000).Token); } } catch { } finally { await webSocket.CloseSocket(); } } return(new EmptyResult()); }
public Form1() { InitializeComponent(); m_chromeBrowser = new ChromiumWebBrowser("http://13.124.243.73:3000/"); panel_Youtube.Controls.Add(m_chromeBrowser); this.FormBorderStyle = FormBorderStyle.None; Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 15, 15)); this.Controls.SetChildIndex(this.panel_leftBackground, 1); Panel transparent = new Panel(); transparent.BackgroundImage = Properties.Resources.transparent30; transparent.Width = 320; transparent.Height = 554; transparent.BackColor = Color.Transparent; this.panel_leftBackground.Controls.Add(transparent); this.Controls.SetChildIndex(this.panel_Youtube, 0); var image = new KalikoImage(@"http://www.jangsada.com/files/attach/images/1572/500/002/db0e26c4043c42908ad321de21aeef76.jpg"); image.ApplyFilter(new FastGaussianBlurFilter(30.0f)); panel_leftBackground.BackgroundImage = image.GetAsBitmap(); var pb_logo = CreatePicturBox(transparent, Properties.Resources.logo, new Size((int)(150 * 0.65f), (int)(36 * 0.65f)), new Point(160 - (int)(150 * 0.65f) / 2, 15)); var pb_close = CreatePicturBox(transparent, Properties.Resources.btnCloseDefault_Normal, new Size(22, 22), new Point(19, 15)); var pb_hide = CreatePicturBox(transparent, Properties.Resources.btnHideDefault_Normal, new Size(22, 22), new Point(42, 15)); var pb_play = CreatePicturBox(transparent, Properties.Resources.btnPauseDefault_Normal, new Size(44, 44), new Point(138, 430)); var pb_prev = CreatePicturBox(transparent, Properties.Resources.btnPrevDefault_Normal, new Size(32, 32), new Point(90, 435)); var pb_next = CreatePicturBox(transparent, Properties.Resources.btnNextDefault_Normal, new Size(32, 32), new Point(198, 435)); var pb_shuffle = CreatePicturBox(transparent, Properties.Resources.btnShuffleDefault_Normal, new Size(32, 32), new Point(48, 435)); var pb_repeat = CreatePicturBox(transparent, Properties.Resources.btnRepeatDefault_Normal, new Size(32, 32), new Point(239, 435)); var pb_volume = CreatePicturBox(transparent, Properties.Resources.btnVolumeDefault_Normal, new Size(32, 32), new Point(144, 487)); label_Title = new Label(); label_Title.Text = "재생을 기다리고 있습니다"; label_Title.Font = new Font("나눔바른고딕", 12); label_Title.ForeColor = Color.FromArgb(255, 255, 255); label_Title.Width = 320; label_Title.Location = new Point(0, 385); label_Title.TextAlign = ContentAlignment.MiddleCenter; transparent.Controls.Add(label_Title); Label leftTime = new Label(); leftTime.Text = "00:00"; leftTime.Font = new Font("나눔바른고딕", 9); leftTime.ForeColor = Color.FromArgb(255, 255, 255); leftTime.Width = 50; leftTime.Location = new Point(16, 355); transparent.Controls.Add(leftTime); Label rightTime = new Label(); rightTime.Text = "00:00"; rightTime.Font = new Font("나눔바른고딕", 9); rightTime.ForeColor = Color.FromArgb(255, 255, 255); rightTime.Width = 50; rightTime.Location = new Point(265, 355); transparent.Controls.Add(rightTime); seekbar = new Ye0junSeekbar(transparent, 280, 300); seekbar.SetPosition(new Point(16, 340)); seekbar.SetValue(0); //////////////////////////////////////////////////////////////// pb_play.MouseClick += new MouseEventHandler((o, e) => { player.Toggle((b) => { if (b) { pb_play.Image = Properties.Resources.btnPauseDefault_Normal; } else { pb_play.Image = Properties.Resources.btnPlayDefault_Normal; } }); }); pb_prev.MouseClick += new MouseEventHandler((o, e) => { player.preVideo(() => { label_Title.Text = player._title; }); }); pb_next.MouseClick += new MouseEventHandler((o, e) => { player.nextVideo(); label_Title.Text = player._title; }); pb_shuffle.MouseClick += new MouseEventHandler((o, e) => { player.shuffle = !player.shuffle; if (player.shuffle) { pb_shuffle.Image = Properties.Resources.btnShuffleOnDefault_Normal; } else { pb_shuffle.Image = Properties.Resources.btnShuffleDefault_Normal; } }); pb_repeat.MouseClick += new MouseEventHandler((o, e) => { if (player.GetRepeatState() == 2) { player.SetRepeatState(0); } else { player.SetRepeatState(player.GetRepeatState() + 1); } switch (player.GetRepeatState()) { case 0: pb_repeat.Image = Properties.Resources.btnRepeatDefault_Normal; break; case 1: pb_repeat.Image = Properties.Resources.btnRepeatOnDefault_Normal; break; case 2: pb_repeat.Image = Properties.Resources.btn1RepeatOnDefault_Normal; break; } }); Youtube youtube = new Youtube(); searchBar.KeyDown += new KeyEventHandler((o, e) => { if (e.KeyCode == Keys.Enter) { pb_myList.Image = Properties.Resources.menuMymusicDefault_Normal; underline_my.Visible = false; UTF8Encoding utf8 = new UTF8Encoding(); byte[] encodedBytes = utf8.GetBytes(searchBar.Text); string utf8String = ""; foreach (byte b in encodedBytes) { utf8String += "%" + String.Format("{0:X}", b); } youtube.Search(utf8String, (arr) => { musicList.SetSearchList(arr); }); } }); //////////////////////////////////////////////////////////////// line_1.BackColor = Color.FromArgb(230, 230, 230); line_2.BackColor = Color.FromArgb(230, 230, 230); panel_rightbottom.BackColor = Color.FromArgb(243); underline_my.BackColor = Color.FromArgb(252, 63, 59); player = new Player(m_chromeBrowser, label_Title, panel_leftBackground, leftTime, seekbar); musicList = new MusicList(panel_right, player); messageFromBrowser = new MessageFromBrowser(() => { Console.WriteLine(player.GetRepeatState() + " "); if (player.GetRepeatState() != 2) { player.nextVideo(); } else { player.reVideo(); } //label_Title.Text = "ffff"; }, m_chromeBrowser, seekbar, rightTime); m_chromeBrowser.RegisterAsyncJsObject("toCSharp", messageFromBrowser); pb_close.MouseClick += new MouseEventHandler(FClose); pb_hide.MouseClick += new MouseEventHandler(FMinimized); var bMouseClick = false; var myX = 0; var myY = 0; transparent.MouseDown += new MouseEventHandler((o, e) => { bMouseClick = true; myX = e.X; myY = e.Y; }); transparent.MouseUp += new MouseEventHandler((o, e) => { bMouseClick = false; }); transparent.MouseMove += new MouseEventHandler((o, e) => { if (bMouseClick) { const short SWP_NOMOVE = 0X2; const short SWP_NOSIZE = 1; const short SWP_NOZORDER = 0X4; const int SWP_SHOWWINDOW = 0x0040; Process process = Process.GetCurrentProcess(); IntPtr handle = process.MainWindowHandle; var finalX = MousePosition.X - myX; var finalY = MousePosition.Y - myY; if (handle != IntPtr.Zero) { SetWindowPos(handle, 0, finalX, finalY, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW); } } }); searchBar.GotFocus += new EventHandler((o, e) => { disappear_icon.Visible = false; disappear_label.Visible = false; }); searchBar.LostFocus += new EventHandler((o, e) => { if (searchBar.Text == "") { disappear_icon.Visible = true; disappear_label.Visible = true; } }); }
static void Main(string[] args) { Console.WriteLine("Starting program..."); HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create("https://login.microsoftonline.com/d3d8e52c-b3c6-4d7a-9857-34c82389369c/oauth2/token"); tokenRequest.Method = "POST"; string postData = "grant_type=+client_credentials&resource=+3f79188f-f9af-4203-96c1-4bcd76fd4fbc&client_id=+3f79188f-f9af-4203-96c1-4bcd76fd4fbc&client_secret=+ZB-bc%3FvCKBRt5F8dY2WEz0%5DDMRfOFrX%2B"; ASCIIEncoding encoding = new ASCIIEncoding(); byte[] byte1 = encoding.GetBytes(postData); tokenRequest.ContentType = "application/x-www-form-urlencoded"; tokenRequest.ContentLength = byte1.Length; Stream newStream = tokenRequest.GetRequestStream(); newStream.Write(byte1, 0, byte1.Length); string jsonString = null; HttpWebResponse response = tokenRequest.GetResponse() as HttpWebResponse; using (Stream responseStream1 = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream1, Encoding.UTF8); jsonString = reader.ReadToEnd(); } if (!string.IsNullOrEmpty(jsonString)) { AuthenticationResponse authenticationResponse = JsonConvert.DeserializeObject <AuthenticationResponse>(jsonString); string accessToken = authenticationResponse.access_token; if (!string.IsNullOrEmpty(accessToken)) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; try { //for (int i = 1; i <= 1; i++) { string data = "{ \"firstName\": \"TestName\"," + "\"lastName\": \"Røgind Jørgensen\"," + "\"jobTitle\": \"Direktør\"," + "\"telePhoneNumber\": \"123456\"," + "\"email\": \"[email protected]\"," + "\"partner\": \"214\"," + "\"mailGroup\": \"string\"," + "\"peSharePointId\": \"testSpecialCharacters512\"," + "\"createdOn\": \"2019-05-18T08:33:33.723Z\"," + "\"createdBy\": \"System account\"," + "\"lastModified\": \"2019-05-18T08:33:33.723Z\"," + "\"lastModifiedBY\": \"Eimantas\"," + "\"modifiedOn\": \"2019-05-18T08:33:33.723Z\"," + "\"modifiedBY\": \"Eimantas\"," + "\"emailNotification\": true," + "\"smsNotification\": true," + "\"identifier\": \"test\"," + "\"deactivatedUser\": false }"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://dkbs-api-dev.azurewebsites.net/api/partneremployee"); request.ContentType = "application/json; charset=utf-8"; request.Headers.Add("Authorization", "Bearer " + accessToken); request.Method = "POST"; ///////////////////////////////////////////////////// //request.Headers.Add("cache-control", "no-cache"); ////request.Headers.Add("accept-encoding", "gzip, deflate"); //request.Headers.Add("Cache-Control", "no-cache"); //request.KeepAlive = true; //request.Host = "dkbs-api-dev.azurewebsites.net"; //request.Accept = "*/*"; //request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; Encoding utfencoding = new UTF8Encoding(); byte[] byte2 = utfencoding.GetBytes(data); request.ContentLength = byte2.Length; Stream newStream2 = request.GetRequestStream(); newStream2.Write(byte2, 0, byte2.Length); string responseString = null; using (HttpWebResponse dataResponse = request.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(dataResponse.GetResponseStream()); responseString = reader.ReadToEnd(); Console.WriteLine("Post request result: " + responseString); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.ReadLine(); } } }
// 인증번호 입력후 최종 확인 버튼 private void ConfirmBtn_Clicked(object sender, EventArgs e) { #region 네트워크 상태 확인 var current_network = Connectivity.NetworkAccess; // 현재 네트워크 상태 if (current_network != NetworkAccess.Internet) // 네트워크 연결 불가 { DisplayAlert("알림", "네트워크에 연결할 수 없습니다. 다시 한번 시도해주세요.", "확인"); return; } #endregion #region 네트워크 연결 가능 else { if (CertificationEntry.Text != "") { string str = @"{"; str += "p_id:'" + Global.ID; str += "',p_phonenum:'" + InputPhoneEntry.Text; str += "',p_key:'" + CertificationEntry.Text; str += "'}"; //// JSON 문자열을 파싱하여 JObject를 리턴 JObject jo = JObject.Parse(str); UTF8Encoding encoder = new UTF8Encoding(); byte[] data = encoder.GetBytes(jo.ToString()); // a json object, or xml, whatever... //request.Method = "POST"; HttpWebRequest request = WebRequest.Create(Global.WCFURL + "UserPhoneUpdateToID") as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = data.Length; //request.Expect = "application/json"; request.GetRequestStream().Write(data, 0, data.Length); using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode); } using (StreamReader reader = new StreamReader(response.GetResponseStream())) { var readdata = reader.ReadToEnd(); string test = JsonConvert.DeserializeObject <string>(readdata); if (test.Equals("false")) { DisplayAlert("알림", "인증번호가 틀렸습니다.", "확인"); Global.ischangemyinfobtn_clicked = true; } else if (test.Equals("true")) { if (timer != null) { timer.Stop(); } DisplayAlert("알림", "핸드폰 번호가 정상적으로 변경되었습니다.", "확인"); Global.ischangemyinfobtn_clicked = true; Navigation.PopAsync(); } else { DisplayAlert("알림", "서버에 연결할 수 없습니다.", "확인"); Global.ischangemyinfobtn_clicked = true; Navigation.PopAsync(); } } } } } #endregion }
private static string GetKnownGoodPercentEncodedValue(int codePoint) { // Convert the code point to UTF16, then call Encoding.UTF8.GetBytes, then hex-encode everything return(String.Concat(_utf8EncodingThrowOnInvalidBytes.GetBytes(Char.ConvertFromUtf32(codePoint)).Select(b => String.Format(CultureInfo.InvariantCulture, "%{0:X2}", b)))); }
// Token: 0x060013FF RID: 5119 RVA: 0x00023C60 File Offset: 0x00021E60 public static byte[] StringToByteArray(string inputString) { UTF8Encoding utf8Encoding = new UTF8Encoding(); return(utf8Encoding.GetBytes(inputString)); }
protected void Page_Load(object sender, EventArgs e) { string account = "C48907006"; //用户名是登录用户中心->验证码、通知短信->帐户及签名设置->APIID string password = "******"; //密码是请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY string mobile = Request.QueryString["mobile"]; Random rad = new Random(); int mobile_code = rad.Next(100000, 999999); Session["smscode"] = mobile_code; //int mobile_code = Convert.ToInt32(Request.QueryString["yzm"]); string content = "您的验证码是:" + mobile_code + "。请不要把验证码泄露给其他人。"; //Session["mobile"] = mobile; //Session["mobile_code"] = mobile_code; string postStrTpl = "account={0}&password={1}&mobile={2}&content={3}"; UTF8Encoding encoding = new UTF8Encoding(); byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content)); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(PostUrl); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentLength = postData.Length; Stream newStream = myRequest.GetRequestStream(); // Send the data. newStream.Write(postData, 0, postData.Length); newStream.Flush(); newStream.Close(); HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); if (myResponse.StatusCode == HttpStatusCode.OK) { StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); //Response.Write(reader.ReadToEnd()); string res = reader.ReadToEnd(); int len1 = res.IndexOf("</code>"); int len2 = res.IndexOf("<code>"); string code = res.Substring((len2 + 6), (len1 - len2 - 6)); //Response.Write(code); int len3 = res.IndexOf("</msg>"); int len4 = res.IndexOf("<msg>"); string msg = res.Substring((len4 + 5), (len3 - len4 - 5)); Response.Write(msg); Response.End(); } else { //访问失败 } }
public void Test_14_FolderResource_DELETE_Folder() { server.Register(new HttpFolderResource("/Test14", "Data", true, true, true, false)); using (CookieWebClient Client = new CookieWebClient()) { Encoding Utf8 = new UTF8Encoding(true); Client.UploadData("http://localhost:8080/Test14/Folder/string.txt", "PUT", Utf8.GetBytes(new string('Ω', 100000))); Client.UploadData("http://localhost:8080/Test14/Folder", "DELETE", new byte[0]); } }
public void Test_13_FolderResource_PUT_CreateFolder() { server.Register(new HttpFolderResource("/Test13", "Data", true, false, true, false)); using (CookieWebClient Client = new CookieWebClient()) { Encoding Utf8 = new UTF8Encoding(true); string s1 = new string('Ω', 100000); Client.UploadData("http://localhost:8080/Test13/Folder/string.txt", "PUT", Utf8.GetBytes(s1)); byte[] Data = Client.DownloadData("http://localhost:8080/Test13/Folder/string.txt"); string s2 = Utf8.GetString(Data); Assert.AreEqual(s1, s2); } }
public static async Task <HttpResponseMessage> RunEstimate([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req, TraceWriter log) { log.Info("Estimate Received."); try { // Load Parameters. var appId = req.GetQueryNameValuePairs() .FirstOrDefault(q => String.Compare(q.Key, "appId", StringComparison.OrdinalIgnoreCase) == 0) .Value; var trigger = req.GetQueryNameValuePairs() .FirstOrDefault(q => String.Compare(q.Key, "trigger", StringComparison.OrdinalIgnoreCase) == 0) .Value; // Load Headers. if (!req.Headers.TryGetValues("X-SecureShare-Signature", out var headerValues)) { log.Error("Signature Header Missing."); return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Signature Header Missing.")); } // Load Request Body. var requestBody = await req.Content.ReadAsStringAsync(); var requestUri = req.RequestUri.ToString(); var secretKeyBytes = new UTF8Encoding().GetBytes(APIKey); // Verify Signature. using (var hmac = new HMACSHA1(secretKeyBytes)) { var encoder = new UTF8Encoding(); var signatureBytes = encoder.GetBytes(requestUri + requestBody.SafeLeft(200)); var signatureHash = hmac.ComputeHash(signatureBytes); var computedSignature = Convert.ToBase64String(signatureHash); var signatureHeaderValue = headerValues.First(); if (!string.Equals(computedSignature, signatureHeaderValue)) { //return BadRequest(computedSignature); log.Error("Invalid Signature."); return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid Signature.")); } } try { // Load VIN. var bmsDocument = new XmlDocument(); bmsDocument.Load(new XmlTextReader(new StringReader(requestBody)) { Namespaces = false }); var vin = bmsDocument.SelectSingleNode("/VehicleDamageEstimateAddRq/VehicleInfo/VINInfo/VIN/VINNum") ?.InnerText; // Lookup Vehicle. if (!string.IsNullOrEmpty(vin)) { var veh = await new ServiceFactory(ConnectionString, new GenericIdentity("*****@*****.**")) .GetByIdAsync <IVehicleDto>(vin); if (!veh.ManualEntryInd) { log.Info($"Vehicle Found: {veh.VehicleVIN}"); } } } catch (Exception e) { log.Error(e.Message); Logger.LogException(e); } // Open Connection. using (var conn = new SqlConnection(ConnectionString)) { // Save Estimate. await conn.ExecuteAsync("Service.usp_SaveCCCEstimate", new { AppId = appId, Trigger = trigger, EstimateXml = requestBody }, commandType : CommandType.StoredProcedure); log.Info("Estimate Saved."); try { // Create Repairs. await conn.ExecuteAsync("Repair.usp_CreateFromCCCEstimates", commandType : CommandType.StoredProcedure); log.Info("Repair Creation Run."); } catch (Exception e) { log.Error(e.Message); Logger.LogException(e); } } } catch (Exception e) { // Record Error. log.Error(e.Message); Logger.LogException(e); // Return. return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Processing Error.")); } // Return. return(req.CreateResponse(HttpStatusCode.OK)); }
// Reading constructor public EncodingStreamWrapper(Stream stream, Encoding?encoding) { try { _isReading = true; _stream = stream; // Decode the expected encoding SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); // Get the byte order mark so we can determine the encoding // May want to try to delay allocating everything until we know the BOM SupportedEncoding declEnc = ReadBOMEncoding(encoding == null); // Check that the expected encoding matches the decl encoding. if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) { ThrowExpectedEncodingMismatch(expectedEnc, declEnc); } // Fastpath: UTF-8 BOM if (declEnc == SupportedEncoding.UTF8) { // Fastpath: UTF-8 BOM, No declaration FillBuffer(2); if (_bytes[_byteOffset + 1] != '?' || _bytes[_byteOffset] != '<') { return; } FillBuffer(BufferLength); CheckUTF8DeclarationEncoding(_bytes, _byteOffset, _byteCount, declEnc, expectedEnc); } else { // Convert to UTF-8 EnsureBuffers(); FillBuffer((BufferLength - 1) * 2); SetReadDocumentEncoding(declEnc); CleanupCharBreak(); int count = _encoding.GetChars(_bytes, _byteOffset, _byteCount, _chars, 0); _byteOffset = 0; _byteCount = s_validatingUTF8.GetBytes(_chars, 0, count, _bytes, 0); // Check for declaration if (_bytes[1] == '?' && _bytes[0] == '<') { CheckUTF8DeclarationEncoding(_bytes, 0, _byteCount, declEnc, expectedEnc); } else { // Declaration required if no out-of-band encoding if (expectedEnc == SupportedEncoding.None) { throw new XmlException(SR.XmlDeclarationRequired); } } } } catch (DecoderFallbackException ex) { throw new XmlException(SR.XmlInvalidBytes, ex); } }
public static byte[] GetUtf8Bytes(String s) { return(utf8Encode.GetBytes(s)); }
static void Main(string[] args) { var urls = new List <string>(); for (int i = 1; i < 9; i++) { string index = i.ToString(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(link); webreq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64;x64; rv: 58.0) Gecko / 20100101 Firefox / 58.0"; webreq.ContentType = "application/x-www-form-urlencoded;charset = UTF - 8"; //webreq.MediaType = "application/json"; webreq.Accept = "application/json, text/javascript, /; q=0.01"; webreq.Method = "POST"; CookieContainer container = new CookieContainer(); Cookie ck = new Cookie(); webreq.Headers.Add("Cookie", @"forty_n_user=AdtdiU80-T3GEVr4aAuQAA~~;forty_n_t=1.cf026a.1534782833.1.4.1534782833.1534782948.4.0;di_roxanne[visit_id]=453190142; di_roxannevisitor_id]=714806210;diGeolocationIgnoreData={""currentRequestCount"":2,""createdAt"":1534782850335};tp_referral=1541655;di_referral=%7B%22ppc_terms%22%3Anull%2C%22url%22%3A%22NA%22%2C%22type%22%3A%22Direct%22%2C%22createdAt%22%3A%222018-08-20T16%3A33%3A55%2B0000%22%7D;di_page_history=a%3A2%3A%7Bi%3A0%3Bs%3A13%3A%22used-vehicles%22%3Bi%3A1%3Bs%3A28%3A%22welcome-to-lexus-of-edmonton%22%3B%7D;di_visited=3; m_sidebar_user_settings_used=type;gwcc=%7B%22expires%22%3A86400%2C%22backoff_expires%22%3A1534869246%7D;im-visitor-ip=23.17.106.204"); string postData = string.Format(@"action=im_ajax_call&perform=get_results&order=t3j5n5&orderby=distance&page={0}&_nonce=fb607d6b7586e676a3010da691f417b7&_post_id={1}&_referer=/used-vehicles/", index, "5"); webreq.ContentLength = postData.Length; using (Stream writeStream = webreq.GetRequestStream()) { UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes(postData); writeStream.Write(bytes, 0, bytes.Length); } string outputstring = string.Empty; using (HttpWebResponse response = (HttpWebResponse)webreq.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8)) { outputstring = readStream.ReadToEnd(); } } } HtmlDocument document = new HtmlDocument(); document.LoadHtml(outputstring); var cars = document.DocumentNode.SelectNodes(".//div[contains(@class,'vehicle-title')]"); foreach (var car in cars) { var carDetail = car.SelectSingleNode(".//a"); var url = carDetail.GetAttributeValue("href", "").Replace("\\\"", "").Replace("/", ""); if (!urls.Contains(url)) { urls.Add(url); } } } Console.ReadKey(); }
public static string EncryptRijndael(string original) { byte[] encrypted; byte[] toEncrypt; UTF8Encoding utf8Converter = new UTF8Encoding(); toEncrypt = utf8Converter.GetBytes(original); RijndaelManaged myRijndael = new RijndaelManaged(); MemoryStream ms = new MemoryStream(); ICryptoTransform encryptor = myRijndael.CreateEncryptor(Key, IV); CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); cs.Write(toEncrypt, 0, toEncrypt.Length); cs.FlushFinalBlock(); encrypted = ms.ToArray(); string encryptedString = Convert.ToBase64String(encrypted); return encryptedString; }