Exemple #1
1
 //Connect to the client
 public void connect()
 {
     if (!clientConnected)
     {
         IPAddress ipAddress = IPAddress.Any;
         TcpListener listener = new TcpListener(ipAddress, portSend);
         listener.Start();
         Console.WriteLine("Server is running");
         Console.WriteLine("Listening on port " + portSend);
         Console.WriteLine("Waiting for connections...");
         while (!clientConnected)
         {
             s = listener.AcceptSocket();
             s.SendBufferSize = 256000;
             Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
             byte[] b = new byte[65535];
             int k = s.Receive(b);
             ASCIIEncoding enc = new ASCIIEncoding();
             Console.WriteLine("Received:" + enc.GetString(b, 0, k) + "..");
             //Ensure the client is who we want
             if (enc.GetString(b, 0, k) == "hello" || enc.GetString(b, 0, k) == "hellorcomplete")
             {
                 clientConnected = true;
                 Console.WriteLine(enc.GetString(b, 0, k));
             }
         }
     }
 }
        public static string MakeRequest(string url, object data) {

            var ser = new JavaScriptSerializer();
            var serialized = ser.Serialize(data);
            
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "POST";
            //request.ContentType = "application/json; charset=utf-8";
            //request.ContentType = "text/html; charset=utf-8";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = serialized.Length;


            /*
            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(serialized);
            writer.Close();
            var ms = new MemoryStream();
            request.GetResponse().GetResponseStream().CopyTo(ms);
            */


            //alternate method
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] byte1 = encoding.GetBytes(serialized);
            Stream newStream = request.GetRequestStream();
            newStream.Write(byte1, 0, byte1.Length);
            newStream.Close();



            
            return serialized;
        }
Exemple #3
0
 //ASCII 码转字符
 public static string Chr(int asciiCode)
 {
     System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                     byte[] byteArray = new byte[] { (byte)asciiCode };
                     string strCharacter = asciiEncoding.GetString(byteArray);
                     return (strCharacter);
 }
Exemple #4
0
 public static string Encode(string value)
 {
     var hash = System.Security.Cryptography.MD5.Create();
     var encoder = new System.Text.ASCIIEncoding();
     var combined = encoder.GetBytes(value ?? string.Empty);
     return BitConverter.ToString(hash.ComputeHash(combined)).ToLower().Replace("-", string.Empty);
 }
Exemple #5
0
 public void Send_Data_By_Server(string data_for_send_by_Server)
 {
     byte[] data = new byte[256];
     Encode_4            = new ASCIIEncoding();
     data                = Encode_4.GetBytes(data_for_send_by_Server);
     soc_1.Send(data);
 }
Exemple #6
0
        public static string CryptString(string val)
        {
            TripleDESCryptoServiceProvider dprov = new TripleDESCryptoServiceProvider();

            dprov.BlockSize = 64;
            dprov.KeySize = 192;
            byte[] IVBuf = BitConverter.GetBytes(DESIV);
            byte[] keyBuf = new byte[24];
            byte[] keyB0 = BitConverter.GetBytes(DESkey[0]);
            byte[] keyB1 = BitConverter.GetBytes(DESkey[1]);
            byte[] keyB2 = BitConverter.GetBytes(DESkey[2]);
            for (int i = 0; i < 8; i++) keyBuf[i] = keyB0[i];
            for (int i = 0; i < 8; i++) keyBuf[i + 8] = keyB1[i];
            for (int i = 0; i < 8; i++) keyBuf[i + 16] = keyB2[i];

            ICryptoTransform ict = dprov.CreateEncryptor(keyBuf, IVBuf);

            System.IO.MemoryStream mstream = new System.IO.MemoryStream();
            CryptoStream cstream = new CryptoStream(mstream, ict, CryptoStreamMode.Write);

            byte[] toEncrypt = new ASCIIEncoding().GetBytes(val);

            // Write the byte array to the crypto stream and flush it.
            cstream.Write(toEncrypt, 0, toEncrypt.Length);
            cstream.FlushFinalBlock();

            byte[] ret = mstream.ToArray();

            cstream.Close();
            mstream.Close();

            return Convert.ToBase64String(ret);
        }
Exemple #7
0
        public void HandleConnection(object state)
        {
            int recv = 1;
              byte[] data = new byte[1024];

              TcpClient client = threadListener.AcceptTcpClient();
              Stream ns = client.GetStream();
              try {
            connections++;
            Console.WriteLine("new Client: Currently {0} active connections", connections);
            ASCIIEncoding encoder = new ASCIIEncoding();
            string welcome = "Welcome";
            data = encoder.GetBytes(welcome);
            ns.Write(data, 0, welcome.Length);

            while (encoder.GetString(data, 0, recv) != "Close") {
              data = new byte[1024];
              recv = ns.Read(data, 0, data.Length);
              Console.WriteLine("Client: " + encoder.GetString(data, 0, recv));
            }
              }
              finally {
            ns.Close();
            client.Close();
            connections--;
            Console.WriteLine("Client disconnected: Currently {0} active connections", connections);
              }
        }
        private string GetResponseFromServer(string input)
        {
            var result = string.Empty;

            using (TcpClient client = new TcpClient())
            {
                client.Connect("127.0.0.1", 1234);
                var stream = client.GetStream();

                ASCIIEncoding ascii = new ASCIIEncoding();
                byte[] inputBytes = ascii.GetBytes(input.ToCharArray());

                stream.Write(inputBytes, 0, inputBytes.Length);

                byte[] readBytes = new byte[100];
                var k = stream.Read(readBytes, 0, 100);

                for (int i = 0; i < k; i++)
                {
                    result += Convert.ToChar(readBytes[i]);
                }

                client.Close();
            }

            return result;
        }
Exemple #9
0
        public void NachrichtAnAlle(ArrayList b, string Nachricht)
        {
            //dringend bearbeiten

            while (true)
            {
                try
                {
                    foreach (Server.extended y in b)
                    {
                        try
                        {
                            NetworkStream clientStream = y.tcp.GetStream();
                            ASCIIEncoding encoder = new ASCIIEncoding();
                            byte[] buffer = encoder.GetBytes(Nachricht);

                            clientStream.Write(buffer, 0, buffer.Length);
                            clientStream.Flush();

                        }
                        catch
                        {
                            b.Remove(y);
                        }

                    }
                    break;
                }
                catch
                {
                }
            }
        }
Exemple #10
0
        // chave privada para assinar e texto
        public static string assinaTexto(string caminhoChave, string texto)
        {
            try
            {
                AsymmetricCipherKeyPair parametrosChave = retornaParametrosChavePrivada(caminhoChave);

                RsaKeyParameters prikey = (RsaKeyParameters)parametrosChave.Private;

                var encoder = new ASCIIEncoding();
                var inputData = encoder.GetBytes(texto);

                var signer = SignerUtilities.GetSigner(MD5);
                signer.Init(true, prikey);
                signer.BlockUpdate(inputData, 0, inputData.Length);

                byte[] assinaturaByte = signer.GenerateSignature();
                string textoAssinado = Convert.ToBase64String(assinaturaByte);

                return textoAssinado;
            }
            catch (excecao.excecao ex)
            {
                throw new excecao.excecao(MSG_CHAVE_INVALIDA);
            }
        }
        public static string getMethod(string path, string proxy)
        {
            path = "http://api.cnc-alliances.com/" + path;
            string param = "{\"api_key\":\"dummy\"}";
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] baASCIIPostData = encoding.GetBytes(param);

            HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(path);
            if (proxy == "")
                HttpWReq.Proxy = new WebProxy();
            else
                HttpWReq.Proxy = new WebProxy(proxy);
            HttpWReq.Method = "POST";
            HttpWReq.Accept = "text/plain";
            HttpWReq.ContentType = "application/x-www-form-urlencoded";
            HttpWReq.ContentLength = baASCIIPostData.Length;
            // Prepare web request and send the data.

            Stream streamReq = HttpWReq.GetRequestStream();
            streamReq.Write(baASCIIPostData, 0, baASCIIPostData.Length);

            HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
            Stream streamResponse = HttpWResp.GetResponseStream();

            // And read it out
            StreamReader reader = new StreamReader(streamResponse);
            return reader.ReadToEnd();
        }
        public XDocument Authenticate(string username, string password)
        {
            ASCIIEncoding enc = new ASCIIEncoding ();

            if (_stream == null || !_stream.CanRead)
                this.GetStream ();

            this.Username = username;
            this.Password = password;

            XDocument authXML = new XDocument (
                                    new XElement ("authenticate",
                                        new XElement ("credentials",
                                            new XElement ("use" +
                                            "rname", username),
                                            new XElement ("password", password)
                                        )));

            this.Stream.Write (enc.GetBytes (authXML.ToString ()));

            string response = ReadMessage (this.Stream);

            XDocument doc = XDocument.Parse (response);

            if (doc.Root.Attribute ("status").Value != "200")
                throw new Exception ("Authentication failed");

            return doc;
        }
        public string GetLessonDownloadLink(Lesson lesson)
        {
            var postdata = string.Format(@"{{a:""{0}"", m:""{1}"", course:""{2}"", cn:{3}, mt:""mp4"", q:""1024x768"", cap:false, lc:""en""}}",
                lesson.Author, lesson.Module.Name, lesson.Module.Course.Name, lesson.Number);

            var tempUri = new Uri(_lessonDownloadUrl);

            var encoding = new ASCIIEncoding();
            var data = encoding.GetBytes(postdata);

            var request = HttpWebRequest.Create(tempUri) as HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            request.ContentLength = data.Length;

            request.CookieContainer = _cookieContainer;

            var newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            var responseHtml = request.GetResponse();

            var r = new StreamReader(responseHtml.GetResponseStream());
            return r.ReadToEnd();
        }
        static void Main(string[] args)
        {
            Console.WriteLine("MD5 und SHA Beispiel");
            Console.WriteLine("====================");

            //Eingabe lesen und in ein Byte-Array verwandeln
            var bytes = new ASCIIEncoding().GetBytes(Input());

            //MD5
            var md5 = new MD5Cng();
            string md5Hash = BitConverter.ToString(md5.ComputeHash(bytes)).Replace("-", "").ToLower();
            Console.WriteLine("MD5-Hash:\t{0}", md5Hash);

            //SHA1
            var sha1Cng = new SHA1Cng();
            string sha1Hash = BitConverter.ToString(sha1Cng.ComputeHash(bytes)).Replace("-","").ToLower();
            Console.WriteLine("SHA1-Hash:\t{0}", sha1Hash);

            //SHA256
            var sha256 = new SHA256Cng();
            string sha256Hash = BitConverter.ToString(sha256.ComputeHash(bytes)).Replace("-", "").ToLower();
            Console.WriteLine("SHA256-Hash:\t{0}", sha256Hash);

            Console.WriteLine("Beliebige Taste drücken zum beenden");
            Console.ReadKey();
        }
Exemple #15
0
        internal static void WriteToLog(SPWeb web, string message)
        {
            ASCIIEncoding enc = new ASCIIEncoding();
            UnicodeEncoding uniEncoding = new UnicodeEncoding();

            string errors = message;

            SPFile files = web.GetFile("/" + DocumentLibraryName + "/" + LogFileName);

            if (files.Exists)
            {
                byte[] fileContents = files.OpenBinary();
                string newContents = enc.GetString(fileContents) + Environment.NewLine + errors;
                files.SaveBinary(enc.GetBytes(newContents));
            }
            else
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (StreamWriter sw = new StreamWriter(ms, uniEncoding))
                    {
                        sw.Write(errors);
                    }

                    SPFolder LogLibraryFolder = web.Folders[DocumentLibraryName];
                    LogLibraryFolder.Files.Add(LogFileName, ms.ToArray(), false);
                }
            }

            web.Update();
        }
 private static string GetHash(string s)
 {
     MD5 sec = new MD5CryptoServiceProvider();
     ASCIIEncoding enc = new ASCIIEncoding();
     byte[] bt = enc.GetBytes(s);
     return GetHexString(sec.ComputeHash(bt));
 }
Exemple #17
0
        public static uint Hash(string data)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] bytes = encoding.GetBytes(data);

            return Hash(ref bytes);
        }
Exemple #18
0
        private void button1_Click(object sender, EventArgs e)
        {
            string strId = textUserId.Text;
            string strName = textTitle.Text;

            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "user_id=" + strId;
            postData += ("&title=" + strName);
            MyWebRequest My = new MyWebRequest("http://zozatree.herokuapp.com/api/titles", "POST", postData);
            string HtmlResult = My.GetResponse();
            //wc.Headers["Content-type"] = "application/x-www-form-urlencoded";

            //string HtmlResult = wc.UploadString(URL, myParamters);

            string bodySeparator = "{";
            string[] stringSeparators = new string[] { bodySeparator };
            string[] splitBodey = HtmlResult.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
            List<UserBO> u = new List<UserBO>();
            foreach (string item in splitBodey)
            {
                UserBO b = new UserBO(item.Replace("}",""));
                u.Add(b);
                if (b.UserId != -1)
                    labResponse.Text += b.toString();
            }
        }
        static void GenKey(string baseName, out byte[] desKey, out byte[] desIV)
        {
            byte[] secretBytes = { 6, 29, 66, 6, 2, 68, 4, 7, 70 };

            byte[] baseNameBytes = new ASCIIEncoding().GetBytes(baseName);

            byte[] hashBytes = new byte[secretBytes.Length + baseNameBytes.Length];

            // copy secret byte to start of hash array
            for (int i = 0; i < secretBytes.Length; i++)
            {
                hashBytes[i] = secretBytes[i];
            }

            // copy filename byte to end of hash array
            for (int i = 0; i < baseNameBytes.Length; i++)
            {
                hashBytes[i + secretBytes.Length] = baseNameBytes[i];
            }

            SHA1Managed sha = new SHA1Managed();

            // run the sha1 hash
            byte[] hashResult = sha.ComputeHash(hashBytes);

            desKey = new byte[8];
            desIV = new byte[8];

            for (int i = 0; i < 8; i++)
            {
                desKey[i] = hashResult[i];
                desIV[i] = hashResult[8 + i];
            }
        }
Exemple #20
0
 public static string Md5EncryptPassword(string data)
 {
     var encoding = new ASCIIEncoding();
     var bytes = encoding.GetBytes(data);
     var hashed = MD5.Create().ComputeHash(bytes);
     return Encoding.UTF8.GetString(hashed);
 }
Exemple #21
0
 /// <summary>
 /// Wrap a message as a CTCP command
 /// </summary>
 /// <param name="message">
 /// The message.
 /// </param>
 /// <param name="ctcpCommand">
 /// The CTCP command.
 /// </param>
 /// <returns>
 /// The <see cref="string"/>.
 /// </returns>
 public static string SetupForCtcp(this string message, string ctcpCommand)
 {
     var asc = new ASCIIEncoding();
     byte[] ctcp = { Convert.ToByte(1) };
     return asc.GetString(ctcp) + ctcpCommand.ToUpper()
            + (message == string.Empty ? string.Empty : " " + message) + asc.GetString(ctcp);
 }
        public String sendSMS(String to_phonenumber, String message)
        {
            //return "";
            String url = "https://rest.nexmo.com/sms/json";
            String postData = "";

            HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);

            ASCIIEncoding encoding = new ASCIIEncoding();

            postData += "api_key=" + Configs.SMS_API_KEY;
            postData += "&api_secret=" + Configs.SMS_API_SECRET;
            postData += "&from=" + "Logic+Uni";
            postData += "&to=" + to_phonenumber;
            postData += "&text=" + message;

            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();
            return responseString;
        }
Exemple #23
0
        public static bool ValidateCaptcha(string challenge = "", string apiresponse = "", string remoteip = "")
        {
            bool valid = false;
            string privatekey = "6Levd8cSAAAAAO_tjAPFuXbfzj6l5viTEaz5YjVv";

            string postdata = "privatekey=" + privatekey +
                                "&challenge=" + challenge +
                                "&response=" + apiresponse +
                                "&remoteip=" + remoteip;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/recaptcha/api/verify");
            request.Method = "POST";
            ASCIIEncoding encoding=new ASCIIEncoding();
            byte[] postbytes = encoding.GetBytes(postdata);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postdata.Length;
            Stream postStream = request.GetRequestStream();
            postStream.Write(postbytes, 0, postbytes.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            string responsestring = reader.ReadToEnd();
            postStream.Close();
            responseStream.Close();
            string[] responselines = responsestring.Split('\n');
            valid = Convert.ToBoolean(responselines[0]);

            return valid;
        }
Exemple #24
0
        public long GetContentLength()
        {
            var ascii = new ASCIIEncoding();
            long contentLength = ascii.GetBytes(_boundary).Length;

            // Multipart Form
            if (_multipartFormData != null)
            {
                foreach (var entry in _multipartFormData)
                {
                    contentLength += ascii.GetBytes(CreateFormBoundaryHeader(entry.Key, entry.Value)).Length; // header
                    contentLength += ascii.GetBytes(_boundary).Length;
                }
            }


            if (_multipartFileData != null)
            {
                foreach (var fileData in _multipartFileData)
                {
                    contentLength += ascii.GetBytes(CreateFileBoundaryHeader(fileData)).Length;
                    contentLength += new FileInfo(fileData.Filename).Length;
                    contentLength += ascii.GetBytes(_boundary).Length;
                }
            }

				contentLength += ascii.GetBytes("--").Length; // ending -- to the boundary

            return contentLength;
        }
Exemple #25
0
        public string Post(string url, Dictionary<string, string> postData)
        {
            StringBuilder requestUrl = new StringBuilder(url);

            StringBuilder postDataStringBuilder = new StringBuilder();
            foreach (string key in postData.Keys)
            {
                postDataStringBuilder.AppendFormat("{0}={1}&", key, postData[key]);
            }
            string postDataString = postDataStringBuilder.ToString();

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl.ToString());

            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] b = encoding.GetBytes(postDataString);
            request.UserAgent = "Mozilla/4.0";
            request.Method = "POST";
            request.CookieContainer = _cookieContainer;
            request.ContentLength = b.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(b, 0, b.Length);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string content = string.Empty;
            using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
            {
                content = streamReader.ReadToEnd();
                _cookieContainer.Add(response.Cookies);
            }
            return content;
        }
        public void SendMessage(string message)
        {
            try
            {
                var baseAddress = "http://79.124.67.13:8080/activities";

                var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
                http.Accept = "application/json";
                http.ContentType = "application/json";
                http.Method = "POST";

                string parsedContent = "{\"content\":\"" + message + "\"}";
                ASCIIEncoding encoding = new ASCIIEncoding();
                Byte[] bytes = encoding.GetBytes(parsedContent);

                Stream newStream = http.GetRequestStream();
                newStream.Write(bytes, 0, bytes.Length);
                newStream.Close();

                var response = http.GetResponse();
                var stream = response.GetResponseStream();
                var sr = new StreamReader(stream);
                var content = sr.ReadToEnd();
            }
            catch (Exception ex) {
                // File.WriteAllText(@"C:\Temp\ex.txt", ex.ToString());
            }
        }
        private async void pin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
        {
                if (args.Edge.CompareTo(GpioPinEdge.RisingEdge) == 0)
                {
                    //Motion Detected UI
                    UiAlert();

                    //Create JSON payload
                    var json = string.Format("{{sensor:Motion,  room:MsConfRoom1,  utc:{0}}}", DateTime.UtcNow.ToString("MM/dd/yyyy_HH:mm:ss"));
                    var data = new ASCIIEncoding().GetBytes(json);

                    //POST Data
                    string url = "https://rrpiot.azurewebsites.net/SensorData";
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.Method = "POST";
                    request.ContentType = "application/json";
                    using (Stream myStream = await request.GetRequestStreamAsync())
                    {
                        myStream.Write(data, 0, data.Length);
                    }
                    await request.GetResponseAsync();
                }
                else
                {
                    //Display No Motion Detected UI
                    UiNoMotion();
                }

        }
 public void sendMessageTo(string message)
 {
     System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
     string sendstring = message;
     byte[] sendData = encode.GetBytes(sendstring);
     server.Send(sendData, sendData.Length, clientAdress, clientPort);
 }
Exemple #29
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pData"></param>
        /// <returns></returns>
        public bool sendContribution(String pData)
        {
            bool lRetVal = false;
              HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://buglist.io/c/contribute.php");
              ASCIIEncoding encoding = new ASCIIEncoding();
              String lUserAgent = String.Format("Mozilla/4.0 (compatible; MSIE 10.0; Windows NT 6.4; .NET CLR 4.1234)");

              try
              {
            byte[] data = encoding.GetBytes(pData);
            String lEncodedData = String.Format("data={0}", System.Web.HttpUtility.UrlEncode(data));

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

            using (Stream stream = httpWReq.GetRequestStream())
            {
              stream.Write(encoding.GetBytes(lEncodedData), 0, lEncodedData.Length);
            }

            HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
            String responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            LogConsole.Main.LogConsole.pushMsg(String.Format("Contribution sent ({0}) : {1}", getMethod(), String.Format("{0} ...", lEncodedData.Substring(0, 30))));

            lRetVal = true;
              }
              catch (Exception lEx)
              {
            LogConsole.Main.LogConsole.pushMsg("Error sending contribution message : " + lEx.Message);
              }

              return (lRetVal);
        }
Exemple #30
0
        /// <summary>
        /// 截取字符长度
        /// </summary>
        /// <param name="inputString">字符</param>
        /// <param name="len">长度</param>
        /// <returns></returns>
        public static string CutString(string inputString, int len)
        {
            if (string.IsNullOrEmpty(inputString))
                return "";
            inputString = DropHTML(inputString);
            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;
        }
 static public int GetEncoder(IntPtr l)
 {
     try {
         System.Text.ASCIIEncoding self = (System.Text.ASCIIEncoding)checkSelf(l);
         var ret = self.GetEncoder();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 static public int ctor_s(IntPtr l)
 {
     try {
         System.Text.ASCIIEncoding o;
         o = new System.Text.ASCIIEncoding();
         pushValue(l, true);
         pushValue(l, o);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #33
0
    public void writeString(string value)
    {
        short length = (short)value.Length;

        writeInt(length);
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        byte[] bytes = encoding.GetBytes(value);
        for (short i = 0; i < length; i++)
        {
            mSendBuffer[mSendByteCounter + i] = bytes[i];
        }
        mSendByteCounter += length;
    }
Exemple #34
0
 //ASCII码转字符
 public static string Chr(int asciiCode)
 {
     if (asciiCode >= 0 && asciiCode <= 255)
     {
         System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
         byte[] byteArray    = new byte[] { (byte)asciiCode };
         string strCharacter = asciiEncoding.GetString(byteArray);
         return(strCharacter);
     }
     else
     {
         throw new Exception("ASCII Code is not valid. ");
     }
 }
    // Get the list of the addresses associated with the requested server.
    public static void IPAddresses(string server)
    {
        try
        {
            System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();

            // Get server related information.
            IPHostEntry heserver = Dns.GetHostEntry(server);

            Console.WriteLine("{0} address.", heserver.AddressList.Length);

            // Loop on the AddressList
            foreach (IPAddress curAdd in heserver.AddressList)
            {
                Console.WriteLine("....");
                // Display the type of address family supported by the server. If the
                // server is IPv6-enabled this value is: InterNetworkV6. If the server
                // is also IPv4-enabled there will be an additional value of InterNetwork.
                Console.WriteLine("AddressFamily: " + curAdd.AddressFamily.ToString());

                // Display the ScopeId property in case of IPV6 addresses.
                if (curAdd.AddressFamily.ToString() == ProtocolFamily.InterNetworkV6.ToString())
                {
                    Console.WriteLine("Scope Id: " + curAdd.ScopeId.ToString());
                }


                // Display the server IP address in the standard format. In
                // IPv4 the format will be dotted-quad notation, in IPv6 it will be
                // in in colon-hexadecimal notation.
                Console.WriteLine("Address: " + curAdd.ToString());

                // Display the server IP address in byte format.
                Console.Write("AddressBytes: ");

                Byte[] bytes = curAdd.GetAddressBytes();
                for (int i = 0; i < bytes.Length; i++)
                {
                    Console.Write(bytes[i]);
                }

                Console.WriteLine("\r\n");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("[DoResolve] Exception: " + e.ToString());
        }
    }
 static public int GetByteCount__A_Char(IntPtr l)
 {
     try {
         System.Text.ASCIIEncoding self = (System.Text.ASCIIEncoding)checkSelf(l);
         System.Char[]             a1;
         checkArray(l, 2, out a1);
         var ret = self.GetByteCount(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 static public int GetBytes__String(IntPtr l)
 {
     try {
         System.Text.ASCIIEncoding self = (System.Text.ASCIIEncoding)checkSelf(l);
         System.String             a1;
         checkType(l, 2, out a1);
         var ret = self.GetBytes(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #38
0
    public string StoreInstanceToString <T>(T instance)
    {
        byte[] packed_instance = StoreInstance(instance);

        IntPtr size_ptr = Marshal.AllocHGlobal(8);

        CheckDLErrors(dl_txt_unpack(ctx, TypeIDOf(instance), packed_instance, (uint)packed_instance.Length, new byte[0], 0, size_ptr));

        byte[] text_data = new byte[(uint)Marshal.ReadInt32(size_ptr)];
        Marshal.FreeHGlobal(size_ptr);

        CheckDLErrors(dl_txt_unpack(ctx, TypeIDOf(instance), packed_instance, (uint)packed_instance.Length, text_data, (uint)text_data.Length, (IntPtr)0));

        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
        return(enc.GetString(text_data));
    }
Exemple #39
0
    private static void TestReadingObjects(string xml)
    {
        System.Xml.Serialization.XmlSerializer xmlSerializer =
            new System.Xml.Serialization.XmlSerializer(typeof(Root));


        System.IO.Stream          stream   = new MemoryStream();
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        Byte[] bytes = encoding.GetBytes(xml);
        stream.Write(bytes, 0, bytes.Length);
        stream.Position = 0;
        Root r = (Root)xmlSerializer.Deserialize(stream);

        Console.WriteLine(string.Format("Element 1 = {0}", r.Element1));

        Console.WriteLine(string.Format("Element 2 = {0}", r.Element2 == null ? "Null" : r.Element2));
    }
Exemple #40
0
    public static uint ComputeCrc32(string str)
    {
        var buffer = new System.Text.ASCIIEncoding().GetBytes(str);

        var offset = 0;
        var count  = buffer.Length;

        uint crc = 0;

        crc ^= CrcSeed;
        while (--count >= 0)
        {
            crc = CrcTable[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >> 8);
        }
        crc ^= CrcSeed;
        return(crc);
    }
Exemple #41
0
    protected void Button7_Click(object sender, EventArgs e)
    {
        string userProvidedText = logtxt.Text;

        byte[] userProvidedTextAsBytes = null;

        if (!string.IsNullOrEmpty(userProvidedText))
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            userProvidedTextAsBytes = encoding.GetBytes(userProvidedText);
        }

        Response.AppendHeader("Content-Disposition", "attachment; filename=ppmp_temp.csv");
        Response.ContentType = "text/HTML";
        Response.BinaryWrite(userProvidedTextAsBytes);
        Response.End();
    }
 public void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         if (Session["dt1"] != null)
         {
             dt1 = (DataTable)Session["dt1"];
             if (dt1.Rows.Count > 0)
             {
                 System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                 b1 = ((byte[])dt1.Rows[0]["Img"]);
                 //Response.ContentType = "image/jpeg";
                 Response.BinaryWrite(b1);
             }
         }
     }
 }
Exemple #43
0
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     try
     {
         if (ddlOfficerMailId.SelectedIndex != 0)
         {
             string str = "";
             System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
             byte[] data = encoding.GetBytes(str);
             objEmailmaster.EmailSenderId    = Convert.ToInt32(Session["StudentId"]);
             objEmailmaster.EMailBodyMsg     = txtbody.Text;
             objEmailmaster.EmailSubjectText = txtsubject.Text;
             objEmailmaster.EmailReciptedId  = Convert.ToInt32(ddlOfficerMailId.SelectedValue);
             if (Session["FileName"] != null && Session["FileContent"] != null)
             {
                 objEmailmaster.EmailAttachFileName    = Convert.ToString(Session["FileName"]);
                 objEmailmaster.EmailAttachFileContent = (byte[])Session["FileContent"];
             }
             else
             {
                 objEmailmaster.EmailAttachFileName    = "No FIle";
                 objEmailmaster.EmailAttachFileContent = data;
             }
             int i = objEmailmaster.InsertEmailMaster();
             if (i > 0)
             {
                 ClearData();
                 lblMsg.Text = "Your message has been sent.";
             }
             else
             {
                 lblMsg.Text = "Message Failed..";
             }
         }
         else
         {
             Page.RegisterClientScriptBlock("Student", "<script>Alert('Select To EmailId')</script>");
         }
     }
     catch (Exception ex)
     {
         lblMsg.Text = ex.Message;
     }
 }
 static public int GetString__A_Byte__Int32__Int32(IntPtr l)
 {
     try {
         System.Text.ASCIIEncoding self = (System.Text.ASCIIEncoding)checkSelf(l);
         System.Byte[]             a1;
         checkArray(l, 2, out a1);
         System.Int32 a2;
         checkType(l, 3, out a2);
         System.Int32 a3;
         checkType(l, 4, out a3);
         var ret = self.GetString(a1, a2, a3);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            string str = "";
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] data = encoding.GetBytes(str);

            objEmailmaster.EmailSenderId    = Convert.ToInt32(Session["VolunteerId"]);
            objEmailmaster.EMailBodyMsg     = txtbody.Text;
            objEmailmaster.EmailSubjectText = txtsubject.Text;
            objEmailmaster.EmailReciptedId  = Convert.ToInt32(ddlto.SelectedValue);
            if (Session["FileName"] != null && Session["FileContent"] != null)
            {
                objEmailmaster.EmailAttachFileName    = Convert.ToString(Session["FileName"]);
                objEmailmaster.EmailAttachFileContent = (byte[])Session["FileContent"];
            }
            else
            {
                objEmailmaster.EmailAttachFileName    = "No FIle";
                objEmailmaster.EmailAttachFileContent = data;
            }

            mainPanel.Enabled = false;
            System.Threading.Thread.Sleep(2000);
            mainPanel.Enabled = true;
            int i = objEmailmaster.InsertEmailMaster();
            if (i > 0)
            {
                ClearData();
                lblMsg.Text = "Sending Email Sucessfully..";
            }
            else
            {
                lblMsg.Text = "Sending Failed..";
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
    }
Exemple #46
0
    public void start_client()
    {
        bool continueLoop = true;

        try
        {
            while (continueLoop)
            {
                byte[] recData = client.Receive(ref receivePoint);
                System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
                server_name = encode.GetString(recData);
                if (connected)
                {
                    server_name = "";
                    client.Close();
                    break;
                }
            }
        } catch {}
    }
Exemple #47
0
    public static void Main()
    {
        string baseIP = "192.168.1.";
        int    classD = 1;

        Console.WriteLine("Pinging 255 destinations of D-class in {0}*", baseIP);

        CreatePingers(255);

        PingOptions po = new PingOptions(ttl, true);

        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
        byte[] data = enc.GetBytes("abababababababababababababababab");

        SpinWait wait = new SpinWait();
        int      cnt  = 1;

        Stopwatch watch = Stopwatch.StartNew();

        foreach (Ping p in pingers)
        {
            lock (@lock) {
                instances += 1;
            }

            p.SendAsync(string.Concat(baseIP, cnt.ToString()), timeOut, data, po);
            cnt += 1;
        }

        while (instances > 0)
        {
            wait.SpinOnce();
        }

        watch.Stop();

        DestroyPingers();

        Console.WriteLine("Finished in {0}. Found {1} active IP-addresses.", watch.Elapsed.ToString(), result);
        Console.ReadKey();
    }
Exemple #48
0
    protected string CutString(object obj)
    {
        string inputString = obj.ToString().Trim();

        System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
        int    tempLen    = 0;
        int    len        = 82;
        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);
    }
    /// <summary>
    /// Builds a whole charset for a specific fontid
    /// </summary>
    public void BuildCharSet(string fontid)
    {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR
        int  istep    = TTFTextFontStore.Instance.defaultInterpolationSteps;
        bool reversed = false;
        charset         = new TTFTextOutline[0x80];
        charset_advance = new Vector3[0x80];
        System.Text.ASCIIEncoding ae = new System.Text.ASCIIEncoding();

        TTF.Font font = TTFTextInternal.Utilities.TryOpenFont(fontid, ref reversed, "", 72); // TODO: < Check the last bool

        if (font == null)
        {
            Debug.LogError("BuildCharSet: no font found");
            return;
        }

        for (byte i = 0x20; i < 0x7F; i++)
        {
            string s = ae.GetString(new byte [] { i });
            charset[i] = TTFTextInternal.Engine.MakeNativeOutline(s, 1, 0, font, reversed, istep);
            //TTFTextInternal.MakeOutline(s, font, 1, 0, null,false,null,null);
            charset_advance[i] = charset[i].advance;
        }


        addCharset = new TTFTextOutline[additionalChar.Length];

        int idx = 0;
        foreach (char c in additionalChar)
        {
            addCharset[idx] = TTFTextInternal.Engine.MakeNativeOutline(
                "" + c, 1, 0, font,
                reversed, istep);
            ++idx;
        }

        font.Dispose();
        _needRebuild = false;
#endif
    }
    /// <summary>
    /// Tries to build a whole charset according current parameters of a textmesh object
    /// </summary>
    public void BuildCharSet(TTFText tm)
    {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR
        int istep = TTFTextFontStore.Instance.defaultInterpolationSteps;
        charset         = new TTFTextOutline[0x80];
        charset_advance = new Vector3[0x80];
        System.Text.ASCIIEncoding ae = new System.Text.ASCIIEncoding();

        TTF.Font font = TTFTextInternal.Utilities.TryOpenFont(tm.InitTextStyle, 1);

        if (font == null)
        {
            Debug.LogError("(TTFText) BuildCharSet: no font found");
            return;
        }
        height = font.Height;
        for (byte i = 0x20; i < 0x7F; i++)
        {
            string s = ae.GetString(new byte [] { i });
            charset[i]         = TTFTextInternal.Engine.MakeNativeOutline(s, 1, 0, font, tm.OrientationReversed, istep);
            charset_advance[i] = charset[i].advance;
        }


        // Additional Custom Characters
        AddRequiredCharacters(TTFTextFontStore.Instance.defaultAdditionalCharacters + (tm.InitTextStyle.GetFontEngineParameters(1)
                                                                                       as TTFTextInternal.FontStoreFontEngine.Parameters).additionalCharacters);

        addCharset = new TTFTextOutline[additionalChar.Length];

        int idx = 0;
        foreach (char c in additionalChar)
        {
            addCharset[idx] = TTFTextInternal.Engine.MakeNativeOutline("" + c, 1, 0, font, tm.OrientationReversed, istep);
            ++idx;
        }

        font.Dispose();
        _needRebuild = false;
#endif
    }
Exemple #51
0
    public static void ContainerMethod(TypeBuilder myDynamicType)
    {
        // <Snippet1>

        MethodBuilder myMethod = myDynamicType.DefineMethod("MyMethod",
                                                            MethodAttributes.Public,
                                                            typeof(int),
                                                            new Type[] { typeof(string) });

        // A 128-bit key in hex form, represented as a byte array.
        byte[] keyVal = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                          0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xFF, 0xFF };

        System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
        byte[] symFullName = encoder.GetBytes("My Dynamic Method");

        myMethod.SetSymCustomAttribute("SymID", keyVal);
        myMethod.SetSymCustomAttribute("SymFullName", symFullName);

        // </Snippet1>
    }
    public string CutString(string str, int len)
    {
        if (len == -1)
        {
            return(str);
        }
        int    tempLen    = 0;
        string tempString = "";

        System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
        byte[] s = ascii.GetBytes(str);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }

            if (i < str.Length)
            {
                tempString += str.Substring(i, 1);
            }

            if (tempLen >= len)
            {
                break;
            }
        }
        byte[] mybyte = System.Text.Encoding.Default.GetBytes(str);
        if (mybyte.Length > len)
        {
            tempString += "…";
        }

        return(tempString);
    }
Exemple #53
0
    public void PortName_FileName()
    {
        string fileName = "PortNameEqualToFileName.txt";

        System.IO.FileStream      testFile  = System.IO.File.Open(fileName, System.IO.FileMode.Create);
        System.Text.ASCIIEncoding asciiEncd = new System.Text.ASCIIEncoding();
        string testStr = "Hello World";

        testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr));

        testFile.Close();
        Debug.WriteLine("Verifying setting PortName={0}", fileName);

        VerifyException(fileName, ThrowAt.Open, typeof(ArgumentException), typeof(InvalidOperationException));

        Debug.WriteLine("Verifying setting PortName={0}", Environment.CurrentDirectory + fileName);

        VerifyException(Environment.CurrentDirectory + fileName, ThrowAt.Open, typeof(ArgumentException),
                        typeof(InvalidOperationException));

        System.IO.File.Delete(fileName);
    }
Exemple #54
0
    public static int GetLength(string str)
    {
        if (str.Length == 0)
        {
            return(0);
        }
        System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
        int tempLen = 0; byte[] s = ascii.GetBytes(str);

        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }
        }
        return(tempLen);
    }
Exemple #55
0
    private void VerifyBytesToRead(int numBytesRead, int numNewLines)
    {
        using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
            using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
            {
                Random rndGen       = new Random(-55);
                byte[] bytesToWrite = new byte[numBytesRead + 1]; //Plus one to accomidate the NewLineByte
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

                //Genrate random characters
                for (int i = 0; i < numBytesRead; i++)
                {
                    byte randByte = (byte)rndGen.Next(0, 256);

                    bytesToWrite[i] = randByte;
                }

                char[] expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
                for (int i = 0; i < numNewLines; i++)
                {
                    int newLineIndex;

                    newLineIndex = rndGen.Next(0, numBytesRead);
                    bytesToWrite[newLineIndex]  = (byte)'\n';
                    expectedChars[newLineIndex] = (char)'\n';
                }

                Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead);

                com1.Open();
                com2.Open();

                bytesToWrite[numBytesRead]  = DEFAULT_NEW_LINE;
                expectedChars[numBytesRead] = (char)DEFAULT_NEW_LINE;

                VerifyRead(com1, com2, bytesToWrite, expectedChars);
            }
    }
Exemple #56
0
    /*
     * public void testFloat ()
     * {
     *      Debug.Log(arduinity.test () );
     * }
     */


    /*
     * Direction should be between 1 and 8 (inclusive)
     *      1 = N (forhead)
     * 2 = NW
     *      3 = W (right ear)
     *      4 = SW
     *      5 = S (back of head)
     *      6 = SE
     *      7 = E (left ear)
     *      8 = NE
     * Distances must be between 1 and 125 (inclusive). This is because a
     * distance of 0 would be interpreted as a null character in the
     * string I send. The same is true of direction. */
    public void setDistance(int direction, int distance)
    {
        if (direction < 1)
        {
            return;
        }
        if (direction > 8)
        {
            return;
        }
        if (distance < 1)
        {
            return;
        }
        if (distance > 125)
        {
            return;
        }

        /* Build up a null terminated string. */
        buffer[0] = (byte)127u;
        buffer[1] = (byte)direction;
        buffer[2] = (byte)distance;
        buffer[3] = (byte)126u;
        buffer[4] = (byte)0u;

        string str;

        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
        str = enc.GetString(buffer);

        arduinity.arduinityWrite(str);

        /* So, this plugin seems to be most reliable if I send the message twice.
         * It works 90% of the time if you only send the message once, but this
         * gets five nines (or something closer to that). */
        arduinity.arduinityWrite(str);
    }
Exemple #57
0
    private IEnumerator ReadIncomingData()
    {
        System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
        while (true) //Loop until stopped by StopCoroutine()
        {
            try
            {
                //Read everything currently in the system input buffer
                int bytesRead = arduino.Read(readBuffer, 0, readBuffer.Length);
                //Convert the byte to ASCII (a string)
                string serialInput = encoder.GetString(readBuffer, 0, bytesRead);
                //Add the new data to our own input buffer
                inputBuffer   += serialInput;
                rawSerialEvent = serialInput;

                if (NewRawSerialEvent != null)   //Check that someone is actually subscribed to the event
                {
                    NewRawSerialEvent(this);     //Fire the event in case someone is subscribed
                }
                //Find a new line flag (indicates end of a data package)
                int endFlagPosition = inputBuffer.IndexOf('\n');
                //If we found a flag, process it further
                while (endFlagPosition > -1)
                {
                    //Check if the start flag is also there (i.e. we have recieved an entire data package
                    if (inputBuffer[0] == StartFlag)
                    {
                        //Hand the data to the function above
                        ProcessInputFromArduino(inputBuffer.Substring(1, endFlagPosition));
                        readTimeouts = 0;
                    }
                    else
                    //If the start flag isn't there, we have only recieved a partial data package, and thus we throw it out
                    {
                        if (PackagesLost > 0) //Don't complain about first lost package, as it usually happens once at startup
                        {
                            Debug.Log("Start flag not found in serial input (corrupted data?)");
                        }
                        PackagesLost++; //Count how many packages we have lost since the start of the scene.
                    }

                    //Remove the data package from our own input buffer (both if it is partial and if it is complete)
                    inputBuffer = inputBuffer.Remove(0, endFlagPosition + 1);
                    //Check if there is another data package available in our input buffer (while-loop). Makes sure we're not behind and only read old data (e.g. if Unity hangs for a second, the Arduino would have send a lot of packages meanwhile that we need to handle)
                    endFlagPosition = inputBuffer.IndexOf('\n');
                }
                //Reset the timeout counter (as we just recieved some data)
                readTimeouts = 0;
            }
            catch (System.Exception e)
            {
                //Catch any timeout errors (can happen if the Arduino is busy with something else)
                readTimeouts++;

                //If we time out many times, then something is propably wrong with the serial port, in which case we will try to reopen it.
                if (readTimeouts > 5000)
                {
                    Debug.Log("No data recieved for a long time (" + PortName + ").\n" + e.ToString());
                    ReopenPort();
                }
            }
            //Make the coroutine take a break, to allow Unity to also use the CPU.
            //This currently doesn't account for the time the coroutine actually takes to run (~1ms) and thus isn't the true polling rate.
            yield return(new WaitForSeconds(1.0f / PollingRate));
        }
    }
Exemple #58
0
    public static bool EncryptFile(string Filename, string Target)
    {
        if (!File.Exists(Filename))
        {
            _exception = new CryptographicException(ERR_NO_FILE);
            return(false);
        }

        //Make sure the target file can be written
        try {
            FileStream fs = File.Create(Target);
            fs.Close();
            //fs.Dispose()  ' Works with VB 2005 only
            File.Delete(Target);
        }
        catch (Exception ex) {
            _exception = new CryptographicException(ERR_FILE_WRITE);
            return(false);
        }

        byte[] inStream    = null;
        byte[] cipherBytes = null;

        try {
            StreamReader objReader = null;
            FileStream   objFS     = null;
            System.Text.ASCIIEncoding objEncoding = new System.Text.ASCIIEncoding();
            objFS     = new FileStream(Filename, FileMode.Open);
            objReader = new StreamReader(objFS);
            inStream  = objEncoding.GetBytes(objReader.ReadToEnd());
        }
        // The following is the VB 2005 equivalent
        //inStream = File.ReadAllBytes(Filename)
        catch (Exception ex) {
            _exception = new CryptographicException(ERR_FILE_READ);
            return(false);
        }

        try {
            cipherBytes = _Encrypt(inStream);
        }
        catch (CryptographicException ex) {
            _exception = ex;
            return(false);
        }

        string encodedString = string.Empty;

        if (_encodingType == EncodingType.BASE_64)
        {
            encodedString = System.Convert.ToBase64String(cipherBytes);
        }
        else
        {
            encodedString = BytesToHex(cipherBytes);
        }

        byte[] encodedBytes = Encoding.UTF8.GetBytes(encodedString);

        //Create the encrypted file
        FileStream outStream = File.Create(Target);

        outStream.Write(encodedBytes, 0, encodedBytes.Length);
        outStream.Close();
        //outStream.Dispose()  ' Works with VB 2005 only

        return(true);
    }
Exemple #59
0
    // 72ec0b31-0be7-444a-9575-1dbcb864e0be
    // How to: Read Image Metadata

    private void Method51(PaintEventArgs e)
    {
        // <snippet51>
        // Create an Image object.
        Image image = new Bitmap(@"c:\FakePhoto.jpg");

        // Get the PropertyItems property from image.
        PropertyItem[] propItems = image.PropertyItems;

        // Set up the display.
        Font       font       = new Font("Arial", 12);
        SolidBrush blackBrush = new SolidBrush(Color.Black);
        int        X          = 0;
        int        Y          = 0;

        // For each PropertyItem in the array, display the ID, type, and
        // length.
        int count = 0;

        foreach (PropertyItem propItem in propItems)
        {
            e.Graphics.DrawString(
                "Property Item " + count.ToString(),
                font,
                blackBrush,
                X, Y);

            Y += font.Height;

            e.Graphics.DrawString(
                "   iD: 0x" + propItem.Id.ToString("x"),
                font,
                blackBrush,
                X, Y);

            Y += font.Height;

            e.Graphics.DrawString(
                "   type: " + propItem.Type.ToString(),
                font,
                blackBrush,
                X, Y);

            Y += font.Height;

            e.Graphics.DrawString(
                "   length: " + propItem.Len.ToString() + " bytes",
                font,
                blackBrush,
                X, Y);

            Y += font.Height;

            count++;
        }
        // Convert the value of the second property to a string, and display
        // it.
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        string manufacturer = encoding.GetString(propItems[1].Value);

        e.Graphics.DrawString(
            "The equipment make is " + manufacturer + ".",
            font,
            blackBrush,
            X, Y);
        // </snippet51>
    }
Exemple #60
0
    protected void ButLogin_Click(object sender, EventArgs e)
    {
        try
        {
            int?   userId;
            string connectionString            = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["CustomerRecoveryConnectionString"].ConnectionString;
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
            string name = builder.InitialCatalog;
            CRBusinessLogicLayer.IsValidUser(txtUserName.Text, txtPassword.Text, out userId);
            if (userId == null)
            {
                txtUserName.Text = "";
                txtPassword.Text = "";
                LbError.Text     = "Invalid  User Name/Password.";
                LbError.Visible  = true;
            }
            else
            {
                var    ds                        = CRBusinessLogicLayer.GetSequerityQuestion((int)userId);
                string SessionuserID             = name + "_" + "userid";
                var    UserType                  = ds.Tables[0].Rows[0]["UserRole"].ToString();
                var    CityID                    = ds.Tables[0].Rows[0]["City"].ToString();
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, txtUserName.Text, DateTime.Now, DateTime.Now.AddDays(7), true, String.Format("{0}|{1}|{2}", txtUserName.Text, userId, UserType));
                string hash                      = FormsAuthentication.Encrypt(ticket);
                FormsAuthentication.SetAuthCookie(txtUserName.Text, true);
                Response.AppendCookie(new HttpCookie(SessionuserID, userId.ToString()));
                Response.AppendCookie(new HttpCookie("UserName", txtUserName.Text));
                Response.AppendCookie(new HttpCookie("UserRole", UserType));
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                Byte[] bytes = encoding.GetBytes(txtPassword.Text);
                string pwd   = CRBusinessLogicLayer.PassEncrypt(bytes);
                Response.AppendCookie(new HttpCookie("Pass", pwd));
                Response.AppendCookie(new HttpCookie("CityID", CityID));
                Response.AppendCookie(new HttpCookie("USERID", userId.ToString()));
                Response.AppendCookie(new HttpCookie("udata", hash));

                string url = string.Empty;
                ds = CRBusinessLogicLayer.GetUserAccessURL((int)userId);
                if (ds.Tables[0].Rows.Count == 1)
                {
                    url = ds.Tables[0].Rows[0]["ScreenURL"].ToString();
                }
                else if (url == string.Empty)
                {
                    Response.Redirect(
                        Convert.ToInt16(UserType) == 2
                            ? "~/DailyTransactions/NPADetails.aspx"
                            : "~/Masters/Farmer.aspx", false);
                }
                if (url != string.Empty)
                {
                    Response.Redirect(url, false);
                }
            }
        }
        catch (Exception ex)
        {
            LbError.Text    = ex.Message;
            LbError.Visible = true;
        }
    }