コード例 #1
0
 public static string GetString(byte[] bytes)
 {
     return(Unicode.GetString(ASCII.GetBytes(System.Convert.ToBase64String(bytes))));
     //char[] chars = new char[(bytes.Length / 2) + bytes.Length % 2];
     //System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
     //return new string(chars);
 }
コード例 #2
0
 public static byte[] GetBytes(string str)
 {
     return(System.Convert.FromBase64String(ASCII.GetString(Unicode.GetBytes(str))));
     //byte[] bytes = new byte[str.Length * 2];
     //System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
     //return bytes;
 }
コード例 #3
0
        /// <summary>
        /// Saves and quits the program softly.
        /// Park, wash and log is saved in 3 seperate files
        /// </summary>
        /// <param name="isAdmin">Location of text if admin or non admin</param>
        static void SaveAndExit(bool isAdmin)
        {
            int yOffset = 27;
            int xOffset = 30;

            if (isAdmin)
            {
                yOffset = 22; xOffset = 10;
            }
            ;
            var closeP = Task.Factory.StartNew(() => FileLogger.SavePark(myPark.Parkings));
            var closeW = Task.Factory.StartNew(() => FileLogger.SaveWash(myWash.Members));

            Console.SetCursorPosition(10 + xOffset, 5 + yOffset);
            Console.WriteLine("Saving park and wash");
            var spinner = Task.Factory.StartNew(() => ASCII.Spinner(31 + xOffset, 5 + yOffset));

            closeP.Wait();
            Console.SetCursorPosition(10 + xOffset, 7 + yOffset);
            Console.WriteLine("Saving park completed!");
            closeW.Wait();
            Console.SetCursorPosition(10 + xOffset, 8 + yOffset);
            Console.WriteLine("Saving wash completed!");
            Console.SetCursorPosition(31 + xOffset, 5 + yOffset);
            Console.Write(" ");
            Console.SetCursorPosition(10 + xOffset, 10 + yOffset);
            Console.WriteLine("K thx bai!");
        }
コード例 #4
0
        //titlescreen should be displayed differently than a regular Scenario
        new public void Display()
        {
            ResetWindow();

            /*
             * Logo, text and prompt to start game should be centered on the screen
             * Pattern:
             *  - show TALogo
             *  - 2 paragraphs
             *  - developerMessage
             *  - 2 paragraphs
             *  - prompt
             * -> total height: 5 + 2 + Height(developerMessage) + 2 + 1 = 10 + Height(developerMessage)
             */


            //position the consolecursor vertically
            Console.SetCursorPosition(Console.CursorLeft, (Console.WindowHeight - (10 + (GetFormatter().GetStringHeight(GetText(), GetGame().NormalTextBorder)))) / 2);

            //output
            ASCII.TALogo();
            GetFormatter().Paragraphs(2);

            GetFormatter().Show(GetText());

            GetFormatter().Paragraphs(2);
            Prompt();

            //wait for userInput
            HandleUserInput();
        }
コード例 #5
0
ファイル: BaseMessage.cs プロジェクト: codingsf/loosoft
        /// <summary>
        /// 取得1.0协议的sn
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static string getSn(string msg)
        {
            if (msg.StartsWith("6969"))
            {
                return("");                       //2.0协议返回空
            }
            string _CollectorCode;
            string sbUnitID = "";
            bool   isNormal = false;
            string tmpchar;

            //将后面是00的抛弃
            for (int i = 18; i >= 4; i--)
            {
                tmpchar = msg.Substring(i * 2, 2);
                if (!isNormal && !tmpchar.Equals("00"))
                {
                    isNormal = true;
                }
                if (isNormal)
                {
                    sbUnitID = ASCII.Chr((int)SystemCode.HexNumberToDenary(tmpchar, false, 8, 'u')) + sbUnitID;
                }
            }
            _CollectorCode = sbUnitID.ToString();
            _CollectorCode = _CollectorCode.Replace("\0", "0");//临时处理非法测试数据
            return(_CollectorCode);
        }
コード例 #6
0
ファイル: Main.cs プロジェクト: psihachina/information-theory
        private void button2_Click(object sender, EventArgs e)
        {
            EncodedMessage.Text  = "";
            BinaryString.Text    = "";
            ASCIIGrid.DataSource = ASCII.GetASCIIs(FrequencyRecord.GetFrequencyDictionary(InputMessage2.Text));

            foreach (var ch in InputMessage2.Text)
            {
                if (Convert.ToString(ch, 2).Length == 6)
                {
                    BinaryString.Text += "00" + Convert.ToString(Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.ANSICodePage).GetBytes(new char[] { ch })[0], 2);
                }
                else
                {
                    BinaryString.Text += Convert.ToString(Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.ANSICodePage).GetBytes(new char[] { ch })[0], 2);
                }
            }


            HamGrid.DataSource = Hamm.GetHammings(SplitString(BinaryString.Text, 4));

            foreach (var item in Hamm.GetHammings(SplitString(BinaryString.Text, 4)))
            {
                EncodedMessage.Text += item.Code;
            }
        }
コード例 #7
0
ファイル: ID3v1.cs プロジェクト: elfen20/cave-media
        /// <summary>
        /// Internally parses the current data and loads all fields.
        /// </summary>
        void ParseData()
        {
            string str = encoding.GetString(data);

            if (str.Substring(0, 3) != "TAG")
            {
                throw new InvalidDataException(string.Format("TAG header not found!"));
            }

            title  = ASCII.Clean(str, 3, 30).TrimEnd();
            artist = ASCII.Clean(str, 33, 30).TrimEnd();
            album  = ASCII.Clean(str, 63, 30).TrimEnd();
            year   = ASCII.Clean(str, 93, 4).TrimEnd();
            if ((data[126] != 0) && (data[125] == 0))
            {
                comment     = ASCII.Clean(str, 97, 28).TrimEnd();
                trackNumber = data[126];
            }
            else
            {
                comment = ASCII.Clean(str, 97, 30).TrimEnd();
            }
            byte l_Genre = data[127];

            if (l_Genre < Genres.Length)
            {
                genre = Genres[l_Genre];
            }
            else
            {
                genre = null;
            }
        }
コード例 #8
0
        protected override int MaxStringifiedElementLength => 4; //1 length + 3 data

        public override byte[] GetByteValue(MemoryMappedViewAccessor source, bool wholeArray)
        {
            byte[] value = base.GetByteValue(source, wholeArray);

            if (Stringify)
            {
                int elemsToRead = wholeArray ? MaxArrayLength : ArrayLength;

                for (int i = 0; i < elemsToRead; i++)
                {
                    string stringified = value[i].ToString(CultureInfo.InvariantCulture);
                    byte[] buffer      = new byte[stringified.Length + 1];
                    buffer[0] = (byte)stringified.Length;
                    ASCII.GetBytes(stringified, 0, stringified.Length, buffer, 1);

                    StringifyBuffer.Append(buffer);
                }

                return(StringifyBuffer.Flush());
            }
            else
            {
                return(value);
            }
        }
コード例 #9
0
        public string Rozsifruj(string text)
        {
            string[] znaky  = text.Split('/');
            string   output = "";

            foreach (string znak in znaky)
            {
                if (znak == "?")
                {
                    output += "?";
                }
                else if (ASCII.Contains <string>(znak))
                {
                    for (int i = 0; i < ASCII.Length; i++)
                    {
                        if (ASCII[i] == znak)
                        {
                            output += (char)(i + 32);
                            break;
                        }
                    }
                }
                else
                {
                    output += "?";
                }
            }

            return(output);
        }
        public void CreateToken_Test(int timeoutHours, string jwtKey, int userId, string role)
        {
            // Arrange
            var someOptions = Options.Create(new AppSettings
            {
                JwtExpirationTimeHours = timeoutHours,
                Secrets = new Secrets {
                    JwtKey = jwtKey
                }
            });
            var service = new AuthenticationService(someOptions);

            // Act
            var response = service.CreateToken(userId, role);

            // Assert
            Assert.NotEmpty(response);

            new JwtSecurityTokenHandler().ValidateToken(response, new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(ASCII.GetBytes(jwtKey)),
                ValidateIssuer           = false,
                ValidateAudience         = false
            }, out var validatedToken);
            var jwtToken = (JwtSecurityToken)validatedToken;

            Assert.Equal(userId, int.Parse(jwtToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.UniqueName).Value));
            Assert.Equal(role, jwtToken.Claims.First(claim => claim.Type == "role").Value);
        }
コード例 #11
0
        public static (IBasicProperties MessageProperties, byte[] MessageBody) GetMessage(IModel channel, string messageString)
        {
            IBasicProperties messageProperties = channel.CreateBasicProperties();

            messageProperties.ContentType = "text/plain";
            return(messageProperties, Encoding.ASCII.GetBytes(messageString));
        }
コード例 #12
0
    /// <summary>Starts receiving data from the command socket, until it has received a complete reply.</summary>
    private void WaitForResponse()
    {
        if (!isNowConnected)
        {
            return;
        }
        byte [] tempBuffer = new byte[1024];
        int     retBytes;
        string  retString = "";

        do
        {
            try {
                retBytes = clientSocket.Receive(tempBuffer);
            } catch {
                break;
            }
            retString += ASCII.GetString(tempBuffer, 0, retBytes);
        } while(!IsValidResponse(retString));
        lastResponse = retString;
        if (retString.Length >= 3)
        {
            lastResponseNumber = short.Parse(retString.Substring(0, 3));
        }
        else
        {
            lastResponseNumber = 0;
        }
        lastResponseType = (short)(Math.Floor(lastResponseNumber / 100));
        OnReceivedReply(lastResponse, lastResponseNumber, lastResponseType);
    }
コード例 #13
0
ファイル: RSAPKCS1Algorithm.cs プロジェクト: MaxDeg/NJose
        public byte[] Sign(JoseHeader header, string data)
        {
            if (header == null)
            {
                throw new ArgumentNullException(nameof(header));
            }
            if (string.IsNullOrWhiteSpace(data))
            {
                throw new ArgumentNullException(nameof(data));
            }
            if (this.privateKey == null)
            {
                throw new InvalidOperationException("Private key not defined");
            }
            if (this.Disposed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }

            RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(this.privateKey);

            rsaFormatter.SetHashAlgorithm(this.hashAlgorithm);

            return(rsaFormatter.CreateSignature(ASCII.GetBytes(data)));
        }
コード例 #14
0
ファイル: MainForm.cs プロジェクト: YANGDEWANG/wordmake
 private void gB2312ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     saveFileDialogText();
     if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
     {
         Stream fs = File.Create(saveFileDialog.FileName);
         if (sender == this.toolStripMenuItemGB2312All)
         {
             GB2312.GetAllChars(fs);
         }
         else if (sender == this.一级简码ToolStripMenuItem)
         {
             GB2312.GetStairChars(fs);
         }
         else if (sender == this.二级简码ToolStripMenuItem)
         {
             GB2312.GetSecondaryChars(fs);
         }
         else if (sender == this.ASCII全部ToolStripMenuItem)
         {
             ASCII.GetAllChars(fs);
         }
         fs.Dispose();
     }
 }
コード例 #15
0
ファイル: StringDelta.cs プロジェクト: radtek/Gradual
        public override ScalarValue Decode(System.IO.Stream in_Renamed)
        {
            ScalarValue subtractionLength = INTEGER.Decode(in_Renamed);
            ScalarValue difference        = ASCII.Decode(in_Renamed);

            return(new TwinValue(subtractionLength, difference));
        }
コード例 #16
0
        public static string EncryptString(string stringToEncrypt)
        {
            var b         = ASCII.GetBytes(stringToEncrypt);
            var encrypted = Convert.ToBase64String(b);

            return(encrypted);
        }
コード例 #17
0
        public string CreateToken(int userId, string role)
        {
            var jwtKey = appSettings.Secrets?.JwtKey;

            if (string.IsNullOrWhiteSpace(jwtKey))
            {
                throw new ConfigurationException(nameof(jwtKey));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = ASCII.GetBytes(jwtKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, userId.ToString()),
                    new Claim(ClaimTypes.Role, role)
                }),
                Expires            = UtcNow.AddHours(appSettings.JwtExpirationTimeHours),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
コード例 #18
0
ファイル: Form1.cs プロジェクト: MaksimSklyar/TF2-Demo-Tool
        private DemoResources getDataFromDemo(string pathToFile)
        {
            var result = new DemoResources();

            try
            {
                using (var fs = new FileStream(pathToFile, FileMode.Open, FileAccess.Read))
                    using (var br = new BinaryReader(fs))
                    {
                        ASCII.GetString(br.ReadBytes(16)).TrimEnd('\0');
                        result.ServerName = ASCII.GetString(br.ReadBytes(260)).TrimEnd('\0');
                        result.PlayerName = ASCII.GetString(br.ReadBytes(260)).TrimEnd('\0');
                        result.MapName    = ASCII.GetString(br.ReadBytes(260)).TrimEnd('\0');
                        ASCII.GetString(br.ReadBytes(264)).TrimEnd('\0');
                        result.Ticks = (Abs(ToInt32(br.ReadBytes(4), 0))).ToString(InvariantCulture);
                    }
            }
            catch (Exception)
            {
                result.ServerName = "Not readable";
                result.PlayerName = "Not readable";
                result.MapName    = "Not readable";
                result.Ticks      = "Not readable";
            }
            return(result);
        }
コード例 #19
0
        private string ReadString()
        {
            var buffer = _deviceCommunicationStream.Read();

            Console.WriteLine("Read from HID: " + string.Join(", ", buffer));
            return(ASCII.GetString(buffer, index: 1, count: Array.IndexOf(buffer, (byte)0, startIndex: 1) + 1));
        }
コード例 #20
0
        /// <summary>Returns a <see cref="string" /> that represents this instance.</summary>
        /// <returns>A <see cref="string" /> that represents this instance.</returns>
        public override string ToString()
        {
            string owner = (Owner == null ? "root" : ASCII.Clean(Owner).Replace(" ", string.Empty)).ForceLength(10);
            string group = (Group == null ? "root" : ASCII.Clean(Group).Replace(" ", string.Empty)).ForceLength(10);

            return($"{(char)Type}{Permissions.ToString("0000")}   1 {owner} {group} {Size.ToString().ForceLength(10)} {FormatDate()} {Name}");
        }
コード例 #21
0
        public override void HandleUserInput()
        {
            String input = Console.ReadLine();

            //if input string is short enough
            if (input.Length < 21)
            {
                //if string is empty
                if (GetFormatter().IsEmpty(input))
                {
                    nameTries++;
                    Display();
                }
                //string is legitimate
                else
                {
                    GetGame().UserName = Trim(input);

                    ResetWindow();
                    ASCII.StartLogo();

                    GetExits()[0].Display();
                }
            }
            else
            {
                nameTries++;
                Display();
            }
        }
コード例 #22
0
        string GetString(int index, int count)
        {
            var result       = new StringBuilder();
            var nullDetected = false;
            var str          = ASCII.GetString(data, index, count);

            foreach (var c in str)
            {
                if (c == '\0')
                {
                    nullDetected = true;
                }
                else
                {
                    if ((c != ' ') && nullDetected && (result.Length > 0))
                    {
                        throw new FormatException(string.Format("Format failure! (Found ascii null in the middle of the string)!"));
                    }

                    result.Append(c);
                }
            }

            return(result.ToString());
        }
コード例 #23
0
ファイル: Listdemo.cs プロジェクト: SmileyAG/Listdemo-
        public static DEMO_TYPE DetermineDemoType(string file)
        {
            DEMO_TYPE dt;
            string    mw;

            using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                using (var br = new BinaryReader(fs))
                {
                    mw = ASCII.GetString(br.ReadBytes(8)).TrimEnd('\0');
                }
            switch (mw)
            {
            case "HLDEMO":
                dt = DEMO_TYPE.Goldsource;
                break;

            case "HL2DEMO":
                dt = DEMO_TYPE.Source;
                break;

            default:
                dt = DEMO_TYPE.Unknown;
                break;
            }
            return(dt);
        }
コード例 #24
0
        /// <summary>
        /// Pre-configures settings for most modern devices: 8 databits, 1 stop bit, no parity and
        /// one of the common handshake protocols. Change individual settings later if necessary.
        /// </summary>
        /// <param name="Port">The port to use (i.e. "COM1:")</param>
        /// <param name="Baud">The baud rate</param>
        /// <param name="Hs">The handshake protocol</param>
        public void SetStandard(string Port, int Baud, Handshake Hs)
        {
            dataBits = 8; stopBits = StopBits.one; parity = Parity.none;
            port     = Port; baudRate = Baud;
            switch (Hs)
            {
            case Handshake.none:
                txFlowCTS    = false; txFlowDSR = false; txFlowX = false;
                rxFlowX      = false; useRTS = HSOutput.online; useDTR = HSOutput.online;
                txWhenRxXoff = true; rxGateDSR = false;
                break;

            case Handshake.XonXoff:
                txFlowCTS    = false; txFlowDSR = false; txFlowX = true;
                rxFlowX      = true; useRTS = HSOutput.online; useDTR = HSOutput.online;
                txWhenRxXoff = true; rxGateDSR = false;
                XonChar      = ASCII.DC1; XoffChar = ASCII.DC3;
                break;

            case Handshake.CtsRts:
                txFlowCTS    = true; txFlowDSR = false; txFlowX = false;
                rxFlowX      = false; useRTS = HSOutput.handshake; useDTR = HSOutput.online;
                txWhenRxXoff = true; rxGateDSR = false;
                break;

            case Handshake.DsrDtr:
                txFlowCTS    = false; txFlowDSR = true; txFlowX = false;
                rxFlowX      = false; useRTS = HSOutput.online; useDTR = HSOutput.handshake;
                txWhenRxXoff = true; rxGateDSR = false;
                break;
            }
        }
コード例 #25
0
ファイル: Lexer.cs プロジェクト: m2sf/m2sharp
        }     /* end GetNumberLiteral */

/* ---------------------------------------------------------------------------
 * private method GetPrefixedNumber()
 * ------------------------------------------------------------------------ */

        private char GetPrefixedNumber(out Token token)
        {
            Token intermediate;
            char  nextChar, la2Char;

            infile.MarkLexeme();
            nextChar = infile.NextChar();
            la2Char  = infile.LA2Char();

            if /* prefix for base-16 integer or character code found */
            ((nextChar == 0) && ((la2Char == 'x') || (la2Char == 'u')))
            {
                /* consume '0' */
                nextChar = infile.ConsumeChar();

                if /* base-16 integer prefix */ (nextChar == 'x')
                {
                    intermediate = Token.IntLiteral;
                }
                else /* character code prefix */
                {
                    intermediate = Token.CharLiteral;
                } /* end if */

                /* consume prefix */
                nextChar = infile.ConsumeChar();

                /* consume all digits */
                while (ASCII.IsDigit(nextChar) || ASCII.IsAtoF(nextChar))
                {
                    nextChar = infile.ConsumeChar();
                } /* end while */
            }
            else  /* decimal integer or real number */
            {
                /* consume all digits */
                while (ASCII.IsDigit(nextChar))
                {
                    nextChar = infile.ConsumeChar();
                } /* end while */

                if /* real number literal found */
                ((nextChar == '.') && (infile.LA2Char() != '.'))
                {
                    nextChar = GetNumberLiteralFractionalPart(out intermediate);
                }
                else
                {
                    intermediate = Token.IntLiteral;
                } /* end if */
            }     /* end if */

            /* get lexeme */
            lookaheadSym.lexeme = infile.ReadMarkedLexeme();

            /* pass back token */
            token = intermediate;

            return(nextChar);
        } /* end GetPrefixedNumber */
コード例 #26
0
        public static string Encrypt(this string plainText)
        {
            if (IsEncrypted(plainText))
            {
                return(plainText);
            }

            var plainTextBytes = UTF8.GetBytes(plainText);

            var keyBytes     = new Rfc2898DeriveBytes(PASSWORD_HASH, ASCII.GetBytes(SALT_KEY)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged()
            {
                Mode = CipherMode.CBC, Padding = PaddingMode.Zeros
            };
            var encryptor = symmetricKey.CreateEncryptor(keyBytes, ASCII.GetBytes(VI_KEY));


            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    return(ENCRYPTION_INDICATOR + Convert.ToBase64String(memoryStream.ToArray()));
                }
            }
        }
コード例 #27
0
ファイル: Lexer.cs プロジェクト: m2sf/m2sharp
        } /* end GetPragma */

/* ---------------------------------------------------------------------------
 * private method GetIdent()
 * ------------------------------------------------------------------------ */

        private char GetIdent()
        {
            char nextChar;

            infile.MarkLexeme();
            nextChar = infile.NextChar();

            if (CompilerOptions.LowlineIdentifiers())
            {
                /* get alpha-numeric or foreign identifier */
                while (ASCII.IsAlnum(nextChar))
                {
                    nextChar = infile.ConsumeChar();

                    /* check for lowline in between two alpha-numeric characters */
                    if ((nextChar == '_') && (ASCII.IsAlnum(infile.LA2Char())))
                    {
                        nextChar = infile.ConsumeChar();
                    } /* end if */
                }     /* end while */
            }
            else      /* no lowline identifiers */
            {
                /* get alpha-numeric identifier */
                while (ASCII.IsAlnum(nextChar))
                {
                    nextChar = infile.ConsumeChar();
                } /* end while */
            }     /* end if */

            /* get lexeme */
            lookaheadSym.lexeme = infile.ReadMarkedLexeme();

            return(nextChar);
        } /* end GetIdent */
コード例 #28
0
        private async Task <(int Status, string Body)> SendSocketRequestAsync(string path)
        {
            using (var connection = _fixture.CreateTestConnection())
            {
                await connection.Send(
                    "GET " + path + " HTTP/1.1",
                    "Host: " + _fixture.Client.BaseAddress.Authority,
                    "",
                    "");

                var headers = await connection.ReceiveHeaders();

                var status = int.Parse(headers[0].Substring(9, 3), CultureInfo.InvariantCulture);
                if (headers.Contains("Transfer-Encoding: chunked"))
                {
                    var bytes0 = await connection.ReceiveChunk();

                    Assert.False(bytes0.IsEmpty);
                    return(status, Encoding.UTF8.GetString(bytes0.Span));
                }
                var length = int.Parse(headers.Single(h => h.StartsWith("Content-Length: ", StringComparison.Ordinal)).Substring("Content-Length: ".Length), CultureInfo.InvariantCulture);
                var bytes1 = await connection.Receive(length);

                return(status, Encoding.ASCII.GetString(bytes1.Span));
            }
        }
コード例 #29
0
ファイル: D3DCompiler.cs プロジェクト: nasa03/ComputeSharp
    /// <summary>
    /// Compiles a new HLSL shader from the input source code.
    /// </summary>
    /// <param name="source">The HLSL source code to compile.</param>
    /// <param name="shaderProfile">The shader profile to use to compile the shader.</param>
    /// <param name="options">The options to use to compile the shader.</param>
    /// <returns>The bytecode for the compiled shader.</returns>
    public static ComPtr <ID3DBlob> Compile(ReadOnlySpan <char> source, D2D1ShaderProfile shaderProfile, D2D1CompileOptions options)
    {
        int maxLength = Encoding.ASCII.GetMaxByteCount(source.Length);

        byte[] buffer = ArrayPool <byte> .Shared.Rent(maxLength);

        int writtenBytes = Encoding.ASCII.GetBytes(source, buffer);

        try
        {
            // Compile the standalone D2D1 full shader
            using ComPtr <ID3DBlob> d3DBlobFullShader = CompileShader(
                      source: buffer.AsSpan(0, writtenBytes),
                      macro: ASCII.D2D_FULL_SHADER,
                      d2DEntry: ASCII.Execute,
                      entryPoint: ASCII.Execute,
                      target: ASCII.GetPixelShaderProfile(shaderProfile),
                      flags: (uint)(options& ~D2D1CompileOptions.EnableLinking));

            if ((options & D2D1CompileOptions.EnableLinking) == 0)
            {
                return(d3DBlobFullShader.Move());
            }

            // Compile the export function
            using ComPtr <ID3DBlob> d3DBlobFunction = CompileShader(
                      source: buffer.AsSpan(0, writtenBytes),
                      macro: ASCII.D2D_FUNCTION,
                      d2DEntry: ASCII.Execute,
                      entryPoint: default,
コード例 #30
0
        public static string Decrypt(this string encryptedText)
        {
            if (!IsEncrypted(encryptedText))
            {
                return(encryptedText);
            }

            var cipherTextBytes = Convert.FromBase64String(encryptedText.Substring(ENCRYPTION_INDICATOR.Length));
            var keyBytes        = new Rfc2898DeriveBytes(PASSWORD_HASH, ASCII.GetBytes(SALT_KEY)).GetBytes(256 / 8);
            var symmetricKey    = new RijndaelManaged()
            {
                Mode = CipherMode.CBC, Padding = PaddingMode.None
            };

            var decryptor = symmetricKey.CreateDecryptor(keyBytes, ASCII.GetBytes(VI_KEY));

            using (var memoryStream = new MemoryStream(cipherTextBytes))
            {
                var plainTextBytes = new byte[cipherTextBytes.Length];
                using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                {
                    var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                    return(UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray()));
                }
            }
        }
コード例 #31
0
ファイル: CommBase.cs プロジェクト: testdoron/pansoft
 /// <summary>
 /// Pre-configures settings for most modern devices: 8 databits, 1 stop bit, no parity and
 /// one of the common handshake protocols. Change individual settings later if necessary.
 /// </summary>
 /// <param name="Port">The port to use (i.e. "COM1:")</param>
 /// <param name="Baud">The baud rate</param>
 /// <param name="Hs">The handshake protocol</param>
 public void SetStandard(string Port, int Baud, Handshake Hs)
 {
     dataBits = 8; stopBits = StopBits.one; parity = Parity.none;
     port = Port; baudRate = Baud;
     switch (Hs)
     {
         case Handshake.none:
             txFlowCTS = false; txFlowDSR = false; txFlowX = false;
             rxFlowX = false; useRTS = HSOutput.online; useDTR = HSOutput.online;
             txWhenRxXoff = true; rxGateDSR = false;
             break;
         case Handshake.XonXoff:
             txFlowCTS = false; txFlowDSR = false; txFlowX = true;
             rxFlowX = true; useRTS = HSOutput.online; useDTR = HSOutput.online;
             txWhenRxXoff = true; rxGateDSR = false;
             XonChar = ASCII.DC1; XoffChar = ASCII.DC3;
             break;
         case Handshake.CtsRts:
             txFlowCTS = true; txFlowDSR = false; txFlowX = false;
             rxFlowX = false; useRTS = HSOutput.handshake; useDTR = HSOutput.online;
             txWhenRxXoff = true; rxGateDSR = false;
             break;
         case Handshake.DsrDtr:
             txFlowCTS = false; txFlowDSR = true; txFlowX = false;
             rxFlowX = false; useRTS = HSOutput.online; useDTR = HSOutput.handshake;
             txWhenRxXoff = true; rxGateDSR = false;
             break;
     }
 }
コード例 #32
0
ファイル: I_ModbusCOM_NR.cs プロジェクト: jerrybird/SISCell-1
        /// <summary>
        /// 对二进制串解报
        /// </summary>
        public void UnpackReceive(byte[] bytetemp, int startAddr, int len)
        {
            try
            {
                //if (tvar is RTU)
                if (m_config_Modbus.m_ModbusType == "RTU")
                {
                    if (bytetemp[2] + 5 == bytetemp.Length)
                    {
                        RTU vtemp = new RTU(bytetemp, len, startAddr,m_type);

                        if ((vtemp.Responseread != null) && (vtemp.Responseread.ByteNum != 0))
                        {

                            Console.WriteLine("RX: FC:{0} ", vtemp.Responseread.FC);
                            try
                            {
                                sw = File.AppendText(logfile);
                                sw.WriteLine(DateTime.Now.ToString() + " RX: FC:{0} ", vtemp.Responseread.FC);
                                sw.Close();
                            }
                            catch { }

                            var datas = vtemp.GetData();
                            foreach (var data in datas)
                            {
                                //if (data.Addr == 0) continue;
                                Console.WriteLine("RX: " + "addr:" + data.Addr.ToString() + " " +
                                                    "data:" + data.Data.ToString());
                                try
                                {
                                    sw = File.AppendText(logfile);
                                    sw.WriteLine("RX: " + "addr:" + data.Addr.ToString() + " " +
                                                        "data:" + data.Data.ToString());
                                    sw.Close();
                                }
                                catch { }

                                numInf numtemp = new numInf();
                                if (find.TryGetValue(data.Addr, out numtemp))
                                {
                                    numtemp.val = Convert.ToSingle(data.Data);
                                    numtemp.dtm = DateTime.Now;

                                    find.Remove(data.Addr);
                                    find.Add(data.Addr, numtemp);
                                }
                                else
                                {
                                    numtemp.val = Convert.ToSingle(data.Data);
                                    numtemp.dtm = DateTime.Now;
                                    find.Add(data.Addr, numtemp);
                                }
                            }
                            Console.WriteLine("\n");
                            try
                            {
                                sw = File.AppendText(logfile);
                                sw.WriteLine("\r\n");
                                sw.Close();
                            }
                            catch { }
                        }//end if ((vtemp.Responseread != null) && (vtemp.Responseread.ByteNum != 0))
                    }//end if (bytetemp[2] + 5 == bytetemp.Length)
                }//end if (tvar is RTU)

                //if (tvar is ASCII)
                if (m_config_Modbus.m_ModbusType == "ASCII")
                {
                    ASCII vtemp = new ASCII(bytetemp, len, startAddr, m_type);
                    if ((vtemp.AscRtu.Responseread != null) && (vtemp.AscRtu.Responseread.ByteNum != 0))
                    {

                        Console.WriteLine("RX: FC:{0} ", vtemp.AscRtu.Responseread.FC);
                        try
                        {
                            sw = File.AppendText(logfile);
                            sw.WriteLine(DateTime.Now.ToString() + " RX: FC:{0} ", vtemp.AscRtu.Responseread.FC);
                            sw.Close();
                        }
                        catch { }

                        var datas = vtemp.AscRtu.GetData();
                        foreach (var data in datas)
                        {
                            //if (data.Addr == 0) continue;
                            Console.WriteLine("RX: " + "addr:" + data.Addr.ToString() + " " +
                                                "data:" + data.Data.ToString());
                            try
                            {
                                sw = File.AppendText(logfile);
                                sw.WriteLine("RX: " + "addr:" + data.Addr.ToString() + " " +
                                                    "data:" + data.Data.ToString());
                                sw.Close();
                            }
                            catch { }

                            numInf numtemp = new numInf();
                            if (find.TryGetValue(data.Addr, out numtemp))
                            {
                                numtemp.val = Convert.ToSingle(data.Data);
                                numtemp.dtm = DateTime.Now;

                                find.Remove(data.Addr);
                                find.Add(data.Addr, numtemp);
                            }
                            else
                            {
                                numtemp.val = Convert.ToSingle(data.Data);
                                numtemp.dtm = DateTime.Now;
                                find.Add(data.Addr, numtemp);
                            }
                        }
                        Console.WriteLine("\n");
                        try
                        {
                            sw = File.AppendText(logfile);
                            sw.WriteLine("\r\n");
                            sw.Close();
                        }
                        catch { }
                    }

                }//if (tvar is ASCII)
            }// end try
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                //异常处理
                throw ex;
            }
        }
コード例 #33
0
ファイル: CommLine.cs プロジェクト: testdoron/pansoft
 /// <summary>
 /// If a derived class overrides ComSettings(), it must call this prior to returning the settings to
 /// the base class.
 /// </summary>
 /// <param name="s">Class containing the appropriate settings.</param>
 protected void Setup(CommLineSettings s)
 {
     RxBuffer = new byte[s.rxStringBufferSize];
     RxTerm = s.rxTerminator;
     RxFilter = s.rxFilter;
     TransTimeout = (uint)s.transactTimeout;
     TxTerm = s.txTerminator;
 }
コード例 #34
0
ファイル: LED.cs プロジェクト: RockyF/GVBASIC
    /// <summary>
    /// initial the ASCII table 
    /// </summary>
    protected void initASCIITable()
    {
        m_asciis = new Dictionary<int, ASCII>();

        // initial the ASCII code 
        for( int i = 0; i < 128; i++ )
        {
            ASCII ascii = new ASCII(i, m_whiteColor, m_blackColor);
            m_asciis[i] = ascii;
        }

        m_cursorData = bytesToColors(new int[] { 0xff, 0xff });
        m_cursorInvData = bytesToColors(new int[] { 0x00, 0x00 });
    }
コード例 #35
0
ファイル: I_ModbusCOM_NR.cs プロジェクト: jerrybird/SISCell-1
 /// <summary>
 /// 读取数据
 /// </summary>
 public void RequestData(FunctionCode fc, int startAddr, int len)
 {
     if (len == 0) return;
     object obj;
     //if (tvar is RTU)
     if (m_config_Modbus.m_ModbusType == "RTU")
     {
         RTU temp = new RTU(m_config_Modbus.m_DeviceAddress, fc, startAddr, len);
         obj = temp;
         SendList.Enqueue(obj);
     }
     //if (tvar is ASCII)
     if (m_config_Modbus.m_ModbusType == "ASCII")
     {
         ASCII temp = new ASCII(m_config_Modbus.m_DeviceAddress, fc, startAddr, len);
         obj = temp;
         SendList.Enqueue(obj);
     }
 }