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;
 }
예제 #2
0
	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);
		}
	}
예제 #3
0
 //============================================================================
 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);
 }
예제 #4
0
    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);
        }
    }
예제 #5
0
 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));
 }
예제 #6
0
    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);
        }
    }
예제 #7
0
 public static int echoMessage(Socket clientSocket)
 {
     string messageToSend = testReceive(clientSocket);
     ASCIIEncoding asn = new ASCIIEncoding();
     clientSocket.Send(asn.GetBytes(messageToSend));
     return messageToSend.Length;
 }
예제 #8
0
    //пытаемся отправить кому-то сообщение о том, что хотим понаблюдать за его игрой
    //если прокатывает - в ответ нам начнут приходить сообщения о состоянии игры
    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);
        }
    }
예제 #9
0
파일: Utils.cs 프로젝트: priceLiu/CMS
    /// <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;
    }
예제 #10
0
    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();
    }
예제 #11
0
    /// <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;

        }
    }
예제 #12
0
파일: test.cs 프로젝트: mono/gert
	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;
	}
예제 #13
0
        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));
        }
예제 #14
0
 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 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();
    }
예제 #16
0
    public void respond()
    {
        ASCIIEncoding encoder = new ASCIIEncoding();
        byte[] buffer = encoder.GetBytes(response + "\n");

        client_stream.Write(buffer, 0 , buffer.Length);
        client_stream.Flush();
    }
예제 #17
0
    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();
    }
예제 #18
0
    static void Main(string[] args)
    {
        string param1 = "value1";
        string param2 = "value2";

        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = string.Format("param1={0}&param2={1}", param1, param2);
        byte[] buffer = encoding.GetBytes(postData);

        // Prepare web request...
        HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create("http://");

        // We use POST ( we can also use GET )
        myRequest.Method = "POST";

        // Set the content type to a FORM
        myRequest.ContentType = "application/x-www-form-urlencoded";

        // Get length of content
        myRequest.ContentLength = buffer.Length;

        // Get request stream
        Stream newStream = myRequest.GetRequestStream();

         // Send the data.
         newStream.Write(buffer, 0, buffer.Length);

        // Close stream
        newStream.Close();

        // Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
        HttpWebResponse myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse();

        // Display the contents of the page to the console.
        Stream streamResponse = myHttpWebResponse.GetResponseStream();
        // Get stream object
        StreamReader streamRead = new StreamReader(streamResponse);
        Char[] readBuffer = new Char[256];

        // Read from buffer
        int count = streamRead.Read(readBuffer, 0, 256);
        while (count > 0)
        {
            // get string
            String resultData = new String(readBuffer, 0, count);
            // Write the data
            Console.WriteLine(resultData);
            // Read from buffer
            count = streamRead.Read(readBuffer, 0, 256);

         }
        // Release the response object resources.
        streamRead.Close();
        streamResponse.Close();
        // Close response
        myHttpWebResponse.Close();
    }
 public bool CheckCalib()
 {
     if(_client != null)
     {
         ASCIIEncoding  encoding = new ASCIIEncoding();
         byte[] myBytes = encoding.GetBytes(_checkCalib);
         _client.GetStream().Write(myBytes,0,sizeof(byte)*_checkCalib.Length);
     }
     return _calibrating;
 }
예제 #20
0
 //******
 public static void sendMessageUI(TcpClient tcpclnt, string message)
 {
     String sendString = message;
     Stream serverSendStream = tcpclnt.GetStream();
     ASCIIEncoding asen = new ASCIIEncoding();
     byte[] bytesInSend = asen.GetBytes(sendString);
     serverSendStream.Write(bytesInSend, 0, bytesInSend.Length);
     serverSendStream.Flush();
     int nBytes = bytesInSend.Length;
 }
예제 #21
0
 //*****
 public static string sendMessage(TcpClient tcpclnt)
 {
     Stream serverSendStream = tcpclnt.GetStream();
     String sendString = "Hellllllllloooooooooooooooooooooooooooooooooooooooooooooooo";
     ASCIIEncoding asen = new ASCIIEncoding();
     byte[] bytesInSend = asen.GetBytes(sendString);
     serverSendStream.Write(bytesInSend, 0, bytesInSend.Length);
     serverSendStream.Flush();
     int nBytes = bytesInSend.Length;
     return sendString;
 }
예제 #22
0
파일: test.cs 프로젝트: mono/gert
	public void Serve ()
	{
		// Create the server socket
		Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		sock.Bind (new IPEndPoint (IPAddress.Loopback, 54321));
		sock.Listen (5);

		// Wait for connection
		iStarted.Set ();
		Socket sock2 = sock.Accept ();

		// connection made - wait for http request
		byte [] data = new byte [1000];
		sock2.Receive (data);

		ASCIIEncoding enc = new ASCIIEncoding ();

		// Send the response - chunked responses will very likely be
		// sent as a series of Send() calls.
		sock2.Send (enc.GetBytes ("HTTP/1.1 200 OK\r\n"));
		sock2.Send (enc.GetBytes ("Transfer-Encoding: chunked\r\n"));
		sock2.Send (enc.GetBytes ("\r\n"));
		sock2.Send (enc.GetBytes ("8\r\n"));
		sock2.Send (enc.GetBytes ("01234567\r\n"));
		sock2.Send (enc.GetBytes ("10\r\n"));
		sock2.Send (enc.GetBytes ("0123456789abcdef\r\n"));
		sock2.Send (enc.GetBytes ("7\r\n"));
		sock2.Send (enc.GetBytes ("abcdefg\r\n"));
		sock2.Send (enc.GetBytes ("9\r\n"));
		sock2.Send (enc.GetBytes ("hijklmnop\r\n"));
		sock2.Send (enc.GetBytes ("a\r\n"));
		sock2.Send (enc.GetBytes ("qrstuvwxyz\r\n"));
		sock2.Send (enc.GetBytes ("0\r\n"));
		sock2.Send (enc.GetBytes ("\r\n"));

		// Close the sockets
		sock2.Close ();
		sock.Close ();
	}
예제 #23
0
 public static string sendMessage(TcpClient tcpclnt)
 {
     //String sendString = Console.ReadLine();
     Stream serverSendStream = tcpclnt.GetStream();
     String sendString = "Hellllllllloooooooooooooooooooooooooooooooooooooooooooooooo";
     ASCIIEncoding asen = new ASCIIEncoding();
     byte[] bytesInSend = asen.GetBytes(sendString);
     //Console.WriteLine("Transmitting.....");
     serverSendStream.Write(bytesInSend, 0, bytesInSend.Length);
     serverSendStream.Flush();
     int nBytes = bytesInSend.Length;
     return sendString;
 }
예제 #24
0
 public static string MD5(string number)
 {
     ASCIIEncoding ASCIIenc = new ASCIIEncoding();
     string strReturn = "";
     byte[] ByteSourceText = ASCIIenc.GetBytes(number);
     MD5CryptoServiceProvider Md5Hash = new MD5CryptoServiceProvider();
     byte[] ByteHash = Md5Hash.ComputeHash(ByteSourceText);
     foreach (byte b in ByteHash)
     {
         strReturn += b.ToString("x2");
     }
     return strReturn;
 }
예제 #25
0
파일: Util.cs 프로젝트: magicJhon/Game
 public static string GetSHA1(string str)
 {
     SHA1 sha = SHA1.Create();
     ASCIIEncoding enc = new ASCIIEncoding();
     byte[] bArr = enc.GetBytes(str);
     bArr = sha.ComputeHash(bArr);
     string validResult = "";
     for (int i = 0; i < bArr.Length; i++)
     {
         validResult = validResult + bArr[i].ToString("x").PadLeft(2, '0');
     }
     return validResult.Trim();
 }
 // Use this for initialization
 void Start()
 {
     try
     {
         _client = new TcpClient(address,System.Convert.ToInt32(port));
         ASCIIEncoding  encoding = new ASCIIEncoding();
         byte[] myBytes = encoding.GetBytes(_connectionParams);
         _client.GetStream().Write(myBytes,0,sizeof(byte)*_connectionParams.Length);
     }
     catch( SocketException e )
     {
         print(e);
     }
 }
예제 #27
0
    /// <summary>
    /// Method that encrypt a String, used for encrypting passwords with the SHA1 hash algorithm
    /// </summary>
    /// <param name="str">Returns the encrypted String</param>
    /// <returns></returns>
    public static string encrypt(string str)
    {
        SHA1 sha1 = SHA1Managed.Create();
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] stream = null;
        StringBuilder sb = new StringBuilder();

        stream = sha1.ComputeHash(encoding.GetBytes(str));
        for (int i = 0; i < stream.Length; i++)
        {
            sb.AppendFormat("{0:x2}", stream[i]);
        }

        return sb.ToString();
    }
    public static HttpWebResponse Post(string url)
    {
        ASCIIEncoding encoding=new ASCIIEncoding();
        string postData="username=zxc";
        postData += ("&password=asd");
        byte[] data = encoding.GetBytes(postData);

        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
        myRequest.Method = "POST";
        myRequest.ContentType="application/x-www-form-urlencoded";
        myRequest.ContentLength = data.Length;
        Stream newStream=myRequest.GetRequestStream();
        newStream.Write(data,0,data.Length);
        newStream.Close();
        HttpWebResponse myResponse=(HttpWebResponse)myRequest.GetResponse();
        return myResponse;
    }
예제 #29
0
    public static void Main()
    {
        try
        {
            // �½��ͻ����׽���
            TcpClient tcpclnt = new TcpClient();
            Console.WriteLine("����.....");

            // ���ӷ�����
            tcpclnt.Connect("127.0.0.1",8001);
            Console.WriteLine("������");
            Console.Write("������Ҫ������ַ��� : ");

            // �����ַ���
            String str=Console.ReadLine();

            // �õ��ͻ��˵���
            Stream stm = tcpclnt.GetStream();

            // �����ַ���
            ASCIIEncoding asen= new ASCIIEncoding();
            byte[] ba=asen.GetBytes(str);
            Console.WriteLine("������.....");
            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);
        }

        Console.ReadKey();
    }
예제 #30
0
            public static SaHpiTextBufferT ToSaHpiTextBufferT( string s )
            {
                // NB: Only BCD+/ASCII6/ASCII(Eng)/ are now supported.
                // TODO implement further

                SaHpiTextBufferT tb = new SaHpiTextBufferT();
                tb.DataType   = HpiConst.SAHPI_TL_TYPE_TEXT;
                tb.Language   = HpiConst.SAHPI_LANG_ENGLISH;
                tb.DataLength = 0;
                tb.Data = new byte[HpiConst.SAHPI_MAX_TEXT_BUFFER_LENGTH];

                ASCIIEncoding ascii = new ASCIIEncoding();
                byte[] encoded = ascii.GetBytes( s );
                tb.DataLength = Math.Min( encoded.Length, HpiConst.SAHPI_MAX_TEXT_BUFFER_LENGTH );
                Array.Copy( encoded, tb.Data, tb.DataLength );

                return tb;
            }
예제 #31
0
        public static async Task Main(string[] args)
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };
            var connection = factory.CreateConnection();
            var channel    = connection.CreateModel();

            channel.QueueDeclare(queue: "donation",
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            var consumer = new EventingBasicConsumer(channel);

            consumer.Received += async(model, ea) =>
            {
                var body    = ea.Body;
                var message = Encoding.UTF8.GetString(body.ToArray());
                Console.WriteLine(" [x] Received {0}", message);

                //Extract data

                string[] words = message.Split(',');

                var cell    = "+27" + words[0].Substring(1, 9);
                var smsbody = String.Format("Hello {0}, thank you for donating R{1} to help the COVID-19 cause. The Donate Team", words[2], words[1]);

                //Twillio
                var nvc = new List <KeyValuePair <string, string> >();
                nvc.Add(new KeyValuePair <string, string>("To", cell));
                nvc.Add(new KeyValuePair <string, string>("From", "+12068884496"));
                nvc.Add(new KeyValuePair <string, string>("Body", smsbody));

                var httpClient = new HttpClient();
                var encoding   = new ASCIIEncoding();
                var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(encoding.GetBytes(string.Format("{0}:{1}", "ACf481ef865eab9691cbd8a198fba944c6", "56a225f8d158ff95f6b5357f72281baf"))));
                httpClient.DefaultRequestHeaders.Authorization = authHeader;

                var req = new HttpRequestMessage(HttpMethod.Post, "https://api.twilio.com/2010-04-01/Accounts/ACf481ef865eab9691cbd8a198fba944c6/Messages.json")
                {
                    Content = new FormUrlEncodedContent(nvc)
                };
                var response = await httpClient.SendAsync(req);

                Console.WriteLine("SMS: " + smsbody);
                Console.WriteLine("Sending SMS to user...");
            };

            channel.BasicConsume(queue: "donation",
                                 autoAck: true,
                                 consumer: consumer);
            Console.ReadLine();
        }
예제 #32
0
        public static string PesquisaDebito(string renavam, string codServico
                                            , string codSubServico
                                            , string tipoConsulta)
        {
            string retorno;

            string json = "{\"TokenCliente\": \"pItRnemCfitpFgjHGhGESA==\"," +
                          "\"FormaPagamento\": \"D\"," +
                          "\"ListaParametroDebitoVeiculo\":" +
                          "[{\"Renavam\":\"" + renavam + "\"," +
                          "\"CodServico\":\"" + codServico + "\"," +
                          "\"CodSubServico\":\"" + codSubServico + "\"," +
                          "\"TipoConsulta\":\"" + tipoConsulta + "\"}]}";

            string        url     = "http://187.9.76.122:8901/Debito/ConsultarDebitos/";
            ASCIIEncoding encoder = new ASCIIEncoding();

            byte[] data = encoder.GetBytes(json);//Aqui no meio vai o json para o post cade esses dados?

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.Method        = "POST";
            request.ContentType   = "application/json";
            request.ContentLength = data.Length;
            request.Expect        = "application/json";

            request.GetRequestStream().Write(data, 0, data.Length);
            HttpWebResponse webResponse = request.GetResponse() as HttpWebResponse;


            using (var stream = webResponse.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    string jsonRetorno = reader.ReadToEnd();
                    retorno = jsonRetorno;
                    //retorno = JSONSerializer<RootObject>.DeSerialize(jsonRetorno);
                    //retorno.StatusCode = webResponse.StatusCode;
                }
            return(retorno);

            //var httpWebRequest = (HttpWebRequest)WebRequest.Create(" http://187.9.76.122:8901/Debito/ConsultarDebitos/");
            //httpWebRequest.ContentType = "application/json";
            //httpWebRequest.Method = "POST";

            //using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            //{
            //    string json = "{\"TokenCliente\": \"pItRnemCfitpFgjHGhGESA==\"," +
            //                       "\"FormaPagamento\": \"D\"," +
            //                        "\"ListaParametroDebitoVeiculo\":" +
            //                        "[{\"Renavam\":\"00303673320\"," +
            //                        "\"CodServico\":\"8\"," +
            //                        "\"CodSubServico\":\"1\"," +
            //                        "\"TipoConsulta\":\"D\"}]}";
            //    streamWriter.Write(json);
            //}

            //var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            //if (httpResponse.StatusCode == HttpStatusCode.OK)

            //    Console.WriteLine("A U T E N T I C A D O -- > ConsultarDebitos");

            //using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            //{
            //    var result = streamReader.ReadToEnd();

            //    System.Console.WriteLine(result);
            //    System.Console.WriteLine("");
            //}
        }
예제 #33
0
        public static byte[] StringToASCIIBytes(string input)
        {
            var enc = new ASCIIEncoding();

            return(enc.GetBytes(input));
        }
예제 #34
0
파일: Crypto.cs 프로젝트: ridvanc/InstaBot
        private static byte[] StringEncode(string text)
        {
            var encoding = new ASCIIEncoding();

            return(encoding.GetBytes(text));
        }
예제 #35
0
파일: Appraise.cs 프로젝트: lntel/Cologne
        public decimal[] Calculate()
        {
            string[]  content = new string[3];
            decimal[] prices  = { };
            int       index   = 0;

            List <Config> configs = new List <Config>();

            for (int i = 0; i < 3; i++)
            {
                string json;
                Config config = new Config();

                switch (i)
                {
                case 0:
                    config.Json = "{ \"key\": \"" + processor + "\" }";

                    config.Url = string.Format("{0}{1}/{2}", API, "processor", "search.php");
                    break;

                case 1:
                    config.Json = "{ \"key\": \"" + memory + "\" }";

                    config.Url = string.Format("{0}{1}/{2}", API, "memory", "search.php");
                    break;

                case 2:
                    config.Json = "{ \"key\": \"" + gpu + "\" }";

                    config.Url = string.Format("{0}{1}/{2}", API, "graphics", "search.php");
                    break;
                }

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(config.Url);
                request.Accept      = "application/json";
                request.ContentType = "application/json";
                request.UserAgent   = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240";
                request.Method      = "POST";
                ASCIIEncoding encoding = new ASCIIEncoding();

                Byte[] bytes = encoding.GetBytes(config.Json);

                Stream str = request.GetRequestStream();
                str.Write(bytes, 0, bytes.Length);
                str.Close();

                WebResponse response = request.GetResponse();

                str = response.GetResponseStream();

                StreamReader sr = new StreamReader(str);

                config.Content = sr.ReadToEnd();
                config.Data    = JsonConvert.DeserializeObject <Item>(config.Content);

                prices = new decimal[10];

                configs.Add(config);

                //diag.Add(config);
            }

            int x = 0;

            for (index = 0; index < configs.Count - 1; index++)
            {
                //if(configs.Count < index)
                //{
                if (configs[index].Data.data[x].Price != 0)
                {
                    prices[index] = configs[index].Data.data[x].Price;
                }
                else
                {
                    while (configs[index].Data.data[x].Price == 0)
                    {
                        x++;
                    }

                    prices[index] = configs[index].Data.data[x].Price;
                }
                //}
            }

            actual = prices.Sum();

            return(prices);
        }
예제 #36
0
파일: JetPay.cs 프로젝트: lulzzz/BrandStore
        // if RefundAmount == 0.0M, then then ENTIRE order amount will be refunded!
        public override String RefundOrder(int OriginalOrderNumber, int NewOrderNumber, decimal RefundAmount, String RefundReason, Address UseBillingAddress)
        {
            String result = AppLogic.ro_OK;

            DB.ExecuteSQL("update orders set RefundTXCommand=NULL, RefundTXResult=NULL where OrderNumber=" + OriginalOrderNumber.ToString());

            bool    useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            String  TransID             = String.Empty;
            String  CardNum             = String.Empty;
            String  CardExpM            = String.Empty;
            String  CardExpY            = String.Empty;
            String  ApprvCode           = String.Empty;
            String  BillingLastName     = String.Empty;
            String  BillingFirstName    = String.Empty;
            String  BillingAddress1     = String.Empty;
            String  BillingCity         = String.Empty;
            String  BillingState        = String.Empty;
            String  BillingZip          = String.Empty;
            String  BillingPhone        = String.Empty;
            String  BillingEmail        = String.Empty;
            decimal TotalAmount         = 0;

            using (SqlConnection conn = DB.dbConn())
            {
                conn.Open();
                using (IDataReader rs = DB.GetRS("select * from orders   with (NOLOCK)  where OrderNumber=" + OriginalOrderNumber.ToString(), conn))
                {
                    if (rs.Read())
                    {
                        TransID = DB.RSField(rs, "AuthorizationPNREF");
                        CardNum = Security.UnmungeString(DB.RSField(rs, "CardNumber"), rs[AppLogic.AppConfig("OrdersCCSaltField")].ToString());
                        if (CardNum.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                        {
                            CardNum = "";
                        }
                        if (String.IsNullOrEmpty(CardNum))
                        {
                            return("JetPay requires that you store credit card numbers to refund orders. To store credit card numbers set the StoreCCInDB app config.You will not be able to refund orders taken before storing card numbers.");
                        }
                        CardExpM         = DB.RSField(rs, "CardExpirationMonth");
                        CardExpY         = DB.RSField(rs, "CardExpirationYear").Substring(2, 2);
                        ApprvCode        = DB.RSField(rs, "AuthorizationCode");
                        TotalAmount      = DB.RSFieldDecimal(rs, "OrderTotal");
                        BillingLastName  = DB.RSField(rs, "BillingLastName");
                        BillingFirstName = DB.RSField(rs, "BillingFirstName");
                        BillingAddress1  = DB.RSField(rs, "BillingAddress1");
                        BillingCity      = DB.RSField(rs, "BillingCity");
                        BillingState     = DB.RSField(rs, "BillingState");
                        BillingZip       = DB.RSField(rs, "BillingZip");
                        BillingPhone     = DB.RSField(rs, "BillingPhone");
                        BillingEmail     = DB.RSField(rs, "Email");
                    }
                }
            }

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("<JetPay><TransactionType>CREDIT</TransactionType>\n");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("JETPAY_MERCHANTID") + "</MerchantID>\n");
            transactionCommand.Append("<TransactionID>" + NewOrderNumber.ToString().PadLeft(18, '0') + "</TransactionID>\n");
            transactionCommand.Append("<CardNum>" + CardNum + "</CardNum>");

            transactionCommand.Append("<CardExpMonth>" + CardExpM + "</CardExpMonth>");
            transactionCommand.Append("<CardExpYear>" + CardExpY + "</CardExpYear>");
            transactionCommand.Append("<CardName>" + BillingFirstName + " " + BillingLastName + "</CardName>");
            transactionCommand.Append("<TotalAmount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(RefundAmount).Replace(",", "").Replace(".", "") + "</TotalAmount>");
            transactionCommand.Append("<BillingAddress>" + XmlCommon.XmlEncode(BillingAddress1) + "</BillingAddress>");
            transactionCommand.Append("<BillingCity>" + XmlCommon.XmlEncode(BillingCity) + "</BillingCity>");
            transactionCommand.Append("<BillingStateProv>" + BillingState + "</BillingStateProv>");
            transactionCommand.Append("<BillingPostalCode>" + BillingZip + "</BillingPostalCode>");

            transactionCommand.Append("<BillingPhone>" + BillingPhone + "</BillingPhone>");
            transactionCommand.Append("<Email>" + BillingEmail + "</Email>");
            transactionCommand.Append("<UDField1>" + XmlCommon.XmlEncode(RefundReason) + "</UDField1>");
            transactionCommand.Append("</JetPay>");

            String CardToken            = String.Format("<CardNum>{0}</CardNum>", CardNum);
            String CardTokenReplacement = String.Format("<CardNum>{0}</CardNum>", AppLogic.SafeDisplayCardNumber(CardNum, "Orders", OriginalOrderNumber));

            DB.ExecuteSQL("update orders set RefundTXCommand=" + DB.SQuote(transactionCommand.ToString().Replace(CardToken, CardTokenReplacement)) + " where OrderNumber=" + OriginalOrderNumber.ToString());

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("JETPAY_LIVE_SERVER"), AppLogic.AppConfig("JETPAY_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.ContentType   = "text/xml";
            myRequest.ContentLength = data.Length;
            myRequest.Method        = "POST";
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response

            String sql       = String.Empty;
            String replyCode = CommonLogic.ExtractToken(rawResponseString, "<ActionCode>", "</ActionCode>");
            //String responseCode = CommonLogic.ExtractToken(rawResponseString,"<RespCode>","</RespCode>");
            String approvalCode = CommonLogic.ExtractToken(rawResponseString, "<Approval>", "</Approval>");
            String authResponse = CommonLogic.ExtractToken(rawResponseString, "<ResponseText>", "</ResponseText>");
            String ErrMsg       = CommonLogic.ExtractToken(rawResponseString, "<ErrMsg>", "</ErrMsg>");

            TransID = CommonLogic.ExtractToken(rawResponseString, "<TransactionID>", "</TransactionID>");


            DB.ExecuteSQL("update orders set RefundTXResult=" + DB.SQuote(rawResponseString) + " where OrderNumber=" + OriginalOrderNumber.ToString());
            if (Convert.ToInt32(replyCode) == 0)
            {
                result = AppLogic.ro_OK;
            }
            else
            {
                result = authResponse;
            }
            return(result);
        }
예제 #37
0
        public void NewCommand(string fullCommand)
        {
            String[]        words   = fullCommand.Split(' ', ',');
            String          clientN = words[1].Split('-')[1];
            IClientToPuppet server;
            ASCIIEncoding   ascii = new ASCIIEncoding();
            String          toPuppet;
            int             serverNumber;

            try
            {
                serverNumber = Convert.ToInt32(clientN);
            }
            catch (Exception e)
            {
                throw new CommandException("ClientProxy: Invalid server number" + fullCommand + " " + e.Message);
            }
            server = ConnectToClient(serverNumber);

            String command = words[0];

            try
            {
                switch (command)
                {
                case "CREATE":
                    // Create(server,words,fullCommand);
                    toPuppet = server.Create(words[3], Convert.ToInt32(words[5]), Convert.ToInt32(words[7]), Convert.ToInt32(words[9]));
                    break;

                case "OPEN":
                    // Open(server, words, fullCommand);
                    toPuppet = server.Open(words[3]);
                    break;

                case "CLOSE":
                    //    Close(server, words, fullCommand);
                    toPuppet = server.Close(words[3]);
                    break;

                case "DELETE":
                    //    Delete(server, words, fullCommand);
                    toPuppet = server.Delete(words[3]);
                    break;

                case "READ":
                    //   Read(server,words,fullCommand);
                    SemanticType type = (words[5].Equals("monotonic")) ? SemanticType.Monotonic : SemanticType.Default;
                    toPuppet = server.Read(Convert.ToInt32(words[3]), type, Convert.ToInt32(words[7]));
                    break;

                case "WRITE":
                    // Write(server,words,fullCommand);
                    if (fullCommand.Split('"').Length > 1)
                    {
                        toPuppet = server.Write(Convert.ToInt32(words[3]), ascii.GetBytes(fullCommand.Split('"')[1]));
                    }
                    else
                    {
                        toPuppet = server.Write(Convert.ToInt32(words[3]), Convert.ToInt32(words[5]));
                    }
                    break;

                case "COPY":
                    //    Copy(server, words, fullCommand);
                    SemanticType type2 = (words[5].Equals("monotonic")) ? SemanticType.Monotonic : SemanticType.Default;
                    toPuppet = server.Copy(Convert.ToInt32(words[3]), type2, Convert.ToInt32(words[7]), ascii.GetBytes(fullCommand.Split('"')[1]));
                    break;

                case "DUMP":
                    //    dump(server);
                    toPuppet = server.Dump();
                    break;

                case "EXESCRIPT":
                    toPuppet = ExeScript(server, words, fullCommand);
                    break;

                default:
                    throw new CommandException("Client Proxy: Invalid Command: " + fullCommand);
                }
            }
            catch (SocketException e)
            {
                throw new CommandException("Client Proxy: SocketException: " + fullCommand + " " + e.Message);
            }
            catch (PadiException exN)
            {
                _core.DisplayMessage(exN.Description);
                return;
            }
            catch (Exception ex)
            {
                _core.DisplayMessage(ex.Message);
                return;
            }
            // Return the String receved from the server to be Displayed
            _core.DisplayMessage(toPuppet);
        }
예제 #38
0
        public string MakeWebRequest(string urlString, RequestMethod method = RequestMethod.GET, WebHeaderCollection headerCollection = null, string queryString = "")
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var storageItem = WebserviceRequestsMapper.GetByUrl(urlString);
            var data        = "";

            if ((storageItem != null) && (EnableCaching) && !storageItem.Response.Contains("unavailable") && storageItem.DateLastModified.AddSeconds(CacheDurationInSeconds) > DateTime.Now)
            {
                return(storageItem.Response);
            }

            WebserviceRequest request = null;

            if (storageItem == null)
            {
                request = new WebserviceRequest();
            }
            else
            {
                request = storageItem;
            }

            request.Url         = urlString;
            request.QueryString = queryString;
            request.Response    = "";
            request.Method      = method.ToString();
            request.UrlReferrer = "";

            if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
            {
                request.UrlReferrer = System.Web.HttpContext.Current.Request.UrlReferrer.AbsoluteUri;
            }

            WebRequest webRequest = WebRequest.Create(urlString);

            if (headerCollection != null)
            {
                webRequest.Headers = headerCollection;
            }

            webRequest.Method = method.ToString();

            try
            {
                if (method == RequestMethod.POST && !string.IsNullOrEmpty(queryString))
                {
                    var    encoding = new ASCIIEncoding();
                    byte[] bytes    = encoding.GetBytes(queryString);

                    webRequest.ContentLength = bytes.Length;
                    webRequest.ContentType   = "application/x-www-form-urlencoded";

                    using (var webRequestStream = webRequest.GetRequestStream())
                    {
                        webRequestStream.Write(bytes, 0, bytes.Length);
                        webRequestStream.Flush();
                        webRequestStream.Close();
                    }
                }

                using (WebResponse webResponse = webRequest.GetResponse())
                {
                    Stream dataStream = webResponse.GetResponseStream();

                    using (StreamReader streamReader = new StreamReader(dataStream))
                    {
                        data = streamReader.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                ErrorHelper.LogException(ex);

                data = ex.Message;

                if (ex.Response != null)
                {
                    // can use ex.Response.Status, .StatusDescription
                    if (ex.Response.ContentLength != 0)
                    {
                        using (var stream = ex.Response.GetResponseStream())
                        {
                            using (var reader = new StreamReader(stream))
                            {
                                data = reader.ReadToEnd();
                            }
                        }
                    }
                }
            }

            if (request != null)
            {
                request.Response = data;

                var ommit = false;

                foreach (var item in OmmitList)
                {
                    if (request.Url.ToLower().Contains(item))
                    {
                        ommit = true;
                        break;
                    }
                }

                if (EnableCaching)
                {
                    if (request.ID == 0)
                    {
                        WebserviceRequestsMapper.Insert(request);
                    }
                    else
                    {
                        request = BaseMapper.GetObjectFromContext(request);
                        WebserviceRequestsMapper.Update(request);
                    }
                }
            }

            return(data);
        }
예제 #39
0
        /// <summary>
        /// Probe the device with the given network interface and raises the event when device is discovered
        /// </summary>
        /// <param name="receiverAddress">Client Network Interface IP Address</param>
        /// <param name="targetAddress">Target device address</param>
        /// <param name="probeMessage">probe message</param>
        /// <param name="port">port number</param>
        /// <returns>List of discovered devices probe match string</returns>
        public static Collection <string> ProbeDevice(IPAddress receiverAddress, IPAddress targetAddress, string probeMessage, int port)
        {
            Socket socket = null;

            Collection <string> devices = new Collection <string>();

            try
            {
                EndPoint receiverEndPoint = new IPEndPoint(receiverAddress, 0);

                // Cast PROBE packet into a byte array
                ASCIIEncoding encoder        = new ASCIIEncoding();
                Byte[]        probeByteArray = encoder.GetBytes(probeMessage);

                // Setup the Socket bound to a receiver (local) EndPoint.
                IPEndPoint destinationEndPoint = new IPEndPoint(targetAddress, port);
                socket = new Socket(targetAddress.AddressFamily, SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
                socket.Bind(receiverEndPoint);

                // Send the PROBE Packet.
                socket.SendTo(probeByteArray, destinationEndPoint);

                DateTime start = DateTime.Now;

                // ProbeMatch must be sent within 4 seconds of the Probe message; otherwise, Windows Firewall may drop the packet.
                // on the safer side we are waiting for the 6 seconds.
                // DP_MAX_TIMEOUT is 5 seconds this information is taken from the Web Services Dynamic Discovery document from Microsoft.
                while (DateTime.Now.Subtract(start).Seconds <= 6)
                {
                    if (socket.Available > 0)
                    {
                        byte[]     buffer = new byte[50000];
                        IPEndPoint endPoint;

                        if (targetAddress.AddressFamily == AddressFamily.InterNetwork)
                        {
                            endPoint = new IPEndPoint(IPAddress.Any, 0);
                        }
                        else
                        {
                            endPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
                        }

                        EndPoint remoteHost = (EndPoint)endPoint;

                        // Get the probe match packet through socket connection
                        socket.ReceiveFrom(buffer, ref remoteHost);

                        buffer = RemoveNull(buffer);
                        // get the probe match string
                        string probeMatchString = Encoding.UTF8.GetString(buffer);

                        devices.Add(probeMatchString);
                    }
                }
            }
            catch (Exception)
            {
                // Do nothing if any exception occurs while looking for probe match keep reading the probe match until the time out.
            }
            finally
            {
                // close the socket
                if (null != socket)
                {
                    socket.Close();
                }
            }

            return(devices);
        }
예제 #40
0
        public static int SinaLogin(string uid, string psw, CookieContainer cc)
        {
            string uidbase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(uid));

            string url =
                "http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.11)&_=" +
                DateTime.Now.Ticks;

            HttpWebRequest webRequest1 = (HttpWebRequest)WebRequest.Create(new Uri(url)); //获取servertime和 nonce

            webRequest1.CookieContainer = cc;
            HttpWebResponse response1 = (HttpWebResponse)webRequest1.GetResponse();
            StreamReader    sr1       = new StreamReader(response1.GetResponseStream(), Encoding.UTF8);
            string          res       = sr1.ReadToEnd();

            string servertime = GetResponseKeyValue("servertime", res);
            string nonce      = GetResponseKeyValue("nonce", res);
            string pubkey     = GetResponseKeyValue("pubkey", res);

            JSRSAUtil rsaUtil = new JSRSAUtil();

            rsaUtil.RSASetPublic(pubkey, "10001");
            var encryPwd = servertime + '\t' + nonce + '\n' + psw;

            Console.WriteLine(encryPwd);
            string password = rsaUtil.RSAEncrypt(encryPwd);//密码RSA加密

            string str = "entry=weibo&gateway=1&from=&savestate=7&useticket=1&vsnf=1&su=" +
                         uidbase64 + "&service=miniblog&servertime=" + servertime + "&nonce=" + nonce + "&pwencode=rsa2&rsakv=1330428213&sp=" + password + "&sr=1366*768&prelt=282&encoding=UTF-8&url=" +
                         HttpUtility.UrlEncode("http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack") +
                         "&returntype=META";

            byte[]        bytes;
            ASCIIEncoding encoding = new ASCIIEncoding();

            bytes = encoding.GetBytes(str);
            // bytes = System.Text.Encoding.UTF8.GetBytes(HttpUtility.UrlEncode(str));
            HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create("http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.16)");

            webRequest2.Method          = "POST";
            webRequest2.ContentType     = "application/x-www-form-urlencoded";
            webRequest2.ContentLength   = bytes.Length;
            webRequest2.CookieContainer = cc;

            Stream stream;

            stream = webRequest2.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();

            HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
            StreamReader    sr2       = new StreamReader(response2.GetResponseStream(), Encoding.Default);
            string          res2      = sr2.ReadToEnd();

            Console.WriteLine(res2);

            if (res2.IndexOf("reason=") >= 0)
            {
                Console.WriteLine("登录失败...");
                return(-1);
            }

            var redirectUrl = GetLoginRedirectUrl(res2);

            if (string.IsNullOrEmpty(redirectUrl))
            {
                Console.WriteLine("登录失败, redict Url没找到...");
                return(-1);
            }
            else
            {
                Console.WriteLine(redirectUrl);
            }


            HttpWebRequest webRequest3 = (HttpWebRequest)WebRequest.Create(new Uri(redirectUrl));

            webRequest3.CookieContainer = cc;
            HttpWebResponse response3 = (HttpWebResponse)webRequest3.GetResponse();
            StreamReader    sr3       = new StreamReader(response3.GetResponseStream(), Encoding.UTF8);

            res = sr3.ReadToEnd();

            Console.WriteLine(res);

            foreach (Cookie cookie in response3.Cookies)
            {
                cc.Add(cookie);
            }
            return(0);
        }
예제 #41
0
파일: JetPay.cs 프로젝트: lulzzz/BrandStore
        public override String CaptureOrder(Order o)
        {
            String result = AppLogic.ro_OK;

            bool useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");

            o.CaptureTXCommand = "";
            o.CaptureTXResult  = "";
            String TransID = o.AuthorizationPNREF;

            String CardNum = Security.UnmungeString(o.CardNumber, o.OrdersCCSaltField);

            if (CardNum.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                CardNum = o.CardNumber;
            }
            String  CardExpM    = o.CardExpirationMonth;
            String  CardExpY    = o.CardExpirationYear.Substring(2, 2);
            String  ApprvCode   = o.AuthorizationCode;
            decimal TotalAmount = o.OrderBalance;

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("<JetPay><TransactionType>CAPT</TransactionType>\n");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("JETPAY_MERCHANTID") + "</MerchantID>\n");
            transactionCommand.Append("<TransactionID>" + TransID + "</TransactionID>\n");
            transactionCommand.Append("<CardNum>" + CardNum + "</CardNum>");
            transactionCommand.Append("<CardExpMonth>" + CardExpM + "</CardExpMonth>");
            transactionCommand.Append("<CardExpYear>" + CardExpY + "</CardExpYear>");
            transactionCommand.Append("<Approval>" + ApprvCode + "</Approval>");
            transactionCommand.Append("<TotalAmount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(TotalAmount).Replace(".", "").Replace(",", "") + "</TotalAmount>");
            transactionCommand.Append("</JetPay>");

            o.CaptureTXCommand = transactionCommand.ToString();

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("JETPAY_LIVE_SERVER"), AppLogic.AppConfig("JETPAY_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.ContentType   = "text/xml";
            myRequest.ContentLength = data.Length;
            myRequest.Method        = "POST";
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response

            String sql          = String.Empty;
            String replyCode    = CommonLogic.ExtractToken(rawResponseString, "<ActionCode>", "</ActionCode>");
            String approvalCode = CommonLogic.ExtractToken(rawResponseString, "<Approval>", "</Approval>");
            String authResponse = CommonLogic.ExtractToken(rawResponseString, "<ResponseText>", "</ResponseText>");

            TransID = CommonLogic.ExtractToken(rawResponseString, "<TransactionID>", "</TransactionID>");

            o.CaptureTXResult = rawResponseString;

            if (Convert.ToInt32(replyCode) == 0)
            {
                result = AppLogic.ro_OK;
            }
            else
            {
                result = authResponse;
            }
            return(result);
        }
예제 #42
0
        public void SaveStream(Stream stream, ITerrainChannel map)
        {
            BinaryWriter bs = new BinaryWriter(stream);

            //find the max and min heights on the map
            double heightMax = map[0, 0];
            double heightMin = map[0, 0];

            for (int y = 0; y < map.Height; y++)
            {
                for (int x = 0; x < map.Width; x++)
                {
                    double current = map[x, y];
                    if (heightMax < current)
                    {
                        heightMax = current;
                    }
                    if (heightMin > current)
                    {
                        heightMin = current;
                    }
                }
            }

            double baseHeight = Math.Floor((heightMax + heightMin) / 2d);

            double horizontalScale = Math.Ceiling((heightMax - heightMin));

            // if we are completely flat add 1cm range to avoid NaN divisions
            if (horizontalScale < 0.01d)
            {
                horizontalScale = 0.01d;
            }

            ASCIIEncoding enc = new ASCIIEncoding();

            bs.Write(enc.GetBytes("TERRAGENTERRAIN "));

            bs.Write(enc.GetBytes("SIZE"));
            bs.Write(Convert.ToInt16(Constants.RegionSize));
            bs.Write(Convert.ToInt16(0)); // necessary padding

            //The XPTS and YPTS chunks are not needed for square regions
            //but L3DT won't load the terrain file properly without them.
            bs.Write(enc.GetBytes("XPTS"));
            bs.Write(Convert.ToInt16(map.Scene.RegionInfo.RegionSizeX));
            bs.Write(Convert.ToInt16(0)); // necessary padding

            bs.Write(enc.GetBytes("YPTS"));
            bs.Write(Convert.ToInt16(map.Scene.RegionInfo.RegionSizeY));
            bs.Write(Convert.ToInt16(0)); // necessary padding

            bs.Write(enc.GetBytes("SCAL"));
            bs.Write(ToLittleEndian(1f)); //we're going to say that 1 terrain unit is 1 metre
            bs.Write(ToLittleEndian(1f));
            bs.Write(ToLittleEndian(1f));

            // as we are square and not projected on a sphere then the other
            // header blocks are not required

            // now write the elevation data
            bs.Write(enc.GetBytes("ALTW"));
            bs.Write(Convert.ToInt16(horizontalScale)); // range between max and min
            bs.Write(Convert.ToInt16(baseHeight));      // base height or mid point

            for (int y = 0; y < map.Height; y++)
            {
                for (int x = 0; x < map.Width; x++)
                {
                    float elevation = (float)((map[x, y] - baseHeight) * 65536) / (float)horizontalScale;
                    // see LoadStream for inverse

                    // clamp rounding issues
                    if (elevation > Int16.MaxValue)
                    {
                        elevation = Int16.MaxValue;
                    }
                    else if (elevation < Int16.MinValue)
                    {
                        elevation = Int16.MinValue;
                    }

                    bs.Write(Convert.ToInt16(elevation));
                }
            }

            //This is only necessary for older versions of Terragen.
            bs.Write(enc.GetBytes("EOF "));

            bs.Close();
        }
예제 #43
0
        public static HttpWebRequest Request; //2014.03.27. - A megállitáshoz

        public void LoginUser()
        {
            string UserText = "";
            string PassText = "";

            this.Invoke(new Action(delegate
            { //2015.04.03.
                UserText           = textBox1.Text;
                PassText           = textBox2.Text;
                linkLabel1.Enabled = false;
                button1.Text       = Language.Translate(Language.StringID.Button_Cancel);
            }));
            HttpWebRequest httpWReq =
                (HttpWebRequest)WebRequest.Create("http://msger.url.ph/client.php");

            Request = httpWReq; //2014.03.27.

            ASCIIEncoding encoding = new ASCIIEncoding();
            string        postData = "username="******"&password="******"&key=cas1fe4a6feFEFEFE1616CE8099VFE1444cdasf48c1ase5dg";
            //postData += "&port=" + Storage.Settings[SettingType.Port]; //2014.08.29.
            postData += "&port=" + CurrentUser.Port; //2015.05.24.
            List <IPAddress> myips = new List <IPAddress>();

            do
            { //Az ips már deklarálva lesz később; megváltoztattam myips-re ezt
                foreach (var ipaddr in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    if (ipaddr.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        myips.Add(ipaddr);
                    }
                }
                string ipstr = "";
                foreach (var ip in myips)
                {
                    ipstr += ip + ";";
                }
                postData += "&ip=" + Uri.EscapeUriString(ipstr);
            } while (false);
            byte[] data = encoding.GetBytes(postData);

            httpWReq.Method        = "POST";
            httpWReq.ContentType   = "application/x-www-form-urlencoded";
            httpWReq.ContentLength = data.Length;

            try
            {
                using (Stream stream = httpWReq.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                    new ErrorHandler(ErrorType.ServerConnectError, e); //2015.06.04.
                    ResetAfterLogin(false);                            //2015.04.03.
                    return;
                }
                else
                {
                    return;
                }
            }

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)httpWReq.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                    new ErrorHandler(ErrorType.ServerConnectError, e); //2015.06.04.
                    ResetAfterLogin(false);                            //2015.04.03.
                    return;
                }
                else
                {
                    return;
                }
            }

            string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            try
            {
                if (responseString[0] == '<')
                {
                    ResetAfterLogin(false); //2015.04.03.
                    new ErrorHandler(ErrorType.ServerConnectError, new Exception(responseString));
                    return;
                }
                else
                {
                    responseString = responseString.Remove(responseString.IndexOf('<'));
                }
            }
            catch
            {
            }

            if (String.Compare(responseString, "Fail") == 0)
            {
                ResetAfterLogin(false); //2015.04.03.
                MessageBox.Show(Language.Translate(Language.StringID.Error) + ": " + Language.Translate(Language.StringID.Login_BadNamePass), Language.Translate(Language.StringID.Error));
            }
            else if (responseString.Contains("Fail"))
            {                                                                                  //2015.04.03.
                ResetAfterLogin(false);
                new ErrorHandler(ErrorType.ServerConnectError, new Exception(responseString)); //2015.06.04.
            }
            else
            {
                //Elmenti az E-mail-t
                if (!Storage.Settings[SettingType.Email].Contains(UserText))
                {
                    if (Storage.Settings[SettingType.Email].Length != 0) //2014.07.08.
                    {
                        Storage.Settings[SettingType.Email] += ",";
                    }
                    Storage.Settings[SettingType.Email] += UserText;
                }
                Storage.Settings[SettingType.LastUsedEmail] = Storage.Settings[SettingType.Email].Split(',').ToList <string>().IndexOf(UserText).ToString();
                string[] respstr = responseString.Split('ͦ');

                if (respstr.Any(entry => entry.Contains("Fail"))) //2014.12.05.
                {
                    //this.Invoke(new MyDelegate(ResetAfterLogin));
                    ResetAfterLogin(false); //2015.04.03.

                    /*try
                     * {
                     *  MessageBox.Show(respstr.Single(entry => entry.Contains("Fail"))); //2014.12.05.
                     * }
                     * catch { }*/
                    MessageBox.Show(respstr.FirstOrDefault(entry => entry.Contains("Fail"))); //2014.12.05. - Single-->FirstOrDefault: 2015.06.06.
                    return;
                }
                string[] entries             = respstr[(int)LoginInfo.IPs].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                IEnumerable <IPEndPoint> ips = entries.Select(entry => ((entry != ",") ? new IPEndPoint(IPAddress.Parse(entry.Split(',')[0]), Int32.Parse(entry.Split(',')[1])) : new IPEndPoint(IPAddress.Loopback, 0)));
                UserInfo.IPs    = new HashSet <IPEndPoint>(ips); //2014.08.30.
                CurrentUser.IPs = myips;

                CurrentUser.UserID = Int32.Parse(respstr[(int)LoginInfo.UserID]); //2014.09.01. - Áthelyeztem, hogy addig ne higgye bejelentkezettnek, amíg el nem küldi a többieknek

                Storage.SaltKey  = CalculateMD5Hash(PassText);                    //2014.08.07.
                Storage.FileName = respstr[(int)LoginInfo.UserID] + ".db";        //2014.09.01. - Felesleges számmá alakítani, majd vissza

                CurrentUser.UserName = UserText;                                  //2014.09.01. - Ha semmit nem tud saját magáról, és más sem, de nem ismerőse saját magának, akkor az itt beállított felhasználónév érvényesül
                CurrentUser.Name     = UserText;                                  //2014.09.01.
                string ReceivedPass = respstr[(int)LoginInfo.Password];           //2014.10.24. 1:39
                LoginForm.UserCode = CalculateMD5Hash(ReceivedPass + " Some text because why not " + CurrentUser.UserID).ToLower();

                this.Invoke(new Action(delegate
                {
                    this.Dispose();
                }));
            }
        }
예제 #44
0
        // Funkcija sa weba izvlači kategoriju i link na sliku proizvoda
        private void katSlik(ref DataRow r)
        {
            try
            {
                int           x, y, a = 0;
                ASCIIEncoding encoding = new ASCIIEncoding();

                string postData = "Ssubmit=Pretraga&kljucna_rijec=" + r["Šifra"].ToString() + "&kategorija_ID=all&podkategorija_ID=all&marka_ID=all&tip_robe=all";
                byte[] data     = encoding.GetBytes(postData);

                WebRequest reguest1 = WebRequest.Create("http://www.tradexco.hr/webshop/pretraga/");
                reguest1.Method        = "POST";
                reguest1.ContentType   = "application/x-www-form-urlencoded";
                reguest1.ContentLength = data.Length;

                Stream stream = reguest1.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();

                WebResponse response = reguest1.GetResponse();
                stream = response.GetResponseStream();

                StreamReader sr     = new StreamReader(stream);
                string       search = sr.ReadToEnd();
                while (true)
                {
                    x = search.IndexOf("artikl_box", a);
                    if (x == -1)
                    {
                        break;
                    }

                    x = search.IndexOf("<a", x) + 9;
                    a = search.IndexOf("\"", x);
                    string novi = search.Substring(x, a - x);

                    WebRequest reguest2 = WebRequest.Create("http://www.tradexco.hr" + novi);
                    stream = reguest2.GetResponse().GetResponseStream();
                    string artikl = new StreamReader(stream).ReadToEnd();

                    x = artikl.IndexOf("Šifra:") + 11;
                    x = artikl.IndexOf(">", x) + 1;
                    y = artikl.IndexOf("<", x);
                    string sifra = artikl.Substring(x, y - x);

                    if (sifra != r["Šifra"].ToString())
                    {
                        continue;
                    }

                    x = artikl.IndexOf("<div class=\"bc\">") + 10;
                    x = artikl.IndexOf("<a", x) + 5;
                    x = artikl.IndexOf("<a", x) + 2;
                    x = artikl.IndexOf("\">", x) + 2;
                    y = artikl.IndexOf("<", x);
                    string kategorija = artikl.Substring(x, y - x);
                    x           = artikl.IndexOf("<a", y) + 2;
                    x           = artikl.IndexOf("\">", x) + 2;
                    y           = artikl.IndexOf("<", x);
                    kategorija += " " + artikl.Substring(x, y - x);

                    r["Podgrupa"] = kategorija;

                    x          = artikl.IndexOf("glavna_slika") + 10;
                    x          = artikl.IndexOf("<a", x) + 9;
                    y          = artikl.IndexOf("\"", x);
                    r["Slika"] = "http://www.tradexco.hr" + artikl.Substring(x, y - x);

                    return;
                }
            }
            catch { }

            return;
        }
예제 #45
0
파일: id3Lib.cs 프로젝트: rajeshwarn/Music1
        public static void updateMP3Tag(ref MP3 paramMP3)
        {
            // Trim any whitespace
            paramMP3.id3Title   = paramMP3.id3Title.Trim();
            paramMP3.id3Artist  = paramMP3.id3Artist.Trim();
            paramMP3.id3Album   = paramMP3.id3Album.Trim();
            paramMP3.id3Year    = paramMP3.id3Year.Trim();
            paramMP3.id3Comment = paramMP3.id3Comment.Trim();

            // Ensure all properties are correct size
            if (paramMP3.id3Title.Length > 30)
            {
                paramMP3.id3Title = paramMP3.id3Title.Substring(0, 30);
            }
            if (paramMP3.id3Artist.Length > 30)
            {
                paramMP3.id3Artist = paramMP3.id3Artist.Substring(0, 30);
            }
            if (paramMP3.id3Album.Length > 30)
            {
                paramMP3.id3Album = paramMP3.id3Album.Substring(0, 30);
            }
            if (paramMP3.id3Year.Length > 4)
            {
                paramMP3.id3Year = paramMP3.id3Year.Substring(0, 4);
            }
            if (paramMP3.id3Comment.Length > 28)
            {
                paramMP3.id3Comment = paramMP3.id3Comment.Substring(0, 28);
            }

            // Build a new ID3 Tag (128 Bytes)
            byte[] tagByteArray = new byte[128];
            for (int i = 0; i < tagByteArray.Length; i++)
            {
                tagByteArray[i] = 0;                                       // Initialise array to nulls
            }
            // Convert the Byte Array to a String
            Encoding instEncoding = new ASCIIEncoding(); // NB: Encoding is an Abstract class // ************ To DO: Make a shared instance of ASCIIEncoding so we don't keep creating/destroying it

            // Copy "TAG" to Array
            byte[] workingByteArray = instEncoding.GetBytes("TAG");
            Array.Copy(workingByteArray, 0, tagByteArray, 0, workingByteArray.Length);
            // Copy Title to Array
            workingByteArray = instEncoding.GetBytes(paramMP3.id3Title);
            Array.Copy(workingByteArray, 0, tagByteArray, 3, workingByteArray.Length);
            // Copy Artist to Array
            workingByteArray = instEncoding.GetBytes(paramMP3.id3Artist);
            Array.Copy(workingByteArray, 0, tagByteArray, 33, workingByteArray.Length);
            // Copy Album to Array
            workingByteArray = instEncoding.GetBytes(paramMP3.id3Album);
            Array.Copy(workingByteArray, 0, tagByteArray, 63, workingByteArray.Length);
            // Copy Year to Array
            workingByteArray = instEncoding.GetBytes(paramMP3.id3Year);
            Array.Copy(workingByteArray, 0, tagByteArray, 93, workingByteArray.Length);
            // Copy Comment to Array
            workingByteArray = instEncoding.GetBytes(paramMP3.id3Comment);
            Array.Copy(workingByteArray, 0, tagByteArray, 97, workingByteArray.Length);
            // Copy Track and Genre to Array
            tagByteArray[126] = paramMP3.id3TrackNumber;
            tagByteArray[127] = paramMP3.id3Genre;

            // SAVE TO DISK: Replace the final 128 Bytes with our new ID3 tag
            FileStream oFileStream = new FileStream(paramMP3.fileComplete, FileMode.Open);

            if (paramMP3.hasID3Tag)
            {
                oFileStream.Seek(-128, SeekOrigin.End);
            }
            else
            {
                oFileStream.Seek(0, SeekOrigin.End);
            }
            oFileStream.Write(tagByteArray, 0, 128);
            oFileStream.Close();
            paramMP3.hasID3Tag = true;
        }
예제 #46
0
        public static byte[] AsciiStringToByteArray(String str)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();

            return(encoding.GetBytes(str));
        }
예제 #47
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="domain"></param>
        /// <param name="accessToken"></param>
        /// <param name="headers"></param>
        /// <param name="isPostMethod"></param>
        /// <param name="requestUriContentType">0-default; 1-JSON</param>
        /// <param name="customTraceLog"></param>
        /// <param name="blockAllExceptions"></param>
        /// <param name="errorCaseResult"></param>
        /// <returns></returns>
        public static string RequestUri(string uri, string username = null, string password = null, string domain = null, /*string accessToken = null, */ List <string> headers = null, bool isPostMethod = false, string postData = null, int requestUriContentType = 0, object customTraceLog = null, bool blockAllExceptions = false, string errorCaseResult = null, bool expectCookies = false, List <Cookie> cookies = null, bool detailedLog = true, System.Text.Encoding encoderForParsingResult = null, string fileNameWhereToDumpResponse = null, bool?allowAutoRedirect = null)
        {
            string r = null;

            CBB_LoggingCustomTraceLog log = CBB_LoggingCustomTraceLog.Unbox(customTraceLog);

            try
            {
                CBB_LoggingCustomTraceLogExtensions.AddLineAndIncreaseIdent(log, "Requesting '" + uri + "'...");

                // used to build entire input
                StringBuilder sb = new StringBuilder();

                // used on each read operation
                byte[] buf = new byte[8192];

                // prepare the web page we will be asking for
                WebRequest request = (WebRequest)WebRequest.Create(uri);
                if (CBB_CommonExtenderClass.IsNOTNullOrWhiteSpace(username) && CBB_CommonExtenderClass.IsNullOrWhiteSpace(password))
                {
                    throw new Exception("Password must be specified if username is.");
                }
                else if (CBB_CommonExtenderClass.IsNullOrWhiteSpace(username) && CBB_CommonExtenderClass.IsNOTNullOrWhiteSpace(password))
                {
                    throw new Exception("Username must be specified when password is.");
                }
                else if (CBB_CommonExtenderClass.IsNOTNullOrWhiteSpace(username) && CBB_CommonExtenderClass.IsNOTNullOrWhiteSpace(password))
                {
                    if (CBB_CommonExtenderClass.IsNullOrWhiteSpace(domain))
                    {
                        request.Credentials = new NetworkCredential(username, password);
                    }
                    else
                    {
                        request.Credentials = new NetworkCredential(username, password, domain);
                    }

                    CBB_LoggingCustomTraceLogExtensions.AssignSensitiveString(log, password, 2);
                    if (detailedLog)
                    {
                        CBB_LoggingCustomTraceLogExtensions.AddLine(log, "Requesting with credentials '" + CBB_CommonExtenderClass.AppendIfNotNullOrWhiteSpace(CBB_CommonExtenderClass.ToNonNullString(domain), "\\") + username + " " + CBB_CommonExtenderClass.ToNonNullString(password) + "'...");
                    }
                }

                //if (accessToken.IsNOTNullOrWhiteSpace())
                //{
                //	request.Headers.Add("access_token", accessToken);
                //}

                if (headers != null)
                {
                    foreach (string header in headers)
                    {
                        //http://stackoverflow.com/questions/239725/cannot-set-some-http-headers-when-using-system-net-webrequest
                        if (header.ToLower() == "connection:keep-alive")
                        {
                            if (request is HttpWebRequest)
                            {
                                (request as HttpWebRequest).KeepAlive = true;
                            }
                            else
                            {
                                throw new Exception("Can not set http headers when using WebRequest.");
                            }
                        }
                        else if (header.Split(':')[0].ToLower() == "referer")
                        {
                            if (request is HttpWebRequest)
                            {
                                (request as HttpWebRequest).Referer = header.Substring(header.IndexOf(':') + 1);
                            }
                            else
                            {
                                throw new Exception("Can not set http headers when using WebRequest.");
                            }
                        }
                        else if (header.Split(':')[0].ToLower() == "user-agent")
                        {
                            if (request is HttpWebRequest)
                            {
                                (request as HttpWebRequest).UserAgent = header.Substring(header.IndexOf(':') + 1);
                            }
                            else
                            {
                                throw new Exception("Can not set http headers when using WebRequest.");
                            }
                        }
                        else if (header.Split(':')[0].ToLower() == "accept")
                        {
                            if (request is HttpWebRequest)
                            {
                                (request as HttpWebRequest).Accept = header.Substring(header.IndexOf(':') + 1);
                            }
                            else
                            {
                                throw new Exception("Can not set http headers when using WebRequest.");
                            }
                        }
                        else
                        {
                            if (request.Headers.AllKeys.Contains(header.Split(':')[0]))
                            {
                                request.Headers.Set(header.Split(':')[0], header.Substring(header.IndexOf(':') + 1));
                            }
                            else
                            {
                                request.Headers.Add(header);
                            }
                        }
                    }
                    if (detailedLog)
                    {
                        CBB_LoggingCustomTraceLogExtensions.AddLine(log, "Requesting with headers '" + CBB_CommonExtenderClass.ToCSV(headers) + "'...");
                    }
                }

                if (isPostMethod)
                {
                    request.Method = "POST";
                }

                switch (requestUriContentType)
                {
                case (int)RequestUriContentType.Default:
                    break;

                case (int)RequestUriContentType.ApplicationJson:
                    //var hk = request.Headers.AllKeys.FirstOrDefault(k => k.ToLower() == "content-type");
                    //if(hk!=null)
                    //{
                    //	request.Headers.Remove(hk);
                    //}
                    //request.Headers.Add("Content-Type", "application/json");
                    request.ContentType = "application/json";

                    if (CBB_CommonExtenderClass.IsNOTNullOrWhiteSpace(postData))
                    {
                        if (detailedLog)
                        {
                            CBB_LoggingCustomTraceLogExtensions.AddLine(log, "Requesting with post data '" + postData + "'...");
                        }
                        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                        {
                            //initiate the request
                            //JavaScriptSerializer serializer = new JavaScriptSerializer();
                            //var d = serializer.Deserialize<Dictionary<string, object>>(postData);
                            streamWriter.Write(postData);
                            streamWriter.Flush();
                            streamWriter.Close();
                        }
                    }
                    break;

                case (int)RequestUriContentType.TextJson:
                    //var hk = request.Headers.AllKeys.FirstOrDefault(k => k.ToLower() == "content-type");
                    //if(hk!=null)
                    //{
                    //	request.Headers.Remove(hk);
                    //}
                    //request.Headers.Add("Content-Type", "application/json");
                    request.ContentType = "text/json";

                    if (CBB_CommonExtenderClass.IsNOTNullOrWhiteSpace(postData))
                    {
                        if (detailedLog)
                        {
                            CBB_LoggingCustomTraceLogExtensions.AddLine(log, "Requesting with post data '" + postData + "'...");
                        }
                        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                        {
                            //initiate the request
                            //JavaScriptSerializer serializer = new JavaScriptSerializer();
                            //var d = serializer.Deserialize<Dictionary<string, object>>(postData);
                            streamWriter.Write(postData);
                            streamWriter.Flush();
                            streamWriter.Close();
                        }
                    }
                    break;

                case (int)RequestUriContentType.ImageJpeg:
                case (int)RequestUriContentType.ImagePng:
                case (int)RequestUriContentType.ImageGif:
                    switch (requestUriContentType)
                    {
                    case (int)RequestUriContentType.ImageJpeg: request.ContentType = "image/jpeg"; break;

                    case (int)RequestUriContentType.ImagePng: request.ContentType = "image/png"; break;

                    case (int)RequestUriContentType.ImageGif: request.ContentType = "image/gif"; break;
                    }

                    if (CBB_CommonExtenderClass.IsNOTNullOrWhiteSpace(postData))
                    {
                        if (detailedLog)
                        {
                            CBB_LoggingCustomTraceLogExtensions.AddLine(log, "Requesting with post data '" + postData + "'...");
                        }
                        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                        {
                            //initiate the request
                            //JavaScriptSerializer serializer = new JavaScriptSerializer();
                            //var d = serializer.Deserialize<Dictionary<string, object>>(postData);
                            streamWriter.Write(postData);
                            streamWriter.Flush();
                            streamWriter.Close();
                        }
                    }
                    break;

                case (int)RequestUriContentType.ApplicationXWwwFormUlrEncoded:
                    request.ContentType = "application/x-www-form-urlencoded";
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    byte[]        data    = encoder.GetBytes(postData);                   // a json object, or xml, whatever...
                    request.ContentLength = data.Length;
                    //request.Expect = "application/json";
                    request.GetRequestStream().Write(data, 0, data.Length);
                    break;
                }

                if (cookies != null)
                {
                    if (request is HttpWebRequest)
                    {
                        (request as HttpWebRequest).CookieContainer = new CookieContainer();
                        foreach (Cookie cookie in cookies)
                        {
                            (request as HttpWebRequest).CookieContainer.Add(cookie);
                        }
                    }
                    else
                    {
                        throw new Exception("Can not set http headers when using WebRequest.");
                    }
                }

                if (request is HttpWebRequest && allowAutoRedirect != null)
                {
                    (request as HttpWebRequest).AllowAutoRedirect = allowAutoRedirect.Value;
                }

                // execute the request
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                //if (
                //	requestUriContentType == (int) RequestUriContentType.ImageJpeg ||
                //	requestUriContentType == (int) RequestUriContentType.ImagePng ||
                //	requestUriContentType == (int) RequestUriContentType.ImageGif
                //	)
                //{
                //	// Check that the remote file was found. The ContentType
                //	// check is performed since a request for a non-existent
                //	// image file might be redirected to a 404-page, which would
                //	// yield the StatusCode "OK", even though the image was not
                //	// found.
                //	if ((response.StatusCode == HttpStatusCode.OK ||
                //		response.StatusCode == HttpStatusCode.Moved ||
                //		response.StatusCode == HttpStatusCode.Redirect) &&
                //		response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
                //	{

                //		// if the remote file was found, download it
                //		//code moved to dump response region below...

                //		return true;
                //	}
                //	else
                //		return false;
                //}

                if (fileNameWhereToDumpResponse != null)
                {
                    using (Stream inputStream = response.GetResponseStream())
                        using (Stream outputStream = File.OpenWrite(fileNameWhereToDumpResponse))
                        {
                            byte[] buffer = new byte[4096];
                            int    bytesRead;
                            do
                            {
                                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                                outputStream.Write(buffer, 0, bytesRead);
                            } while (bytesRead != 0);

                            inputStream.Seek(0, SeekOrigin.Begin);
                        }
                }

                if (encoderForParsingResult == null)
                {
                    r = DecodeWebResponse(response, log);
                }
                else
                {
                    // we will read data via the response stream
                    Stream resStream = response.GetResponseStream();

                    string tempString = null;
                    int    count      = 0;

                    encoderForParsingResult = encoderForParsingResult ?? Encoding.ASCII;

                    do
                    {
                        // fill the buffer with data
                        count = resStream.Read(buf, 0, buf.Length);

                        // make sure we read some data
                        if (count != 0)
                        {
                            // translate from bytes to ASCII text
                            tempString = encoderForParsingResult.GetString(buf, 0, count);

                            // continue building the string
                            sb.Append(tempString);
                        }
                    } while (count > 0);                     // any more data to read?

                    r = sb.ToString();
                }

                if (expectCookies && response.Cookies != null && response.Cookies.Count > 0)
                {
                    cookies.Clear();
                    for (int i = 0; i < response.Cookies.Count; i++)
                    {
                        cookies.Add(response.Cookies[i]);
                    }
                }

                if (detailedLog)
                {
                    CBB_LoggingCustomTraceLogExtensions.AddLine(log, "Requesting succeeded. Response length in chars:" + r.Length);
                }
            }
            catch (Exception exception)
            {
                if (detailedLog)
                {
                    CBB_LoggingCustomTraceLogExtensions.AddLine(log, "Requesting of '" + uri + "' failed. Error details:" + exception.Message);
                }
                if (!blockAllExceptions)
                {
                    throw;
                }
                else
                {
                    r = errorCaseResult;
                }
            }
            finally {
                CBB_LoggingCustomTraceLogExtensions.DecreaseIdent(log);
            }
            return(r);
        }
예제 #48
0
        private void _output()
        {
            ASCIIEncoding asciiEncoding = new ASCIIEncoding();

            if (!_ser_out.IsOpen)
            {
                try
                {
                    _ser_out.Open();
                    _ser_out.DtrEnable = _horn;
                    _ser_out.RtsEnable = _shotclock_horn;
                }
                catch
                {
                }
            }
            while (true)
            {
                StringBuilder stringBuilder = new StringBuilder();
                if (_sending_active)
                {
                    try
                    {
                        string str1 = GetFieldValue("GameTime").Trim();
                        string str2 = GetFieldValue("ShotTime").Trim();
                        if (!str1.Contains(".") && !str1.Contains(":"))
                        {
                            str1 = "0:" + str1.Trim().PadLeft(2, '0');
                        }
                        stringBuilder.Append('\x0002');
                        if (str2 == "0" && str1 != "10:00" && str2 != string.Empty || str1 == "0.0")
                        {
                            stringBuilder.Append('\x0012');
                            stringBuilder.Append('ò');
                            stringBuilder.Append('\x000F');
                        }
                        else if (str1 != "10:00")
                        {
                            stringBuilder.Append(' ');
                            stringBuilder.Append('\x000F');
                        }
                        else
                        {
                            stringBuilder.Append('\x000F');
                        }
                        if (str1.Contains("."))
                        {
                            if (str1.Length < 4)
                            {
                                stringBuilder.Append(' ');
                                stringBuilder.Append((char)((int)str1[1] & 15 | 192));
                                stringBuilder.Append((char)((int)str1[3] & 15 | 160));
                                stringBuilder.Append(' ');
                            }
                            else
                            {
                                stringBuilder.Append((char)((int)str1[0] & 15 | 160));
                                stringBuilder.Append((char)((int)str1[1] & 15 | 192));
                                stringBuilder.Append((char)((int)str1[3] & 15 | 160));
                                stringBuilder.Append(' ');
                            }
                        }
                        else if (str1.Length < 5)
                        {
                            stringBuilder.Append(' ');
                            try
                            {
                                stringBuilder.Append((char)((int)str1[1] & 15 | 192));
                                stringBuilder.Append((char)((int)str1[3] & 15 | 160));
                                stringBuilder.Append((char)((int)str1[4] & 15 | 176));
                            }
                            catch
                            {
                                stringBuilder.Append(32);
                            }
                        }
                        else
                        {
                            stringBuilder.Append((char)((int)str1[0] & 15 | 160));
                            stringBuilder.Append((char)((int)str1[1] & 15 | 192));
                            stringBuilder.Append((char)((int)str1[3] & 15 | 160));
                            stringBuilder.Append((char)((int)str1[4] & 15 | 176));
                        }
                        stringBuilder.Append('\x0012');
                        if (str2 != string.Empty)
                        {
                            stringBuilder.Append(64);
                        }
                        else
                        {
                            stringBuilder.Append(str2.PadLeft(2));
                        }
                        stringBuilder.Append('\x0003');
                        byte[] bytes = asciiEncoding.GetBytes(stringBuilder.ToString());
                        _ser_out.Write(bytes, 0, bytes.Length);
                    }
                    catch
                    {
                    }
                }
                Thread.Sleep(_refresh_interval);
            }
        }
예제 #49
0
파일: JetPay.cs 프로젝트: lulzzz/BrandStore
        public override String ProcessCard(int OrderNumber, int CustomerID, Decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, Address UseBillingAddress, String CardExtraCode, Address UseShippingAddress, String CAVV, String ECI, String XID, out String AVSResult, out String AuthorizationResult, out String AuthorizationCode, out String AuthorizationTransID, out String TransactionCommandOut, out String TransactionResponse)
        {
            String result = AppLogic.ro_OK;

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("<JetPay><TransactionType>" + CommonLogic.IIF(TransactionMode == TransactionModeEnum.auth, "AUTHONLY", "SALE") + "</TransactionType>\n");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("JETPAY_MERCHANTID") + "</MerchantID>\n");
            transactionCommand.Append("<TransactionID>" + OrderNumber.ToString().PadLeft(18, '0') + "</TransactionID>\n");
            transactionCommand.Append("<CardNum>" + UseBillingAddress.CardNumber + "</CardNum>");
            transactionCommand.Append("<CVV2>" + CardExtraCode + "</CVV2>");
            transactionCommand.Append("<CardExpMonth>" + UseBillingAddress.CardExpirationMonth.PadLeft(2, '0') + "</CardExpMonth>");
            transactionCommand.Append("<CardExpYear>" + UseBillingAddress.CardExpirationYear.ToString().Substring(2, 2) + "</CardExpYear>");
            transactionCommand.Append("<CardName>" + UseBillingAddress.FirstName + " " + UseBillingAddress.LastName + "</CardName>");
            transactionCommand.Append("<TotalAmount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal).Replace(",", "").Replace(".", "") + "</TotalAmount>");
            transactionCommand.Append("<BillingAddress>" + XmlCommon.XmlEncode(UseBillingAddress.Address1) + "</BillingAddress>");
            transactionCommand.Append("<BillingCity>" + XmlCommon.XmlEncode(UseBillingAddress.City) + "</BillingCity>");
            transactionCommand.Append("<BillingStateProv>" + XmlCommon.XmlEncode(UseBillingAddress.State) + "</BillingStateProv>");
            transactionCommand.Append("<BillingPostalCode>" + XmlCommon.XmlEncode(UseBillingAddress.Zip) + "</BillingPostalCode>");
            //transactionCommand.Append("<BillingCountry>" + UseBillingAddress.Country + "</BillingCountry>");
            transactionCommand.Append("<BillingPhone>" + XmlCommon.XmlEncode(UseBillingAddress.Phone) + "</BillingPhone>");
            transactionCommand.Append("<Email>" + XmlCommon.XmlEncode(UseBillingAddress.EMail) + "</Email>");
            transactionCommand.Append("</JetPay>");

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("JETPAY_LIVE_SERVER"), AppLogic.AppConfig("JETPAY_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.ContentType   = "text/xml";
            myRequest.ContentLength = data.Length;
            myRequest.Method        = "POST";
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response
            TransactionResponse = rawResponseString;

            String sql       = String.Empty;
            String replyCode = CommonLogic.ExtractToken(rawResponseString, "<ActionCode>", "</ActionCode>");
            //String responseCode = CommonLogic.ExtractToken(rawResponseString,"<RespCode>","</RespCode>");
            String approvalCode = CommonLogic.ExtractToken(rawResponseString, "<Approval>", "</Approval>");
            String authResponse = CommonLogic.ExtractToken(rawResponseString, "<ResponseText>", "</ResponseText>");
            String ErrMsg       = CommonLogic.ExtractToken(rawResponseString, "<ErrMsg>", "</ErrMsg>");
            String TransID      = CommonLogic.ExtractToken(rawResponseString, "<TransactionID>", "</TransactionID>");

            int idx = authResponse.IndexOf(">");

            if (idx != -1)
            {
                // pick only text out:
                authResponse = authResponse.Substring(idx + 1, authResponse.Length - idx - 1);
            }

            AuthorizationCode     = approvalCode;
            AuthorizationResult   = rawResponseString;
            AuthorizationTransID  = TransID;
            AVSResult             = String.Empty;
            TransactionCommandOut = transactionCommand.ToString();
            TransactionResponse   = String.Empty;

            if (Convert.ToInt32(replyCode) == 0)
            {
                result = AppLogic.ro_OK;
            }
            else
            {
                if (ErrMsg.Trim().Length > 0)
                {
                    result = "System Error: " + authResponse + ErrMsg;  //you'll only get one of these messages back
                }
                else
                {
                    result = "DECLINED: " + authResponse;
                }
            }
            return(result);
        }
예제 #50
0
        private void buttonUploadToPastebin_Click(object sender, EventArgs e)
        {
            try
            {
                WebRequest    wr       = WebRequest.Create(@"http://pastebin.com/api/api_post.php");
                ASCIIEncoding encoding = new ASCIIEncoding();

                string pasteName = "SAI-Editor: ";

                if (richTextBoxSqlOutput.Lines.Count > 0)
                {
                    pasteName += richTextBoxSqlOutput.Lines[0].ToString().Replace("-- ", String.Empty);
                }
                else
                {
                    pasteName += "ERROR";
                }

                byte[] bData = encoding.GetBytes(String.Concat("api_paste_code=", richTextBoxSqlOutput.Text, "&api_paste_private=0" +
                                                               "&api_paste_expire_date=N&api_dev_key=afac889230d290e94a94fb96d951773e&api_option=paste&api_paste_format=mysql" +
                                                               "&api_paste_name=" + pasteName));

                wr.Method        = "POST";
                wr.ContentType   = "application/x-www-form-urlencoded";
                wr.ContentLength = bData.Length;
                Stream sMyStream = wr.GetRequestStream();
                sMyStream.Write(bData, 0, bData.Length);
                sMyStream.Close();
                WebResponse  response           = wr.GetResponse();
                Stream       dataStream         = response.GetResponseStream();
                StreamReader reader             = new StreamReader(dataStream);
                string       responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();
                response.Close();

                if (!String.IsNullOrWhiteSpace(responseFromServer) && responseFromServer.Contains("pastebin.com"))
                {
                    DialogResult dialogResult = MessageBox.Show("Do you wish to open the pastebin now? If not, the URL will be copied to your clipboard.", "Open Pastebin?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (dialogResult == DialogResult.Yes)
                    {
                        SAI_Editor_Manager.Instance.StartProcess(responseFromServer);
                    }
                    else
                    {
                        Clipboard.SetText(responseFromServer);
                    }

                    //! Save pastebin to the settings.
                    //! Format: link-name;
                    Settings.Default.PastebinLinksStore += responseFromServer + "|" + pasteName + ";";
                    Settings.Default.Save();
                }
                else
                {
                    MessageBox.Show("Something went wrong with uploading to pastebin.com.", "Oops!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Oops!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #51
0
        /// <summary>
        /// Stolen from ScriptEngine Common
        /// </summary>
        /// <param name="Script"></param>
        /// <param name="uuid">Unique ID for this module</param>
        /// <returns></returns>
        internal string CompileFromDotNetText(string Script, string uuid)
        {
            m_log.Info("MRM 1");
            const string ext        = ".cs";
            const string FilePrefix = "MiniModule";

            // Output assembly name
            string OutFile = Path.Combine("MiniModules", Path.Combine(
                                              m_scene.RegionInfo.RegionID.ToString(),
                                              FilePrefix + "_compiled_" + uuid + "_" +
                                              Util.RandomClass.Next(9000) + ".dll"));

            // Create Directories for Assemblies
            if (!Directory.Exists("MiniModules"))
            {
                Directory.CreateDirectory("MiniModules");
            }
            string tmp = Path.Combine("MiniModules", m_scene.RegionInfo.RegionID.ToString());

            if (!Directory.Exists(tmp))
            {
                Directory.CreateDirectory(tmp);
            }

            m_log.Info("MRM 2");

            try
            {
                File.Delete(OutFile);
            }
            catch (UnauthorizedAccessException e)
            {
                throw new Exception("Unable to delete old existing " +
                                    "script-file before writing new. Compile aborted: " +
                                    e);
            }
            catch (IOException e)
            {
                throw new Exception("Unable to delete old existing " +
                                    "script-file before writing new. Compile aborted: " +
                                    e);
            }

            m_log.Info("MRM 3");

            // DEBUG - write source to disk
            string srcFileName = FilePrefix + "_source_" +
                                 Path.GetFileNameWithoutExtension(OutFile) + ext;

            try
            {
                File.WriteAllText(Path.Combine(Path.Combine(
                                                   "MiniModules",
                                                   m_scene.RegionInfo.RegionID.ToString()),
                                               srcFileName), Script);
            }
            catch (Exception ex) //NOTLEGIT - Should be just FileIOException
            {
                m_log.Error("[Compiler]: Exception while " +
                            "trying to write script source to file \"" +
                            srcFileName + "\": " + ex);
            }

            m_log.Info("MRM 4");

            // Do actual compile
            CompilerParameters parameters = new CompilerParameters();

            parameters.IncludeDebugInformation = true;

            string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);

            List <string> libraries = new List <string>();

            string[] lines = Script.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string s in lines)
            {
                if (s.StartsWith("//@DEPENDS:"))
                {
                    libraries.Add(s.Replace("//@DEPENDS:", ""));
                }
            }

            libraries.Add("OpenSim.Region.OptionalModules.dll");
            libraries.Add("OpenMetaverseTypes.dll");
            libraries.Add("log4net.dll");

            foreach (string library in libraries)
            {
                parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, library));
            }

            parameters.GenerateExecutable      = false;
            parameters.OutputAssembly          = OutFile;
            parameters.IncludeDebugInformation = true;
            parameters.TreatWarningsAsErrors   = false;

            m_log.Info("MRM 5");

            CompilerResults results = CScodeProvider.CompileAssemblyFromSource(
                parameters, Script);

            m_log.Info("MRM 6");

            int display = 5;

            if (results.Errors.Count > 0)
            {
                string errtext = String.Empty;
                foreach (CompilerError CompErr in results.Errors)
                {
                    // Show 5 errors max
                    //
                    if (display <= 0)
                    {
                        break;
                    }
                    display--;

                    string severity = "Error";
                    if (CompErr.IsWarning)
                    {
                        severity = "Warning";
                    }

                    string text = CompErr.ErrorText;

                    // The Second Life viewer's script editor begins
                    // countingn lines and columns at 0, so we subtract 1.
                    errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n",
                                             CompErr.Line - 1, CompErr.Column - 1,
                                             CompErr.ErrorNumber, text, severity);
                }

                if (!File.Exists(OutFile))
                {
                    throw new Exception(errtext);
                }
            }

            m_log.Info("MRM 7");

            if (!File.Exists(OutFile))
            {
                string errtext = String.Empty;
                errtext += "No compile error. But not able to locate compiled file.";
                throw new Exception(errtext);
            }

            FileInfo fi = new FileInfo(OutFile);

            Byte[] data = new Byte[fi.Length];

            try
            {
                FileStream fs = File.Open(OutFile, FileMode.Open, FileAccess.Read);
                fs.Read(data, 0, data.Length);
                fs.Close();
            }
            catch (IOException)
            {
                string errtext = String.Empty;
                errtext += "No compile error. But not able to open file.";
                throw new Exception(errtext);
            }

            m_log.Info("MRM 8");

            // Convert to base64
            //
            string filetext = Convert.ToBase64String(data);

            ASCIIEncoding enc = new ASCIIEncoding();

            Byte[] buf = enc.GetBytes(filetext);

            m_log.Info("MRM 9");

            FileStream sfs = File.Create(OutFile + ".cil.b64");

            sfs.Write(buf, 0, buf.Length);
            sfs.Close();

            m_log.Info("MRM 10");

            return(OutFile);
        }
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            mHttpCameraUser.mWorkerLogMessage = "snapshot worker kicked off"; mHttpCameraUser.mWorkerLogMessageAvailable = true;

            VideoCaptureByMJPEGDefinition defObject = (VideoCaptureByMJPEGDefinition)mHttpCameraUser.Definition();

            int readSize   = 1024;
            int bufferSize = defObject.bufferSize;

            byte[]         buffer   = defObject.bufferForWorker;
            HttpWebRequest request  = null;
            WebResponse    response = null;
            Stream         stream   = null;
            Random         randomNumberGenerator = new Random((int)DateTime.Now.Ticks);

            byte[] jpegMarker       = new byte[] { 0xFF, 0xD8, 0xFF };
            int    jpegMarkerLength = 3;// jpegMarker.GetUpperBound(0) + 1;

            byte[] boundary = null;
            int    boundaryLength;

            HttpRequestCachePolicy bypassCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.BypassCache);

            try
            {
                string uri = mHttpCameraUser.Camera.CompleteVideoRequestURL(null, -1, -1, -1);
                if (mHttpCameraUser.Camera.ProxyCacheProtection)
                {
                    uri += ((uri.IndexOf('?') == -1) ? '?' : '&') + "proxyprevention=" + randomNumberGenerator.Next().ToString();
                }
                request             = (HttpWebRequest)WebRequest.Create(uri);
                request.CachePolicy = bypassCachePolicy;
                request.Timeout     = mHttpCameraUser.ConnectionTimeout;

                if (mHttpCameraUser.Camera.Login != null && mHttpCameraUser.Camera.Login.Length > 0)
                {
                    if (mHttpCameraUser.Camera.Password == null)
                    {
                        mHttpCameraUser.Camera.Password = String.Empty;
                    }
                    request.Credentials = new NetworkCredential(mHttpCameraUser.Camera.Login, mHttpCameraUser.Camera.Password);
                }

                // setting ConnectionGroupName to make sure we don't run out of connections amongst all the cameras (see http://msdn2.microsoft.com/en-us/library/ms998562.aspx section: "Connections")
                request.ConnectionGroupName = mHttpCameraUser.TestSequence().Name + " : " + mHttpCameraUser.Name; // a unique group for each HTTP user within each TestSequence. We don't want to create unique groups every request because that would be inefficient
                // TODO: check maxconnection attribute in Machine.config (limits the number of concurrent outbound calls)

                ///////////
                response = request.GetResponse();

                string contentType = response.ContentType;
                if (contentType.IndexOf("multipart/x-mixed-replace") == -1)
                {
                    mHttpCameraUser.mWorkerLogMessage = "Invalid content type from camera; type='" + contentType + "'"; mHttpCameraUser.mWorkerLogMessageAvailable = true;
                    e.Result = ResultCodes.InvalidContentType;
                    return;
                }

                ASCIIEncoding encoding = new ASCIIEncoding();
                boundary       = encoding.GetBytes(contentType.Substring(contentType.IndexOf("boundary=", 0) + 9));
                boundaryLength = boundary.Length;

                stream = response.GetResponseStream();

                int              startIndex     = -1;
                int              endIndex       = -1;
                int              searchPosition = 0;
                int              newBytesRead   = 0;
                int              bytesInBuffer  = 0;
                int              totalBytesRead = 0;
                bool             needMoreData   = true;
                StreamSearchMode searchMode     = StreamSearchMode.SearchingForImageStart;
                while (true) // loop "indefinitely" grabbing frames until whomever started this worker(thread) cancels it
                {
                    bool done = false;
                    while (!done)
                    {
                        if (CancellationPending)
                        {
                            e.Cancel = true;
                            return;
                        }

                        if (needMoreData)
                        {
                            if (bytesInBuffer > bufferSize - readSize)
                            {
                                e.Result = ResultCodes.BufferTooSmall;
                                return;
                            }

                            newBytesRead = stream.Read(buffer, bytesInBuffer, readSize);
                            if (newBytesRead == 0)
                            {
                                e.Result = ResultCodes.VideoStreamConnectionLost;
                                return;
                            }
                            else
                            {
                                totalBytesRead += newBytesRead;
                                bytesInBuffer  += newBytesRead;
                            }
                        }

                        switch (searchMode)
                        {
                        case StreamSearchMode.SearchingForImageStart:
                            startIndex = FindBytePattern(buffer, jpegMarker, searchPosition, bytesInBuffer - searchPosition);
                            if (startIndex != -1)
                            {
                                // found start of JPEG image within stream
                                searchPosition = startIndex;
                                searchMode     = StreamSearchMode.SearchingForImageBoundary;
                                needMoreData   = false;   // we don't need data until we can't find the image's end. We don't want more data until we verify we don't have the entire image in the buffer already (since if we overfill the buffer we will error out)
                            }
                            else
                            {
                                // image start not found
                                searchPosition = bytesInBuffer - (jpegMarkerLength - 1);   // after we add more bytes to buffer, start searching in the current tail end. (ie if marker is 3 bytes, search searching in the last 2...we can't tell if the tail is a marker until we have more data)
                                needMoreData   = true;
                            }
                            break;

                        case StreamSearchMode.SearchingForImageBoundary:
                            endIndex = FindBytePattern(buffer, boundary, searchPosition, bytesInBuffer - searchPosition);
                            if (endIndex != -1)
                            {
                                // found image boundary within stream, so we know we found the end
                                mImage = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, startIndex, endIndex - startIndex));
                                mHttpCameraUser.ProcessNewImage(mImage);

                                searchPosition = endIndex + boundaryLength;                   // now we only care about the data in the buffer after the boundary (e.g. the start of the next image)
                                bytesInBuffer  = bytesInBuffer - searchPosition;              // adjust the number of bytes in the buffer
                                Array.Copy(buffer, searchPosition, buffer, 0, bytesInBuffer); // shift the buffer to remove the 'used' data and make room for data for the next image
                                searchPosition = 0;                                           // after the shift, our seachPosition is now at 0
                                searchMode     = StreamSearchMode.SearchingForImageStart;
                                needMoreData   = false;                                       // we don't need data until we can't find the next image's start or end. We don't want more data until we verify we don't have another entire image in the buffer
                            }
                            else
                            {
                                // didn't find the image boundary, so grab some more data and search on
                                searchPosition = bytesInBuffer - (boundaryLength - 1);
                                needMoreData   = true;
                            }
                            break;

                        default:
                            e.Result = ResultCodes.UnexpectedError;
                            return;
                        }
                    }
                }
                // we never get here since the while loop never terminates...we exit the loop on worker cancellation (above) or an exception (below)
            }
            catch (WebException exception)
            {
                switch (exception.Status)
                {
                // http://msdn2.microsoft.com/en-us/library/system.net.webexceptionstatus(vs.80).aspx
                case WebExceptionStatus.Timeout:
                    e.Result = ResultCodes.Timeout;
                    break;

                default:
                    e.Result = ResultCodes.Unspecified;
                    break;
                }
            }
            catch (Exception exception)
            {
                e.Result = ResultCodes.NonWebException;
            }
            finally
            {
                if (request != null)
                {
                    request.Abort();
                    request = null;
                }
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                }
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
예제 #53
0
        private void RegistarArticulo_Click(object sender, RoutedEventArgs e)
        {
            if (aRCHIVO_Seleccionado)
            {
                if (Tipo.SelectedIndex == 0)
                {
                    string     postdata = "NOM=" + NombreArticulo.Text + "&TIP=" + Tipo.SelectedIndex + "&CAT=" + Categoria.SelectedIndex + "&DES=" + Descripcion.Text + "&PREC=" + Precio.Text + "&NCO=" + Clase_php.No_Control_Usuario;
                    byte[]     data     = encoding.GetBytes(postdata);
                    WebRequest request  = WebRequest.Create("http://sicconviene.com/img.php");
                    request.Method        = "POST";
                    request.ContentType   = "application/x-www-form-urlencoded";
                    request.ContentLength = data.Length;

                    Stream stream = request.GetRequestStream();
                    stream.Write(data, 0, data.Length);
                    stream.Close();

                    WebResponse response = request.GetResponse();
                    stream = response.GetResponseStream();
                    StreamReader leer        = new StreamReader(stream);
                    string       lectura_php = leer.ReadToEnd();
                    MessageBox.Show(lectura_php);
                    if (lectura_php.Contains("Registrado_bien"))
                    {
                        Registrado = true;
                    }
                    leer.Close();
                    stream.Close();
                    if (Registrado)
                    {
                        Hecho.IsOpen = true;
                    }
                    else
                    {
                        MessageBox.Show("No se registró");
                    }
                }
                else if (Tipo.SelectedIndex == 1)
                {
                    string     postdata = "NOM=" + NombreArticulo.Text + "&MAT=" + Categoria.SelectedIndex + "&COS=" + Precio.Text + "&HOR=" + HoraInicio.Text + "-" + HoraFin.Text + "&DES=" + Descripcion.Text + "&NCO=" + Clase_php.No_Control_Usuario;
                    byte[]     data     = encoding.GetBytes(postdata);
                    WebRequest request  = WebRequest.Create("http://sicconviene.com/img_2.php");
                    request.Method        = "POST";
                    request.ContentType   = "application/x-www-form-urlencoded";
                    request.ContentLength = data.Length;

                    Stream stream = request.GetRequestStream();
                    stream.Write(data, 0, data.Length);
                    stream.Close();

                    WebResponse response = request.GetResponse();
                    stream = response.GetResponseStream();
                    StreamReader leer        = new StreamReader(stream);
                    string       lectura_php = leer.ReadToEnd();
                    //MessageBox.Show(lectura_php);
                    if (lectura_php.Contains("Registrado_bien"))
                    {
                        Registrado = true;
                    }
                    leer.Close();
                    stream.Close();
                    if (Registrado)
                    {
                        Hecho.IsOpen = true;
                    }
                    else
                    {
                        MessageBox.Show("No se registró");
                    }
                }
            }
        }
예제 #54
0
    protected void Page_Load(object sender, EventArgs e)
    {
        bool   usePost     = false;
        string returnValue = "";
        string URL         = Request["url"];
        string userName    = "";
        string password    = "";

        ASCIIEncoding encoding = new ASCIIEncoding();
        //string queryString="address=8+nixon&suburb=otahuhu&town=auckland&sort=name&start=1&maxResults=10";
        string queryString = Request["qs"];

        if (Request["q"] + "" != "")
        {
            queryString = "q=" + Request["q"] + "&" + queryString;
        }
        //queryString+="&rn="+VB.rnd(); //cache buster

        string fullUrl = URL + ((!usePost && queryString + "" != "")?"?" + queryString:"");


        HttpWebRequest httpRequest = null;

        try
        {
            httpRequest = WebRequest.Create(fullUrl) as HttpWebRequest;
        }catch (Exception) {}

        if (httpRequest != null)
        {
            if (userName != "")
            {
                httpRequest.Credentials = new NetworkCredential(userName, password);
            }
            if (usePost)
            {
                httpRequest.Method      = "POST";
                httpRequest.ContentType = "application/x-www-form-urlencoded";
                byte[] data = encoding.GetBytes(queryString);
                httpRequest.ContentLength = data.Length;
                Stream newStream = httpRequest.GetRequestStream();
                // Send the data.
                newStream.Write(data, 0, data.Length);
                newStream.Close();
            }
            else
            {
                httpRequest.Method = "GET";
            }

            try
            {
                HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse;
                if (httpResponse != null)
                {
                    StreamReader sr = new StreamReader(httpResponse.GetResponseStream());
                    returnValue = sr.ReadToEnd();
                    sr.Close();
                    httpResponse.Close();
                }
            }
            catch (Exception ex)
            {
                // try and replace the URL if we find it - if not, just return the user's Error String
                returnValue = "error " + ex.Message;
            }
        }


        Response.ContentType = "image/jpeg";

        Response.Write(returnValue);
    }
예제 #55
0
        public static object GetJsConfig(string url)
        {
            //HttpContext context = HttpContext.Current;

            //Logger logger = new Logger(AppSettings.LogPath);
            //logger.Info("Url = " + context.Request.Url);
            //logger.Info("UrlReferrer = " + context.Request.UrlReferrer);

            //logger.Info("ticket = " + JsApiTicket.Value);

            string noncestr  = "wechat4net";
            long   timestamp = DateTimeConverter.GetWeixinDateTime(DateTime.Now);

            //string url = "";
            //if (context.Request.UrlReferrer != null)
            //{
            //    url = context.Request.UrlReferrer.ToString().Split('#')[0];
            //}
            if (string.IsNullOrEmpty(url))
            {
                return(null);
            }
            else
            {
                url = url.Split('#')[0];
            }

            string unencrypted = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", JsApiTicket.Value, noncestr, timestamp, url);

            SHA1          sha;
            ASCIIEncoding enc;
            string        hash = "";

            try
            {
                sha = new SHA1CryptoServiceProvider();
                enc = new ASCIIEncoding();
                byte[] dataToHash = enc.GetBytes(unencrypted);
                byte[] dataHashed = sha.ComputeHash(dataToHash);
                hash = BitConverter.ToString(dataHashed).Replace("-", "");
                hash = hash.ToLower();
            }
            catch (Exception)
            {
                return(null);
            }

            //{
            //debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            //appId: '', // 必填,企业号的唯一标识,此处填写企业号corpid
            //timestamp: , // 必填,生成签名的时间戳
            //nonceStr: '', // 必填,生成签名的随机串
            //signature: '',// 必填,签名,见附录1
            //jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
            //}

            var config = new
            {
                debug     = false,
                appId     = WechatConfig.CorpID,
                timestamp = timestamp,
                nonceStr  = noncestr,
                signature = hash,
                jsApiList = new List <string>()
                {
                    "checkJsApi",
                    "onMenuShareTimeline",
                    "onMenuShareAppMessage",
                    "onMenuShareQQ",
                    "onMenuShareWeibo",
                    "onMenuShareQZone",
                    "hideMenuItems",
                    "showMenuItems",
                    "hideAllNonBaseMenuItem",
                    "showAllNonBaseMenuItem",
                    "translateVoice",
                    "startRecord",
                    "stopRecord",
                    "onVoiceRecordEnd",
                    "playVoice",
                    "onVoicePlayEnd",
                    "pauseVoice",
                    "stopVoice",
                    "uploadVoice",
                    "downloadVoice",
                    "chooseImage",
                    "previewImage",
                    "uploadImage",
                    "downloadImage",
                    "getNetworkType",
                    "openLocation",
                    "getLocation",
                    "hideOptionMenu",
                    "showOptionMenu",
                    "closeWindow",
                    "scanQRCode",
                    "chooseWXPay",
                    "openProductSpecificView",
                    "addCard",
                    "chooseCard",
                    "openCard",
                    "openEnterpriseChat"
                }
            };

            return(config);
        }
예제 #56
0
파일: JetPay.cs 프로젝트: lulzzz/BrandStore
        public override String VoidOrder(int OrderNumber)
        {
            String result = AppLogic.ro_OK;

            DB.ExecuteSQL("update orders set VoidTXCommand=NULL, VoidTXResult=NULL where OrderNumber=" + OrderNumber.ToString());
            bool    useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            String  TransID             = String.Empty;
            String  CardNum             = String.Empty;
            String  ApprvCode           = String.Empty;
            decimal TotalAmount         = 0;

            using (SqlConnection conn = DB.dbConn())
            {
                conn.Open();
                using (IDataReader rs = DB.GetRS("select * from orders   with (NOLOCK)  where OrderNumber=" + OrderNumber.ToString(), conn))
                {
                    if (rs.Read())
                    {
                        TransID     = DB.RSField(rs, "AuthorizationPNREF");
                        ApprvCode   = DB.RSField(rs, "AuthorizationCode");
                        TotalAmount = DB.RSFieldDecimal(rs, "OrderTotal");
                        CardNum     = Security.UnmungeString(DB.RSField(rs, "CardNumber"), rs[AppLogic.AppConfig("OrdersCCSaltField")].ToString());
                        if (CardNum.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                        {
                            CardNum = DB.RSField(rs, "CardNumber");
                        }
                    }
                }
            }

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("<JetPay><TransactionType>VOID</TransactionType>\n");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("JETPAY_MERCHANTID") + "</MerchantID>\n");
            transactionCommand.Append("<TransactionID>" + TransID + "</TransactionID>\n");
            transactionCommand.Append("<CardNum>" + CardNum + "</CardNum>");
            transactionCommand.Append("<Approval>" + ApprvCode + "</Approval>");
            transactionCommand.Append("<TotalAmount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(TotalAmount).Replace(".", "").Replace(",", "") + "</TotalAmount>");
            transactionCommand.Append("</JetPay>");

            DB.ExecuteSQL("update orders set VoidTXCommand=" + DB.SQuote(transactionCommand.ToString()) + " where OrderNumber=" + OrderNumber.ToString());

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("JETPAY_LIVE_SERVER"), AppLogic.AppConfig("JETPAY_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.ContentType   = "text/xml";
            myRequest.ContentLength = data.Length;
            myRequest.Method        = "POST";
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response

            String sql          = String.Empty;
            String replyCode    = CommonLogic.ExtractToken(rawResponseString, "<ActionCode>", "</ActionCode>");
            String approvalCode = CommonLogic.ExtractToken(rawResponseString, "<Approval>", "</Approval>");
            String authResponse = CommonLogic.ExtractToken(rawResponseString, "<ResponseText>", "</ResponseText>");

            TransID = CommonLogic.ExtractToken(rawResponseString, "<TransactionID>", "</TransactionID>");


            DB.ExecuteSQL("update orders set VoidTXResult=" + DB.SQuote(rawResponseString) + " where OrderNumber=" + OrderNumber.ToString());

            if (Convert.ToInt32(replyCode) == 0)
            {
                result = AppLogic.ro_OK;
            }
            else
            {
                result = authResponse;
            }
            return(result);
        }
예제 #57
0
        // private static System.Timers.Timer aTimer;


        // private static void SetTimer()
        // {
        //   // Create a timer with a two second interval.
        //    aTimer = new System.Timers.Timer(10000);
        //    // Hook up the Elapsed event for the timer.
        //    aTimer.Elapsed += OnTimedEvent;
        //    aTimer.AutoReset = true;
        //    aTimer.Enabled = true;
        // }

        // private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        // {
        //     Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
        //                      e.SignalTime);
        //}

        public static void Main()
        {
            IPAddress myIP = TCPUtils.GetIPV4FromHostName(hostName);

            // // Start our timer which will interrupt us every ten seconds.
            // SetTimer();


            try
            {
                // Outer loop: we enter this loop without an instantiated TCPClient object. If we get back to the
                // top of the loop again it's because the client has been closed and we need to start it up again
                while (true)
                {
                    TcpClient tcpclnt = new TcpClient();
                    // Inner try clause. We want to intercept socket connection failures, try again after
                    // socktimeout seconds
                    while (!tcpclnt.Connected)
                    {
                        try
                        {
                            Console.WriteLine("Connecting to {0:S} on port {1:D}...", hostName, hostPort);
                            //Console.WriteLine("Connecting...");
                            tcpclnt.Connect(myIP, hostPort);
                        }
                        // Inner catch clause. We want to intercept socket connection failures here.
                        // But we are only catching socket exceptions; anything else will blow up the program
                        catch (SocketException e)
                        {
                            Console.WriteLine("Inner SocketException 1: " + e.ToString());
                            // Console.WriteLine("Exception: " + e.GetType().ToString());
                            // Console.WriteLine("Error..... " + e.StackTrace);
                        }
                        if (!tcpclnt.Connected)
                        {
                            // Wait "socktimeout" seconds and then we'll try again
                            DateTime timer = DateTime.Now;

                            while (TCPUtils.ElapsedSecondsSince(timer) < sockTimeout)
                            {
                                // elapsed = TCPUtils.ElapsedSecondsSince(timer);
                                // Console.WriteLine("Connect retry loop: elapsed seconds: " + elapsed.ToString());
                                Thread.Sleep(1000);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Connected");
                        }
                    } // while (!tcpclnt.connected)

                    // Loop until a null string is entered
                    while (true)
                    {
                        Console.Write("Enter the string to be transmitted : ");

                        String str = Console.ReadLine();
                        if (str.Length == 0)
                        {
                            break;
                        }
                        // add back the terminating newline that we'll use as end-of-record separator
                        str = str + "\n";

                        // Try clause for writing to and reading from the socket.
                        // Catch exceptions like other end closed
                        try
                        {
                            Stream stm = tcpclnt.GetStream();

                            ASCIIEncoding asen = new ASCIIEncoding();

                            // HACK: Add a prefix with no trailing record separator
                            string prefix = ":prefix:";
                            byte[] ba     = asen.GetBytes(prefix);
                            Console.WriteLine("Transmitting.....");

                            stm.Write(ba, 0, ba.Length);

                            // Now send the terminated string
                            //byte[] ba = asen.GetBytes(str);
                            ba = asen.GetBytes(str);
                            Console.WriteLine("Transmitting.....");

                            stm.Write(ba, 0, ba.Length);

                            // byte[] bb = new byte[100];
                            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]));
                            }
                            Console.WriteLine("");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Inner Exception 2: " + e.ToString());
                            Console.WriteLine("Exception Type: " + e.GetType().ToString());
                            tcpclnt.Close();
                            break;
                        }
                    }
                    Console.WriteLine("Broke out of loop. Closing TCP client.");
                    tcpclnt.Close();
                } // while (true()
            }

            // We can have multiple catch clauses tailored to specific error conditions. These are all
            // redundant because they don't do anything specific to the type of exception being caught.
            catch (SocketException e)
            {
                Console.WriteLine("Outer Socket Exception: " + e.ToString());
                Console.WriteLine("Exception: " + e.GetType().ToString());
            }
            catch (IOException e)
            {
                Console.WriteLine("Outer IO Exception: " + e.ToString());
                Console.WriteLine("Exception: " + e.GetType().ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Outer General Exception: " + e.ToString());
                Console.WriteLine("Exception: " + e.GetType().ToString());
            }

            // // Clean up our timer
            // aTimer.Stop();
            // aTimer.Dispose();
        } // end public static void Main()
예제 #58
0
        // Worker thread
        private void WorkerThread()
        {
            // buffer to read stream
            var buffer = new byte[BufSize];
            // JPEG magic number
            var jpegMagic = new byte[] { 0xFF, 0xD8, 0xFF };


            var encoding = new ASCIIEncoding();
            var res      = ReasonToFinishPlaying.StoppedByUser;

            while (!_stopEvent.WaitOne(0, false))
            {
                // reset reload event
                _reloadEvent.Reset();
                // HTTP web request
                HttpWebRequest request = null;
                // web response
                WebResponse response = null;
                // stream for MJPEG downloading
                Stream stream = null;
                // boundary between images (string and binary versions)
                string boudaryStr = null;
                // length of boundary
                // flag signaling if boundary was checked or not
                bool boundaryIsChecked = false;
                // read amounts and positions
                int todo = 0, total = 0, pos = 0, align = 1;
                int start = 0;


                // align
                //  1 = searching for image start
                //  2 = searching for image end

                try
                {
                    // create request
                    // get response
                    response = ConnectionFactory.GetResponse(_source, Cookies, Headers, HttpUserAgent, Login, Password, "GET", "", UseHttp10, out request);
                    if (response == null)
                    {
                        throw new Exception("Stream could not connect");
                    }
                    // check content type
                    string   contentType      = response.ContentType;
                    string[] contentTypeArray = contentType.Split('/');

                    // "application/octet-stream"
                    int    boundaryLen;
                    byte[] boundary;
                    if ((contentTypeArray[0] == "application") && (contentTypeArray[1] == "octet-stream"))
                    {
                        boundaryLen = 0;
                        boundary    = new byte[0];
                    }
                    else if ((contentTypeArray[0] == "multipart") && (contentType.Contains("mixed")))
                    {
                        // get boundary
                        int boundaryIndex = contentType.IndexOf("boundary", 0, StringComparison.Ordinal);
                        if (boundaryIndex != -1)
                        {
                            boundaryIndex = contentType.IndexOf("=", boundaryIndex + 8, StringComparison.Ordinal);
                        }

                        if (boundaryIndex == -1)
                        {
                            // try same scenario as with octet-stream, i.e. without boundaries
                            boundaryLen = 0;
                            boundary    = new byte[0];
                        }
                        else
                        {
                            boudaryStr = contentType.Substring(boundaryIndex + 1);
                            // remove spaces and double quotes, which may be added by some IP cameras
                            boudaryStr = boudaryStr.Trim(' ', '"');

                            boundary          = encoding.GetBytes(boudaryStr);
                            boundaryLen       = boundary.Length;
                            boundaryIsChecked = false;
                        }
                    }
                    else
                    {
                        throw new Exception("Invalid content type.");
                    }

                    // get response stream
                    try
                    {
                        stream = response.GetResponseStream();
                    }
                    catch (NullReferenceException)
                    {
                        throw new Exception("Connection failed");
                    }
                    stream.ReadTimeout = _requestTimeout;

                    // loop
                    while ((!_stopEvent.WaitOne(0, false)) && (!_reloadEvent.WaitOne(0, false)))
                    {
                        // check total read
                        if (total > BufSize - ReadSize)
                        {
                            total = pos = todo = 0;
                        }

                        // read next portion from stream
                        int read;
                        if ((read = stream.Read(buffer, total, ReadSize)) == 0)
                        {
                            throw new ApplicationException();
                        }

                        total += read;
                        todo  += read;

                        // increment received bytes counter
                        _bytesReceived += read;

                        // do we need to check boundary ?
                        if ((boundaryLen != 0) && (!boundaryIsChecked))
                        {
                            // some IP cameras, like AirLink, claim that boundary is "myboundary",
                            // when it is really "--myboundary". this needs to be corrected.

                            pos = ByteArrayUtils.Find(buffer, boundary, 0, todo);
                            // continue reading if boudary was not found
                            if (pos == -1)
                            {
                                continue;
                            }

                            for (int i = pos - 1; i >= 0; i--)
                            {
                                byte ch = buffer[i];

                                if ((ch == (byte)'\n') || (ch == (byte)'\r'))
                                {
                                    break;
                                }

                                boudaryStr = (char)ch + boudaryStr;
                            }

                            boundary          = encoding.GetBytes(boudaryStr);
                            boundaryLen       = boundary.Length;
                            boundaryIsChecked = true;
                        }

                        // search for image start
                        if ((align == 1) && (todo >= jpegMagic.Length))
                        {
                            start = ByteArrayUtils.Find(buffer, jpegMagic, pos, todo);
                            if (start != -1)
                            {
                                // found JPEG start
                                pos   = start + jpegMagic.Length;
                                todo  = total - pos;
                                align = 2;
                            }
                            else
                            {
                                // delimiter not found
                                todo = jpegMagic.Length - 1;
                                pos  = total - todo;
                            }
                        }

                        bool decode = !string.IsNullOrEmpty(DecodeKey);

                        // search for image end ( boundaryLen can be 0, so need extra check )
                        while ((align == 2) && (todo != 0) && (todo >= boundaryLen))
                        {
                            int stop = ByteArrayUtils.Find(buffer,
                                                           (boundaryLen != 0) ? boundary : jpegMagic,
                                                           pos, todo);

                            if (stop != -1)
                            {
                                // increment frames counter
                                _framesReceived++;
                                var nf = NewFrame;
                                // image at stop
                                if (nf != null && (!_stopEvent.WaitOne(0, false)))
                                {
                                    if (decode)
                                    {
                                        byte[] marker = Encoding.ASCII.GetBytes(DecodeKey);

                                        using (var ms = new MemoryStream(buffer, start + jpegMagic.Length, jpegMagic.Length + marker.Length))
                                        {
                                            var key = new byte[marker.Length];
                                            ms.Read(key, 0, marker.Length);

                                            if (!ByteArrayUtils.UnsafeCompare(marker, key))
                                            {
                                                throw (new Exception("Image Decode Failed - Check the decode key matches the encode key on ispy server"));
                                            }
                                        }


                                        using (var ms = new MemoryStream(buffer, start + marker.Length, stop - start - marker.Length))
                                        {
                                            ms.Seek(0, SeekOrigin.Begin);
                                            ms.WriteByte(jpegMagic[0]);
                                            ms.WriteByte(jpegMagic[1]);
                                            ms.WriteByte(jpegMagic[2]);
                                            ms.Seek(0, SeekOrigin.Begin);

                                            using (var bmp = (Bitmap)Image.FromStream(ms))
                                            {
                                                var da = new NewFrameEventArgs(bmp);
                                                nf.Invoke(this, da);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        using (var ms = new MemoryStream(buffer, start, stop - start))
                                        {
                                            using (var bmp = (Bitmap)Image.FromStream(ms)) {
                                                var da = new NewFrameEventArgs(bmp);
                                                nf.Invoke(this, da);
                                            }
                                        }
                                    }
                                }

                                // shift array
                                pos  = stop + boundaryLen;
                                todo = total - pos;
                                System.Array.Copy(buffer, pos, buffer, 0, todo);

                                total = todo;
                                pos   = 0;
                                align = 1;
                            }
                            else
                            {
                                // boundary not found
                                if (boundaryLen != 0)
                                {
                                    todo = boundaryLen - 1;
                                    pos  = total - todo;
                                }
                                else
                                {
                                    todo = 0;
                                    pos  = total;
                                }
                            }
                        }
                    }
                }
                catch (ApplicationException)
                {
                    // do nothing for Application Exception, which we raised on our own
                    // wait for a while before the next try
                    Thread.Sleep(250);
                }
                catch (ThreadAbortException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    // provide information to clients
                    Logger.LogExceptionToFile(ex, "MJPEG");
                    res = ReasonToFinishPlaying.DeviceLost;
                    break;
                    // wait for a while before the next try
                    //Thread.Sleep(250);
                }
                finally
                {
                    // abort request
                    request?.Abort();
                    stream?.Flush();
                    stream?.Close();
                    response?.Close();
                }
            }

            PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(res));
        }
예제 #59
0
        static void Main(string[] args)
        {
            SqlCommand    command;
            SqlDataReader reader;

            //replace [servername] with the name of the database server
            // [dbname] is name of database you set up in WDTU
            // [user] this is the SQL user you are connecting with
            // [password] this is the password for the user account
            using (SqlConnection connection = new SqlConnection(@"Data Source=[servername];Initial Catalog=[dbname];Persist Security Info=True;User ID=[user];Password=[password];Network Library=dbmssocn"))
            {
                connection.Open();
                command = new SqlCommand(@"SELECT TOP 1 [ReceiverRecID]
                          ,[ChannelIndex]
                          ,[RecDateTime]
                          ,[TempOut]
                          ,[HumOut]
                          ,[WindSpeed]
                          ,[DominantDir]
                          ,[DewPoint]
                          ,[Barometer]
                          ,[RainfallHour]
                          ,[RainfallDay]
                          ,[WindGust]
                          ,[Rainfall24]
                      FROM [Weather].[dbo].[Wunderground]
                      ORDER BY RecDateTime DESC;",
                                         connection);
                reader = command.ExecuteReader();
                reader.Read();

                if (reader.HasRows)
                {
                    TcpClient client = new TcpClient();

                    client.Connect("cwop.aprs.net", 14580);

                    NetworkStream clientStream = client.GetStream();

                    ASCIIEncoding encoder = new ASCIIEncoding();
                    // Replace [stationid] with your CWOP station id - CWXXXX or DWXXXX
                    byte[] buffer = encoder.GetBytes("user [stationid] pass -1 vers ThreePines Weather 1.0\r\n");
                    clientStream.Write(buffer, 0, buffer.Length);
                    clientStream.Flush();
                    Thread.Sleep(3000);

                    // Replace [stationid] with your CWOP station id - CWXXXX or DWXXXX
                    string datapacket = "[stationid]>APRS,TCPXX*:";

                    datapacket += "@" + DateTime.Parse(reader[2].ToString()).ToUniversalTime().ToString("ddHHmm") + "z";                     //day/time

                    //replace with your lat/lon in the line below
                    datapacket += "4153.27N/07253.55W";                        //lat/lon
                    datapacket += "_" + ((byte)reader[6]).ToString("000");     //direction of wind
                    datapacket += "/" + ((decimal)reader[5]).ToString("000");  //average wind speed
                    datapacket += "g" + ((decimal)reader[11]).ToString("000"); //gust windspeed

                    if ((short)reader[3] >= 0 && (short)reader[3] < 1000)
                    {
                        datapacket += "t" + ((short)reader[3] * .1).ToString("000");                          //temperature
                    }
                    else if ((short)reader[3] >= 0 && (short)reader[3] >= 1000)
                    {
                        datapacket += "t" + ((short)reader[3]).ToString("00");
                    }
                    else
                    {
                        datapacket += "t" + ((short)reader[3]).ToString("00");
                    }

                    datapacket += "r" + ((decimal)reader[9]).ToString("000");                      //rainfall last hour
                    datapacket += "p" + ((decimal)reader[12]).ToString("000");                     //rainfall last 24 hours
                    datapacket += "P" + ((decimal)reader[10]).ToString("000");                     //rainfaill since midnight
                    if (reader[4].ToString() == "100")
                    {
                        datapacket += "h" + "00";                          //humidity
                    }
                    else
                    {
                        datapacket += "h" + reader[4].ToString();
                    }
                    datapacket += "b" + (((short)reader[8] / (double)1000) * 33.8637526 * 10).ToString("00000");                      //barometer
                    datapacket += "eEnvoy8x\r\n";

                    byte[] buffer2 = encoder.GetBytes(datapacket);
                    clientStream.Write(buffer2, 0, buffer2.Length);
                    clientStream.Flush();
                    Thread.Sleep(3000);

                    client.Close();
                }

                reader.Close();
            }
        }
예제 #60
0
        private void thrHandleClientComm(object client)
        {
            TcpClient     tcpClient = (TcpClient)client;
            string        clientIP  = tcpClient.Client.RemoteEndPoint.ToString();
            NetworkStream clientStream;

            byte[]        buf_read;
            byte[]        send_buf;
            int           bytes_read;
            string        recv_str     = "";
            List <string> command_list = new List <string>();

            try
            {
                clientStream = tcpClient.GetStream();
                logger.LogText(LogLevel.INFO, string.Format("Client thread start: {0}", clientIP));
                while (true)
                {
                    bytes_read = 0;
                    try
                    {
                        buf_read   = new byte[kBufSize];
                        bytes_read = clientStream.Read(buf_read, 0, kBufSize);
                    }
                    catch (Exception ex)
                    {
                        logger.FatalText(string.Format("Client stream IO error when reading, ip {0}, expexction: {1}", clientIP, ex));
                        break;
                    }

                    if (bytes_read == 0)
                    {
                        logger.InfoText(string.Format("EDCClient disconnected, ip: {0}", clientIP));
                        break;
                    }

                    //message has successfully been received
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    recv_str += encoder.GetString(buf_read, 0, bytes_read);
                    while (true)
                    {
                        // header include '|'
                        int header_len     = recv_str.IndexOf("|") + 1;
                        int content_length = 0;
                        if (header_len <= 1)
                        {
                            //Can't find '|', read more
                            break;
                        }

                        try
                        {
                            content_length = int.Parse(recv_str.Substring(0, header_len - 1));
                        }
                        catch
                        {
                            logger.InfoText(string.Format("Protocol error, skip current received payload, ip: {0}", clientIP));
                            recv_str = "";
                            break;
                        }

                        if (recv_str.Length - header_len < content_length)
                        {
                            logger.DebugText(string.Format("There are still unread payload, read again, ip: {0}", clientIP));
                            break;
                        }

                        // OK, now I have at least one command
                        string command = recv_str.Substring(header_len, content_length);
                        //By now, if two command arrived at the same time, only first will be handled
                        //But I don't know whether it is possible.
                        string[] cmd_tokens = command.Split('\n')[0].Split('\t');
                        string   cmd        = cmd_tokens[0];
                        string   send_str   = "";
                        switch (cmd)
                        {
                        case kSyncVerCmd:
                            logger.InfoText(string.Format("Client EDC{0}({1}) sync version: {2}", cmd_tokens[2], clientIP, cmd_tokens[1]));
                            updateEDCVersion(cmd_tokens);
                            logger.InfoText(string.Format("Sync version: {1}", clientIP, cmd_tokens[1]));
                            break;

                        case kSyncEmpCmd:
                            logger.InfoText(string.Format("Client EDC{0}({1}) require to sync Employee List", cmd_tokens[1], clientIP));
                            send_str = getEmployeeList(cmd_tokens);
                            send_buf = encoder.GetBytes(send_str);
                            clientStream.Write(send_buf, 0, send_buf.Length);
                            clientStream.Flush();
                            logger.DebugText(string.Format("Send Employee list to Client EDC{0}({1}) OK", cmd_tokens[1], clientIP));
                            break;

                        case kSyncEDCCmd:
                            logger.InfoText(string.Format("Client EDC{0}({1}) require to sync EDC List", cmd_tokens[1], clientIP));
                            send_str = getEDCList(cmd_tokens);
                            send_buf = encoder.GetBytes(send_str);
                            clientStream.Write(send_buf, 0, send_buf.Length);
                            clientStream.Flush();
                            logger.DebugText(string.Format("Send EDC list to Client EDC{0}({1}) OK", cmd_tokens[1], clientIP));
                            break;

                        case kSyncProjCmd:
                            logger.InfoText(string.Format("Client EDC{0}({1}) require to sync Project List", cmd_tokens[1], clientIP));
                            send_str = getProjectList(cmd_tokens);
                            send_buf = encoder.GetBytes(send_str);
                            clientStream.Write(send_buf, 0, send_buf.Length);
                            clientStream.Flush();
                            logger.DebugText(string.Format("Send Project list to Client EDC{0}({1}) OK", cmd_tokens[1], clientIP));
                            break;

                        case kSyncLogCmd:
                            logger.InfoText(string.Format("Client EDC{0}({1}) sync EDC Log", cmd_tokens[1], clientIP));
                            syncEDCLog(command, clientStream);
                            logger.DebugText(string.Format("Sync EDCLog from Client EDC{0}({1}) OK", cmd_tokens[1], clientIP));
                            break;

                        case kSyncEmpDeltaCmd:
                            logger.InfoText(string.Format("Client EDC{0}({1}) require to sync Employee Delta", cmd_tokens[1], clientIP));
                            send_str = getEmployeeDelta(cmd_tokens);
                            send_buf = encoder.GetBytes(send_str);
                            //TODO write error check
                            clientStream.Write(send_buf, 0, send_buf.Length);
                            clientStream.Flush();
                            logger.DebugText(string.Format("Send Employee delta to Client EDC{0}({1}) OK, data: {2}", cmd_tokens[1], clientIP, send_str));
                            break;

                        case kSyncEDCDeltaCmd:
                            logger.WarnText(string.Format("Client EDC{0}({1}) require to sync EDC Delta, but this isn't implement", cmd_tokens[1], clientIP));
                            break;

                        case kSyncProjDeltaCmd:
                            logger.InfoText(string.Format("Client EDC{0}({1}) require to sync Project Delta", cmd_tokens[1], clientIP));
                            send_str = getProjectDelta(cmd_tokens);
                            send_buf = encoder.GetBytes(send_str);
                            clientStream.Write(send_buf, 0, send_buf.Length);
                            clientStream.Flush();
                            logger.DebugText(string.Format("Send Project delta to Client EDC{0}({1}) OK", cmd_tokens[1], clientIP));
                            break;

                        case kSyncEmpDeltaOkCmd:
                            logger.InfoText(string.Format("Client EDC{0}({1}) response sync Employee Delta OK", cmd_tokens[1], clientIP));
                            handleEmployeeDeltaOk(cmd_tokens);
                            break;

                        case kSyncEDCDeltaOkCmd:
                            logger.InfoText(string.Format("Client EDC{0}({1}) response sync EDC Delta OK", cmd_tokens[1], clientIP));
                            handleEDCDeltaOk(cmd_tokens);
                            break;

                        case kSyncProjDeltaOkCmd:
                            logger.InfoText(string.Format("Client EDC{0}({1}) response sync Project Delta OK", cmd_tokens[1], clientIP));
                            handleProjectDeltaOk(cmd_tokens);
                            break;

                        default:
                            break;
                        }
                        int protocol_len = header_len + content_length;

                        if (recv_str.Length > protocol_len)
                        {
                            recv_str = recv_str.Substring(header_len + content_length);
                        }
                        else
                        {
                            recv_str = "";
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("Unexception error occur in client, ip: {0}, exception: {1}", clientIP, ex.Message));
            }
            finally
            {
                tcpClient.Close();
            }

            connectedClient.Remove(tcpClient);
            logger.Error(string.Format("Client thread terminated, ip: {0}", clientIP));
        }