/// <summary>
        /// Function for getting a token from ACS using Application Service principal Id and Password.
        /// </summary>
        public static AADJWTToken GetAuthorizationToken(string tenantName, string appPrincipalId, string password)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format(StringConstants.AzureADSTSURL, tenantName));
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            string postData = "grant_type=client_credentials";            
            postData += "&resource=" + HttpUtility.UrlEncode(StringConstants.GraphPrincipalId);
            postData += "&client_id=" + HttpUtility.UrlEncode(appPrincipalId);
            postData += "&client_secret=" + HttpUtility.UrlEncode(password);
            byte[] data = encoding.GetBytes(postData);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            using (var response = request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(AADJWTToken));
                    AADJWTToken token = (AADJWTToken)(ser.ReadObject(stream));
                    return token;
                }
            }
        }
Ejemplo n.º 2
0
        public void Encode(IPEndPoint local_endpoint)
        {
            Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sock.Bind (local_endpoint);
            sock.Listen (5);

            //      		for (;;)
            //      		{
            //				allDone.Reset ();
            //				Console.Error.WriteLine ("Waiting for connection on port {0}", local_endpoint);
            //				sock.BeginAccept (new AsyncCallback (this.AcceptCallback), sock);
            //				allDone.WaitOne ();
            //      		}

              		Console.Error.WriteLine ("Waiting for connection on port {0}", local_endpoint);
              		Socket client = sock.Accept();

            NetworkStream stream = new NetworkStream(client);

            Console.Error.WriteLine ("Got connection from {0}", client.RemoteEndPoint);

              		byte[] buffer = new byte[1024];
              		System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

              		Stream stdin = Console.OpenStandardInput(buffer.Length);

              		while (stdin.Read(buffer, 0, buffer.Length) != 0)
            {
                Console.WriteLine("Data: {0}", encoding.GetString(buffer));
                stream.Write(buffer, 0, buffer.Length);
            }

              		Console.Error.WriteLine ("Closing socket");
            sock.Close ();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Uidチェック(0~9|a~z|A~Z)かつ18桁
        /// </summary>
        /// <param name="uid">UID</param>
        /// <returns></returns>
        private static bool CheckMuid(string uid)
        {
            var asciiEncoding = new System.Text.ASCIIEncoding();

            var rst = uid.Select((t, i) => (int)asciiEncoding.GetBytes(uid.Substring(i, 1))[0]).Aggregate(true, (current, z) => current && ((47 < z && z < 58) || (64 < z && z < 91) || (96 < z && z < 123) || z==46));
            return  rst;
        }
Ejemplo n.º 4
0
 private string Response()
 {
     System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
     byte[] serverbuff = new Byte[1024];
     NetworkStream stream = GetStream();
     int count = 0;
     while (true)
     {
         byte[] buff = new Byte[2];
         int bytes = stream.Read(buff, 0, 1);
         if (bytes == 1)
         {
             serverbuff[count] = buff[0];
             count++;
             if (buff[0] == '\n')
             {
                 break;
             }
         }
         else
         {
             break;
         }
     }
     string retval = enc.GetString(serverbuff, 0, count);
     return retval;
 }
Ejemplo n.º 5
0
        public new Boolean ExtractMetaData()
        {
            // Create an Image object.
            System.Drawing.Image image = new Bitmap(@"G:\projects\MugShot\test_photos\ClayShoot0001.JPG");

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

            // For each PropertyItem in the array, display the ID, type, and
            // length.
            int count = 0;
            foreach (PropertyItem propItem in propItems)
            {

                Console.WriteLine(propItem.Id.ToString("x"));
                Console.WriteLine(propItem.Type.ToString());
                Console.WriteLine(propItem.Len.ToString());
                Console.WriteLine("-----------------------");

                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);

            Console.WriteLine("Manufacturer: {0}", manufacturer.ToString());

            //need to fill this in with real metadata
            MetaData = new ArrayList();

            return true;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 指定されたUIDを暗号化して返します。
        /// </summary>
        /// <param name="uid">MUID</param>
        /// <returns></returns>
        public static string Encrypt(string uid)
        {
            var encryptStr = "";
            if (!string.IsNullOrEmpty(uid))
            {
                if (CheckMuid(uid))
                {
                    uid = uid.Replace(".", "");
                    if(uid.Length%2!=0)
                    {
                        uid = uid + "0";
                    }
                    var asciiEncoding = new System.Text.ASCIIEncoding();

                    for (int i = 0; i < uid.Length / 2; i++)
                    {
                        var subUid = uid.Substring(i * 2, 2);
                        encryptStr = encryptStr + subUid + ((asciiEncoding.GetBytes(uid.Substring(i * 2, 1))[0] + asciiEncoding.GetBytes(uid.Substring(i * 2 + 1, 1))[0]) % 15).ToString("x");
                    }
                    char[] arr = encryptStr.ToCharArray();
                    Array.Reverse(arr);
                    encryptStr = new string(arr);
                }
                else
                {
                    encryptStr = "00000";
                }
            }
            else
            {
                encryptStr = "00000";
            }
            return encryptStr;
        }
Ejemplo n.º 7
0
        public string GetCurrentAirInstall(string Location)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            DirectoryInfo dInfo = new DirectoryInfo(Location);
            DirectoryInfo[] subdirs = null;
            try
            {
                subdirs = dInfo.GetDirectories();
            }
            catch { return "0.0.0.0"; }
            string latestVersion = "0.0.1";
            foreach (DirectoryInfo info in subdirs)
            {
                latestVersion = info.Name;
            }

            string AirLocation = Path.Combine(Location, latestVersion, "deploy");
            if (!File.Exists(Path.Combine(Client.ExecutingDirectory, "ClientLibCommon.dat")))
            {
                File.Copy(Path.Combine(AirLocation, "lib", "ClientLibCommon.dat"), Path.Combine(Client.ExecutingDirectory, "ClientLibCommon.dat"));
            }
            if (!File.Exists(Path.Combine(Client.ExecutingDirectory, "gameStats_en_US.sqlite")))
            {
                File.Copy(Path.Combine(AirLocation, "assets", "data", "gameStats", "gameStats_en_US.sqlite"), Path.Combine(Client.ExecutingDirectory, "gameStats_en_US.sqlite"));
            }

            Copy(Path.Combine(AirLocation, "assets", "images", "abilities"), Path.Combine(Client.ExecutingDirectory, "Assets", "abilities"));
            Copy(Path.Combine(AirLocation, "assets", "images", "champions"), Path.Combine(Client.ExecutingDirectory, "Assets", "champions"));

            var VersionAIR = File.Create(Path.Combine("Assets", "VERSION_AIR"));
            VersionAIR.Write(encoding.GetBytes(latestVersion), 0, encoding.GetBytes(latestVersion).Length);
            VersionAIR.Close();
            return latestVersion;
        }
Ejemplo n.º 8
0
		public string Post(Uri uri, NameValueCollection input)
		{
			ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
			WebRequest request = WebRequest.Create(uri);
			string strInput = GetInputString(input);
			
			request.Method = "POST";
			request.ContentType = "application/x-www-form-urlencoded";
			request.ContentLength = strInput.Length;
			
			Stream writeStream = request.GetRequestStream();
			System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
			byte[] bytes = encoding.GetBytes(strInput);
			writeStream.Write(bytes, 0, bytes.Length);
			writeStream.Close();

            using (WebResponse response = request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader streamReader = new StreamReader(responseStream);
                    return streamReader.ReadToEnd();
                }
            }
		}
Ejemplo n.º 9
0
        public static string GetExifPropertyTagDateTime(string file)
        {
            const int PropertyTagDateTime = 0x0132;
            string DateTime = "";
            try {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            using (FileStream stream = File.OpenRead(file)) {
                Image image = Image.FromStream(stream, true, false);
                PropertyItem[] propItems = image.PropertyItems;

                // For each PropertyItem in the array, display the ID, type, and length and value.
                // 0x0132 _=

                foreach (PropertyItem propItem in propItems) {
                    if (propItem.Id == PropertyTagDateTime) {
                        DateTime = encoding.GetString(propItem.Value);
                        break;
                    }
                }
            }
            } catch (Exception) {
            // if there was an error (such as read a defect image file), just ignore
            }
            return(DateTime);
        }
Ejemplo n.º 10
0
        public static string ErrorString(uint hekkaError)
        {
            byte[] text = new byte[200];
            int size = text.Length;

            IntPtr textPtr = Marshal.AllocHGlobal(size);

            string result = null;
            try
            {
                ITCMM.ITC_AnalyzeError((int)hekkaError, textPtr, (uint)size);

                Marshal.Copy(textPtr, text, 0, size);

                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

                result = enc.GetString(text);
            }
            finally
            {
                Marshal.FreeHGlobal(textPtr);
            }

            return result;
        }
Ejemplo n.º 11
0
 /// <summary>
 /// 截取指定长度字符串,汉字为2个字符
 /// </summary>
 /// <param name="inputString">要截取的目标字符串</param>
 /// <param name="len">截取长度</param>
 /// <returns>截取后的字符串</returns>
 public static string CutString(string inputString, int len)
 {
     System.Text.ASCIIEncoding ascii = new System.Text.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;
     }
     return tempString;
 }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            /*
             * Make sure this path contains the umundoNativeCSharp.dll!
             */
            SetDllDirectory("C:\\Users\\sradomski\\Desktop\\build\\umundo\\lib");
            org.umundo.core.Node node = new org.umundo.core.Node();
            Publisher pub = new Publisher("pingpong");
            PingReceiver recv = new PingReceiver();
            Subscriber sub = new Subscriber("pingpong", recv);
            node.addPublisher(pub);
            node.addSubscriber(sub);

            while (true)
            {
                Message msg = new Message();
                String data = "data";
                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                byte[] buffer = enc.GetBytes(data);
                msg.setData(buffer);
                msg.putMeta("foo", "bar");
                Console.Write("o");
                pub.send(msg);
                System.Threading.Thread.Sleep(1000);
            }
        }
Ejemplo n.º 13
0
 public static string ByteArrayToStr(byte[] dBytes)
 {
     string str;
     System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
     str = enc.GetString(dBytes);
     return str;
 }
Ejemplo n.º 14
0
 public ActionResult BatchUpload(DateTime date, HttpPostedFileBase file, int? fundid, string text)
 {
     string s;
     if (file != null)
     {
         byte[] buffer = new byte[file.ContentLength];
         file.InputStream.Read(buffer, 0, file.ContentLength);
         System.Text.Encoding enc = null;
         if (buffer[0] == 0xFF && buffer[1] == 0xFE)
         {
             enc = new System.Text.UnicodeEncoding();
             s = enc.GetString(buffer, 2, buffer.Length - 2);
         }
         else
         {
             enc = new System.Text.ASCIIEncoding();
             s = enc.GetString(buffer);
         }
     }
     else
         s = text;
     var id = PostBundleModel.BatchProcess(s, date, fundid);
     if (id.HasValue)
         return Redirect("/PostBundle/Index/" + id);
     return RedirectToAction("Batch");
 }
Ejemplo n.º 15
0
 public static string Encode(string value)
 {
     var hash = System.Security.Cryptography.SHA1.Create();
     var encoder = new System.Text.ASCIIEncoding();
     var combined = encoder.GetBytes(value ?? "");
     return BitConverter.ToString(hash.ComputeHash(combined)).ToLower().Replace("-", "");
 }
Ejemplo n.º 16
0
        public string GetCurrentGameInstall(string GameLocation)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            DirectoryInfo dInfo = new DirectoryInfo(Path.Combine(GameLocation, "projects", "lol_game_client", "filearchives"));
            DirectoryInfo[] subdirs = null;
            try
            {
                subdirs = dInfo.GetDirectories();
            }
            catch { return "0.0.0.0"; }
            string latestVersion = "0.0.1";
            foreach (DirectoryInfo info in subdirs)
            {
                latestVersion = info.Name;
            }

            string ParentDirectory = Directory.GetParent(GameLocation).FullName;
            Copy(Path.Combine(ParentDirectory, "Config"), Path.Combine(Client.ExecutingDirectory, "Config"));

            Copy(Path.Combine(GameLocation, "projects", "lol_game_client"), Path.Combine(Client.ExecutingDirectory, "RADS", "projects", "lol_game_client"));
            File.Copy(Path.Combine(GameLocation, "RiotRadsIO.dll"), Path.Combine(Client.ExecutingDirectory, "RADS", "RiotRadsIO.dll"));

            var VersionAIR = File.Create(Path.Combine("RADS", "VERSION_LOL"));
            VersionAIR.Write(encoding.GetBytes(latestVersion), 0, encoding.GetBytes(latestVersion).Length);
            VersionAIR.Close();
            return latestVersion;
        }
Ejemplo n.º 17
0
        public static bool sendmessage(MessageTypes type, string msg, ref byte[] data)
        {
            try
            {
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] message = encoding.GetBytes(msg);
                int size = HEADERSIZE + message.Length;
                data = new byte[size];
                byte[] sizebyte = BitConverter.GetBytes(size);
                byte[] typebyte = BitConverter.GetBytes((int)type);
                Array.Copy(sizebyte, 0, data, LENGTHOFFSET, sizebyte.Length);
                Array.Copy(typebyte, 0, data, TYPEOFFSET, typebyte.Length);
                Array.Copy(message, 0, data, HEADERSIZE, message.Length);
            }
#if DEBUG
            catch (Exception ex)
            {
                Console.WriteLine("error processing: " + type.ToString() + " msg: " + msg + " err: " + ex.Message + ex.StackTrace);
                return false;
            }
#else
            catch (Exception)
            {
            }
#endif

            return true;

            
        }
Ejemplo n.º 18
0
 public static string ByteArrayToString(byte[] b)
 {
     string s;
                 System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                 s = enc.GetString(b, 0, b.Length);
                 return s;
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Convert string to a byte array.
        /// </summary>
        /// <param name="text">String to convert.</param>
        /// <returns>Byte array. null if text is null, and empty array if
        /// the string is empty.
        ///</returns>
        public static byte[] StringToByteArray(string text)
        {
            if (text == null)
                return null;

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            return encoding.GetBytes(text);
        }
Ejemplo n.º 20
0
 private void WriteData(Stream requestStream, string data)
 {
     System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
     byte[] dataAsBytes = encoding.GetBytes(data);
     Stream dataStream = requestStream;
     dataStream.Write(dataAsBytes, 0, dataAsBytes.Length);
     dataStream.Close();
 }
Ejemplo n.º 21
0
 public static string ByteArrayToString(byte[] arr)
 {
     System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
     string result = System.Text.Encoding.UTF8.GetString(arr);
     string result2 = enc.GetString(arr);
     string s3 = Convert.ToBase64String(arr);
     return s3;
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["FIG_ID"] != null)
                {
                    decimal lFIG_ID = decimal.Parse(Request.QueryString["FIG_ID"].ToString());

                    DataTable lTable = FIGURASTo.GetFIGURASByID(lFIG_ID, LocalInstance.ConnectionInfo);

                    if (lTable.Rows.Count > 0)
                    {
                        string tpArquivo = ".jpg";
                        byte[] documento = new byte[0];

                        try
                        {

                            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                            documento = (byte[])lTable.Rows[0][FIGURASQD._FIG_IMAGEN.Name];

                            int ArraySize = new int();
                            ArraySize = documento.GetUpperBound(0);

                            Response.Clear();
                            Response.ClearHeaders();
                            Response.AppendHeader("Content-Disposition", "filename = " + lTable.Rows[0][FIGURASQD._FIG_FORMATO.Name].ToString());
                            if (tpArquivo == ".pdf")
                                Response.ContentType = "application/pdf";
                            else if (tpArquivo == ".doc")
                                Response.ContentType = "application/msword";
                            else if (tpArquivo == ".xls")
                                Response.ContentType = "application/vnd.ms-excel";
                            else if (tpArquivo == ".txt")
                                Response.ContentType = "application/msword";
                            else if (tpArquivo == ".jpg")
                                Response.ContentType = "image/jpeg";

                            Response.BinaryWrite(documento);
                            Response.End();

                        }
                        catch (Exception err)
                        {
                            (new UnknownException(err)).TratarExcecao(true);
                        }
                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "alerta", "<script language=\"javascript\">window.close();</script>");
                    }
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "alerta", "<script language=\"javascript\">window.close();</script>");
                }
            }
        }
Ejemplo n.º 23
0
 string Response()
 {
     System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
     byte[] serverbuff = new byte[1024];
     NetworkStream stream = GetStream();
     int count = stream.Read(serverbuff, 0, 1024);
     if (count == 0)
         return "";
     return enc.GetString(serverbuff, 0, count);
 }
Ejemplo n.º 24
0
        void Write(string format, params object[] args)
        {
            System.Text.ASCIIEncoding en = new System.Text.ASCIIEncoding();

            byte[] WriteBuffer = new byte[1024];
            WriteBuffer = en.GetBytes(string.Format(format, args));

            NetworkStream stream = GetStream();
            stream.Write(WriteBuffer, 0, WriteBuffer.Length);
        }
Ejemplo n.º 25
0
 public RTP_Protocol(int cID, RTPServerMainView refToView)
 {
     /*Pre : server needs to stream video
      *Post: server is able to stream videos to a remote client*/
     streaming = false;
     referenceToView = refToView;
     encode = new System.Text.ASCIIEncoding();
     packet = new RTPpacket(2, 0, 0, 0, 0, 26, StreamingServer.NameOfServer);
     clientID = cID;
 }
Ejemplo n.º 26
0
		/// <summary>
		/// Constrói uma chave
		/// </summary>
		/// <param name="usuário">Usuário</param>
		/// <param name="senha">Senha</param>
		public Chave(string usuário, string senha)
		{
			MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
			System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
			byte [] dados;

			dados = ascii.GetBytes(DateTime.Now.Ticks.ToString() + usuário + senha);

			código = md5.ComputeHash(dados);
		}
Ejemplo n.º 27
0
        private static int[] AsciiToIntArray(string ascii)
        {
            System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();

            byte[] bytes = encoder.GetBytes(ascii.ToCharArray());
            int[] intArr = new int[bytes.Length];
            for (int i = 0; i < bytes.Length; i++)
                intArr[i] = System.Convert.ToInt32(bytes[i]);

            return intArr;
        }
Ejemplo n.º 28
0
        public void GetDataSize()
        {
            string identifier = ProceduralDb.TempName();
              var encoding = new System.Text.ASCIIEncoding();

              const string testString = "This is a test";
              var data = encoding.GetBytes(testString);
              ProceduralDb.SetData(identifier, data);

              Assert.AreEqual(data.Length, ProceduralDb.GetDataSize(identifier));
        }
Ejemplo n.º 29
0
        public void Write (byte[] data)
        {
            this.NoisyLog ("Write {0}",
                        data.Select (x => x.ToString ("X")).Aggregate ((x,y) => x + " " + y));
            switch ((Mode)data [0]) {
            case Mode.Model:
                currentRetValue = new System.Text.ASCIIEncoding ().GetBytes (" EP0700M06*A0G_110610$");
                break;
            case Mode.Data:
                PrepareTouchData ();
                break;
            case Mode.Register:
                byte val;
                switch ((Registers)(data [1] & 0x3f)) {
                case Registers.WorkRegisterThreshold:
                    val = 40;
                    break;
                case Registers.WorkRegisterGain:
                    val = 8;
                    break;
                case Registers.WorkRegisterOffset:
                    val = 0;
                    break;
                case Registers.WorkRegisterReportRate:
                    val = 8;
                    break;
                case Registers.WorkRegisterNumX:
                    val = NumX;
                    break;
                case Registers.WorkRegisterNumY:
                    val = NumY;
                    break;
                default:
                    this.Log (
                        LogLevel.Warning,
                        "Unknown register write: {0}",
                        data.Select (x => x.ToString ("X")).Aggregate ((x,y) => x + " " + y)
                    );
                    val = 0;
                    break;
                }

                currentRetValue = new byte[]{val, GetCRC (data, val)};

                break;
            default:
                this.Log (
                    LogLevel.Warning,
                    "Unknown mode write: {0}",
                    data.Select (x => x.ToString ("X")).Aggregate ((x,y) => x + " " + y)
                    );
                break;
            }
        }
        //Response.Write();
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (hdExport.Value == "ON")
            {
                hdExport.Value = "OFF";
                string strHeaderCols = "CourseID|CourseGrade|GradeLow|CourseCode|CourseName|CourseCount|AlternateCount";
                string strFileName = CP.SetExportFileName("StudentCountByCourses", strSchoolID);

                #region Send Request to ExcelWriter
                string strPostInfo;
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                strPostInfo = "SQL=" + strSQL.Replace("+", "~");
                strPostInfo += "&HeaderCols=" + strHeaderCols;
                strPostInfo += "&ReportName=" + lblReportName.Text;
                strPostInfo += "&Description=" + lblDescription.Text;
                strPostInfo += "&SortFilter=" + hdOldSortColumn.Value;
                //Response.Write(strPostInfo);
                //Response.End();
                byte[] buffer1 = encoding.GetBytes(strPostInfo);
                HttpWebRequest NewRequest = (HttpWebRequest)WebRequest.Create("http://172.16.10.19/School/GetXLSUserReport.aspx");
                NewRequest.Method = "POST";
                NewRequest.ContentType = "application/x-www-form-urlencoded";
                NewRequest.ContentLength = buffer1.Length;
                Stream RequestStream = NewRequest.GetRequestStream();
                RequestStream.Write(buffer1, 0, buffer1.Length);

                WebResponse XLSResponse = NewRequest.GetResponse();
                Stream XLSStream2 = XLSResponse.GetResponseStream();

                RequestStream.Close();
                MemoryStream XLSMemoryStram = new MemoryStream();

                // 2048 bytes seemed like a safe amount to read in at a time.
                byte[] buffer2 = new byte[2048];

                int intBytesRead = 0;
                do
                {
                    intBytesRead = XLSStream2.Read(buffer2, 0, buffer2.Length);
                    XLSMemoryStram.Write(buffer2, 0, intBytesRead);
                }
                while (intBytesRead != 0);

                XLSStream2.Close();
                buffer2 = XLSMemoryStram.ToArray();

                Response.Clear();
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("content-disposition", "attachment;filename=\"" + strFileName + ".xls\"");
                Response.BinaryWrite(buffer2);
                Response.End();
                #endregion
            }
        }
Ejemplo n.º 31
0
        public XmlDocument ParseSAMLResponse(string strEncodedSAMLResponse)
        {
            System.Text.ASCIIEncoding encencoder = new System.Text.ASCIIEncoding();
            string strCleanResponse = encencoder.GetString(Convert.FromBase64String(strEncodedSAMLResponse));

            XmlDocument xDoc = new XmlDocument();

            xDoc.PreserveWhitespace = true;
            xDoc.XmlResolver        = null;
            xDoc.LoadXml(strCleanResponse);

            return(xDoc);
        }
Ejemplo n.º 32
0
        private static int[] AsciiToIntArray(string ascii)
        {
            System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();

            byte[] bytes  = encoder.GetBytes(ascii.ToCharArray());
            int[]  intArr = new int[bytes.Length];
            for (int i = 0; i < bytes.Length; i++)
            {
                intArr[i] = System.Convert.ToInt32(bytes[i]);
            }

            return(intArr);
        }
Ejemplo n.º 33
0
        public IActionResult CreateTimeSignature()
        {
            var timeStamp = $"{DateTime.Now:yyyyMMddHHmmss}";
            var secret    = "953225403197";
            var encoding  = new System.Text.ASCIIEncoding();

            byte[] keyByte      = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(timeStamp);
            using (var hmacsha256 = new HMACSHA256(keyByte)) {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return(Content(Convert.ToBase64String(hashmessage)));
            }
        }
Ejemplo n.º 34
0
 public static int ToASCIICode(string input)
 {
     try
     {
         System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
         int rs = (int)encode.GetBytes(input)[0];
         return(rs);
     }
     catch
     {
         return(-1);
     }
 }
Ejemplo n.º 35
0
        private void Write(string message)
        {
            System.Text.ASCIIEncoding en = new System.Text.ASCIIEncoding();

            byte[] WriteBuffer = new byte[1024];
            WriteBuffer = en.GetBytes(message);

            NetworkStream stream = GetStream();

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

            //Debug.WriteLine("WRITE:" + message);
        }
Ejemplo n.º 36
0
        }//0行向移动,1列向移动

        /// <summary>
        /// Excel单元格的移动 列数 小于676
        /// </summary>
        /// <param name="character"></param>
        /// <returns></returns>
        public static int Asc(string character)
        {
            if (character.Length == 1)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
                return(intAsciiCode);
            }
            else
            {
                throw new Exception("Character is not valid.");
            }
        }
Ejemplo n.º 37
0
        // Create base 64 sha1 encrypted signature
        private static string CreateSig(string apiKey, string secretKey, double expires)
        {
            var encoding = new System.Text.ASCIIEncoding();

            byte[] keyByte      = encoding.GetBytes(secretKey);
            byte[] messageBytes = encoding.GetBytes(apiKey + expires);
            using (var hmacsha1 = new HMACSHA1(keyByte))
            {
                byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
                var    signature   = Convert.ToBase64String(hashmessage);
                return(HttpUtility.UrlEncode(signature));
            }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Gets the Webhook Notification Token based on the message and secret.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static string GetWebhookNotificationToken(string message, string secret)
        {
            secret = secret ?? "";
            var encoding = new System.Text.ASCIIEncoding();

            byte[] keyByte      = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return(Convert.ToBase64String(hashmessage));
            }
        }
Ejemplo n.º 39
0
        private static string SecureValue(string message)
        {
            const string key = "msdevmtl";

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            var keyByte = encoding.GetBytes(key);

            var sha = new HMACSHA256(keyByte);

            byte[] messageBytes = encoding.GetBytes(message);
            byte[] hashmessage  = sha.ComputeHash(messageBytes);
            return(ByteToString(hashmessage));
        }
Ejemplo n.º 40
0
        public static string Encode(string value)
        {
            var hash = System.Security.Cryptography.SHA512.Create();

            var encoder = new System.Text.ASCIIEncoding();

            var combined = encoder.GetBytes(value ?? "");

            return(BitConverter
                   .ToString(hash.ComputeHash(combined))
                   .ToLower()
                   .Replace("-", ""));
        }
Ejemplo n.º 41
0
        public void SetGetData()
        {
            string identifier = ProceduralDb.TempName();
            var    encoding   = new System.Text.ASCIIEncoding();

            const string testString = "This is a test";
            var          data       = encoding.GetBytes(testString);

            ProceduralDb.SetData(identifier, data);

            data = ProceduralDb.GetData(identifier);
            Assert.AreEqual(testString, encoding.GetString(data));
        }
Ejemplo n.º 42
0
        /**
         * The IPAddresses method obtains the selected server IP address information.
         * It then displays the type of address family supported by the server and its
         * IP address in standard and byte format.
         **/
        private static void IPAddresses(string server)
        {
            try
            {
                System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();

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

                // Loop on the AddressList
                foreach (IPAddress curAdd in heserver.AddressList)
                {
//<Snippet3>

                    // 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());
                    }

//</Snippet3>

                    // 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: ");

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

                    Console.WriteLine("\r\n");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("[DoResolve] Exception: " + e.ToString());
            }
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Creates a new CreateFromAuditInfo from given <see cref="auditInfo"/>.
        /// </summary>
        /// <param name="auditInfo">Source <see cref="AuditInfo"/> object</param>
        /// <returns>The <see cref="AuditLog"/> object that is created using <see cref="auditInfo"/></returns>
        //public static AuditLog CreateFromAuditInfo(AuditInfo auditInfo)
        //{
        //    var exceptionMessage = auditInfo.Exception != null ? auditInfo.Exception.ToString() : null;
        //    //var _appsettings = IocManager.Instance.Resolve<AppSettingsCfg>();
        //    return new AuditLog
        //    {
        //        SystemCode = "Stat001",
        //        TenantId = auditInfo.TenantId,
        //        UserId = auditInfo.UserId,
        //        ServiceName = auditInfo.ServiceName.TruncateWithPostfix(MaxServiceNameLength),
        //        MethodName = auditInfo.MethodName.TruncateWithPostfix(MaxMethodNameLength),
        //        Parameters = auditInfo.Parameters.TruncateWithPostfix(MaxParametersLength),
        //        ExecutionTime = auditInfo.ExecutionTime,
        //        ExecutionDuration = auditInfo.ExecutionDuration,
        //        ClientIpAddress = auditInfo.ClientIpAddress.TruncateWithPostfix(MaxClientIpAddressLength),
        //        ClientName = auditInfo.ClientName.TruncateWithPostfix(MaxClientNameLength),
        //        BrowserInfo = auditInfo.BrowserInfo.TruncateWithPostfix(MaxBrowserInfoLength),
        //        Exception = exceptionMessage.TruncateWithPostfix(MaxExceptionLength),
        //        ImpersonatorUserId = auditInfo.ImpersonatorUserId,
        //        ImpersonatorTenantId = auditInfo.ImpersonatorTenantId,
        //        CustomData = auditInfo.CustomData.TruncateWithPostfix(MaxCustomDataLength)
        //    };
        //}

        /// <summary>
        /// 截取指定长度字符串
        /// </summary>
        /// <param name="inputString">要处理的字符串</param>
        /// <param name="len">指定长度</param>
        /// <returns>返回处理后的字符串</returns>
        public string ClipString(string inputString, int len)
        {
            if (string.IsNullOrWhiteSpace(inputString))
            {
                return("");
            }
            bool isShowFix = false;

            if (len % 2 == 1)
            {
                isShowFix = true;
                len--;
            }
            System.Text.ASCIIEncoding ascii = new System.Text.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 (isShowFix && mybyte.Length > len)
            {
                tempString += "…";
            }
            return(tempString);
        }
Ejemplo n.º 44
0
 public void OriginClickHandler(object sender, EventArgs e)
 {
     if (image1 != null)
     {
         Image  image    = new Bitmap(path);
         string make     = null;
         string model    = null;
         string quality  = null;
         string software = null;
         // QView qv = this.WorkItem.SmartParts.AddNew<QView>();
         PropertyItem[]            propItems = image.PropertyItems;
         System.Text.ASCIIEncoding encoding  = new System.Text.ASCIIEncoding();
         try
         {
             make     = encoding.GetString(image.GetPropertyItem(0x010F).Value);
             model    = encoding.GetString(image.GetPropertyItem(0x0110).Value);
             software = encoding.GetString(image.GetPropertyItem(0x0131).Value);
             quality  = encoding.GetString(image.GetPropertyItem(0x5010).Value);
         }catch (Exception) {
         }
         byte[] lumi = image.GetPropertyItem(0x5090).Value;
         byte[] chro = image.GetPropertyItem(0x5091).Value;
         byte[] data = new byte[256];
         Array.Copy(lumi, 0, data, 0, 128);
         Array.Copy(chro, 0, data, 128, 128);
         MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
         for (int i = 0; i < lumi.Length / 2; i++)
         {
             temparr[i] = BitConverter.ToUInt16(lumi, 2 * i);
             // setTable1(qv);
         }
         for (int i = 0; i < chro.Length / 2; i++)
         {
             temparr[i] = BitConverter.ToUInt16(chro, 2 * i);
             //  setTable2(qv);
         }
         byte[] hash        = md5.ComputeHash(data);
         string hashedValue = "";
         foreach (byte b in hash)
         {
             hashedValue += b.ToString("x2");
         }
         // qv.sign1.Text = hashedValue;
         SmartPartInfo spi =
             new SmartPartInfo("Source Detection", "MyOwnDescription");
         //this.WorkItem.Workspaces[WorkspaceNames.TabWorkspace].Show(qv, spi);
         MySQLConnectionTest conn2 = new MySQLConnectionTest();
         conn2.DBSelect(this, hashedValue, software, make, model, quality);
     }
 }
Ejemplo n.º 45
0
 private 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 ApplicationException("ASCII Code is not valid.");
     }
 }
Ejemplo n.º 46
0
        private static DateTime?GetMetadata_TakenDate(HttpPostedFileBase item)
        {
            DateTime?takenDate = null;
            Image    img       = Image.FromStream(item.InputStream);
            //http://msdn.microsoft.com/en-us/library/system.drawing.imaging.propertyitem.id.aspx
            PropertyItem prop = img.PropertyItems.Where(r => r.Id == 306).FirstOrDefault();

            if (prop != null)
            {
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                takenDate = DateTime.Parse(encoding.GetString(prop.Value).Trim('\0').Replace(4, '/').Replace(7, '/'));
            }
            return(takenDate);
        }
Ejemplo n.º 47
0
        public static byte[] EncodeMessage(string content)
        {
            byte[] cont = new byte[content.Length];

            System.Text.ASCIIEncoding coidn = new System.Text.ASCIIEncoding();
            System.Text.Encoder       enc   = coidn.GetEncoder();
            int  charsconv = 0;
            int  bytesconv = 0;
            bool conv      = false;

            enc.Convert(content.ToCharArray(), 0, content.Length, cont, 0, cont.Length, true, out charsconv, out bytesconv, out conv);

            return(cont);
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Convert from a TransportMessage to a MQMessage
        /// </summary>
        /// <param name="transportMessage"></param>
        /// <returns></returns>
        public MQMessage Convert(TransportMessage transportMessage)
        {
            MQMessage           queueMessage           = new MQMessage();
            MQPutMessageOptions queuePutMessageOptions = new MQPutMessageOptions();
            Stream messageStream = new MemoryStream();

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            if (transportMessage.Body == null && transportMessage.BodyStream != null)
            {
                messageStream = transportMessage.BodyStream;
            }
            else
            {
                // convert the message body to a stream
                this.messageSerializer.Serialize(transportMessage.Body, messageStream);
            }

            //write content to the message
            StreamReader sr = new StreamReader(messageStream);

            messageStream.Position = 0;
            queueMessage.WriteString(sr.ReadToEnd());
            queueMessage.Format = MQC.MQFMT_STRING;

            if (transportMessage.CorrelationId != null)
            {
                queueMessage.GroupId = encoding.GetBytes(transportMessage.CorrelationId);
            }

            //TODO Set the recoverable and response queue on the message being sent
            //toSend.Recoverable = m.Recoverable;
            //toSend.ResponseQueue = new MessageQueue(GetFullPath(m.ReturnAddress));
            queueMessage.ReplyToQueueName = transportMessage.ReturnAddress;
            FillApplicationIdData(queueMessage, transportMessage);

            //TODO Can we set the timeout on a message being sent?
            //if (m.TimeToBeReceived < MessageQueue.InfiniteTimeout)
            //    toSend.TimeToBeReceived = m.TimeToBeReceived;

            //TODO How can we pass header information on the message
            //if (m.Headers != null && m.Headers.Count > 0)
            //{
            //    MemoryStream stream = new MemoryStream();
            //    headerSerializer.Serialize(stream, m.Headers);
            //    toSend.Extension = stream.GetBuffer();
            //}

            return(queueMessage);
        }
        public static string sign(string Attributes, string Hash_Method = "MD5")
        {
            // Check for valid session

            string Signature = "error";

            if ((Attributes != null) && !string.IsNullOrEmpty(Attributes))
            {
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] keyByte      = encoding.GetBytes(key);
                byte[] messageBytes = encoding.GetBytes(Attributes);
                byte[] hashmessage;

                try
                {
                    switch ((Hash_Method).ToUpper())
                    {
                    case "SHA1":
                        hashmessage = null;
                        Signature   = null;
                        HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
                        hashmessage = hmacsha1.ComputeHash(messageBytes);
                        Signature   = ByteToString(hashmessage);
                        break;

                    case "SHA256":
                        hashmessage = null;
                        Signature   = null;
                        HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
                        hashmessage = hmacsha256.ComputeHash(messageBytes);
                        Signature   = ByteToString(hashmessage);
                        break;

                    default:
                    case "MD5":
                        hashmessage = null;
                        Signature   = null;
                        HMACMD5 hmacmd5 = new HMACMD5(keyByte);
                        hashmessage = hmacmd5.ComputeHash(messageBytes);
                        Signature   = ByteToString(hashmessage);
                        break;
                    }
                }
                catch (Exception e)
                {
                    return(e.Message);
                }
            }
            return(Signature);
        }
Ejemplo n.º 50
0
 /// <summary>
 /// int转Ascll字符
 /// </summary>
 /// <param name="ascllCode"></param>
 /// <returns></returns>
 public static string ToAscllStr(this int ascllCode)
 {
     if (ascllCode >= 0 && ascllCode <= 255)
     {
         System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
         byte[] byteArray    = new byte[] { (byte)ascllCode };
         string strCharacter = asciiEncoding.GetString(byteArray);
         return(strCharacter);
     }
     else
     {
         throw new Exception("ASCII Code is not valid.");
     }
 }
Ejemplo n.º 51
0
        private void Init()
        {
            byte[] buf = new byte[1500];
            string rec_buffer;

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            UdpClient  listener = new UdpClient(1025);
            IPEndPoint groupEP  = new IPEndPoint(IPAddress.Any, 1025);

            buf        = listener.Receive(ref groupEP);
            rec_buffer = encoding.GetString(buf);
            richTextBox1.AppendText(rec_buffer);
        }
Ejemplo n.º 52
0
        protected override string GetContentFromStreamReader(string filePath)
        {
            //return base.GetContentFromStreamReader(filePath);
            SystemLogger.Log(SystemLogger.Module.PLATFORM, "# IPhoneResourceHandler. Getting Content From StreamReader on file path: " + filePath);

            Stream sr = IPhoneUtils.GetInstance().GetResourceAsStream(filePath);

            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            string content = enc.GetString(((MemoryStream)sr).GetBuffer());

            sr.Close();

            return(content);
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Base64s the encode.
        /// </summary>
        /// <returns>The encode.</returns>
        /// <param name="http_user">Http_user.</param>
        /// <param name="http_pw">Http_pw.</param>
        public string base64Encode(string http_user, string http_pw)
        {
            //zum testen
            //http_user = "******";
            //http_pw = "scdsoft1";

            string user_pw = http_user + ":" + http_pw;

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] bytes  = encoding.GetBytes(user_pw);
            string base64 = System.Convert.ToBase64String(bytes);

            return("Basic " + base64);
        }
Ejemplo n.º 54
0
        public bool WriteStr(string src)
        {
            if (locked || !m_data.CanWrite)
            {
                return(false);
            }

            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

            byte[] i = enc.GetBytes(src);
            m_data.Write(i, (int)m_data.Position, src.Length);

            return(true);
        }
Ejemplo n.º 55
0
        public void AppendID3(System.IO.FileStream Stream)
        {
            //Blank string, used to prevent substring from running out of index
            System.String BlankString = "                                ";

            //Getting values
            System.String Title   = LastManager.RemoveIllegalChars(this._Track) + BlankString;
            System.String Artist  = LastManager.RemoveIllegalChars(this._Artist) + BlankString;
            System.String Album   = LastManager.RemoveIllegalChars(this._Album) + BlankString;
            System.String Year    = "0000" + BlankString;
            System.String Comment = "Last.FM by TheLastRipper." + BlankString;

            //Settings max length
            Title   = Title.Substring(0, 30);
            Artist  = Artist.Substring(0, 30).Trim();
            Album   = Album.Substring(0, 30).Trim();
            Year    = Year.Substring(0, 4).Trim();
            Comment = Comment.Substring(0, 28).Trim();

            System.Byte[] TagArray = new System.Byte[128];
            for (int i = 0; i < TagArray.Length; i++)
            {
                TagArray[i] = 0;
            }

            //Get encoder
            System.Text.Encoding Coder = new System.Text.ASCIIEncoding();

            //Get the bytes
            System.Byte[] Buffer = Coder.GetBytes("TAG");
            System.Array.Copy(Buffer, 0, TagArray, 0, Buffer.Length);
            Buffer = Coder.GetBytes(Title);
            System.Array.Copy(Buffer, 0, TagArray, 3, Buffer.Length);
            Buffer = Coder.GetBytes(Artist);
            System.Array.Copy(Buffer, 0, TagArray, 33, Buffer.Length);
            Buffer = Coder.GetBytes(Album);
            System.Array.Copy(Buffer, 0, TagArray, 63, Buffer.Length);
            Buffer = Coder.GetBytes(Year);
            System.Array.Copy(Buffer, 0, TagArray, 93, Buffer.Length);
            Buffer = Coder.GetBytes(Comment);
            System.Array.Copy(Buffer, 0, TagArray, 97, Buffer.Length);

            //Set Track number to 0, and genre to other
            TagArray[126] = System.Convert.ToByte(0);
            TagArray[127] = System.Convert.ToByte(12);

            //Write data to end of stream
            Stream.Seek(0, System.IO.SeekOrigin.End);
            Stream.Write(TagArray, 0, 128);
        }
Ejemplo n.º 56
0
        private static string CreateToken(string message, string secret)
        {
            // don't allow null secrets
            secret = secret ?? "";
            var encoding     = new System.Text.ASCIIEncoding();
            var keyByte      = encoding.GetBytes(secret);
            var messageBytes = encoding.GetBytes(message);

            using (var hmacsha256 = new System.Security.Cryptography.HMACSHA256(keyByte))
            {
                var hashmessage = hmacsha256.ComputeHash(messageBytes);
                return(Convert.ToBase64String(hashmessage));
            }
        }
Ejemplo n.º 57
0
        /// <summary>
        /// ToAsc 字符串转换为 ASCII
        /// </summary>
        /// <param name="character">character 字符码</param>
        /// <returns>returns ASCII数值</returns>
        public static int ToAsc(string character)
        {
            if (character.Length == 1)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];

                return(intAsciiCode);
            }
            else
            {
                return(0);
            }
        }
Ejemplo n.º 58
0
        void SendRequest(RequestCommand command)
        {
            writeBuffer[0] = (byte)command;
            int    requestLength   = 1;
            string requestCommands = "";

            if (gearDirectionRequested)
            {
                requestCommands       += "g:" + (int)gearDirectionRequest + ";";
                gearDirectionRequested = false;
            }
            if (steeringAngleRequested)
            {
                requestCommands       += "s:" + steeringAngleRequest + ";";
                steeringAngleRequested = false;
            }
            if (throttleRequested)
            {
                requestCommands  += "t:" + throttleRequest + ";";
                throttleRequested = false;
            }
            if (brakeRequested)
            {
                requestCommands += "b:" + brakeRequest + ";";
                brakeRequested   = false;
            }
            if (turnSinalRequested)
            {
                requestCommands   += "ts:" + (int)turnSignalRequest + ";";
                turnSinalRequested = false;
            }

            if (requestCommands.Length > 0)
            {
                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                byte[] b = enc.GetBytes(requestCommands);

                System.Buffer.BlockCopy(b, 0, writeBuffer, 1, b.Length);

                requestLength += b.Length;
            }

            clientSocket.BeginSend(writeBuffer, 0, requestLength, SocketFlags.None, EndSend, writeBuffer);

            if (command == RequestCommand.VehicleType)
            {
                BeginReceiveData();
            }
        }
Ejemplo n.º 59
0
        private void changePictureNameByDateShot2()
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            foreach (string fn in listView_SelectedFiles.Items)
            {
                string on = Path.Combine(dir, fn);
                string t,
                       exifDTOrig = "",
                       dateTime   = "";
                try
                {
                    using (var image = System.Drawing.Image.FromFile(on))
                    {
                        foreach (var pi in image.PropertyItems)
                        {
                            if (pi.Id == 0x0132)
                            {
                                dateTime = encoding.GetString(pi.Value);
                            }
                            if (pi.Id == 0x9003)
                            {
                                exifDTOrig = encoding.GetString(pi.Value);
                                break;
                            }
                        }
                    }
                }
                catch
                {
                    continue;
                }
                if (exifDTOrig != "")
                {
                    t = exifDTOrig;
                }
                else
                {
                    t = dateTime;
                }
                t = t.Substring(0, 19);
                DateTime date = DateTime.ParseExact(t, "yyyy:MM:dd hh:mm:ss",
                                                    CultureInfo.InvariantCulture);

                var    d = date.ToString("MM.dd-");
                string nn;
                nn = d + fn;
                File.Move(on, Path.Combine(dir, nn));
            }
        }
        public void threadRead()
        {
            uint uBytesRead = 0;

            byte [] byData = new byte[100];
            System.Text.ASCIIEncoding asciiEncoder = new System.Text.ASCIIEncoding();

            try
            {
                PurgeComm(m_hCOMPort, PURGE_RXCLEAR);
                while (!m_bClose)                 //close thread
                {
                    if (ReadFile(m_hCOMPort, byData, 20, ref uBytesRead, IntPtr.Zero))
                    {
                        if (uBytesRead > 0 && m_bClose == false)
                        {
                            string sData = asciiEncoder.GetString(byData, 0, (int)uBytesRead);
                            m_GpsTracker.COMCallback(m_iIndex, sData);

                            try
                            {
                                if (m_GpsTracker.m_MessageMonitor != null)
                                {
                                    m_GpsTracker.m_MessageMonitor.AddMessageCOMRaw(sData);
                                }
                            }
                            catch (Exception)
                            {
                                m_GpsTracker.m_MessageMonitor = null;
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(50);
                        if (GetLastError() == ERROR_OPERATION_ABORTED)
                        {
                            uint    uxErrors = 0;
                            COMSTAT xstat    = new COMSTAT();
                            ClearCommError(m_hCOMPort, ref uxErrors, ref xstat);
                            PurgeComm(m_hCOMPort, PURGE_RXCLEAR);
                        }
                    }
                }                 //while
            }
            catch (Exception)
            {
            }
        }