private void DoPosTest(ASCIIEncoding ascii, string source, int charIndex, int count, byte[] bytes, int byteIndex) { int actualValue; actualValue = ascii.GetBytes(source, charIndex, count, bytes, byteIndex); Assert.True(VerifyASCIIEncodingGetBytesResult(ascii, source, charIndex, count, bytes, byteIndex, actualValue)); }
private void DoPosTest(ASCIIEncoding ascii, int byteCount, int expectedValue) { int actualValue; ascii = new ASCIIEncoding(); actualValue = ascii.GetMaxCharCount(byteCount); Assert.Equal(expectedValue, actualValue); }
private bool VerifyASCIIEncodingGetBytesResult( ASCIIEncoding ascii, char[] chars, int charIndex, int count, byte[] bytes, int byteIndex, int actualValue) { if (0 == chars.Length) return 0 == actualValue; int currentCharIndex; //index of current encoding character int currentByteIndex; //index of current encoding byte int charEndIndex = charIndex + count - 1; for (currentCharIndex = charIndex, currentByteIndex = byteIndex; currentCharIndex <= charEndIndex; ++currentCharIndex) { if (chars[currentCharIndex] <= c_MAX_ASCII_CHAR && chars[currentCharIndex] >= c_MIN_ASCII_CHAR) { //verify normal ASCII encoding character if ((int)chars[currentCharIndex] != (int)bytes[currentByteIndex]) { return false; } ++currentByteIndex; } else //Verify ASCII encoder replacment fallback { ++currentByteIndex; } } return actualValue == (currentByteIndex - byteIndex); }
private void DoNegAOORTest(ASCIIEncoding ascii, int charCount) { Assert.Throws<ArgumentOutOfRangeException>(() => { ascii.GetMaxByteCount(charCount); }); }
public static void Main() { try { TcpClient tcpclnt = new TcpClient(); Console.WriteLine("Connecting....."); tcpclnt.Connect("172.21.5.99",8001); // use the ipaddress as in the server program Console.WriteLine("Connected"); Console.Write("Enter the string to be transmitted : "); String str=Console.ReadLine(); Stream stm = tcpclnt.GetStream(); ASCIIEncoding asen= new ASCIIEncoding(); byte[] ba=asen.GetBytes(str); Console.WriteLine("Transmitting....."); stm.Write(ba,0,ba.Length); byte[] bb=new byte[100]; int k=stm.Read(bb,0,100); for (int i=0;i<k;i++) Console.Write(Convert.ToChar(bb[i])); tcpclnt.Close(); } catch (Exception e) { Console.WriteLine("Error..... " + e.StackTrace); } }
public static void Main() { try { TcpClient tcpclnt = new TcpClient(); //Console.WriteLine("Connecting....."); tcpclnt.Connect("161.115.86.57",8001); // use the ipaddress as in the server program //Console.WriteLine("Connected"); //Console.Write("Enter the string to be transmitted : "); String sendString = Console.ReadLine(); Stream serverSendStream = tcpclnt.GetStream(); ASCIIEncoding asen = new ASCIIEncoding(); byte[] bytesInSend = asen.GetBytes(sendString); //Console.WriteLine("Transmitting....."); // send length then string to read to length+1 serverSendStream.Write(bytesInSend, 0, bytesInSend.Length); byte[] bytesToRead = new byte[100]; int numberOfBytesRead = serverSendStream.Read(bytesToRead, 0, bytesToRead.Length); for (int i = 0; i < numberOfBytesRead; i++) Console.Write(Convert.ToChar(bytesToRead[i])); tcpclnt.Close(); } catch (Exception e) { Console.WriteLine("Error..... " + e.StackTrace); } }
private void DoPosTest(ASCIIEncoding ascii, byte[] bytes, int index, int count) { int actualValue; ascii = new ASCIIEncoding(); actualValue = ascii.GetCharCount(bytes, index, count); Assert.Equal(count, actualValue); }
//============================================================================ public static String stringToBase64(String str) { var encoding = new ASCIIEncoding(); byte[] buf = encoding.GetBytes(str); int size = buf.Length; char[] ar = new char[((size + 2) / 3) * 4]; int a = 0; int i = 0; while (i < size) { byte b0 = buf[i++]; byte b1 =(byte) ((i < size) ? buf[i++] : 0); byte b2 = (byte) ((i < size) ? buf[i++] : 0); ar[a++] = BASE64_ALPHABET[(b0 >> 2) & 0x3f]; ar[a++] = BASE64_ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & 0x3f]; ar[a++] = BASE64_ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & 0x3f]; ar[a++] = BASE64_ALPHABET[b2 & 0x3f]; } int o=0; switch (size % 3) { case 1: ar[--a] = '='; break; case 2: ar[--a] = '='; break; } return new String(ar); }
static void RunTest () { // Start the server thread ServerThread serverThread = new ServerThread (); serverThread.Start (); // Create the client HttpWebRequest rq = (HttpWebRequest) WebRequest.Create ("http://" + IPAddress.Loopback.ToString () + ":54321"); rq.ProtocolVersion = HttpVersion.Version11; rq.KeepAlive = false; // Get the response HttpWebResponse rsp = (HttpWebResponse) rq.GetResponse (); ASCIIEncoding enc = new ASCIIEncoding (); StringBuilder result = new StringBuilder (); // Stream the body in 1 byte at a time byte [] bytearr = new byte [1]; Stream st = rsp.GetResponseStream (); while (true) { int b = st.Read (bytearr, 0, 1); if (b == 0) { break; } result.Append (enc.GetString (bytearr)); } Assert.AreEqual ("012345670123456789abcdefabcdefghijklmnopqrstuvwxyz", result.ToString (), "#1"); }
public static void sendMessage(Socket clientSocket) { ASCIIEncoding asn = new ASCIIEncoding(); String sendString = Console.ReadLine(); //String sendString = "This is a test!!!!!!!!!!!!!!!!!!!!!!!!"; clientSocket.Send(asn.GetBytes(sendString)); }
//пытаемся отправить кому-то сообщение о том, что хотим понаблюдать за его игрой //если прокатывает - в ответ нам начнут приходить сообщения о состоянии игры public void TryConnect(string ip, string port) { try { TcpClient tcpclnt = new TcpClient(); tcpclnt.Connect(IPAddress.Parse(ip), int.Parse(port)); String str = Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString(); Stream stm = tcpclnt.GetStream(); ASCIIEncoding asen = new ASCIIEncoding(); byte[] ba = asen.GetBytes(str); stm.Write(ba, 0, ba.Length); byte[] bb = new byte[255]; int k = stm.Read(bb, 0, 255); string an = ""; for (int i = 0; i < k; i++) an += Convert.ToChar(bb[i]); stm.Close(); tcpclnt.Close(); } catch (Exception e) { Debug.LogError(e.StackTrace); } }
public static void Main() { try { TcpListener Listener; Socket client_socket; acceptconnection(out Listener, out client_socket); Receive(client_socket); //int gh = testReceive(client_socket); ASCIIEncoding asen = new ASCIIEncoding(); client_socket.Send(asen.GetBytes("The string was recieved by the server.")); Console.WriteLine("\nSent Acknowledgement"); client_socket.Close(); Listener.Stop(); } catch (Exception error) { Console.WriteLine("Error..... " + error.StackTrace); } }
static int Main () { HttpWebRequest request = (HttpWebRequest) WebRequest.Create ("http://localhost:8081/Default.aspx"); request.Method = "POST"; ASCIIEncoding ascii = new ASCIIEncoding (); byte [] byData = ascii.GetBytes ("Mono ASP.NET"); request.ContentLength = byData.Length; Stream rs = request.GetRequestStream (); rs.Write (byData, 0, byData.Length); rs.Flush (); try { HttpWebResponse response = (HttpWebResponse) request.GetResponse (); using (StreamReader sr = new StreamReader (response.GetResponseStream (), Encoding.UTF8, true)) { string result = sr.ReadToEnd (); if (result.IndexOf ("<p>REQ:0</p>") == -1) { Console.WriteLine (result); return 1; } } response.Close (); } catch (WebException ex) { if (ex.Response != null) { StreamReader sr = new StreamReader (ex.Response.GetResponseStream ()); Console.WriteLine (sr.ReadToEnd ()); } else { Console.WriteLine (ex.ToString ()); } return 2; } return 0; }
public static bool OnActivate() { encoding = new ASCIIEncoding(); InitializeComponents(); installerForm.ShowDialog(); if (installSelected == false) return false; if (! InstallModuleCore()) return false; if (cyberwareSelected) { if (! InstallModuleCyberware()) return false; } if (equipmentSelected) { if (! InstallModuleEquipment()) return false; } if (rebalanceSelected) { if (! InstallModuleRebalance()) return false; } return true; }
/// <summary> /// 截取字符长度 /// </summary> /// <param name="inputString">字符</param> /// <param name="len">长度</param> /// <returns></returns> public static string CutString(string inputString, int len) { ASCIIEncoding ascii = new ASCIIEncoding(); int tempLen = 0; string tempString = ""; byte[] s = ascii.GetBytes(inputString); for (int i = 0; i < s.Length; i++) { if ((int)s[i] == 63) { tempLen += 2; } else { tempLen += 1; } try { tempString += inputString.Substring(i, 1); } catch { break; } if (tempLen > len) break; } //如果截过则加上半个省略号 byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString); if (mybyte.Length > len) tempString += "…"; return tempString; }
public string sendMessage() { ASCIIEncoding encoding = new ASCIIEncoding(); Byte[] userPassBytes = encoding.GetBytes(String.Format("{0}:{1}", appId, password)); String authHeader = "Authorization: Basic " + (Convert.ToBase64String(userPassBytes)); string postData = "version=1.0" + "&address=" + address + "&message=" + message; byte[] byteArray = encoding.GetBytes(postData); WebRequest request = WebRequest.Create("http://192.168.0.250:65182/"); request.Headers.Add(authHeader); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse response = request.GetResponse(); Console.WriteLine(((HttpWebResponse)response).StatusDescription); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); return responseFromServer; }
public KalimbaPdImplNetwork() { asciiEncoding = new ASCIIEncoding(); t = new Thread(NetworkRun); t.Start(); }
protected void Page_Load(object sender, EventArgs e) { string url = "https://graph.facebook.com/567517451/notifications"; HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url); ASCIIEncoding encoding = new ASCIIEncoding(); string postData = "access_token=355242331161855|qyYMEnPyR2y3sWK8H7rN-6n3lBU"; postData += "&template=Test"; postData += "&href=http://postaround.me"; byte[] data = encoding.GetBytes(postData); 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); } HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse(); string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); }
/// <summary> /// �����������վ��UTF-8���룬Http Post�������Ҳ��Ҫ��UTF-8���� /// HttpUtility.UrlEncode(merId, myEncoding) /// </summary> /// <param name="url">���ʵ�ַ����������</param> /// <param name="para">�����ַ���</param> /// <returns></returns> public static string PostHtmlFromUrl(string url, string postData) { String sResult = ""; try { ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(postData); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; request.ContentLength = postData.Length; Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); return content; } catch (Exception e) { sResult = "-101"; return sResult; } }
public static int echoMessage(Socket clientSocket) { string messageToSend = testReceive(clientSocket); ASCIIEncoding asn = new ASCIIEncoding(); clientSocket.Send(asn.GetBytes(messageToSend)); return messageToSend.Length; }
private void HandleClientComm(object client) { tcp_client = (TcpClient)client; NetworkStream client_stream = tcp_client.GetStream(); byte[] message = new byte[2048]; int bytes_read; while(isTrue == true) { bytes_read = 0; try { //blocks until a client sends a message bytes_read = client_stream.Read(message, 0, 2048); //Debug.Log(message); } catch (Exception e) { //a socket error has occured Debug.Log(e.Message); break; } if(bytes_read == 0) { //client has disconnected Debug.Log("Disconnected"); tcp_client.Close(); break; } ASCIIEncoding encoder = new ASCIIEncoding(); String msg = encoder.GetString(message,0,bytes_read); //Debug.Log(msg); String[] nums = msg.Split('!'); float x,y,z; if (nums.Length==3) { x = float.Parse(nums[0], CultureInfo.InvariantCulture.NumberFormat); y = float.Parse(nums[1], CultureInfo.InvariantCulture.NumberFormat); z = float.Parse(nums[2], CultureInfo.InvariantCulture.NumberFormat); Vector3 newPos = new Vector3(x,y,z); player.changePos(newPos); } else { tcp_client.GetStream().Close(); tcp_client.Close(); } } if(isTrue == false) { tcp_client.Close(); Debug.Log("closing tcp client"); } }
public static bool StartInjection(string DllName, uint ProcessID) { bool flag; try { IntPtr hProcess = new IntPtr(0); IntPtr lpBaseAddress = new IntPtr(0); IntPtr lpStartAddress = new IntPtr(0); IntPtr hHandle = new IntPtr(0); int nSize = DllName.Length + 1; hProcess = OpenProcess(0x1f0fff, false, ProcessID); if (!(hProcess != IntPtr.Zero)) { throw new Exception("Processus non ouvert...injection \x00e9chou\x00e9e"); } lpBaseAddress = VirtualAllocEx(hProcess, IntPtr.Zero, (UIntPtr) nSize, 0x1000, 0x40); if (!(lpBaseAddress != IntPtr.Zero)) { throw new Exception("M\x00e9moire non allou\x00e9e...injection \x00e9chou\x00e9e"); } ASCIIEncoding encoding = new ASCIIEncoding(); int lpNumberOfBytesWritten = 0; if (!WriteProcessMemory(hProcess, lpBaseAddress, encoding.GetBytes(DllName), nSize, lpNumberOfBytesWritten)) { throw new Exception("Erreur d'\x00e9criture dans le processus...injection \x00e9chou\x00e9e"); } lpStartAddress = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); if (!(lpStartAddress != IntPtr.Zero)) { throw new Exception("Adresse LoadLibraryA non trouv\x00e9e...injection \x00e9chou\x00e9e"); } hHandle = CreateRemoteThread(hProcess, IntPtr.Zero, 0, lpStartAddress, lpBaseAddress, 0, 0); if (!(hHandle != IntPtr.Zero)) { throw new Exception("Probl\x00e8me au lancement du thread...injection \x00e9chou\x00e9e"); } uint num3 = WaitForSingleObject(hHandle, 0x2710); if (((num3 == uint.MaxValue) && (num3 == 0x80)) && ((num3 == 0) && (num3 == 0x102))) { throw new Exception("WaitForSingle \x00e9chou\x00e9 : " + num3.ToString() + "...injection \x00e9chou\x00e9e"); } if (!VirtualFreeEx(hProcess, lpBaseAddress, 0, 0x8000)) { throw new Exception("Probl\x00e8me lib\x00e8ration de m\x00e9moire...injection \x00e9chou\x00e9e"); } if (hHandle == IntPtr.Zero) { throw new Exception("Mauvais Handle du thread...injection \x00e9chou\x00e9e"); } CloseHandle(hHandle); return true; } catch (Exception exception) { Console.WriteLine(exception.Message); flag = false; } return flag; }
private void DoPosTest(string source, int expectedValue) { ASCIIEncoding ascii; int actualValue; ascii = new ASCIIEncoding(); actualValue = ascii.GetByteCount(source); Assert.Equal(expectedValue, actualValue); }
public void Can_deserialize_into_object_with_missing_properties() { var xml_with_extra_property = _simpleObjectXml.Replace("SimpleObject", "SimpleObject3"); var simpleObject3 = new ASCIIEncoding().GetBytes(xml_with_extra_property).DeserializeXml<SimpleObject3>(); Assert.IsNotNull(simpleObject3); Assert.AreEqual("a property", simpleObject3.A); }
public void respond() { ASCIIEncoding encoder = new ASCIIEncoding(); byte[] buffer = encoder.GetBytes(response + "\n"); client_stream.Write(buffer, 0 , buffer.Length); client_stream.Flush(); }
public BfsBinaryReader(BinaryReader binaryReader, Endianness fileEndianness) { reader = binaryReader; FileEndianness = fileEndianness; asciienc = new ASCIIEncoding(); utf7enc = new UTF7Encoding(); utf32enc = new UTF32Encoding(); }
public void Can_deserialzie_simple_object() { var simpleObject = new ASCIIEncoding().GetBytes(_simpleObjectXml).DeserializeXml<SimpleObject>(); Assert.IsNotNull(simpleObject); Assert.AreEqual("a property", simpleObject.A); Assert.AreEqual("b property", simpleObject.B); }
/*private void WriteMessage(string msg) { if (this.rtbServer.InvokeRequired) { WriteMessageDelegate d = new WriteMessageDelegate(WriteMessage); this.rtbServer.Invoke(d, new object[] { msg }); } else { this.rtbServer.AppendText(msg + Environment.NewLine); } }*/ /// <summary> /// Echo the message back to the sending client /// </summary> /// <param name="msg"> /// String: The Message to send back /// </param> /// <param name="encoder"> /// Our ASCIIEncoder /// </param> /// <param name="clientStream"> /// The Client to communicate to /// </param> private void Echo(string msg, ASCIIEncoding encoder, NetworkStream clientStream) { // Now Echo the message back byte[] buffer = encoder.GetBytes(msg); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); }
protected void Page_Load(object sender, EventArgs e) { string sURL; sURL = "http://192.168.1.40:9101/api/query"; string stringData = "select data in (now -5minutes, now) limit 10 where Path = '/FH-RPi02/Meter31/Energy'"; //stringData = "select data in ('7/1/2013', '7/2/2013') limit 10 where Path = '/RasPi1/Meter29/Energy'"; stringData = "select data in (now -5minutes, now) limit 5 streamlimit 1 where Metadata/Location/Building='Faculty Housing'"; HttpWebRequest req = WebRequest.Create(sURL) as HttpWebRequest; IWebProxy iwprxy = WebRequest.GetSystemWebProxy(); req.Proxy = iwprxy; req.Method = "POST"; req.ContentType = ""; ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(stringData); req.ContentLength = data.Length; Stream os = req.GetRequestStream(); os.Write(data, 0, data.Length); os.Close(); HttpWebResponse response = req.GetResponse() as HttpWebResponse; Stream objStream; objStream = req.GetResponse().GetResponseStream(); StreamReader objReader = new StreamReader(objStream); var jss = new JavaScriptSerializer(); string sline = objReader.ReadLine(); //sline = objReader.ReadLine(); var f1 = jss.Deserialize<dynamic>(sline); var f21 = f1[0]; var f2 = f21["uuid"]; var f3 = f21["Readings"]; timeSt = new int[f3.Length]; val = new double[f3.Length]; timeSeries = new string[f3.Length]; for (int i = 0; i < f3.Length; i++) { var f4 = f3[i]; timeSt[i] = Convert.ToInt32( f4[0]/1000); val[i] = Convert.ToDouble( f4[1]); } timeSeries = Utilitie_S.TimeFormatterBar(timeSt); response.Close(); }
public static bool OnActivate() { encoding = new ASCIIEncoding(); if (! InstallModuleCyberware()) return false; return true; }
public void run() { try { LeapMotion.LeapMotion leapmotion = new LeapMotion.LeapMotion(); leapmotion.SetParameters("Leap Motion", "local", ListeningMode.UsbConnection); leapmotion.Initialise(); IPAddress ipAd = IPAddress.Parse("127.0.0.1"); // use local m/c IP address, and // use the same in the client /* Initializes the Listener */ TcpListener myList = new TcpListener(ipAd, 8001); /* Start Listeneting at the specified port */ myList.Start(); Console.WriteLine("The server is running at port 8001..."); Console.WriteLine("The local End point is :" + myList.LocalEndpoint); Console.WriteLine("Waiting for a connection....."); Socket s = myList.AcceptSocket(); Console.WriteLine("Connection accepted from " + s.RemoteEndPoint); String str = ""; ASCIIEncoding asen = new ASCIIEncoding(); float[] lastValue = new float[2]; float[] coordinates = new float[2]; while (true) { try { coordinates = leapmotion.getCoordinate(); //Console.WriteLine("X: " + coordinates[0] + ", Y: " + coordinates[1]); str = lastValue[0] + "," + lastValue[1] + "!"; if (coordinates != null) { str = coordinates[0] + "," + coordinates[1] + "!"; //Console.WriteLine("X: " + coordinates[0] + ", Y: " + coordinates[1]); //Console.WriteLine("Sent: " + str); } s.Send(asen.GetBytes(str)); } catch (Exception e) { //Console.WriteLine("Error recieved:" + e); } } /* clean up */ s.Close(); myList.Stop(); Console.ReadLine(); //tcpclnt.Close(); } catch (Exception e) { Console.WriteLine("Error..... " + e.StackTrace); } }
private void Communication_Submit() { // send to server try { TcpClient tcpclnt = new TcpClient(); Console.WriteLine("Connecting....."); tcpclnt.Connect(GlobalData.IP, 5567); // use the ipaddress as in the server program Console.WriteLine("Connected"); Console.Write("Enter the string to be transmitted : "); String str = "Game" + "$" + GlobalData.UserID + "$" + Convert.ToString(GlobalData.numRound_FourLink) + "$" + Convert.ToString(GlobalData.numRoute_FourLink) + "$" + GlobalData.NumGame.ToString() + "$" + GlobalData.Score_total.ToString() + "$" + GlobalData.NumScenario.ToString(); Stream stm = tcpclnt.GetStream(); ASCIIEncoding asen = new ASCIIEncoding(); byte[] ba = asen.GetBytes(str); Console.WriteLine("Transmitting....."); stm.Write(ba, 0, ba.Length);//send route info to server //receive data from server once submit byte[] dat = new byte[100]; int datLength = stm.Read(dat, 0, 100); string strDat = Encoding.ASCII.GetString(dat, 0, datLength); //label_submit.Visible = true; //label_submit.Text = strDat; DialogResult dialog = MessageBox.Show(strDat, "Important Message");//, MessageBoxIcon.Asterisk); button_Submit.Enabled = false; //receive data from server byte[] data = new byte[100]; int receivedDataLength = stm.Read(data, 0, 100); GlobalData.strData = Encoding.ASCII.GetString(data, 0, receivedDataLength); for (int i = 0; i < receivedDataLength; i++) { Console.Write(Convert.ToChar(data[i])); } //tcpclnt.Close(); } catch (Exception err) { Console.WriteLine("Error..... " + err.StackTrace); } try { GlobalData.msg_received = GlobalData.strData.Split('$'); GlobalData.TT[0] = GlobalData.msg_received[3]; GlobalData.TT[1] = GlobalData.msg_received[4]; GlobalData.Path_shortest = GlobalData.msg_received[5]; GlobalData.IsEquilibrium = Convert.ToBoolean(GlobalData.msg_received[6]); GlobalData.Score_total -= Convert.ToInt32(GlobalData.TT[GlobalData.numRoute_FourLink - 1]); label4_score_total.Text = GlobalData.Score_total.ToString(); } catch { } ResultsForm result = new ResultsForm(); result.Visible = true; //this.Visible = false; this.Close(); }
protected override void ProcessReceive(SocketAsyncEventArgs e) { if (!ValidateAsyncResult(e)) { return; } var context = (ConnectContext)e.UserToken; int prevMatched = context.SearchState.Matched; int result = e.Buffer.SearchMark(e.Offset, e.BytesTransferred, context.SearchState); if (result < 0) { int total = e.Offset + e.BytesTransferred; if (total >= m_ReceiveBufferSize) { OnException("receive buffer size has been exceeded"); return; } e.SetBuffer(total, m_ReceiveBufferSize - total); StartReceive(context.Socket, e); return; } int responseLength = prevMatched > 0 ? (e.Offset - prevMatched) : (e.Offset + result); if (e.Offset + e.BytesTransferred > responseLength + m_LineSeparator.Length) { OnException("protocol error: more data has been received"); return; } var lineReader = new StringReader(ASCIIEncoding.GetString(e.Buffer, 0, responseLength)); var line = lineReader.ReadLine(); if (string.IsNullOrEmpty(line)) { OnException("protocol error: invalid response"); return; } //HTTP/1.1 2** OK var pos = line.IndexOf(m_Space); if (pos <= 0 || line.Length <= (pos + 2)) { OnException("protocol error: invalid response"); return; } var httpProtocol = line.Substring(0, pos); if (!m_ResponsePrefix11.Equals(httpProtocol) && !m_ResponsePrefix10.Equals(httpProtocol)) { OnException("protocol error: invalid protocol"); return; } var statusPos = line.IndexOf(m_Space, pos + 1); if (statusPos < 0) { OnException("protocol error: invalid response"); return; } int statusCode; //Status code should be 2** if (!int.TryParse(line.Substring(pos + 1, statusPos - pos - 1), out statusCode) || (statusCode > 299 || statusCode < 200)) { OnException("the proxy server refused the connection"); return; } OnCompleted(new ProxyEventArgs(context.Socket, TargetHostHame)); }
private void ReceiveCallback(IAsyncResult result) { try { if (WorkingSocket != null && WorkingSocket.Connected) { try { int num_read = WorkingSocket.EndReceive(result); sw.AutoFlush = true; ASCIIEncoding asen = new ASCIIEncoding(); string name = asen.GetString(receive_buffer, 0, num_read); name = name.Replace("\0", ""); name = name.Replace("\n", ""); name = name.Replace("\r", ""); if (name == "" || name == null) { return; } // process input data here!!!! switch (name.ToUpper()) { case "HELP": // list of all commands sw.Write("* Commands are:\n" + "* HELP - show list of commands\n" + "* DX - shows last 5 spots\n" + "* BYE(or QUIT) - disconnect\n"); break; case "DX": // last 5 spots sw.Write("DX DE YT7PWR 14070.0 S56A RTTY CQ 1026Z \n"); break; case "BYE": case "QUIT": sw.Write("Bye!\n"); sw.Flush(); sw.Close(); connected = false; WorkingSocket.Disconnect(true); WorkingSocket.Close(1000); s.Close(); server_event.Set(); break; default: if (login) { sw.Write(name + "\n" + "Welcome to DX Cluster Server CWExpert 2.0.0 " + "YT7PWR S56A\n"); login = false; } else { string[] val = new string[1]; val[0] = ""; string[] delimiter = new string[1]; delimiter[0] = "SET/"; string[] delimiter_1 = new string[3]; delimiter_1[0] = "SET "; if (name.StartsWith("set/")) { val = name.ToUpper().Split(delimiter, StringSplitOptions.RemoveEmptyEntries); } else if (name.StartsWith("set ")) { val = name.ToUpper().Split(delimiter_1, StringSplitOptions.RemoveEmptyEntries); } foreach (string vals in val) { if (vals.StartsWith("NAME")) { string[] q; q = vals.Split(' '); op_name = q[1]; sw.Write("Name set to: " + op_name + "\n"); } else if (vals.StartsWith("QTH")) { string[] q; q = vals.Split(' '); qth = q[1]; sw.Write("QTH set to: " + qth + "\n"); } else { sw.Write("Unknow command: " + name + "\n" + "* Commands are:\n" + "* HELP - show list of commands\n" + "* DX - shows last 5 spots\n" + "* BYE(or QUIT) - disconnect\n"); } } } break; } if (connected) { WorkingSocket.BeginReceive(receive_buffer, 0, receive_buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null); } } catch (IOException ex) { Debug.Write(ex.ToString()); connected = false; sock.Disconnect(true); server_event.Set(); } } else { Debug.Write("Disconnected!\n"); WorkingSocket.Close(); WorkingSocket = null; server_event.Set(); } } catch (SocketException socketException) { //WSAECONNRESET, the other side closed impolitely if (socketException.ErrorCode == 10054) { if (WorkingSocket != null) { WorkingSocket.Close(1000); WorkingSocket = null; } server_event.Set(); } } catch (ObjectDisposedException) { // The socket was closed out from under me if (WorkingSocket != null) { WorkingSocket.Close(1000); WorkingSocket = null; } server_event.Set(); } }
/// <summary> /// Adds the current user to the chat list /// </summary> /// <param name="clientSocket">The client's socket.</param> /// <param name="clientInput">The client's input.</param> private static void ControlChat(Socket clientSocket, string clientInput) { ASCIIEncoding asen = new ASCIIEncoding(); string[] clientInputSeparated = clientInput.Split(':'); membersInChat.Add(clientInputSeparated[1]); clientSocket.Send(asen.GetBytes("JoinedChat")); Console.WriteLine("User {0} has successfully joined the chat", clientInputSeparated[1]); byte[] givenInput = new byte[100]; int k = clientSocket.Receive(givenInput); Console.WriteLine("Got some input"); char[] test = new char[k]; for (int i = 0; i < k; i++) { test[i] = (Convert.ToChar(givenInput[i])); } clientInput = new string(test); Console.WriteLine("Input was: {0}", clientInput); if (clientInput != "RECEIVECHATNUMBER") { Console.WriteLine("Error in accessing Chat Number"); return; } asen = new ASCIIEncoding(); clientSocket.Send(asen.GetBytes(chatLines.ToString())); Console.WriteLine("Sent the ChatLine number, {0}", chatLines.ToString()); givenInput = new byte[100]; k = clientSocket.Receive(givenInput); test = new char[k]; for (int i = 0; i < k; i++) { test[i] = (Convert.ToChar(givenInput[i])); } clientInput = new string(test); if (clientInput != "RECEIVEPREVIOUSCHAT") { Console.WriteLine("Error in accessing Previous Chat"); return; } foreach (var currentChatLine in currentChatList) { clientSocket.Send(asen.GetBytes(currentChatLine)); givenInput = new byte[100]; k = clientSocket.Receive(givenInput); test = new char[k]; for (int i = 0; i < k; i++) { test[i] = (Convert.ToChar(givenInput[i])); } clientInput = new string(test); if (clientInput == "RECEIVEDPREVIOUSCHAT") { //TODO: Add error handling; continue; } } }
internal static byte[] _SystemDataToPLCData(object data, int destByteWidth, int plcDataFormat) { switch (plcDataFormat) { case 0: { if (destByteWidth != 1) { throw new ArgumentException("sourceByteWidth"); } bool flag = (bool)Convert.ChangeType(data, typeof(bool)); return(new byte[] { (flag ? ((byte)1) : ((byte)0)) }); } case 1: switch (destByteWidth) { case 2: { ushort hostValue = (ushort)Convert.ChangeType(data, typeof(ushort)); return(BitConverter.GetBytes(PLCByteOrderConverter.HostToPLCOrder(hostValue))); } case 3: goto Label_01D0; case 4: { uint num5 = (uint)Convert.ChangeType(data, typeof(uint)); return(BitConverter.GetBytes(PLCByteOrderConverter.HostToPLCOrder(num5))); } case 8: { ulong num6 = (ulong)Convert.ChangeType(data, typeof(ulong)); return(BitConverter.GetBytes(PLCByteOrderConverter.HostToPLCOrder(num6))); } } goto Label_01D0; case 2: switch (destByteWidth) { case 2: { short num7 = (short)Convert.ChangeType(data, typeof(short)); num7 = (short)PLCByteOrderConverter.HostToPLCOrder((ushort)num7); return(BitConverter.GetBytes(num7)); } case 3: goto Label_0274; case 4: { int num8 = (int)Convert.ChangeType(data, typeof(int)); return(BitConverter.GetBytes((int)PLCByteOrderConverter.HostToPLCOrder((uint)num8))); } case 8: { long num9 = (long)Convert.ChangeType(data, typeof(long)); return(BitConverter.GetBytes((long)PLCByteOrderConverter.HostToPLCOrder((ulong)num9))); } } goto Label_0274; case 3: switch (destByteWidth) { case 2: { ushort num = (ushort)Convert.ChangeType(data, typeof(ushort)); return(BitConverter.GetBytes(PLCByteOrderConverter.HostToPLCOrder(Convert.ToUInt16(num.ToString(), 0x10)))); } case 4: { uint num2 = (uint)Convert.ChangeType(data, typeof(uint)); return(BitConverter.GetBytes(PLCByteOrderConverter.HostToPLCOrder(Convert.ToUInt32(num2.ToString(), 0x10)))); } case 8: { ulong num3 = (ulong)Convert.ChangeType(data, typeof(ulong)); return(BitConverter.GetBytes(PLCByteOrderConverter.HostToPLCOrder(Convert.ToUInt64(num3.ToString(), 0x10)))); } } break; case 4: switch (destByteWidth) { case 4: { float num10 = (float)Convert.ChangeType(data, typeof(float)); return(PLCByteOrderConverter.SwapByteIfNeed(BitConverter.GetBytes(num10))); } case 8: { double num11 = (double)Convert.ChangeType(data, typeof(double)); return(PLCByteOrderConverter.SwapByteIfNeed(BitConverter.GetBytes(num11))); } } throw new ArgumentOutOfRangeException("destByteWidht"); case 5: { byte[] destinationArray = new byte[destByteWidth]; for (int i = 0; i < destByteWidth; i++) { destinationArray[i] = 0; } string s = (string)Convert.ChangeType(data, typeof(string)); ASCIIEncoding encoding = new ASCIIEncoding(); Array.Copy(encoding.GetBytes(s), 0, destinationArray, 0, Math.Min(encoding.GetByteCount(s), destinationArray.Length)); return(destinationArray); } default: throw new ArgumentOutOfRangeException("destByteWidht"); } throw new ArgumentOutOfRangeException("destByteWidht"); Label_01D0: throw new ArgumentOutOfRangeException("destByteWidth"); Label_0274: throw new ArgumentOutOfRangeException("destByteWidht"); }
public ALFTcpClient(string connectionName) { this.ConnectionName = connectionName; this.Connected = false; this._encoder = new ASCIIEncoding(); }
public static string slurpInputStreamAsString(Stream stream) { var encoding = new ASCIIEncoding(); return(encoding.GetString(slurpInputStream(stream))); }
/// <summary> /// 获取token /// </summary> /// <param name="apiUrl"></param> /// <returns></returns> public static TokenStyle GetTokenString(string apiUrl) { string strJson = string.Empty; HttpWebRequest request = null; HttpWebResponse response = null; try { ASCIIEncoding encoding = new ASCIIEncoding(); request = WebRequest.Create(apiUrl) as HttpWebRequest; request.AllowWriteStreamBuffering = true; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); request.ContentType = "multipart/form-data; boundary=" + boundary;//获取token request.Method = "POST"; request.KeepAlive = true; string format = "--" + boundary + "\r\nContent-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}\r\n"; //自带项目分隔符 MemoryStream stream = new MemoryStream(); //以下添加服务器token验证键值对 string s1 = string.Format(format, "client_id", "client.gate"); string s2 = string.Format(format, "client_secret", "ETP.Gate.2018!"); string s3 = string.Format(format, "grant_type", "client_credentials"); string s4 = string.Format(format, "scope", "ETPApi"); byte[] data1 = Encoding.UTF8.GetBytes(s1); byte[] data2 = Encoding.UTF8.GetBytes(s2); byte[] data3 = Encoding.UTF8.GetBytes(s3); byte[] data4 = Encoding.UTF8.GetBytes(s4); stream.Write(data1, 0, data1.Length); stream.Write(data2, 0, data2.Length); stream.Write(data3, 0, data3.Length); stream.Write(data4, 0, data4.Length); byte[] foot_data = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); //项目最后的分隔符字符串需要带上-- stream.Write(foot_data, 0, foot_data.Length); request.ContentLength = stream.Length; Stream requestStream = request.GetRequestStream(); //写入请求 stream.Position = 0L; //stream.CopyTo(requestStream); //framework4.0以上使用,改为以下方式写入 byte[] array = new byte[81920]; int count; while ((count = stream.Read(array, 0, array.Length)) != 0) { requestStream.Write(array, 0, count); } stream.Close(); requestStream.Close(); //获取服务器返回 using (response = request.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { strJson = reader.ReadToEnd(); reader.Close(); } } var result = JsonConvert.DeserializeObject <TokenStyle>(strJson); return(result); } catch (Exception ex) { return(null); } finally { if (response != null) { response.Close(); } } }
/// <summary> /// Gets content from the PagerDuty API /// </summary> /// <typeparam name="T">Type to return</typeparam> /// <param name="path">The path to return, including any query string</param> /// <param name="getFromJson"></param> /// <param name="httpMethod"></param> /// <param name="data"></param> /// <returns></returns> public async Task <T> GetFromPagerDutyAsync <T>(string path, Func <string, T> getFromJson, string httpMethod = "GET", object data = null) { var url = Settings.APIBaseUrl; var fullUri = url + path; using (MiniProfiler.Current.CustomTiming("http", fullUri, httpMethod)) { var req = (HttpWebRequest)WebRequest.Create(fullUri); req.Method = httpMethod; req.Headers.Add("Authorization: Token token=" + APIKey); if (httpMethod == "POST" || httpMethod == "PUT") { if (data != null) { var stringData = JSON.Serialize(data, JilOptions); var byteData = new ASCIIEncoding().GetBytes(stringData); req.ContentType = "application/json"; req.ContentLength = byteData.Length; var putStream = await req.GetRequestStreamAsync(); await putStream.WriteAsync(byteData, 0, byteData.Length); } } try { var resp = await req.GetResponseAsync(); using (var rs = resp.GetResponseStream()) { if (rs == null) { return(getFromJson(null)); } using (var sr = new StreamReader(rs)) { return(getFromJson(sr.ReadToEnd())); } } } catch (WebException e) { try { using (var ers = e.Response.GetResponseStream()) { if (ers == null) { return(getFromJson("fail")); } using (var er = new StreamReader(ers)) { e.AddLoggedData("API Response JSON", er.ReadToEnd()); } } } catch { } Current.LogException( e.AddLoggedData("Sent Data", JSON.Serialize(data, JilOptions)) .AddLoggedData("Endpoint", fullUri) .AddLoggedData("Headers", req.Headers.ToString()) .AddLoggedData("Contecnt Type", req.ContentType)); return(getFromJson("fail")); } } }
public void OnAuthenticateRequest(object source, EventArgs eventArgs) { HttpApplication app = (HttpApplication)source; // Get the request stream Stream httpStream = app.Request.InputStream; // I converted the stream to string so I can search for a known substring byte[] byteStream = new byte[httpStream.Length]; httpStream.Read(byteStream, 0, (int)httpStream.Length); string strRequest = Encoding.ASCII.GetString(byteStream); // This is the end of the initial SOAP envelope // Not sure if the fastest way to do this but works fine int idx = strRequest.IndexOf("</t:RequestSecurityToken></s:Body></s:Envelope>", 0); httpStream.Seek(0, SeekOrigin.Begin); if (idx != -1) { // Initial packet found, do nothing (HTTP status code is set to 200) return; } //the Authorization header is checked if present string authHeader = app.Request.Headers["Authorization"]; if (!string.IsNullOrEmpty(authHeader)) { if (authHeader == null || authHeader.Length == 0) { // No credentials; anonymous request return; } authHeader = authHeader.Trim(); if (authHeader.IndexOf("Basic", 0) != 0) { // the header doesn't contain basic authorization token // we will pass it along and // assume someone else will handle it return; } string encodedCredentials = authHeader.Substring(6); byte[] decodedBytes = Convert.FromBase64String(encodedCredentials); string s = new ASCIIEncoding().GetString(decodedBytes); string[] userPass = s.Split(new char[] { ':' }); string username = userPass[0]; string password = userPass[1]; // the user is validated against the SqlMemberShipProvider // If it is validated then the roles are retrieved from // the role provider and a generic principal is created // the generic principal is assigned to the user context // of the application if (Membership.ValidateUser(username, password)) { string[] roles = Roles.GetRolesForUser(username); app.Context.User = new GenericPrincipal(new GenericIdentity(username, "Membership Provider"), roles); } else { DenyAccess(app); return; } } else { app.Response.StatusCode = 401; app.Response.End(); } }
internal static string GetThumbnail(SPUser user, DirectoryEntry directoryEntry) { if (FoundationSyncSettings.Local.PictureExpiryDays <= -1) { return(null); } var siteUri = FoundationSyncSettings.Local.PictureStorageUrl; if (siteUri == null) { return(null); } if (string.IsNullOrEmpty(siteUri.AbsoluteUri)) { return(null); } var fileUri = string.Empty; //One-way hash of SystemUserKey, typically a SID. var sHash = SHA1.Create(); var encoding = new ASCIIEncoding(); var userBytes = encoding.GetBytes(user.SystemUserKey); var userHash = sHash.ComputeHash(userBytes); var userHashString = Convert.ToBase64String(userHash); //The / is the only illegal character for SharePoint in a Base64 string //Replacing it with $, which is not valid in a Base64 string, but works for our purposes userHashString = userHashString.Replace("/", "$"); var fileName = string.Format("{0}{1}", userHashString, ".jpg"); try { using (SPSite site = new SPSite(siteUri.AbsoluteUri)) { var web = site.RootWeb; var list = web.GetList("UserPhotos"); var folder = list.RootFolder; var file = folder.Files[fileName]; if (file.Length > 1) { var pictureExpiryDays = 1; try { pictureExpiryDays = FoundationSyncSettings.Local.PictureExpiryDays; } catch (InvalidCastException) { FoundationSyncSettings.Local.PictureExpiryDays = 1; pictureExpiryDays = 1; } catch (OverflowException) { FoundationSyncSettings.Local.PictureExpiryDays = 1; pictureExpiryDays = 1; } if ((file.TimeLastModified - DateTime.Now).TotalDays < pictureExpiryDays) { return((string)file.Item[SPBuiltInFieldId.EncodedAbsUrl]); } } } } catch (ArgumentNullException) { return(null); } catch (FileNotFoundException) { FoundationSync.LogMessage(1004, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Unexpected, string.Format("Invalid Site URL specified for Picture Site Collection URL."), null); return(null); } catch (Exception) { FoundationSync.LogMessage(2001, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Verbose, string.Format("Error retrieving picture file from UserPhotos library, continuing to pull new picture."), null); } if (FoundationSyncSettings.Local.UseExchange) { var ewsPictureSize = "648x648"; if (FoundationSyncSettings.Local.EwsPictureSize != null) { ewsPictureSize = FoundationSyncSettings.Local.EwsPictureSize; } var uri = new UriBuilder(string.Format("{0}/s/GetUserPhoto?email={1}&size=HR{2}", FoundationSyncSettings.Local.EwsUrl, user.Email, ewsPictureSize)); SPSecurity.RunWithElevatedPrivileges(delegate { var request = (HttpWebRequest)WebRequest.Create(uri.Uri); request.UseDefaultCredentials = true; try { using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NotModified) { if (response.GetResponseStream() != null) { var image = new Bitmap(response.GetResponseStream()); fileUri = SaveImage(image, siteUri.AbsoluteUri, fileName); } } else if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.InternalServerError || response.StatusCode == HttpStatusCode.ServiceUnavailable) { fileUri = string.Empty; } //else Exchange is not online, incorrect URL, etc. } } catch (Exception exception) { FoundationSync.LogMessage(601, FoundationSync.LogCategories.FoundationSync, TraceSeverity.Medium, exception.Message + exception.StackTrace, null); } }); } else { try { var byteArray = (byte[])directoryEntry.Properties["thumbnailPhoto"].Value; if (byteArray.Length > 0) { using (var ms = new MemoryStream(byteArray)) { var image = new Bitmap(ms); fileUri = SaveImage(image, siteUri.AbsoluteUri, fileName); } } } catch (Exception) { return(string.Empty); } } return(!string.IsNullOrEmpty(fileUri) ? fileUri : null); }
public static MidsCharacterFileFormat.eLoadReturnCode MxDExtractAndLoad(Stream iStream) { StreamReader streamReader; MidsCharacterFileFormat.eLoadReturnCode eLoadReturnCode; try { streamReader = new StreamReader(iStream); streamReader.BaseStream.Seek(0L, SeekOrigin.Begin); } catch (Exception ex) { MessageBox.Show("Unable to read data - " + ex.Message, "ExtractAndLoad Failed"); eLoadReturnCode = MidsCharacterFileFormat.eLoadReturnCode.Failure; return(eLoadReturnCode); } string[] strArray = new string[] { "ABCD", "0", "0", "0" }; string a = ""; try { string str = streamReader.ReadToEnd().Replace("||", "|\n|"); streamReader.Close(); string[] strArray2 = str.Split(new char[] { '\n' }); int num = -1; if (strArray2.Length < 1) { MessageBox.Show("Unable to locate data header - Zero-Length Input!", "ExtractAndLoad Failed"); eLoadReturnCode = MidsCharacterFileFormat.eLoadReturnCode.Failure; } else { for (int index = 0; index < strArray2.Length; index++) { int startIndex = strArray2[index].IndexOf("MxDu", StringComparison.Ordinal); if (startIndex < 0) { startIndex = strArray2[index].IndexOf("MxDz", StringComparison.Ordinal); } if (startIndex < 0) { startIndex = strArray2[index].IndexOf("MHDz", StringComparison.OrdinalIgnoreCase); } if (startIndex > -1) { strArray = strArray2[index].Substring(startIndex).Split(new char[] { ';' }); a = ((strArray.Length > 0) ? strArray[0] : string.Empty); num = index; break; } } if (num < 0) { MessageBox.Show("Unable to locate data header - Magic Number not found!", "ExtractAndLoad Failed"); eLoadReturnCode = MidsCharacterFileFormat.eLoadReturnCode.Failure; } else if (string.Equals(a, "MHDz", StringComparison.OrdinalIgnoreCase)) { eLoadReturnCode = MidsCharacterFileFormat.eLoadReturnCode.IsOldFormat; } else if (num + 1 == strArray2.Length) { MessageBox.Show("Unable to locate data - Nothing beyond header!", "ExtractAndLoad Failed"); eLoadReturnCode = MidsCharacterFileFormat.eLoadReturnCode.Failure; } else { string iString = string.Empty; for (int index2 = num + 1; index2 <= strArray2.Length - 1; index2++) { iString = iString + strArray2[index2] + "\n"; } int int32_ = Convert.ToInt32(strArray[1]); int int32_2 = Convert.ToInt32(strArray[2]); int int32_3 = Convert.ToInt32(strArray[3]); bool flag = false; if (strArray.Length > 4) { flag = string.Equals(strArray[4], "HEX", StringComparison.OrdinalIgnoreCase); } ASCIIEncoding asciiencoding = new ASCIIEncoding(); byte[] iBytes = asciiencoding.GetBytes(flag ? Zlib.UnbreakHex(iString) : Zlib.UnbreakString(iString, true)); streamReader.Close(); if (iBytes.Length < int32_3) { MessageBox.Show("Data chunk was incomplete! Check that the entire chunk was copied to the clipboard.", "ExtractAndLoad Failed"); eLoadReturnCode = MidsCharacterFileFormat.eLoadReturnCode.Failure; } else { if (iBytes.Length > int32_3) { Array.Resize <byte>(ref iBytes, int32_3); } iBytes = (flag ? Zlib.HexDecodeBytes(iBytes) : Zlib.UUDecodeBytes(iBytes)); if (iBytes.Length == 0) { eLoadReturnCode = MidsCharacterFileFormat.eLoadReturnCode.Failure; } else { if (a == "MxDz") { Array.Resize <byte>(ref iBytes, int32_2); iBytes = Zlib.UncompressChunk(ref iBytes, int32_); } if (iBytes.Length == 0) { eLoadReturnCode = MidsCharacterFileFormat.eLoadReturnCode.Failure; } else if (!MidsCharacterFileFormat.MxDReadSaveData(ref iBytes, false)) { eLoadReturnCode = MidsCharacterFileFormat.eLoadReturnCode.Failure; } else { eLoadReturnCode = MidsCharacterFileFormat.eLoadReturnCode.Success; } } } } } } catch (Exception ex2) { MessageBox.Show("Unable to read data - " + ex2.Message, "ExtractAndLoad Failed"); if (streamReader != null) { streamReader.Close(); } eLoadReturnCode = MidsCharacterFileFormat.eLoadReturnCode.Failure; } return(eLoadReturnCode); }
/// <summary> /// Make an HTTP request, with the given query args /// </summary> private string MakeRequest(Uri url, HttpVerb httpVerb, List <KeyValuePair <string, string> > args, JSONObject body, ContentType contentType = ContentType.JSON) { // Prepare HTTP url url = PrepareUrl(url, AccessToken, args); // Set request HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = httpVerb.ToString(); if ((httpVerb == HttpVerb.POST) || (httpVerb == HttpVerb.PUT)) { // Prepare HTTP body string postData = EncodeBody(body, contentType); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] postDataBytes = encoding.GetBytes(postData); // Set content type & length if (contentType == ContentType.JSON) { request.ContentType = "application/json"; } else { request.ContentType = "application/x-www-form-urlencoded"; } request.ContentLength = postDataBytes.Length; // Call API Stream requestStream = request.GetRequestStream(); requestStream.Write(postDataBytes, 0, postDataBytes.Length); requestStream.Close(); } // Resolve the API response try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Read response data StreamReader reader = new StreamReader(response.GetResponseStream()); string responseBody = reader.ReadToEnd(); // Throw the API call event APICallEventArgs apiCallEvent = new APICallEventArgs(); if (body != null) { apiCallEvent.Body = body.ToString(); } apiCallEvent.Response = responseBody; apiCallEvent.Url = url.ToString(); OnAPICall(apiCallEvent); // Return API response body return(responseBody); } } catch (WebException e) { JSONObject response = null; try { // Try throwing a well-formed api error Stream stream = e.Response.GetResponseStream(); StreamReader reader = new StreamReader(stream); response = JSONObject.CreateFromString(reader.ReadToEnd().Trim()); int status = Convert.ToInt16(response.GetJSONStringAttribute("status")); string error = response.GetJSONStringAttribute("error"); string message = response.GetJSONStringAttribute("message"); // optional: cause string cause = ""; try { cause = response.Dictionary["cause"].Dictionary["message"].String; } catch { } throw new RESTAPIException(status, error, message, cause); } catch (RESTAPIException restEx) { throw restEx; // this is a well-formed error message } catch { throw new RESTAPIException(999, e.Status.ToString(), e.Message); // this is not a well-formed message } } }
public void ClientServiceLoop() { try { IPHostEntry ipHostInfo = Dns.GetHostEntry(remote_addr); IPAddress ipAddress; IPEndPoint ipepRemote = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 100); if (remote_addr == "127.0.0.1") { ipepRemote = new IPEndPoint(IPAddress.Parse(remote_addr), int.Parse(remote_port)); } else { ipAddress = ipHostInfo.AddressList[0]; ipepRemote = new IPEndPoint(ipAddress, int.Parse(remote_port)); } byte[] buffer = new byte[2048]; int count = 0; string text = ""; ASCIIEncoding buf = new ASCIIEncoding(); text = "DXClusterClient - Connecting to " + remote_addr.ToString(); buf.GetBytes(text, 0, text.Length, buffer, 0); ClusterForm.Invoke(new CrossThreadCallback(ClusterForm.CrossThreadCommand), 1, buffer, text.Length); ClusterClient.Connect(ipepRemote); if (ClusterClient.Connected) { sw = ClusterClient.GetStream(); sr = ClusterClient.GetStream(); text = "DXClusterClient - Connected to " + remote_addr.ToString(); buf.GetBytes(text, 0, text.Length, buffer, 0); ClusterForm.Invoke(new CrossThreadCallback(ClusterForm.CrossThreadCommand), 1, buffer, text.Length); } while (ClusterClient.Connected) { count = sr.Read(buffer, 0, 2048); if (count == 0) { ClusterClient.Close(); } else { ClusterForm.Invoke(new CrossThreadCallback(ClusterForm.CrossThreadCommand), 0, buffer, count); } } text = "DXClusterClient - Disconnected"; buf = new ASCIIEncoding(); buf.GetBytes(text, 0, text.Length, buffer, 0); ClusterForm.Invoke(new CrossThreadCallback(ClusterForm.CrossThreadCommand), 1, buffer, text.Length); ClusterClient.Close(); } catch (Exception ex) { Debug.Write(ex.ToString()); byte[] buffer = new byte[100]; string text = "DXClusterClient - Disconnected"; ASCIIEncoding buf = new ASCIIEncoding(); buf.GetBytes(text, 0, text.Length, buffer, 0); try { ClusterForm.Invoke(new CrossThreadCallback(ClusterForm.CrossThreadCommand), 1, buffer, text.Length); } catch { } } }
private static void Main() { string hostName = DemoConfig.Default.busHostName; ushort hostPort = DemoConfig.Default.busHostPort; bool useSSL = DemoConfig.Default.useSSL; string clientUser = DemoConfig.Default.clientUser; string clientThumbprint = DemoConfig.Default.clientThumbprint; string serverUser = DemoConfig.Default.serverUser; string serverThumbprint = DemoConfig.Default.serverThumbprint; ushort serverSSLPort = DemoConfig.Default.serverSSLPort; ushort serverOpenPort = DemoConfig.Default.serverOpenPort; string busIORFile = DemoConfig.Default.busIORFile; if (useSSL) { Utils.InitSSLORB(clientUser, clientThumbprint, serverUser, serverThumbprint, serverSSLPort, serverOpenPort, true, true, "required", false, false); } else { ORBInitializer.InitORB(); } /* * ConsoleAppender appender = new ConsoleAppender { * Threshold = Level.Off, * Layout = * new SimpleLayout(), * }; * BasicConfigurator.Configure(appender); */ ConnectionProperties props = new ConnectionPropertiesImpl(); OpenBusContext context = ORBInitializer.Context; Connection conn; if (useSSL) { string ior = File.ReadAllText(busIORFile); conn = context.ConnectByReference((MarshalByRefObject)OrbServices.CreateProxy(typeof(MarshalByRefObject), ior), props); } else { conn = context.ConnectByAddress(hostName, hostPort, props); } context.SetDefaultConnection(conn); const string userLogin = "******"; byte[] userPassword = new ASCIIEncoding().GetBytes(userLogin); string loginFile = DemoConfig.Default.loginFile; conn.LoginByPassword(userLogin, userPassword, "testing"); SharedAuthSecret secret = conn.StartSharedAuth(); byte[] sharedAuth = context.EncodeSharedAuth(secret); File.WriteAllBytes(loginFile, sharedAuth); conn.Logout(); Logger.Info("Fim."); Logger.Info( "Execute o cliente que fará o login por autenticação compartilhada."); }
private void tcpread(object client) { TcpClient tcpclient = (TcpClient)client; tcpclient.Client.SendTimeout = 5; tcpclient.Client.ReceiveTimeout = 5; tcpstream = tcpclient.GetStream(); byte[] message = new byte[4096]; int bytesRead; while (!closeport1) { //读过程 bytesRead = 0; Boolean isonline = IsOnline(tcpclient); if (isonline && tcpstream.CanRead && tcpstream.DataAvailable) { try { //blocks until a client sends a message bytesRead = tcpstream.Read(message, 0, 4096); } catch { //a socket error has occured //return; } //if (bytesRead == 0) //{ // break; //} //message has successfully been received ASCIIEncoding encoder = new ASCIIEncoding(); // Convert the Bytes received to a string and display it on the Server Screen string msg = encoder.GetString(message, 0, bytesRead); tcpmessages += msg; totalnums += bytesRead; } if (isonline == false) { tcpstream.Close(); tcpclient.Close(); return; } if (closeport1 == true) { tcpstream.Close(); tcpclient.Close(); return; } } tcpclient.Close(); return; }
public static void Main() { long rv; long sid; rv = Api.saHpiSessionOpen(HpiConst.SAHPI_UNSPECIFIED_DOMAIN_ID, out sid, null); if (rv != HpiConst.SA_OK) { Console.WriteLine("Error: saHpiSessionOpen: {0}", rv); return; } long last_hid = HpiConst.SAHPI_LAST_ENTRY; // List all handlers ASCIIEncoding ascii = new ASCIIEncoding(); foreach (long hid in OhpiIterators.HandlerIds(sid)) { last_hid = hid; Console.WriteLine("Handler {0}", hid); oHpiHandlerInfoT hinfo; oHpiHandlerConfigT hconf; rv = Api.oHpiHandlerInfo(sid, hid, out hinfo, out hconf); if (rv != HpiConst.SA_OK) { Console.WriteLine("Error: oHpiHandlerInfo: {0}", rv); continue; } Console.WriteLine(" Info"); Console.WriteLine(" id {0}", hinfo.id); Console.WriteLine(" name {0}", ascii.GetString(hinfo.plugin_name)); Console.WriteLine(" entity_root {0}", HpiUtil.FromSaHpiEntityPathT(hinfo.entity_root)); Console.WriteLine(" load_failed {0}", hinfo.load_failed); Console.WriteLine(" Config"); foreach (var kv in OhpiUtil.FromoHpiHandlerConfigT(hconf)) { Console.WriteLine(" {0} = {1}", kv.Key, kv.Value); } } // Retry last handler if (last_hid != HpiConst.SAHPI_LAST_ENTRY) { Console.WriteLine("Re-trying last handler: {0}", last_hid); rv = Api.oHpiHandlerRetry(sid, last_hid); if (rv != HpiConst.SA_OK) { Console.WriteLine("Error: oHpiHandlerRetry: {0}", rv); } } // Destroy last handler if (last_hid != HpiConst.SAHPI_LAST_ENTRY) { Console.WriteLine("Destroying last handler: {0}", last_hid); rv = Api.oHpiHandlerDestroy(sid, last_hid); if (rv != HpiConst.SA_OK) { Console.WriteLine("Error: oHpiHandlerDestroy: {0}", rv); } } // Look for handler providing specified resource { long hid = HpiConst.SAHPI_LAST_ENTRY; long rid = 5; rv = Api.oHpiHandlerFind(sid, rid, out hid); if (rv != HpiConst.SA_OK) { Console.WriteLine("Error: oHpiHandlerFind: {0}", rv); } if (hid != HpiConst.SAHPI_LAST_ENTRY) { Console.WriteLine("Resource {0} is provided by handler {1}", rid, hid); } } // Create new instance of test_agent plugin { Console.WriteLine("Creating new handler"); var d = new Dictionary <String, String> { { "plugin", "libtest_agent" }, { "port", "9999" } }; var hconf = OhpiUtil.TooHpiHandlerConfigT(d); long hid; rv = Api.oHpiHandlerCreate(sid, hconf, out hid); if (rv == HpiConst.SA_OK) { Console.WriteLine("Created handler {0}", hid); } else { Console.WriteLine("Error: oHpiHandlerCreate: {0}", rv); } } rv = Api.saHpiSessionClose(sid); if (rv != HpiConst.SA_OK) { Console.WriteLine("Error: saHpiSessionClose: {0}", rv); return; } }
public string PostHtml() { Random Rdm = new Random(); //产生0到100的随机数 int iRdm = Rdm.Next(423456789, 499999999); string wxuin = iRdm.ToString(); string pass_ticket = "1KLZo5j/85JCXGrbyj5vH6Wn2Ek1qDqjqj2U5tik1232P47mLxmwM+avvXgfWjy5"; string appmsg_token = "954_1hcOzNorDwiokamoRrnyUm3rQ1fVwUQk-ZDN0s061MxSYtM-BH5313uQ0n5bDgdUat4FJSVA7RrhkCIN"; string postData = "action=vote&__biz=MzA4MDIzOTQ5OQ%3D%3D&uin=777&key=777&pass_ticket=" + pass_ticket + "&appmsg_token=" + appmsg_token + "&f=json&json=%7B%22super_vote_item%22%3A%5B%7B%22vote_id%22%3A495474521%2C%22item_idx_list%22%3A%7B%22item_idx%22%3A%5B%2216%22%5D%7D%7D%2C%7B%22vote_id%22%3A495474522%2C%22item_idx_list%22%3A%7B%22item_idx%22%3A%5B%2219%22%5D%7D%7D%5D%2C%22super_vote_id%22%3A495474497%7D&idx=2&mid=2653078119&wxtoken=777"; string cookieStr = "rewardsn=; wxuin=" + wxuin + "; devicetype=android-23; version=26060636; lang=zh_CN; pass_ticket=" + pass_ticket + "; wap_sid2=CLfb39UBElw3ZDlXaU5iNlVsYzB0UVlia3NvZktSWHpoM3FfVl9udFhBWlhJdlRrV0N4NVVwTUZ3V2ZCYW5aWUZrTkxMSVBZYlZyc2xUbTc0THZmWE16ZDNBWEkxYm9EQUFBfjCyyoTXBTgNQAE=; wxtokenkey=777"; string RefererURl = "https://mp.weixin.qq.com/mp/newappmsgvote?action=show&__biz=MzA4MDIzOTQ5OQ==&supervoteid=495474497&uin=777&key=777&pass_ticket=" + pass_ticket + "&wxtoken=777&mid=2653078119&idx=2&appmsg_token=" + appmsg_token; string URL = "https://mp.weixin.qq.com/mp/newappmsgvote"; string[] cookstr = cookieStr.Split(';'); foreach (string str in cookstr) { string[] cookieNameValue = str.Split('='); Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString()); ck.Domain = "mp.weixin.qq.com"; _cc.Add(ck); } ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(postData);//Encoding.UTF8.GetBytes(postData); HttpWebRequest httpWebRequest; HttpWebResponse webResponse; Stream getStream; StreamReader streamReader; httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL); httpWebRequest.Host = "mp.weixin.qq.com"; httpWebRequest.ContentLength = data.Length; httpWebRequest.Accept = "application/json"; httpWebRequest.Headers.Add("Origin", "https://mp.weixin.qq.com"); httpWebRequest.Headers.Add("X-Requested-With", "XMLHttpRequest"); httpWebRequest.UserAgent = "Mozilla/5.0 (Linux; Android 6.0; 1501-A02 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/044028 Mobile Safari/537.36 MicroMessenger/6.6.6.1300(0x26060636) NetType/WIFI Language/zh_CN"; httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.Referer = RefererURl; httpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate"); httpWebRequest.Headers.Add("Accept-Language", "zh-CN,en-US;q=0.8"); httpWebRequest.Headers.Add("Q-UA2", "QV=3&PL=ADR&PR=WX&PP=com.tencent.mm&PPVN=6.6.6&TBSVC=43607&CO=BK&COVC=044028&PB=GE&VE=GA&DE=PHONE&CHID=0&LCID=9422&MO= 1501-A02 &RL=720*1280&OS=6.0&API=23"); httpWebRequest.Headers.Add("Q-GUID", "04dd8ef186bdc34bdedac5a413b788cb"); httpWebRequest.Headers.Add("Q-Auth", "31045b957cf33acf31e40be2f3e71c5217597676a9729f1b"); httpWebRequest.CookieContainer = _cc; httpWebRequest.Method = "POST"; // httpWebRequest.AllowAutoRedirect = true; Stream pReqStream = httpWebRequest.GetRequestStream(); // Send the data. pReqStream.Write(data, 0, data.Length); pReqStream.Close(); webResponse = (HttpWebResponse)httpWebRequest.GetResponse(); getStream = webResponse.GetResponseStream(); streamReader = new StreamReader(getStream, Encoding.UTF8); string getString = ""; getString = streamReader.ReadToEnd(); streamReader.Close(); getStream.Close(); webResponse.Close(); return(getString); }
static void Main(string[] args) { //Declare the server queue: TcpListener serverQueue = null; try { // 1. Set up an IP object to represent one IP of your computer: IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //Or the wired or WiFi IP of your computer // 2. Create the queue to listen for and accept incoming connection requests: serverQueue = new TcpListener(ipAd, 63000); // TCP port numbers range from 0 to 65536, i.e., 16 bits. // DO NOT use a port number in the range from 0 to 1023. They are the well-known ports or // system ports. // Port numbers from 1024 to 49151 are the registered ports. You may use them like 63000 // if they are not registered or registered but the program is not running in your computer. // Use the Start method to begin listening for incoming connection requests. // It will queue incoming connections until the Stop method is called. serverQueue.Start(); Console.WriteLine("[Server] The server is running at port 63000"); Console.WriteLine("[Server] So, the server's local end point is: " + serverQueue.LocalEndpoint); Console.WriteLine("[Server] Waiting for a client's connection........"); // 3. Pull a connection from the queue to make a socket: Socket aSocket = serverQueue.AcceptSocket(); Console.WriteLine("\n[Server] Connection accepted from a client " + "whose end point is: " + aSocket.RemoteEndPoint); // 4. Get the message sent by client through socket: byte[] incomingDataBuffer = new byte[1000]; char aChar = new char(); int totalBytes = aSocket.Receive(incomingDataBuffer); // Receive from client, byte by byte char aVowel = new char(); // 5. Display the received message: Console.WriteLine("[Server] Message of client recieved"); for (int i = 0; i < totalBytes; i++) { aChar = Convert.ToChar(incomingDataBuffer[i]); Console.Write(aChar); } //---------------------------------------------------------------- //---------------------------------------------------------------- //---------------------------------------------------------------- // EDIT: Display the vowels in the received message: Console.WriteLine("\n[Server] Vowel characters detected ="); for (int i = 0; i < totalBytes; i++) { aVowel = Convert.ToChar(incomingDataBuffer[i]); if ("aeiouAEIOU".IndexOf(aVowel) > 0) { Console.Write(aVowel); } } //---------------------------------------------------------------- //---------------------------------------------------------------- //---------------------------------------------------------------- // 6. Tell client its message was received: ASCIIEncoding ascii = new ASCIIEncoding(); Console.Write("\n[Server] Hit 'Enter' to send acknowledgement to clicnt and end the session...."); Console.ReadLine(); aSocket.Send(ascii.GetBytes("[Server] Your message was recieved.")); // Send to client, byte by byte through socket aSocket.Close(); } catch (SocketException se) { Console.WriteLine("\n[Server] Socket Error Code: " + se.ErrorCode.ToString()); Console.WriteLine(" " + se.StackTrace); } finally { // 7. Stop listening request and recycle the queue: serverQueue.Stop(); Console.WriteLine("\nBye!"); } }
private static void HandleHttpSessionRequest(TcpClient Client, string httpCmd, Stream clientStream, string tunnelHostName, List <string> requestLines, CustomBinaryReader clientStreamReader, string securehost) { if (httpCmd == null) { return; } var args = new SessionEventArgs(BUFFER_SIZE); args.Client = Client; args.tunnelHostName = tunnelHostName; args.securehost = securehost; try { //break up the line into three components (method, remote URL & Http Version) var splitBuffer = httpCmd.Split(spaceSplit, 3); if (splitBuffer.Length != 3) { TcpHelper.SendRaw(httpCmd, tunnelHostName, ref requestLines, args.IsSSLRequest, clientStreamReader.BaseStream); if (clientStream != null) { clientStream.Close(); } return; } var method = splitBuffer[0]; var remoteUri = splitBuffer[1]; Version version; if (splitBuffer[2] == "HTTP/1.1") { version = new Version(1, 1); } else { version = new Version(1, 0); } if (securehost != null) { remoteUri = securehost + remoteUri; args.IsSSLRequest = true; } //construct the web request that we are going to issue on behalf of the client. args.ProxyRequest = (HttpWebRequest)HttpWebRequest.Create(remoteUri.Trim()); args.ProxyRequest.Proxy = null; args.ProxyRequest.UseDefaultCredentials = true; args.ProxyRequest.Method = method; args.ProxyRequest.ProtocolVersion = version; args.ClientStream = clientStream; args.ClientStreamReader = clientStreamReader; for (int i = 1; i < requestLines.Count; i++) { var rawHeader = requestLines[i]; String[] header = rawHeader.ToLower().Trim().Split(colonSpaceSplit, 2, StringSplitOptions.None); //if request was upgrade to web-socket protocol then relay the request without proxying if ((header[0] == "upgrade") && (header[1] == "websocket")) { TcpHelper.SendRaw(httpCmd, tunnelHostName, ref requestLines, args.IsSSLRequest, clientStreamReader.BaseStream); if (clientStream != null) { clientStream.Close(); } return; } } ReadRequestHeaders(ref requestLines, args.ProxyRequest); int contentLen = (int)args.ProxyRequest.ContentLength; args.ProxyRequest.AllowAutoRedirect = false; args.ProxyRequest.AutomaticDecompression = DecompressionMethods.None; //If requested interception if (BeforeRequest != null) { args.RequestHostname = args.ProxyRequest.RequestUri.Host; args.RequestURL = args.ProxyRequest.RequestUri.OriginalString; args.RequestLength = contentLen; args.RequestHttpVersion = version; args.ClientPort = ((IPEndPoint)Client.Client.RemoteEndPoint).Port; args.ClientIpAddress = ((IPEndPoint)Client.Client.RemoteEndPoint).Address; args.RequestIsAlive = args.ProxyRequest.KeepAlive; BeforeRequest(null, args); } string tmpLine; if (args.CancelRequest) { if (args.RequestIsAlive) { requestLines.Clear(); while (!String.IsNullOrEmpty(tmpLine = clientStreamReader.ReadLine())) { requestLines.Add(tmpLine); } httpCmd = requestLines.Count > 0 ? requestLines[0] : null; return; } else { return; } } args.ProxyRequest.ConnectionGroupName = args.RequestHostname; args.ProxyRequest.AllowWriteStreamBuffering = true; //If request was modified by user if (args.RequestWasModified) { ASCIIEncoding encoding = new ASCIIEncoding(); byte[] requestBytes = encoding.GetBytes(args.RequestHtmlBody); args.ProxyRequest.ContentLength = requestBytes.Length; Stream newStream = args.ProxyRequest.GetRequestStream(); newStream.Write(requestBytes, 0, requestBytes.Length); args.ProxyRequest.BeginGetResponse(new AsyncCallback(HandleHttpSessionResponse), args); } else { //If its a post/put request, then read the client html body and send it to server if (method.ToUpper() == "POST" || method.ToUpper() == "PUT") { args.ProxyRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), args); } else { //otherwise wait for response asynchronously args.ProxyRequest.BeginGetResponse(new AsyncCallback(HandleHttpSessionResponse), args); //Now read the next request (if keep-Alive is enabled, otherwise exit thus thread) //If client is pipeling the request, this will be immediately hit before response for previous request was made if (args.ProxyRequest.KeepAlive) { requestLines = new List <string>(); requestLines.Clear(); while (!String.IsNullOrEmpty(tmpLine = args.ClientStreamReader.ReadLine())) { requestLines.Add(tmpLine); } httpCmd = requestLines.Count() > 0 ? requestLines[0] : null; HandleHttpSessionRequest(Client, httpCmd, args.ClientStream, args.tunnelHostName, requestLines, args.ClientStreamReader, args.securehost); } } } } catch (IOException) { return; } catch (UriFormatException) { return; } catch (WebException) { return; } finally { } }
public static string Cut_title(string html, int len) { System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" no[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>]+\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex1.Replace(html, ""); //过滤<script></script>标记 html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 html = regex4.Replace(html, ""); //过滤iframe html = regex5.Replace(html, ""); //过滤frameset html = regex6.Replace(html, ""); //过滤frameset html = regex7.Replace(html, ""); //过滤frameset html = regex8.Replace(html, ""); //过滤frameset html = regex9.Replace(html, ""); html = html.Replace(" ", ""); html = html.Replace("< >", ""); html = html.Replace("<strong>", ""); ASCIIEncoding ascii = new ASCIIEncoding(); int tempLen = 0; string tempString = ""; byte[] s = ascii.GetBytes(html); for (int i = 0; i < s.Length; i++) { if ((int)s[i] == 63) { tempLen += 2; } else { tempLen += 1; } try { tempString += html.Substring(i, 1); } catch { break; } if (tempLen > len) { break; } } //如果截过则加上半个省略号 byte[] mybyte = System.Text.Encoding.Default.GetBytes(html); if (mybyte.Length > len) { tempString += "…"; } return(tempString); }
private void myTextBox_KeyPress(object sender, KeyPressEventArgs e) { ////处理回车事件 //if (this.IsEnterToTab && e.KeyChar == 13) //{ // SendKeys.Send("{tab}"); //} /* * '判断是否是数字 * Dim inputkey As Integer * inputkey = Asc(e.KeyChar) * * Select Case inputkey * Case 48 To 57 '数字 * * Case 8 ' 删除键(backspace) * * Case 127 ' DEL * * Case 46 ' 小数点. * If IsDecimal = True Then '可以输入小数点 * * Else * inputkey = 0 '不可以输入小数点 * End If * Case 45 '负数符号- * If IsNegative = True Then '可以输入负数 * * Else '不可以输入负数 * inputkey = 0 * End If * Case Else * inputkey = 0 * End Select */ ASCIIEncoding AE1 = new ASCIIEncoding(); byte[] ByteArray1 = AE1.GetBytes(e.KeyChar.ToString()); int inputkey = ByteArray1[0]; /* * //如果不是字符串的话 * if (this.DataType != DataTypeEnum.DataTypeString) * { * //数字、删除键(backspace)、DEL * if ((inputkey >= 48 && inputkey <= 57) || inputkey == 8 || inputkey == 127) * { * e.Handled = false; * } * else if(inputkey == 46) //小数点 * { * //如果是小数点的话,再判断小数点的位置及出现的次数 * if (this.DataType == DataTypeEnum.DataTypeDecimal || this.DataType == DataTypeEnum.DataTypeDecimalNegative || this.DataType == DataTypeEnum.DataTypeDecimalPositive) * { * //e.Handled = false; * } * else //如果不是带小数点的数值,则不允许接收事件 * { * e.Handled = true; * } * } * } * switch (this.DataType) * { * case DataTypeEnum.DataTypeDecimal: * * break; * case DataTypeEnum.DataTypeDecimalNegative: * * break; * case DataTypeEnum.DataTypeDecimalPositive: * * break; * case DataTypeEnum.DataTypeInteger: * * break; * case DataTypeEnum.DataTypeIntegerNegative: * * break; * case DataTypeEnum.DataTypeIntegerPositive: * * break; * default : * * break; * } */ /* * bool bInput = false; * if(this.DataType != DataTypeEnum.DataTypeString//如果是数值型 * { * if(inputkey >= 48 && inputkey <=57) * '判断是否是数字 * Select Case inputkey * Case 48 To 57 '数字 * * Case 8 ' 删除键(backspace) * * Case 127 ' DEL * * Case 46 ' 小数点. * If IsDecimal = True Then '可以输入小数点 * * Else * inputkey = 0 '不可以输入小数点 * End If * Case 45 '负数符号- * If IsNegative = True Then '可以输入负数 * * Else '不可以输入负数 * inputkey = 0 * End If * Case Else * inputkey = 0 * End Select * * If inputkey = 0 Then '忽略 * e.Handled = True * Else '响应 * 'e.Handled = False * If MaxLenth = 0 Then '表示没有设置长度(再对负数和小数点进行判断) * If inputkey = 45 Then '如果是负数符号 * If Len(Me.Text) = 0 Then '如果是第一个字符,就响应 * e.Handled = False * Else * e.Handled = True * End If * End If * If inputkey = 46 Then '如果是小数点符号 * If Len(Me.Text) = 0 Then '如果是第一个字符,则不响应,小数点不能为第一个字符 * e.Handled = True * Else '否则,根据小数点的个数来判断,如果有存在,则不响应 * If InStr(Me.Text, ".") = 0 Then '如果在控件字符串中找不到.的所在位置,则响应 * e.Handled = False * Else '如果能找到,说明已经有.存在,就不能输入第二个小数点符号 * e.Handled = True * End If * End If * End If * If inputkey <> 46 And inputkey <> 45 And inputkey <> 8 Then '如果输入的值不是小数点和负数、删除号,再进行小数点后面位数判断 * If Count > 0 Then '小数点位数判断 * If InStr(Me.Text, ".") = 0 Then '如果不存在小数点,直接响应 * e.Handled = False * Else '存在小数点,对小数点位数进行判断 * If InStr(Mid(StrReverse(Me.Text), 1, Count), ".") = 0 Then '对字符串进行反向,然后对反向后的字符串读取从第一个字符串的值到设置的个数,如果里面包含“.”,说明已经达到设置的小数点位数,则不响应,否则,表示未达到设置位数,响应 * e.Handled = True * Else * e.Handled = False * End If * End If * Else * e.Handled = False * End If * 'Else * ' e.Handled = False * End If * * 'e.Handled = False * Else '表示有设置字符串长度限制 * If Len(Me.Text) >= MaxLenth Then '如果输入的字符串数长于等于设置长度,则不响应事件(但Backspace键要响应,删除) * If inputkey = 8 Then '如果是Backspace就响应,删除 * e.Handled = False * Else * e.Handled = True * End If * Else '如果输入的字符串数小于设置长度,就响应事件 * If inputkey = 45 Then '如果是负数符号 * If Len(Me.Text) = 0 Then '如果是第一个字符,就响应 * e.Handled = False * Else * e.Handled = True * End If * End If * If inputkey = 46 Then '如果是小数点符号 * If Len(Me.Text) = 0 Then '如果是第一个字符,则不响应,小数点不能为第一个字符 * e.Handled = True * Else '否则,根据小数点的个数来判断,如果有存在,则不响应 * If InStr(Me.Text, ".") = 0 Then '如果在控件字符串中找不到.的所在位置,则响应 * e.Handled = False * Else '如果能找到,说明已经有.存在,就不能输入第二个小数点符号 * e.Handled = True * End If * End If * End If * * If inputkey <> 46 And inputkey <> 45 And inputkey <> 8 Then '如果输入的值不是小数点和负数、删除号,再进行小数点后面位数判断 * If Count > 0 Then '小数点位数判断 * If InStr(Me.Text, ".") = 0 Then '如果不存在小数点,直接响应 * e.Handled = False * Else '存在小数点,对小数点位数进行判断 * If InStr(Mid(StrReverse(Me.Text), 1, Count), ".") = 0 Then '对字符串进行反向,然后对反向后的字符串读取从第一个字符串的值到设置的个数,如果里面包含“.”,说明已经达到设置的小数点位数,则不响应,否则,表示未达到设置位数,响应 * e.Handled = True * Else * e.Handled = False * End If * End If * Else * e.Handled = False * End If * 'Else * ' e.Handled = False * End If * 'e.Handled = False * End If * End If * End If * Else '如果不是数值型,只需要判断数值字符串大小即可 * If MaxLenth = 0 Then '没有长度限制 * e.Handled = False * Else * If Len(Me.Text) >= MaxLenth Then '如果输入的字符串数长于等于设置长度,则不响应事件(但Backspace键要响应,删除) * If Asc(e.KeyChar) = 8 Then * e.Handled = False * Else * e.Handled = True * End If * Else * e.Handled = False * End If * End If * * End If * */ }
/// <summary> /// Export acquisition data to a XML file /// </summary> /// <param name="Filename">Target file name</param> /// <param name="protocol">Reference to protocol to connected ECU</param> public void XmlExport(string Filename, ref ProtocolBase protocol) { XmlWriter xf = null; XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = false; settings.ConformanceLevel = ConformanceLevel.Document; settings.Encoding = System.Text.Encoding.UTF8; //"iso-8859-1"; settings.Indent = true; settings.IndentChars = "\t"; settings.NewLineOnAttributes = true; try { xf = XmlWriter.Create(Filename, settings); xf.WriteStartElement("acqui_root"); xf.WriteStartElement("ECU"); xf.WriteStartElement("Serialnumber"); xf.WriteValue(protocol.SerialNumber); xf.WriteEndElement(); // S/N xf.WriteStartElement("Hardware"); xf.WriteValue(string.Format("{0}.{1}.{2}", protocol.HardwareVersion.Hauptversion, protocol.HardwareVersion.Nebenversion, protocol.HardwareVersion.Revision)); xf.WriteEndElement(); // HW V xf.WriteStartElement("Software"); xf.WriteValue(string.Format("{0}.{1}.{2}", protocol.SoftwareVersion.Hauptversion, protocol.SoftwareVersion.Nebenversion, protocol.SoftwareVersion.Revision)); xf.WriteEndElement(); // SW V xf.WriteStartElement("Configuration"); xf.WriteValue(string.Format("{0}.{1}.{2}", protocol.ConfigurationVersion.Hauptversion, protocol.ConfigurationVersion.Nebenversion, protocol.ConfigurationVersion.Revision)); xf.WriteEndElement(); // CFG V xf.WriteStartElement("Datamap"); xf.WriteValue(string.Format("{0}.{1}.{2}", protocol.DatamapVersion.Hauptversion, protocol.DatamapVersion.Nebenversion, protocol.DatamapVersion.Revision)); xf.WriteEndElement(); // KF V xf.WriteEndElement(); // ECU ASCIIEncoding ascii = new ASCIIEncoding(); byte[] byteArray; byte[] asciiArray; string convString; for (int item = 0; item < mItem.Length; item++) { xf.WriteStartElement("acqui_item"); for (int row = 0; row < ((mRowLength - 1) / 2) - 1; row++) { // Name auf ascii zeichen beschraenken, und ? durch _ ersetzen byteArray = Encoding.UTF8.GetBytes(mHead[row]); asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray); convString = ascii.GetString(asciiArray); convString = convString.Replace("?", "_"); xf.WriteStartElement(convString); xf.WriteValue(mItem[item].Row[row]); xf.WriteEndElement(); } xf.WriteEndElement(); } xf.WriteEndElement(); // root xf.Flush(); } catch (Exception ex) { Console.WriteLine("Exception during opening XML file: {0}", ex.Message); } finally { xf.Close(); } }
/// <summary> /// 发送数据到Api服务接口(青岛) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="apiUrl"></param> /// <param name="requestType"></param> /// <param name="param"></param> /// <returns></returns> public static ApiResult_QD <T> SendDataToApiService_QD <T>(string apiUrl, string requestType, string param, TokenStyle token) { if (string.IsNullOrEmpty(apiUrl) || string.IsNullOrEmpty(requestType)) { return(ApiResultHelper_QD <T> .getFailApiResult("没有找到api接口地址", default(T))); } string strJson = string.Empty; HttpWebRequest request = null; HttpWebResponse response = null; try { ASCIIEncoding encoding = new ASCIIEncoding(); request = WebRequest.Create(apiUrl) as HttpWebRequest; request.AllowWriteStreamBuffering = true;// request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; //request.ProtocolVersion = HttpVersion.Version11; //request.AllowAutoRedirect = true; //request.KeepAlive = true; //request.Headers.Add("Accept-Language", "zh-cn"); //request.Accept = "*/*"; //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0;)"; byte[] b = Encoding.UTF8.GetBytes(param); //Header中添加token验证(服务器要求) request.Headers.Add("Authorization", token.token_type + " " + token.access_token); //已有token添加入头 request.ContentType = "application/json"; //已有token使用json类型 request.ContentLength = b.Length; request.Method = requestType; if (b.Length > 0) { using (Stream stream = request.GetRequestStream()) { stream.Write(b, 0, b.Length); stream.Close(); } } //获取服务器返回 using (response = request.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { strJson = reader.ReadToEnd(); reader.Close(); } } return(JsonConvert.DeserializeObject <ApiResult_QD <T> >(strJson)); } catch (Exception exception) { //new Common.LogHelper().WriteLine(exception.ToString()); return(ApiResultHelper_QD <T> .getFailApiResult(exception.Message, default(T))); } finally { if (response != null) { response.Close(); } } }
//串口数据处理 private void DataHandlerThread(object data) { //形参data为串口接收的数据 int minusLocation = -1; byte[] receiveData = data as byte[]; //用于将byte[]数组解析成字符串 ASCIIEncoding asciiEncoding = new ASCIIEncoding(); //更新数据 switch (Flag.nFunc) { case 1: //设置电机转速 break; case 2: //电机转速 Data.MotoSpeed = receiveData[3] * 256 + receiveData[4]; Data.PlatSpeed = (int)(Data.MotoSpeed / 3 * 10) / 10.0; Data.FricSpeed = (int)(Data.PlatSpeed / 60 * SysParam.FricRadius * 100) / 100.0; RTDatas.uiDataRT.MotoSpeed = Data.MotoSpeed.ToString(); RTDatas.uiDataRT.PlatSpeed = Data.PlatSpeed.ToString(); RTDatas.uiDataRT.FricSpeed = Data.FricSpeed.ToString(); //更新界面 Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "PlateSpeed", new PlotPoint(Flag.SysTime, Data.PlatSpeed)); Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "MotoSpeed", new PlotPoint(Flag.SysTime, Data.MotoSpeed)); Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "FricSpeed", new PlotPoint(Flag.SysTime, Data.FricSpeed)); break; case 3: //电机扭矩 Data.MotoTorque = receiveData[3] * 256 + receiveData[4]; RTDatas.uiDataRT.MotoTorque = Data.MotoTorque.ToString(); //更新界面 Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "MotoTor", new PlotPoint(Flag.SysTime, Data.MotoTorque)); break; case 4: //查询温湿度及压力 //以ASCII码方式解析收到的byte数组 string s = asciiEncoding.GetString(receiveData); s = s.Substring(0, s.Length - 2); //判断是否出现负号 minusLocation = s.IndexOf("-"); if (minusLocation >= 0) { s = s.Insert(minusLocation, "+"); } string[] strs = s.Split('+'); Data.Pressure1 = double.Parse(strs[1]) + SysParam.ExtraPress_1; Data.Pressure2 = double.Parse(strs[2]) + SysParam.ExtraPress_2; Data.Temperature = double.Parse(strs[3]); Data.Humidity = double.Parse(strs[4]); RTDatas.uiDataRT.Pressure = Data.Pressure1.ToString(); RTDatas.uiDataRT.FricForce = (Data.Pressure2 * SysParam.ArmRatio).ToString(); RTDatas.uiDataRT.Temperature = Data.Temperature.ToString(); RTDatas.uiDataRT.Humidity = Data.Humidity.ToString(); //将系统参数写出到文件 if (MotoData.StartMoto == true) { string str = MotoData.MotoTime.ToString() + "\t" + DateTime.Now.ToString("yyyy-MM-dd") + "\t" + DateTime.Now.ToString("HH:mm:ss") + "\t"; str = str + RTDatas.uiDataRT.Pressure + "\t" + RTDatas.uiDataRT.Temperature + "\t" + RTDatas.uiDataRT.Humidity + "\t"; str = str + RTDatas.uiDataRT.PlatSpeed + "\t" + RTDatas.uiDataRT.MotoSpeed + "\t" + RTDatas.uiDataRT.MotoTorque + "\t"; str = str + RTDatas.uiDataRT.FricForce + "\t" + RTDatas.uiDataRT.FricSpeed; SetParam.dataFile.WriteLine(str); //写出数据 if (Flag.RecData == true) { RTDatas.mydataFile.WriteLine(str); } } //更新界面 Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "Pressure", new PlotPoint(Flag.SysTime, Data.Pressure1)); Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "Temperature", new PlotPoint(Flag.SysTime, Data.Temperature)); Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "Humidity", new PlotPoint(Flag.SysTime, Data.Humidity)); Dispatcher.Invoke(new InterfaceUpdate(updateDataCurve), "FricForce", new PlotPoint(Flag.SysTime, Data.Pressure2 * SysParam.ArmRatio)); break; } }
private void b_DocumentCompleted2(object sender, WebBrowserDocumentCompletedEventArgs e) { WebBrowser b = sender as WebBrowser; string response = b.DocumentText; string postData = "ctl00_ContentPlaceHolder1_ctl00_ToolkitScriptManager_CauHinh_HiddenField=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUKMTIyNzU5NDYyNA9kFgJmD2QWAgIDD2QWCgIBDxYCHgRUZXh0BQMoMClkAgMPFgIfAAUSxJBvw6BuIEhp4bq%2FdSBUw6JtZAIFD2QWAgIBD2QWAmYPZBYIAgQPDxYIHgtfIURhdGFCb3VuZGceFEFwcGVuZERhdGFCb3VuZEl0ZW1zZx4NU2VsZWN0ZWRWYWx1ZQUFMTQtMTUeC18hSXRlbUNvdW50AgJkFgJmD2QWBGYPDxYCHgdUb29sVGlwZWRkAgEPZBYCAgEPZBYCAgEPZBYEZg9kFghmD2QWAmYPFgIfAAUOLS1U4bqldCBj4bqjLS1kAgEPZBYCZg8WAh8ABQEwZAICD2QWAmYPFgIfAAUOLS1U4bqldCBj4bqjLS1kAgMPZBYCZg8WAh8ABQEwZAIBDw8WBB8ABQUxNC0xNR4FVmFsdWUFBTE0LTE1ZBYEZg9kFgJmDxYCHwAFBTE0LTE1ZAIBD2QWAmYPFgIfAAUFMTQtMTVkAgYPDxYGHwFnHwMFATIfBAICZBYCZg9kFgRmDw8WAh8FZWRkAgEPZBYCAgEPZBYCAgEPZBYEZg8PFgQfAAUBMR8GBQExZBYEZg9kFgJmDxYCHwAFATFkAgEPZBYCZg8WAh8ABQExZAIBDw8WBB8ABQEyHwYFATJkFgRmD2QWAmYPFgIfAAUBMmQCAQ9kFgJmDxYCHwAFATJkAgoPFgIeB1Zpc2libGVoZAIMDxYCHwdnFgICAQ8WAh8EAgkWEgIBD2QWAmYPFQgFMTQtMTUBMgZOTkEwMDIKQW5oIHbEg24gMgMzLjAHMTRDVFQzMQQ3LjAwBDcuNTBkAgIPZBYCZg8VCAUxNC0xNQEyBlRUSDAwMw7EkOG6oWkgc%2BG7kSBCMQMzLjAGMTRDVFQzBCA2LjAENi4wMGQCAw9kFgJmDxUIBTE0LTE1ATIGVFRIMDI2D0dp4bqjaSB0w61jaCBCMQMzLjADSEwxBCA1LjAENS4wMGQCBA9kFgJmDxUIBTE0LTE1ATIGVFRIMDI3D0dp4bqjaSB0w61jaCBCMgMzLjAGMTRDVFQzBCAzLjAEMy4wMGQCBQ9kFgJmDxUIBTE0LTE1ATIGQ1RUMDA4GUvhu7kgVGh14bqtdCBM4bqtcCBUcsOsbmgDNC4wBzE0Q1RUMzEEIDkuNQQ5LjUwZAIGD2QWAmYPFQgFMTQtMTUBMgZEVFYwMTIuTMO9IHRodXnhur90IE3huqFjaCBz4buRIChjaG8gQ8O0bmcgTmdo4buHIFRUKQMzLjAGMTRDVFQzBCA1LjAENS4wMGQCBw9kFgJmDxUIBTE0LTE1ATIGQ1RUMDEwEk5o4bqtcCBtw7RuIENOVFQgMgMzLjAHMTRDVFQzMQQxMC4wBTEwLjAwZAIID2QWAmYPFQgFMTQtMTUBMgZUQ0gwMDINVGjhu4MgZOG7pWMgMgMyLjAHMTRDVFQzMQQgNS4wBDUuMDBkAgkPZBYCZg8VCAUxNC0xNQEyBkRUVjA5MhhUaOG7sWMgaMOgbmggbeG6oWNoIHPhu5EDMS4wBzE0Q1RUMzIEIDkuMAQ5LjAwZAIHDxYCHwAFBTIuMi44ZAIJDxYCHwAFCzIwMDcgLSAyMDE0ZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WAgU3Y3RsMDAkQ29udGVudFBsYWNlSG9sZGVyMSRjdGwwMCRjYm9OYW1Ib2NfZ3ZES0hQTGljaFRoaQU2Y3RsMDAkQ29udGVudFBsYWNlSG9sZGVyMSRjdGwwMCRjYm9Ib2NLeV9ndkRLSFBMaWNoVGhp5EqBE0WY4dx7mg4r%2F8fsGwu2GyFCJBYU6p%2F8QvJKE14%3D&ctl00%24ContentPlaceHolder1%24ctl00%24cboNamHoc_gvDKHPLichThi%24ob_CbocboNamHoc_gvDKHPLichThiTB=--T%E1%BA%A5t+c%E1%BA%A3--&ctl00%24ContentPlaceHolder1%24ctl00%24cboNamHoc_gvDKHPLichThi%24ob_CbocboNamHoc_gvDKHPLichThiSIS=0&ctl00%24ContentPlaceHolder1%24ctl00%24cboNamHoc_gvDKHPLichThi=0&ctl00%24ContentPlaceHolder1%24ctl00%24cboHocKy_gvDKHPLichThi%24ob_CbocboHocKy_gvDKHPLichThiSIS=0&ctl00%24ContentPlaceHolder1%24ctl00%24cboHocKy_gvDKHPLichThi=&ctl00%24ContentPlaceHolder1%24ctl00%24btnXemDiemThi=Xem+K%E1%BA%BFt+Qu%E1%BA%A3+H%E1%BB%8Dc+T%E1%BA%ADp"; ASCIIEncoding enc = new ASCIIEncoding(); time1++; // we are encoding the postData to a byte array b.Navigate("http://portal1.hcmus.edu.vn/SinhVien.aspx?pid=211", "", enc.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n"); response = b.DocumentText; string res = ""; if (response.Contains("Điểm Tổng Kết")) { isLoggedIn = true; int index_start = response.IndexOf("Điểm Tổng Kết"); int index_end = response.IndexOf("</fieldset>"); res = response.Substring(index_start, (index_end - index_start)); textBox2.Text = "<!DOCTYPE html>\r\n<html xmlns='http://www.w3.org/1999/xhtml'>\r\n<head>\r\n\t<title></title>\r\n</head>\r\n<body>\r\n\t<table id='tbDiemThiGK' class='dkhp-table'>\r\n\t\t<thead>\r\n\t\t\t<tr>\r\n\t\t\t\t<th title='Năm Học'>Năm Học</th>\r\n\t\t\t\t<th title='Học Kỳ'>Học Kỳ</th>\r\n\t\t\t\t<th title='Mã MH'>Mã Môn Học</th>\r\n\t\t\t\t<th class='left' title='Môn Học'>Môn Học</th>\r\n\t\t\t\t<th title='Số Tín Chỉ'>Số TC</th>\r\n\t\t\t\t<th title='Lớp'>Lớp</th>\r\n\t\t\t\t<th class='left'>Điểm Thi</th>\r\n\t\t\t<th class='left'>" + res + "</body>\r\n</html>"; } else { time1++; isLoggedIn = false; } //textBox3.Text = response; if (time1 == 2) { this.Text = "Portal HCMUS v0.1"; b.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted2); time1 = 0; if (isLoggedIn) { test = "<!DOCTYPE html>\r\n<html xmlns='http://www.w3.org/1999/xhtml'>\r\n<head>\r\n\t<title></title>\r\n</head>\r\n<body>\r\n\t<table id='tbDiemThiGK' class='dkhp-table'>\r\n\t\t<thead>\r\n\t\t\t<tr>\r\n\t\t\t\t<th title='Năm Học'>Năm Học</th>\r\n\t\t\t\t<th title='Học Kỳ'>Học Kỳ</th>\r\n\t\t\t\t<th title='Mã MH'>Mã Môn Học</th>\r\n\t\t\t\t<th class='left' title='Môn Học'>Môn Học</th>\r\n\t\t\t\t<th title='Số Tín Chỉ'>Số TC</th>\r\n\t\t\t\t<th title='Lớp'>Lớp</th>\r\n\t\t\t\t<th class='left'>Điểm Thi</th>\r\n\t\t\t<th class='left'>" + res + "</body>\r\n</html>"; webBrowser1.DocumentText = test; MessageBox.Show("Thành công!", "Portal HCMUS v0.1"); isLoggedIn = false; test = ""; } else { MessageBox.Show("Sai tài khoản hoặc mật khẩu!", "Portal HCMUS v0.1"); } } }
static HttpConnectProxy() { m_LineSeparator = ASCIIEncoding.GetBytes("\r\n\r\n"); }
public static object PLCDataToSystemData(byte[] array, int index, int sourceByteWidth, int plcDataFormat, Type systemDataType) { ulong num; object obj2; object obj3; byte[] destinationArray = new byte[sourceByteWidth]; Array.Copy(array, index, destinationArray, 0, sourceByteWidth); switch (plcDataFormat) { case 0: { if (sourceByteWidth != 1) { throw new ArgumentOutOfRangeException("sourceByteWidth"); } bool flag = destinationArray[0] != 0; return(Convert.ChangeType(flag, systemDataType)); } case 1: case 3: destinationArray = PLCByteOrderConverter.SwapByteIfNeed(destinationArray); switch (sourceByteWidth) { case 1: num = destinationArray[0]; goto Label_00BB; case 2: num = BitConverter.ToUInt16(destinationArray, 0); goto Label_00BB; case 4: num = BitConverter.ToUInt32(destinationArray, 0); goto Label_00BB; case 8: num = BitConverter.ToUInt64(destinationArray, 0); goto Label_00BB; } break; case 2: destinationArray = PLCByteOrderConverter.SwapByteIfNeed(destinationArray); switch (sourceByteWidth) { case 1: obj2 = destinationArray[0]; goto Label_015F; case 2: obj2 = BitConverter.ToInt16(destinationArray, 0); goto Label_015F; case 3: goto Label_0154; case 4: obj2 = BitConverter.ToInt32(destinationArray, 0); goto Label_015F; case 8: obj2 = BitConverter.ToInt64(destinationArray, 0); goto Label_015F; } goto Label_0154; case 4: destinationArray = PLCByteOrderConverter.SwapByteIfNeed(destinationArray); switch (sourceByteWidth) { case 4: obj3 = BitConverter.ToSingle(destinationArray, 0); goto Label_01AA; case 8: obj3 = BitConverter.ToDouble(destinationArray, 0); goto Label_01AA; } throw new ArgumentOutOfRangeException("sourceByteWidth"); case 5: { ASCIIEncoding encoding = new ASCIIEncoding(); return(Convert.ChangeType(encoding.GetString(destinationArray, index, sourceByteWidth), systemDataType)); } default: throw new ArgumentOutOfRangeException("plcDataFormat"); } throw new ArgumentOutOfRangeException("sourceByteWidth"); Label_00BB: if (plcDataFormat == 3) { try { num = Convert.ToUInt64(num.ToString("X")); } catch (FormatException exception) { throw new BCDFormatException((long)num, exception); } } return(Convert.ChangeType(num, systemDataType)); Label_0154: throw new ArgumentOutOfRangeException("sourceByteWidth"); Label_015F: return(Convert.ChangeType(obj2, systemDataType)); Label_01AA: return(Convert.ChangeType(obj3, systemDataType)); }
private void button9_Click(object sender, EventArgs e) { int x = 0; int x1 = 0; int x2 = 0; int x3 = 0; int mq = 0; int numpd = Convert.ToInt32(textBox19.Text); // d int numpnn = Convert.ToInt32(textBox18.Text); // n string l = textBox17.Text; string a; ASCIIEncoding aSCII = new ASCIIEncoding(); Byte[] vs = aSCII.GetBytes(l); char[] vs1 = l.ToCharArray(); for (int i = 3; i < vs1.Length; i += 4) { if (vs1[i - 3] == '0') { x = 0; } if (vs1[i - 3] == '1') { x = 1 * (16 * 16 * 16); } if (vs1[i - 3] == '2') { x = 2 * (16 * 16 * 16); } if (vs1[i - 3] == '3') { x = 3 * (16 * 16 * 16); } if (vs1[i - 3] == '4') { x = 4 * (16 * 16 * 16); } if (vs1[i - 3] == '5') { x = 5 * (16 * 16 * 16); } if (vs1[i - 3] == '6') { x = 6 * (16 * 16 * 16); } if (vs1[i - 3] == '7') { x = 7 * (16 * 16 * 16); } if (vs1[i - 3] == '8') { x = 8 * (16 * 16 * 16); } if (vs1[i - 3] == '9') { x = 9 * (16 * 16 * 16); } if (vs1[i - 3] == 'A') { x = 10 * (16 * 16 * 16); } if (vs1[i - 3] == 'B') { x = 11 * (16 * 16 * 16); } if (vs1[i - 3] == 'C') { x = 12 * (16 * 16 * 16); } if (vs1[i - 3] == 'D') { x = 13 * (16 * 16 * 16); } if (vs1[i - 3] == 'E') { x = 14 * (16 * 16 * 16); } if (vs1[i - 3] == 'F') { x = 15 * (16 * 16 * 16); } if (vs1[i - 2] == '0') { x1 = 0; } if (vs1[i - 2] == '1') { x1 = 1 * (16 * 16); } if (vs1[i - 2] == '2') { x1 = 2 * (16 * 16); } if (vs1[i - 2] == '3') { x1 = 3 * (16 * 16); } if (vs1[i - 2] == '4') { x1 = 4 * (16 * 16); } if (vs1[i - 2] == '5') { x1 = 5 * (16 * 16); } if (vs1[i - 2] == '6') { x1 = 6 * (16 * 16); } if (vs1[i - 2] == '7') { x1 = 7 * (16 * 16); } if (vs1[i - 2] == '8') { x1 = 8 * (16 * 16); } if (vs1[i - 2] == '9') { x1 = 9 * (16 * 16); } if (vs1[i - 2] == 'A') { x1 = 10 * (16 * 16); } if (vs1[i - 2] == 'B') { x1 = 11 * (16 * 16); } if (vs1[i - 2] == 'C') { x1 = 12 * (16 * 16); } if (vs1[i - 2] == 'D') { x1 = 13 * (16 * 16); } if (vs1[i - 2] == 'E') { x1 = 14 * (16 * 16); } if (vs1[i - 2] == 'F') { x1 = 15 * (16 * 16); } if (vs1[i - 1] == '0') { x2 = 0; } if (vs1[i - 1] == '1') { x2 = 1 * 16; } if (vs1[i - 1] == '2') { x2 = 2 * 16; } if (vs1[i - 1] == '3') { x2 = 3 * 16; } if (vs1[i - 1] == '4') { x2 = 4 * 16; } if (vs1[i - 1] == '5') { x2 = 5 * 16; } if (vs1[i - 1] == '6') { x2 = 6 * 16; } if (vs1[i - 1] == '7') { x2 = 7 * 16; } if (vs1[i - 1] == '8') { x2 = 8 * 16; } if (vs1[i - 1] == '9') { x2 = 9 * 16; } if (vs1[i - 1] == 'A') { x2 = 10 * 16; } if (vs1[i - 1] == 'B') { x2 = 11 * 16; } if (vs1[i - 1] == 'C') { x2 = 12 * 16; } if (vs1[i - 1] == 'D') { x2 = 13 * 16; } if (vs1[i - 1] == 'E') { x2 = 14 * 16; } if (vs1[i - 1] == 'F') { x2 = 15 * 16; } if (vs1[i] == '0') { x3 = 0; } if (vs1[i] == '1') { x3 = 1; } if (vs1[i] == '2') { x3 = 2; } if (vs1[i] == '3') { x3 = 3; } if (vs1[i] == '4') { x3 = 4; } if (vs1[i] == '5') { x3 = 5; } if (vs1[i] == '6') { x3 = 6; } if (vs1[i] == '7') { x3 = 7; } if (vs1[i] == '8') { x3 = 8; } if (vs1[i] == '9') { x3 = 9; } if (vs1[i] == 'A') { x3 = 10; } if (vs1[i] == 'B') { x3 = 11; } if (vs1[i] == 'C') { x3 = 12; } if (vs1[i] == 'D') { x3 = 13; } if (vs1[i] == 'E') { x3 = 14; } if (vs1[i] == 'F') { x3 = 15; } mq = x3 + x2 + x1 + x; textBox16.AppendText(mq.ToString() + ','); int c = 1; for (int k = 0; k < numpd; k++) { c = (c * mq) % numpnn; } c = c % numpnn; //textBox15.AppendText(c.ToString() + ','); char ch = (char)c; textBox15.AppendText(Convert.ToString(ch)); mq = 0; } }