Beispiel #1
0
        public void PushFile(byte[] data, string entryName, DataMode dataMode)
        {
            var file = GetFreePushFileName();

            File.WriteAllBytes(file, data);
            InternalPushFile(file, entryName, dataMode, false);
        }
Beispiel #2
0
 private void rbGateHex_CheckedChanged(object sender, EventArgs e)
 {
     if (rbGateHex.Checked)
     {
         CurrentGateDataMode = DataMode.Hex;
     }
 }
Beispiel #3
0
        public IBuffer AsBuffer(String MACAddress, DataMode DataMode)
        {
            Byte[] buffer = new Byte[20];

            // copiamos el entero del uid a los cuatro primeros
            Array.Copy(BitConverter.GetBytes(this.uid), buffer, 4);
            buffer[4] = (byte)(male ? 1 : 0);
            buffer[5] = this.age;
            buffer[6] = this.height;
            buffer[7] = this.weight;
            buffer[8] = (byte)DataMode;
            Array.Copy(Encoding.UTF8.GetBytes(this.alias), 0, buffer, 9, this.alias.Length);

            Byte[] crcBuffer = new Byte[19];
            Array.Copy(buffer, crcBuffer, 19);
            Int32 CRC = crc(crcBuffer);

            string macEnd  = MACAddress.Substring(MACAddress.Length - 2, 2);
            Int16  crcaddr = Int16.Parse(macEnd, System.Globalization.NumberStyles.HexNumber);

            CRC        = (CRC ^ crcaddr) & 0xFF;
            buffer[19] = (byte)CRC;

            return(buffer.AsBuffer());
        }
Beispiel #4
0
        static DependencyResolver()
        {
            var dataReadConfig = DataMode.GetLogic("DataMode");

            switch (dataReadConfig)
            {
            case "XML":
                UserDAO  = new UserXmlDAO();
                AwardDAO = new AwardXMLDAO();
                break;

            case "Memory":
                UserDAO  = new UserFakeDAO();
                AwardDAO = new AwardFakeDAO();
                break;

            case "DB":
                UserDAO  = new UserDbDAO();
                AwardDAO = new AwardDbDAO();
                break;

            default:
                UserDAO  = new UserFakeDAO();
                AwardDAO = new AwardFakeDAO();
                break;
            }
            AuthUserDAO = new AuthUserDAO();
        }
 private void OptionTextCheckedChanged(object sender, EventArgs e)
 {
     if (this.dataModeOptionText.Checked)
     {
         this.CurrentDataMode = DataMode.Text;
     }
 }
 public ExportTypeAttribute(Type @from, CreateAs createAs = CreateAs.Default, DataMode datamode = Bootstrap.DataMode.Any, string name = null)
 {
     _from     = @from;
     _createAs = createAs;
     _dataMode = datamode;
     _name     = name;
 }
Beispiel #7
0
        public void SendData(DataMode CurrentDataMode, SerialPort comport, string txtSendDataText, TextBox txtSendData, RichTextBox rtfTerminal)
        {
            if (CurrentDataMode == DataMode.Text)
            {
                // Send the user's text straight out the port
                comport.Write(txtSendDataText);

                // Show in the terminal window the user's text
                Log(rtfTerminal, LogMsgType.Outgoing, txtSendDataText + "\n");
            }
            else
            {
                try
                {
                    // Convert the user's string of hex digits (ex: B4 CA E2) to a byte array
                    byte[] data = HexStringToByteArray(txtSendDataText);

                    // Send the binary data out the port
                    comport.Write(data, 0, data.Length);

                    // Show the hex digits on in the terminal window
                    Log(rtfTerminal, LogMsgType.Outgoing, ByteArrayToHexString(data) + "\n");
                }
                catch (FormatException)
                {
                    // Inform the user if the hex string was not properly formatted
                    Log(rtfTerminal, LogMsgType.Error, "Not properly formatted hex string: " + txtSendDataText + "\n");
                }
            }
            txtSendData.SelectAll();
        }
 private void OptionHexCheckedChanged(object sender, EventArgs e)
 {
     if (this.dataModeOptionHex.Checked)
     {
         this.CurrentDataMode = DataMode.Hex;
     }
 }
Beispiel #9
0
        protected string GetEditUrl(object container)
        {
            MetricTrac.Bll.MetricValue.Extend val = GetValue(container);
            int BackPageIndex = 4;

            switch (DataMode)
            {
            case Mode.Input:
                BackPageIndex = 3;
                break;

            case Mode.View:
                BackPageIndex = 4;
                break;

            case Mode.Approve:
                BackPageIndex = 5;
                break;

            default:
                BackPageIndex = 4;
                break;
            }
            return("MetricInputEdit.aspx?MetricID=" + val.MetricID +
                   "&Date=" + val.Date.ToString("MM-dd-yyyy") +
                   "&OrgLocationID=" + LastMetricMetricValue.OrgLocationID +
                   "&Mode=" + DataMode.ToString() +
                   "&BackPage=" + BackPageIndex.ToString());
        }
Beispiel #10
0
        protected string GetEditUrl(object container)
        {
            System.Web.UI.WebControls.RepeaterItem ri  = container as System.Web.UI.WebControls.RepeaterItem;
            MetricTrac.Bll.MetricValue.Extend      val = ri.DataItem as MetricTrac.Bll.MetricValue.Extend;
            int BackPageIndex = 1;

            switch (DataMode)
            {
            case Mode.Input:
                BackPageIndex = 1;
                break;

            case Mode.Approve:
                BackPageIndex = 2;
                break;

            default:
                BackPageIndex = 1;
                break;
            }
            return("MetricInputEdit.aspx?MetricID=" + val.MetricID +
                   "&Date=" + val.Date.ToString("MM-dd-yyyy") +
                   "&OrgLocationID=" + LastMetricMetricValue.OrgLocationID +
                   "&Mode=" + DataMode.ToString() +
                   "&BulkEdit=True" +
                   "&BackPage=" + BackPageIndex.ToString());
        }
Beispiel #11
0
 private void rbGateText_CheckedChanged(object sender, EventArgs e)
 {
     if (rbGateText.Checked)
     {
         CurrentGateDataMode = DataMode.Text;
     }
 }
Beispiel #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encoding"></param>
        /// <param name="dataMode"></param>
        /// <returns></returns>
        protected byte[] StringToBytes(string str, Encoding encoding, DataMode dataMode)
        {
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            byte[] byteArray = new byte[0];
            switch (dataMode)
            {
            case DataMode.Plain:
                byteArray = encoding.GetBytes(str);
                break;

            case DataMode.Hex:
                byteArray = HexEncoding.GetBytes(str);
                break;

            case DataMode.Base64:
                byteArray = Convert.FromBase64String(str);
                break;
            }

            return(byteArray);
        }
Beispiel #13
0
 /// <summary>
 /// 校验加密算法数据模式。
 /// </summary>
 /// <param name="dataMode"></param>
 protected void ValidateDataMode(DataMode dataMode)
 {
     if (!AvailableDataModes.Contains(dataMode))
     {
         throw new NotSupportedException(string.Format("DataMode {0} & CrytoAlgorithm {1} not support!", dataMode.ToString(), CryptoAlgorithm.ToString()));
     }
 }
        public DataBlock ReadDataBlock(int index, DataMode mode)
        {
            DataBlock dataBlock = new DataBlock();

            dataBlock.GroupMode = new List <int>();
            byte[] bytes = new byte[Constant.Constant.Blocksize];
            //读取数据块
            fileStream = _diskConnectService.GetFileStream();
            fileStream.Seek(
                Constant.Constant.Datastart + Constant.Constant.Blocksize * index,
                SeekOrigin.Begin
                );
            fileStream.Read(bytes, 0, Constant.Constant.Blocksize);
            fileStream.Close();
            dataBlock.Bytes = bytes.ToList();
            //组长块转换
            if (mode == DataMode.Group)
            {
                for (int i = 0; i < Constant.Constant.Blocksize; i += 4)
                {
                    dataBlock.GroupMode.Add(BitConverter.ToInt32(bytes, i));
                }
            }
            return(dataBlock);
        }
Beispiel #15
0
    public void Load()
    {
        Debug.Log("After Load Data :" + jsonGameMode);
        dataGameModes.Clear();


        if (!string.IsNullOrEmpty(jsonGameMode))
        {
            DataMode[] datas = JsonArray.FromJson <DataMode>(jsonGameMode);
            for (int i = 0; i < datas.Length; i++)
            {
                dataGameModes.Add(datas[i]);
            }
        }
        else
        {
            foreach (var enumValue in Enum.GetValues(typeof(DataGameMode)))
            {
                DataMode mode = new DataMode();
                mode.dataGameMode = (DataGameMode)enumValue;
                mode.bestScore    = 0;
                mode.currentScore = 0;
                dataGameModes.Add(mode);
            }
            Save();
        }
    }
Beispiel #16
0
        public void PushFile(string fileName, string entryName, DataMode dataMode)
        {
            var file = GetFreePushFileName();

            File.Copy(fileName, file);
            InternalPushFile(file, entryName, dataMode, false);
        }
Beispiel #17
0
        private T getArray <T>()
        {
            if (DataMode != RhspDataMode.Array)
            {
                throw new RhspException(
                          "Cannot get array data when mode is " + DataMode.ToString() + ".");
            }

            if (RawData != null)
            {
                return((T)(object)RawData.Cast(typeof(T).GetElementType()));

                //return (T)(object)createArray(typeof(T).GetElementType(), RawData);

                //List<T> list = new List<T>();
                //foreach (object o in RawData)
                //{
                //    list.Add((T)o);
                //}
                //return list.ToArray();
            }
            else
            {
                return((T)(object)(new T[0]));
            }
        }
Beispiel #18
0
 private static void PassiveModeWriter(DataMode processMode, StreamWriter sw, string output)
 {
     if (processMode == DataMode.Passive)
     {
         sw.WriteLine(output);
     }
 }
Beispiel #19
0
 private void rbHex_Checked(object sender, RoutedEventArgs e)
 {
     if (rbHex.IsChecked == true)
     {
         CurrentDataMode = DataMode.Hex;
     }
 }
Beispiel #20
0
        private static void FixedWidthSortMurgePurge <T>(string dbConnPath, string line,
                                                         MasterFixedWidthFileSource <T> master,
                                                         DelimitedFileSource <T> detail,
                                                         MergePurgeParam mgPurgeParam,
                                                         Action <MergePurgeParam> processData,
                                                         MergePurgeResults mgPurgeResults,
                                                         DataMode processMode,
                                                         StreamWriter[] actionWriters)
        {
            SortKey <T> srtKey = null;

            using (SqliteRepository <T> sqlRepo = new SqliteRepository <T>(dbConnPath))
            {
                srtKey = sqlRepo.KeyInDb(detail.GetKey(mgPurgeParam.DetailFields, line));
            }
            mgPurgeParam.KeyFound = srtKey.Found;
            string masterData = !srtKey.Found ? string.Empty : srtKey.Data;

            if (mgPurgeParam.KeyFound)
            {
                mgPurgeParam.MasterFields = GetMasterFields <T>(master, masterData);
            }
            if (processData != null)
            {
                processData(mgPurgeParam);
                mgPurgeResults.IncrementAction(mpAction: mgPurgeParam.DataAction);
                string detailLine    = GetDetailLine <T>(detail, mgPurgeParam);
                string newMasterData = GetNewMasterDataFixedWidth(GetMasterLine <T>(master, mgPurgeParam));
                PerformDataActionForPassiveModeWriter(mgPurgeParam.DataAction, mgPurgeParam.KeyFound, processMode, detailLine, actionWriters);
                PerformDataAction(mgPurgeParam, dbConnPath, processMode, newMasterData, srtKey);
            }
        }
Beispiel #21
0
        private void SearchClick(object sender, RoutedEventArgs e)
        {
            Address address;

            try
            {
                address = Storage.Retrieve(IndexSearch.Text);
            }
            catch (KeyNotFoundException knfe)
            {
                return;
            }

            if (CurrentData != DataMode.Pages)
            {
                CurrentData = DataMode.Pages;
                Transitioner.SelectedIndex = 0;
            }

            var page = Pages[address.Page];

            foreach (var word in page)
            {
                if (String.Equals(word.Text, IndexSearch.Text, StringComparison.CurrentCultureIgnoreCase))
                {
                    PageDataGrid.ScrollIntoView(word);
                }
            }
        }
Beispiel #22
0
 private void rbText_Checked(object sender, RoutedEventArgs e)
 {
     if (rbText.IsChecked == true)
     {
         CurrentDataMode = DataMode.Text;
     }
 }
Beispiel #23
0
    public void OnAddOrEraseDropDownChanged()
    {
        int val     = AddOrErseDropdown.value;
        int curMode = (int)dataMode;

        dataMode = (DataMode)(curMode / 2 * 2 + val);
    }
Beispiel #24
0
 public override string DoEncrypt(string plainText, string key, Encoding encoding, DataMode encryptedType)
 {
     byte[] bytes = Encoding.Unicode.GetBytes(plainText);
     RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
     provider.FromXmlString(this.rsaKey);
     byte[] inArray = provider.Encrypt(bytes, false);
     return Convert.ToBase64String(inArray, 0, inArray.Length);
 }
Beispiel #25
0
 public override string DoDecrypt(string encryptedText, string key, Encoding encoding, DataMode encryptedType)
 {
     byte[] rgb = Convert.FromBase64String(encryptedText);
     RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
     provider.FromXmlString(this.rsaKey);
     byte[] bytes = provider.Decrypt(rgb, false);
     return Encoding.Unicode.GetString(bytes);
 }
        public override string DoEncrypt(string plainText, Encoding encoding, DataMode encryptedType)
        {
            AssertUtils.ArgumentNotNull("encoding", encoding);

            byte[] data = encoding.GetBytes(plainText);
            byte[] result = new SHA1CryptoServiceProvider().ComputeHash(data);
            return BytesToString(result, encoding, encryptedType);
        }
        public override string DoEncrypt(string plainText, Encoding encoding, DataMode encryptedType)
        {
            AssertUtils.ArgumentNotNull("encoding", encoding);

            byte[] data   = encoding.GetBytes(plainText);
            byte[] result = new SHA1CryptoServiceProvider().ComputeHash(data);
            return(BytesToString(result, encoding, encryptedType));
        }
Beispiel #28
0
        public void PushData(CsvFile csvFile, string entryName, DataMode dataMode)
        {
            var file = GetFreePushFileName();

            using (var csvWriter = new CsvWriter())
                csvWriter.WriteCsv(csvFile, file, Encoding.UTF8);
            InternalPushFile(file, entryName, dataMode, true);
        }
Beispiel #29
0
 /// <summary>
 /// Constructor of the class used during binary data extraction
 /// </summary>
 /// <param name="topicOffset">offset of the associated topic entry</param>
 /// <param name="ImageIndex">image index to use</param>
 /// <param name="associatedFile">associated chm file</param>
 public TOCItem(int topicOffset, int ImageIndex, CHMFile associatedFile)
 {
     _tocMode        = DataMode.Binary;
     _associatedFile = associatedFile;
     _chmFile        = associatedFile.ChmFilePath;
     _topicOffset    = topicOffset;
     _imageIndex     = ImageIndex;
 }
Beispiel #30
0
 /// <summary>
 /// Constructor of the class used during text-based data extraction
 /// </summary>
 /// <param name="name">name of the item</param>
 /// <param name="local">local content file</param>
 /// <param name="ImageIndex">image index</param>
 /// <param name="chmFile">associated chm file</param>
 public TOCItem(string name, string local, int ImageIndex, string chmFile)
 {
     _tocMode    = DataMode.TextBased;
     _name       = name;
     _local      = local;
     _imageIndex = ImageIndex;
     _chmFile    = chmFile;
 }
 /// <summary>
 /// Constructor of the class
 /// </summary>
 /// <param name="Title">topic title</param>
 /// <param name="local">topic local (content filename)</param>
 /// <param name="compilefile">name of the chm file (location of topic)</param>
 /// <param name="chmpath">path of the chm file</param>
 public IndexTopic(string Title, string local, string compilefile, string chmpath)
 {
     _topicMode   = DataMode.TextBased;
     _title       = Title;
     _local       = local;
     _compileFile = compilefile;
     _chmPath     = chmpath;
 }
Beispiel #32
0
        public void WriteCppFile(DataMode mode, string outputCppFile)
        {
            var partials = RenderedTable.Length;
            var tableCount = RenderedTable[0].Length;
            var tableSize = RenderedTable[0][0].Length;
            var dataType = mode == DataMode.Bytes ? "char" : "float";

            var cppFile = outputCppFile;
            if (!cppFile.EndsWith(".cpp")) cppFile += ".cpp";
            var hppFile = cppFile.Substring(0, cppFile.Length - 3) + "h";
            var hppFilename = Path.GetFileName(hppFile);

            // Write header
            var hppFileData = new StringBuilder();
            hppFileData.AppendLine($"const int {TableName}WavetablePartials = {partials};");
            hppFileData.AppendLine($"const int {TableName}WavetableCount = {tableCount};");
            hppFileData.AppendLine($"const int {TableName}WavetableSize = {tableSize};");
            hppFileData.AppendLine("");
            hppFileData.AppendLine($"extern {dataType} {TableName}WavetableData[{TableName}WavetablePartials][{TableName}WavetableCount][{TableName}WavetableSize];");
            hppFileData.AppendLine("");
            File.WriteAllText(hppFile, hppFileData.ToString());

            Func<float, string> format = number =>
            {
                if (mode == DataMode.Bytes)
                {
                    var value = (int)(number * 127.999);
                    return value.ToString();
                }
                else
                {
                    return number.ToString();
                }
            };

            var data = new StringBuilder();
            foreach (var partial in RenderedTable)
            {
                data.AppendLine("\t{");
                foreach (var table in partial)
                {
                    var tableData = string.Join(", ", table.Select(format));
                    data.AppendLine("\t\t{ " + tableData + " },");
                }
                data.AppendLine("\t},");
            }

            // Write main
            var cppFileData = new StringBuilder();
            cppFileData.AppendLine($"#include \"{hppFilename}\"");
            cppFileData.AppendLine("");
            cppFileData.AppendLine($"{dataType} {TableName}WavetableData[{TableName}WavetablePartials][{TableName}WavetableCount][{TableName}WavetableSize] =");
            cppFileData.AppendLine("{");
            cppFileData.AppendLine(data.ToString());
            cppFileData.AppendLine("};");
            cppFileData.AppendLine("");
            File.WriteAllText(cppFile, cppFileData.ToString());
        }
Beispiel #33
0
        /// <summary>
        /// Set the server to Binary mode.
        /// </summary>
        /// <returns>A server message in response to this action.</returns>
        private ServerMessage Binary()
        {
            //Send TYPE I
            SendCmd("TYPE", "I");
            ServerMessage reply = cmdCon.ReadMessage();

            DatMode = DataMode.Binary;
            Console.WriteLine("Switching to Binary mode.");
            return(reply);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="plainText"></param>
        /// <param name="key"></param>
        /// <param name="encoding"></param>
        /// <param name="encryptedType"></param>
        /// <returns></returns>
        public override string DoEncrypt(string plainText, string key, Encoding encoding, DataMode encryptedType)
        {
            byte[] keyByte = encoding.GetBytes(key);
            HMACMD5 hmacMD5 = new HMACMD5(keyByte);

            byte[] messageBytes = encoding.GetBytes(plainText);
            byte[] hashMessage = hmacMD5.ComputeHash(messageBytes);

            return BytesToString(hashMessage, encoding, encryptedType);
        }
Beispiel #35
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="encryptedText"></param>
        /// <param name="key"></param>
        /// <param name="encoding"></param>
        /// <param name="dataMode"></param>
        /// <returns></returns>
        public string Decrypt(string encryptedText, string key, Encoding encoding, DataMode dataMode)
        {
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            ValidateDataMode(dataMode);
            return(DoDecrypt(encryptedText, key, encoding, dataMode));
        }
Beispiel #36
0
 // Methods
 public override string DoEncrypt(string plainText, string key, Encoding encoding, DataMode encryptedType)
 {
     MemoryStream stream = new MemoryStream(200);
     stream.SetLength(0L);
     byte[] bytes = Encoding.Unicode.GetBytes(plainText);
     RC2 rc = new RC2CryptoServiceProvider();
     CryptoStream stream2 = new CryptoStream(stream, rc.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
     stream2.Write(bytes, 0, bytes.Length);
     stream2.FlushFinalBlock();
     stream.Flush();
     stream.Seek(0L, SeekOrigin.Begin);
     byte[] buffer = new byte[stream.Length];
     stream.Read(buffer, 0, buffer.Length);
     stream2.Close();
     stream.Close();
     return Convert.ToBase64String(buffer, 0, buffer.Length);
 }
Beispiel #37
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="encryptedText"></param>
 /// <param name="key"></param>
 /// <param name="encoding"></param>
 /// <param name="encryptedType"></param>
 /// <returns></returns>
 public override string DoDecrypt(string encryptedText, string key, Encoding encoding, DataMode encryptedType)
 {
     MemoryStream stream = new MemoryStream(200);
     stream.SetLength(0L);
     byte[] buffer = Convert.FromBase64String(encryptedText);
     RC2 rc = new RC2CryptoServiceProvider();
     rc.KeySize = 0x40;
     CryptoStream stream2 = new CryptoStream(stream, rc.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
     stream2.Write(buffer, 0, buffer.Length);
     stream2.FlushFinalBlock();
     stream.Flush();
     stream.Seek(0L, SeekOrigin.Begin);
     byte[] buffer2 = new byte[stream.Length];
     stream.Read(buffer2, 0, buffer2.Length);
     stream2.Close();
     stream.Close();
     return Encoding.Unicode.GetString(buffer2);
 }
Beispiel #38
0
 /// <summary>
 /// Constructor. Initailise an Lcd object to drive an HD44780 display in 8 bit mode.
 /// </summary>
 /// <param name="device">Type of device to be driven.</param>
 /// <param name="rs">GPIO pin connected to the LCD register select pin.</param>
 /// <param name="e">GPIO pin connected to the LCD enable pin.</param>
 /// <param name="d0">GPIO pin connected to the LCD D0 pin.</param>
 /// <param name="d1">GPIO pin connected to the LCD D1 pin.</param>
 /// <param name="d2">GPIO pin connected to the LCD D2 pin.</param>
 /// <param name="d3">GPIO pin connected to the LCD D3 pin.</param>
 /// <param name="d4">GPIO pin connected to the LCD D4 pin.</param>
 /// <param name="d5">GPIO pin connected to the LCD D5 pin.</param>
 /// <param name="d6">GPIO pin connected to the LCD D6 pin.</param>
 /// <param name="d7">GPIO pin connected to the LCD D7 pin.</param>
 public Lcd(
     Device device,
     Cpu.Pin rs, Cpu.Pin e,
     Cpu.Pin d0, Cpu.Pin d1, Cpu.Pin d2, Cpu.Pin d3, Cpu.Pin d4, Cpu.Pin d5, Cpu.Pin d6, Cpu.Pin d7)
 {
     this.device = device;
     this.rs = new OutputPort(rs, false);
     this.e = new OutputPort(e, false);
     this.d0 = new OutputPort(d0, false);
     this.d1 = new OutputPort(d1, false);
     this.d2 = new OutputPort(d2, false);
     this.d3 = new OutputPort(d3, false);
     this.d4 = new OutputPort(d4, false);
     this.d5 = new OutputPort(d5, false);
     this.d6 = new OutputPort(d6, false);
     this.d7 = new OutputPort(d7, false);
     dataMode = DataMode.EightBit;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="encryptedText"></param>
        /// <param name="key"></param>
        /// <param name="encoding"></param>
        /// <param name="encryptedType"></param>
        /// <returns></returns>
        public override string DoDecrypt(string encryptedText, string key, Encoding encoding, DataMode encryptedType)
        {
            TripleDES tripleDes = new TripleDESCryptoServiceProvider();
            tripleDes.Key = StringToByte(publicKey, 24);
            tripleDes.IV = StringToByte(key, 8);
            byte[] desKey = tripleDes.Key;
            byte[] desIV = tripleDes.IV;

            ICryptoTransform decryptor = tripleDes.CreateDecryptor(desKey, desIV);

            string decryptedString = string.Empty;
            byte[] encryptedBytes = StringToBytes(encryptedText, encoding, encryptedType);
            using (MemoryStream msDecrypt = new MemoryStream(encryptedBytes))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    decryptedString = BytesToString(csDecrypt, encoding);
                }
            }

            return decryptedString;
        }
Beispiel #40
0
 private void rbText_CheckedChanged(object sender, EventArgs e)
 { 
     if (rbText.Checked) 
         CurrentDataMode = DataMode.Text; 
 }
Beispiel #41
0
 private void rbHex_CheckedChanged(object sender, EventArgs e)
 {
     if (rbHex.Checked) 
         CurrentDataMode = DataMode.Hex; 
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="plainText"></param>
        /// <param name="encoding"></param>
        /// <param name="dataMode"></param>
        /// <returns></returns>
        public string Encrypt(string plainText, Encoding encoding, DataMode dataMode)
        {
            ValidateDataMode(dataMode);

            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            return DoEncrypt(plainText, encoding, dataMode);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="plainText"></param>
 /// <param name="encryptedType"></param>
 /// <returns></returns>
 public string Encrypt(string plainText, DataMode encryptedType)
 {
     return Encrypt(plainText, Encoding.UTF8, encryptedType);
 }
 public override string DoEncrypt(string plainText, string key, Encoding encoding, DataMode encryptedType)
 {
     throw new NotSupportedException();
 }
        /// <summary>
        /// 把字节数组转换成字符串。
        /// </summary>
        /// <param name="buff">要转换的字节数组。</param>
        /// <param name="encoding">编码类型。</param>
        /// <param name="dataMode"></param>
        protected string BytesToString(byte[] buff,  Encoding encoding, DataMode dataMode)
        {
            string bytesString = string.Empty;
            switch (dataMode)
            {
                case DataMode.Plain:
                    bytesString = encoding.GetString(buff);
                    break;
                case DataMode.Hex:
                    bytesString = HexEncoding.ToString(buff);
                    break;
                case DataMode.Base64:
                    bytesString = Convert.ToBase64String(buff);
                    break;
            }

            return bytesString;
        }
        /// <summary> Populate the form's controls with default settings. </summary>
        private void InitializeControlValues()
        {
            cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
            cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));

            cmbParity.Text = Settings.Default.Parity.ToString();
            cmbStopBits.Text = Settings.Default.StopBits.ToString();
            cmbDataBits.Text = Settings.Default.DataBits.ToString();
            cmbParity.Text = Settings.Default.Parity.ToString();
            cmbBaudRate.Text = Settings.Default.BaudRate.ToString();
            CurrentDataMode = Settings.Default.DataMode;

            ScanSerialPort();
        }
Beispiel #47
0
        /// <summary> Populate the form's controls with default settings. </summary>
        private void InitializeControlValues()
        {
            this.automationButtonGroup = new Button[] { this.btn1, this.btn2, this.btn3, this.btn4, this.btn5, this.btn6,this.btn7,this.btn8};

            txtRemoteAddress.Text = Settings.Default.HostIP;
            txtPort.Text = Settings.Default.Port.ToString();
            CurrentDataMode = Settings.Default.DataMode;

            try
            {
                this.loadAutomationButtonGroupConfig();
            }
            catch (Exception exception)
            {
                MessageBox.Show(this, "Automation XML file parser error. Details:" + exception.Message, "automation XML parser error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                base.Close();
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 5000);
        }
 /// <summary>
 /// 校验加密算法数据模式。
 /// </summary>
 /// <param name="dataMode"></param>
 protected void ValidateDataMode(DataMode dataMode)
 {
     if (!AvailableDataModes.Contains(dataMode))
     {
         throw new NotSupportedException(string.Format("DataMode {0} & CrytoAlgorithm {1} not support!", dataMode.ToString(),CryptoAlgorithm.ToString()));
     }
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="encryptedText"></param>
 /// <param name="dataMode"></param>
 /// <returns></returns>
 public string Decrypt(string encryptedText, DataMode dataMode)
 {
     return Decrypt(encryptedText, Encoding.UTF8, dataMode);
 }
        private bool Tab3_Update_Status()
        {
            // View Mode
            if (Tab3_View_Hex.Checked == true) t3_dataView = DataMode.Hex;
            else t3_dataView = DataMode.Text;

            // Protocol
            if (Tab3_Protocol2_RBt.Checked == true) t3_protocol = Tab3_protocol.NoneCTS;
            else t3_protocol = Tab3_protocol.CTS;

            // Device
            if (Tab3_Cradle_RBt.Checked == true) t3_device = Tab3_device.Cradle;
            else t3_device = Tab3_device.Magallen;

            // Update status
            Tab3_Mode_update();

            return true;
        }
Beispiel #51
0
        /// <summary> Populate the form's controls with default settings. </summary>
        private void InitializeControlValues()
        {
            CurrentDataMode = settings.DataMode;

            RefreshComPortList();

            // If it is still avalible, select the last com port used
            if (cmbPortName.Items.Contains(settings.PortName)) cmbPortName.Text = settings.PortName;
              else if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex = cmbPortName.Items.Count - 1;
              else
              {
            MessageBox.Show(this, "There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.", "No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.Close();
              }
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="encryptedText"></param>
 /// <param name="plainText"></param>
 /// <param name="key"></param>
 /// <param name="encoding"></param>
 /// <param name="encryptedType"></param>
 /// <returns></returns>
 public virtual bool IsMatch(string encryptedText, string plainText, string key, Encoding encoding, DataMode encryptedType)
 {
     string plainTextToCompare = Decrypt(encryptedText, key, encoding, encryptedType);
     return (string.Compare(plainText, plainTextToCompare, false) == 0);
 }
Beispiel #53
0
		void PostProcessHeaders()
		{
			if(httpVersion == "1.1" && host == null)
			{
				RequestError("400", "HTTP/1.1 requests must include Host header");
				return;
			}

			if(client.server.RequireAuthentication && Server.Authenticator.Authenticate(username, password) == false)
			{
				this.Response.SetHeader("WWW-Authenticate", "Basic realm=\"" + client.server.AuthenticateRealm + "\"");
				RequestError("401", StatusCodes.GetDescription("401"));
				return;
			}

			try
			{
				// Try parsing a relative URI
				//uri = new Uri(client.server.ServerUri, requestUri);
				uri = client.server.GetRelUri(requestUri);
			}
			catch
			{
				try
				{
					// Try parsing an absolute URI
					//uri = new Uri(requestUri);
					uri = client.server.GetAbsUri(requestUri);
				}
				catch(UriFormatException)
				{
					RequestError("400", "Invalid URI");
					return;
				}
				catch(IndexOutOfRangeException)	// System.Uri in .NET 1.1 throws this exception in certain cases
				{
					RequestError("400", "Invalid URI");
					return;
				}
			}

			if(host != null)
			{
				uri = client.server.GetHostUri(host, requestUri);
			}

			// Try to determine the time difference between the client and this computer; adjust ifModifiedSince and ifUnmodifiedSince accordingly
			if(date != DateTime.MinValue)
			{
				if(ifModifiedSince != DateTime.MinValue)
					ifModifiedSince.Add(DateTime.UtcNow.Subtract(date));
				if(ifUnmodifiedSince != DateTime.MinValue)
					ifUnmodifiedSince.Add(DateTime.UtcNow.Subtract(date));
			}

			if(method == "POST")
			{
				if(contentLength == long.MinValue)
				{
					RequestError("411", StatusCodes.GetDescription("411"));
					return;
				}
				dataMode = DataMode.Binary;
			}
			else
				isRequestFinished = true;
		}
 /// <summary>
 /// 
 /// </summary>
 /// <param name="encryptedText"></param>
 /// <param name="plainText"></param>
 /// <param name="key"></param>
 /// <param name="encryptedType"></param>
 /// <returns></returns>
 public bool IsMatch(string encryptedText, string plainText, string key, DataMode encryptedType)
 {
     return IsMatch(encryptedText, plainText, key, Encoding.UTF8, encryptedType);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="plainText"></param>
 /// <param name="key"></param>
 /// <param name="encoding"></param>
 /// <param name="dataMode"></param>
 /// <returns></returns>
 public abstract string DoEncrypt(string plainText, string key, Encoding encoding, DataMode dataMode);
 /// <summary>
 /// 
 /// </summary>
 /// <param name="plainText"></param>
 /// <param name="key"></param>
 /// <param name="encoding"></param>
 /// <param name="dataMode"></param>
 /// <returns></returns>
 public string Encrypt(string plainText, string key, Encoding encoding, DataMode dataMode)
 {
     ValidateDataMode(dataMode);
     return DoEncrypt(plainText, key, encoding, dataMode);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="plainText"></param>
 /// <param name="encoding"></param>
 /// <param name="dataMode"></param>
 /// <returns></returns>
 public virtual string DoEncrypt(string plainText, Encoding encoding, DataMode dataMode)
 {
     return Encrypt(plainText, string.Empty, encoding, dataMode);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="plainText"></param>
 /// <param name="key"></param>
 /// <param name="dataMode"></param>
 /// <returns></returns>
 public string Encrypt(string plainText, string key, DataMode dataMode)
 {
     return Encrypt(plainText, key, Encoding.UTF8, dataMode);
 }
Beispiel #59
0
        /// <summary> Populate the form's controls with default settings. </summary>
        private void InitializeControlValues()
        {
            cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
              cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));

            cmbParity.Text = settings.Parity.ToString();
            cmbStopBits.Text = settings.StopBits.ToString();
            cmbDataBits.Text = settings.DataBits.ToString();
            cmbParity.Text = settings.Parity.ToString();
            cmbBaudRate.Text = settings.BaudRate.ToString();
            CurrentDataMode = settings.DataMode;

            RefreshComPortList();

            chkClearOnOpen.Checked = settings.ClearOnOpen;
            chkClearWithDTR.Checked = settings.ClearWithDTR;

            // If it is still avalible, select the last com port used
            if (cmbPortName.Items.Contains(settings.PortName)) cmbPortName.Text = settings.PortName;
              else if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex = cmbPortName.Items.Count - 1;
              else
              {
            MessageBox.Show(this, "There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.", "No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.Close();
              }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encoding"></param>
        /// <param name="dataMode"></param>
        /// <returns></returns>
        protected byte[] StringToBytes(string str, Encoding encoding, DataMode dataMode)
        {
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            byte[] byteArray = new byte[0];
            switch(dataMode)
            {
                case DataMode.Plain:
                    byteArray = encoding.GetBytes(str);
                    break;
                case DataMode.Hex:
                    byteArray = HexEncoding.GetBytes(str);
                    break;
                case DataMode.Base64:
                    byteArray = Convert.FromBase64String(str);
                    break;
            }

            return byteArray;
        }