Ejemplo n.º 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);
 }
        protected bool WriteCredential(string targetName, Credential credentials)
        {
            if (targetName is null)
            {
                throw new ArgumentNullException(nameof(targetName));
            }
            if (credentials is null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            try
            {
                string name = credentials.Username;
                byte[] data = Unicode.GetBytes(credentials.Password);

                return(Storage.TryWriteSecureData(targetName, name, data));
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);

                Trace.WriteException(exception);
            }

            return(false);
        }
Ejemplo n.º 3
0
        public async ValueTask <byte[]> EncryptAsync(string plainText, bool hasSalt = true)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                return(Array.Empty <byte>());
            }
            // adding a salt to prevent same result in same plain texts
            if (hasSalt)
            {
                plainText = ASCII.GetString(rng.GetNonZeroRandomBytes(SaltSize)) + plainText;
            }

            using Aes aes = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
                            new AesCng() as Aes : new AesManaged();
            aes.Mode = CipherMode.CBC;
            aes.Key  = KeyProvider.Key.ToArray();
            aes.IV   = KeyProvider.IV.ToArray();

            using var memoryStream = new MemoryStream();
            using var cryptoStream =
                      new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
            var plainTextBytes = Unicode.GetBytes(plainText);
            await cryptoStream.WriteAsync(plainTextBytes, 0, plainTextBytes.Length);

            cryptoStream.Close();
            return(memoryStream.ToArray());
        }
Ejemplo n.º 4
0
    private static void ExactSpellingFalse_NonWindows()
    {
        int intManaged = 1000;
        int intNative  = 2000;

        Console.WriteLine("Method Unicode.Marshal_Int_InOut2: ExactSpelling = false");
        int int5 = intManaged;

        Assert.Throws <EntryPointNotFoundException>(() => Unicode.Marshal_Int_InOut2(int5));

        Console.WriteLine("Method Unicode.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int6 = intManaged;

        Assert.Throws <EntryPointNotFoundException>(() => Unicode.MarshalPointer_Int_InOut2(ref int6));

        Console.WriteLine("Method Ansi.Marshal_Int_InOut2: ExactSpelling = false");
        int int7 = intManaged;

        Assert.Throws <EntryPointNotFoundException>(() => Ansi.Marshal_Int_InOut2(int7));

        Console.WriteLine("Method Ansi.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int8 = intManaged;

        Assert.Throws <EntryPointNotFoundException>(() => Ansi.MarshalPointer_Int_InOut2(ref int8));
    }
Ejemplo n.º 5
0
        public static IEnumerable <CharacterInfo> GetCharacters(string s)
        {
            var bytes = UTF32.GetBytes(s);

            for (int i = 0; i < bytes.Length; i += 4)
            {
                var cp = new CharacterInfo();

                var utf32 = new byte[4];
                Array.Copy(bytes, i, utf32, 0, 4);
                cp.utf32 = utf32;

                cp.codePoint = (utf32[0] << 0)
                               | (utf32[1] << 8)
                               | (utf32[2] << 16)
                               | (utf32[3] << 24);

                var decoded = UTF32.GetString(utf32);
                cp.@char = decoded;
                cp.utf16 = Unicode.GetBytes(decoded);
                cp.utf8  = UTF8.GetBytes(decoded);

                yield return(cp);
            }
        }
Ejemplo n.º 6
0
    private static void ExactSpellingTrue()
    {
        int intManaged = 1000;
        int intNative  = 2000;
        int intReturn  = 3000;

        Console.WriteLine("Method Unicode.Marshal_Int_InOut: ExactSpelling = true");
        int int1    = intManaged;
        int intRet1 = Unicode.Marshal_Int_InOut(int1);

        Verify(intReturn, intManaged, intRet1, int1);

        Console.WriteLine("Method Unicode.MarshalPointer_Int_InOut: ExactSpelling = true");
        int int2    = intManaged;
        int intRet2 = Unicode.MarshalPointer_Int_InOut(ref int2);

        Verify(intReturn, intNative, intRet2, int2);

        Console.WriteLine("Method Ansi.Marshal_Int_InOut: ExactSpelling = true");
        int int3    = intManaged;
        int intRet3 = Ansi.Marshal_Int_InOut(int3);

        Verify(intReturn, intManaged, intRet3, int3);

        Console.WriteLine("Method Ansi.MarshalPointer_Int_InOut: ExactSpelling = true");
        int int4    = intManaged;
        int intRet4 = Ansi.MarshalPointer_Int_InOut(ref int4);

        Verify(intReturn, intNative, intRet4, int4);
    }
Ejemplo n.º 7
0
        private void DoText(string text)
        {
            var  list = new List <Unicode.Summary>(text.Length);
            bool after_high_surrogate = false;

            foreach (var c in text)
            {
                if (IsCancelled())
                {
                    return;
                }
                int code = c;

                if (after_high_surrogate && Unicode.IsLowSurrogate(code))
                {
                    var high = list[list.Count - 1];
                    code = Unicode.DecodeSurrogatePair((int)high.Code, code);
                    list[list.Count - 1] = Unicode.GetSummary(code);
                }
                else
                {
                    list.Add(Unicode.GetSummary(c));
                }

                after_high_surrogate = Unicode.IsHighSurroate(code);
            }

            OnUpdated(list.ToArray());
        }
Ejemplo n.º 8
0
        private void DoCode(string text)
        {
            var  list = new List <Unicode.Summary>(text.Length);
            bool after_high_surrogate = false;

            var a = text
                    .Replace(";", "; ").Replace("\\", " \\").Replace("&#", " &#")
                    .Split((char[])null, StringSplitOptions.RemoveEmptyEntries);

            foreach (var s in a)
            {
                if (IsCancelled())
                {
                    return;
                }
                int code = ParseCodepointNotation(s);

                if (after_high_surrogate && Unicode.IsLowSurrogate(code) && !s.StartsWith("&#"))
                {
                    var high = list[list.Count - 1] as UnicodeSummaryEx;
                    code = Unicode.DecodeSurrogatePair((int)high.Code, code);
                    list[list.Count - 1] = new UnicodeSummaryEx(Unicode.GetSummary(code), high.Orig + " " + s);
                }
                else
                {
                    list.Add(new UnicodeSummaryEx(Unicode.GetSummary(code), s));
                }

                after_high_surrogate = Unicode.IsHighSurroate(code) && !s.StartsWith("&#");
            }
            OnUpdated(list.ToArray());
        }
Ejemplo n.º 9
0
        protected virtual ProcessCharResult ProcessNormalChar(char ch)
        {
            //既に画面右端にキャレットがあるのに文字が来たら改行をする
            int tw = GetDocument().TerminalWidth;

            if (_manipulator.CaretColumn + Unicode.GetCharacterWidth(ch) > tw)
            {
                GLine l = _manipulator.Export();
                l.EOLType = EOLType.Continue;
                this.LogService.TextLogger.WriteLine(l); //ログに行をcommit
                GetDocument().ReplaceCurrentLine(l);
                GetDocument().LineFeed();
                _manipulator.Load(GetDocument().CurrentLine, 0);
            }

            //画面のリサイズがあったときは、_manipulatorのバッファサイズが不足の可能性がある
            if (tw > _manipulator.BufferSize)
            {
                _manipulator.ExpandBuffer(tw);
            }

            //通常文字の処理
            _manipulator.PutChar(ch, _currentdecoration);

            return(ProcessCharResult.Processed);
        }
Ejemplo n.º 10
0
        static void append_key(RegistryKey rk, Stream s)
        {
            string t = $"\"{rk.Name}\"";

            s.Write(Unicode.GetBytes(t), 0, t.Length * 2);
            foreach (string val in rk.GetValueNames())
            {
                try
                {
                    t = $" \"{xml_esc(val)}\"=\"{xml_esc(rk.GetValue(val).ToString())}\"";
                    s.Write(Unicode.GetBytes(t), 0, t.Length * 2);
                }
                catch (Exception e)
                {
                    SulogWrite(e);
                }
            }
            s.WriteLfUnicode();
            foreach (string skname in rk.GetSubKeyNames())
            {
                try
                {
                    append_key(rk.OpenSubKey(skname, false), s);
                }
                catch (Exception e)
                {
                    SulogWrite(e);
                }
            }
            rk.Dispose();
        }
Ejemplo n.º 11
0
        public static GPSLocation GetClientGPSLocationInfo(string IP = "")
        {
            if (IP.Trim() == string.Empty)
            {
                IP = GetClientIP();
            }

            //Query GPS Location info by IP
            GPSLocation gpsLocationInfo = new GPSLocation();
            string      result          = "";

            result = HttpHelper.DoHttpPost("http://www.pttip.com/server_ip2coordinates.php?nocache=1369992040861", IP);

            //Parser string
            result = result.Substring(1, result.Length - 2).Replace("[", "").Replace("]", "").Replace(@"""", "");
            string[] resultArray = result.Split(',');
            gpsLocationInfo.County     = Unicode.UnicodeToString(resultArray[2]); //.Substring(1, resultArray[2].Length-2));
            gpsLocationInfo.CountyCode = resultArray[4];
            gpsLocationInfo.Area       = Unicode.UnicodeToString(resultArray[3]); //.Substring(1, resultArray[2].Length - 2));
            gpsLocationInfo.Location1  = Convert.ToDouble(resultArray[0]);
            gpsLocationInfo.Location2  = Convert.ToDouble(resultArray[1]);

            //= result;

            return(gpsLocationInfo);
        }
Ejemplo n.º 12
0
    public static int Main(string[] args)
    {
        int failures   = 0;
        int intManaged = 1000;
        int intNative  = 2000;
        int intReturn  = 3000;

        Console.WriteLine("Method Unicode.Marshal_Int_InOut: ExactSpelling = true");
        int int1    = intManaged;
        int intRet1 = Unicode.Marshal_Int_InOut(int1);

        failures += Verify(intReturn, intManaged, intRet1, int1);

        Console.WriteLine("Method Unicode.MarshalPointer_Int_InOut: ExactSpelling = true");
        int int2    = intManaged;
        int intRet2 = Unicode.MarshalPointer_Int_InOut(ref int2);

        failures += Verify(intReturn, intNative, intRet2, int2);

        Console.WriteLine("Method Ansi.Marshal_Int_InOut: ExactSpelling = true");
        int int3    = intManaged;
        int intRet3 = Ansi.Marshal_Int_InOut(int3);

        failures += Verify(intReturn, intManaged, intRet3, int3);

        Console.WriteLine("Method Ansi.MarshalPointer_Int_InOut: ExactSpelling = true");
        int int4    = intManaged;
        int intRet4 = Ansi.MarshalPointer_Int_InOut(ref int4);

        failures += Verify(intReturn, intNative, intRet4, int4);

        int intReturnAnsi    = 4000;
        int intReturnUnicode = 5000;

        Console.WriteLine("Method Unicode.Marshal_Int_InOut2: ExactSpelling = false");
        int int5    = intManaged;
        int intRet5 = Unicode.Marshal_Int_InOut2(int5);

        failures += Verify(intReturnUnicode, intManaged, intRet5, int5);

        Console.WriteLine("Method Unicode.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int6    = intManaged;
        int intRet6 = Unicode.MarshalPointer_Int_InOut2(ref int6);

        failures += Verify(intReturnUnicode, intNative, intRet6, int6);

        Console.WriteLine("Method Ansi.Marshal_Int_InOut2: ExactSpelling = false");
        int int7    = intManaged;
        int intRet7 = Ansi.Marshal_Int_InOut2(int7);

        failures += Verify(intReturnAnsi, intManaged, intRet7, int7);

        Console.WriteLine("Method Ansi.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int8    = intManaged;
        int intRet8 = Ansi.MarshalPointer_Int_InOut2(ref int8);

        failures += Verify(intReturnAnsi, intNative, intRet8, int8);

        return(100 + failures);
    }
Ejemplo n.º 13
0
 private void SkipWhitespace()
 {
     while (Unicode.IsWhitespace(_values[_valuesIndex]))
     {
         _valuesIndex++;
     }
 }
Ejemplo n.º 14
0
        public static PR SendSMS(string Number, string Message, string CountryCode = null, bool Force = false)
        {
            if (!Force && !Application.Configurations.SMSConfiguration.SMSEnabled)
            {
                return(new PR(PS.Success));
            }
            if (CountryCode == null)
            {
                CountryCode = Application.Configurations.SMSConfiguration.DefaultCountryCode;
            }

            Number  = PhoneNumbers.EnsureCountryCode(Number, CountryCode);
            Message = Unicode.ConvertToUnicode(Message);

            switch (Application.Configurations.SMSConfiguration.Provider)
            {
            case SMSProviders.PostToUrl:
                return(SendByPostToUrl(Number, Message));

            case SMSProviders.GetUrl:
                return(SendByGetUrl(Number, Message));

            case SMSProviders.GetUrl2:
                return(SendByGetUrl2(Number, Message));

            default:
                return(new PR(PS.Warning));
            }
        }
Ejemplo n.º 15
0
        public IReadOnlyList <Character> GetCharacters()
        {
            if (Characters == null)
            {
                var characters = new List <Character>();
                foreach (var range in FontFace.UnicodeRanges)
                {
                    CharacterHash += range.First;
                    CharacterHash += range.Last;

                    int last = (int)range.Last;
                    for (int i = (int)range.First; i <= last; i++)
                    {
                        if (!_characters.TryGetValue(i, out Character c))
                        {
                            c = new Character
                            {
                                Char         = Unicode.GetHexValue(i),
                                UnicodeIndex = i
                            };

                            _characters[i] = c;
                        }

                        characters.Add(c);
                    }
                }
                Characters = characters;
            }

            return(Characters);
        }
Ejemplo n.º 16
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;
 }
        protected Credential ReadCredentials(string targetName)
        {
            if (targetName is null)
            {
                throw new ArgumentNullException(nameof(targetName));
            }

            try
            {
                if (Storage.TryReadSecureData(targetName, out string name, out byte[] data))
                {
                    string password = Unicode.GetString(data);

                    return(new Credential(name, password));
                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);

                Trace.WriteException(exception);
            }

            return(null);
        }
Ejemplo n.º 18
0
            public string Label()
            {
                string label;

                if (Character != (char)0)
                {
                    label = Character.ToString() + " (" + Unicode.NameOf(Character) + ")";
                }
                else if (Word != null)
                {
                    label = Word;
                }
                else if (Other == Special.Division)
                {
                    label = ToChar(Other).ToString() + " Division line";
                }
                else if (Other == Special.Imaginary)
                {
                    label = ToChar(Other).ToString() + " Imaginary Number";
                }
                else if (Other == Special.NatLogBase)
                {
                    label = ToChar(Other).ToString() + " Natural Log Base";
                }
                else
                {
                    label = "null?";
                }
                if (Tag != null)
                {
                    label += " " + Tag.ToString();
                }
                return(label);
            }
        /// <summary>
        /// Converts the specified value to binary.
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <returns>The converted value in binary form.</returns>
        protected virtual byte[] ValueAsBinary(object value)
        {
            Arg.NotNull(value, nameof(value));
            Contract.Ensures(Contract.Result <byte[]>() != null);

            switch (value)
            {
            case short @short:
                return(GetBytes(@short));

            case int @int:
                return(GetBytes(@int));

            case long @long:
                return(GetBytes(@long));

            case ushort @ushort:
                return(GetBytes(@ushort));

            case uint @uint:
                return(GetBytes(@uint));

            case ulong @ulong:
                return(GetBytes(@ulong));

            case Guid guid:
                return(guid.ToByteArray());

            case string @string:
                return(Unicode.GetBytes(@string));
            }

            throw new ArgumentException(SR.UnsupportedCorrelationValueType.FormatDefault(value.GetType().Name));
        }
Ejemplo n.º 20
0
        public ActionResult Create(ProductCategory productCategory)
        {
            if (((User)Session[Constants.USER_INFO]).GroupID == Constants.GROUP_ADMIM)
            {
                if (ModelState.IsValid)
                {
                    var userinfo = (User)Session[Constants.USER_INFO];
                    productCategory.MetaTitle = Unicode.RemoveUnicode(productCategory.Name).Replace(" ", "-").ToLower().ToString();
                    productCategory.Status    = true;
                    productCategory.CreatedBy = userinfo.UserName;

                    //tạo màu cho thể loại
                    Random r       = new Random();
                    Color  color   = Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255));
                    string hexcode = "#" + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
                    int    lenght  = 1;
                    for (int i = 0; i < lenght; i++)
                    {
                        var checkcolor = new ProductCategoryDao().CheckByColor(hexcode);
                        if (checkcolor)
                        {
                            lenght++;
                            color   = Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255));
                            hexcode = "#" + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
                        }
                        else
                        {
                            break;
                        }
                    }
                    //hết tạo màu cho thể loại
                    productCategory.Color = hexcode;
                    //productCategory.CreatedBy = Session[Constants.USER_USERNAME].ToString();

                    long id = new ProductCategoryDao().Insert(productCategory);
                    if (id > 0)
                    {
                        SetAlert("Tạo Product Category thành công", Constants.ALERTTYPE_SUCCESS);
                        new LogDao().SetLog("Admin_ProductCategory_Create", "Tạo Product Category thành công", ((User)Session[Constants.USER_INFO]).ID);
                        return(RedirectToAction("Index", "ProductCategory"));
                    }
                    else
                    {
                        SetAlert("Tạo ProductCategory không thành công", Constants.ALERTTYPE_ERROR);
                        new LogDao().SetLog("Admin_ProductCategory_Create", "Tạo ProductCategory không thành công", ((User)Session[Constants.USER_INFO]).ID);
                        return(RedirectToAction("Index", "ProductCategory"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Dữ liệu không lệ");
                    new LogDao().SetLog("Admin_ProductCategory_Create", "Dữ liệu không hợp lệ", ((User)Session[Constants.USER_INFO]).ID);
                    return(View("Create", productCategory));
                }
            }
            SetAlert("Tài khoản của bạn không có quyền", Constants.ALERTTYPE_ERROR);
            new LogDao().SetLog("Admin_ProductCategory_Create", "Tài khoản của bạn không có quyền", ((User)Session[Constants.USER_INFO]).ID);
            return(RedirectToAction("Index", "ProductCategory"));
        }
Ejemplo n.º 21
0
 /**
  * Hydrates the SFX instance properties with inbound data previously created by Serialise().
  */
 public void Deserialise(byte[] data)
 {
     using (var sr = new StringReader(Unicode.GetString(data)))
     {
         var sfx = (SFX) new XmlSerializer(typeof(SFX)).Deserialize(sr);
         Entries = sfx.Entries;
     }
 }
Ejemplo n.º 22
0
        public ActionResult Create(Author author, HttpPostedFileBase postedFile)
        {
            if (((User)Session[Constants.USER_INFO]).GroupID == Constants.GROUP_ADMIM)
            {
                if (ModelState.IsValid)
                {
                    var    userinfo = (User)Session[Constants.USER_INFO];
                    string path;
                    string filename     = "";
                    string fullfilename = "";
                    if (postedFile == null)
                    {
                        fullfilename = "computer-icons-user-profile-login-my-account-icon-png-clip-art.png";
                        path         = Path.Combine(Server.MapPath("~/Data/ImgAuthor"), fullfilename);
                        //postedFile.SaveAs(path);
                    }
                    else
                    {
                        //Luu ten fie, luu y bo sung thu vien using System.IO;
                        filename     = Path.GetFileName(postedFile.FileName);
                        fullfilename = filename.Split('.')[0] + "(" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ")." + filename.Split('.')[1];
                        //Luu duong dan cua file
                        path = Path.Combine(Server.MapPath("~/Data/ImgAuthor"), fullfilename);
                        postedFile.SaveAs(path);
                    }

                    author.Image     = fullfilename;
                    author.Status    = true;
                    author.CreatedBy = userinfo.UserName;
                    author.MetaTitle = Unicode.RemoveUnicode(author.Name).Replace(" ", "-").ToLower().ToString();
                    author.Tag       = Unicode.RemoveUnicode(author.Name).ToLower().ToString();
                    //author.CreatedBy = Session[Constants.USER_USERNAME].ToString();

                    long id = new AuthorDao().Insert(author);
                    if (id > 0)
                    {
                        SetAlert("Tạo Author thành công", Constants.ALERTTYPE_SUCCESS);
                        new LogDao().SetLog("Admin_Author_Create", "Tạo Author thành công", ((User)Session[Constants.USER_INFO]).ID);
                        return(RedirectToAction("Index", "Author"));
                    }
                    else
                    {
                        SetAlert("Tạo Author không thành công", Constants.ALERTTYPE_ERROR);
                        new LogDao().SetLog("Admin_Author_Create", "Tạo Author không thành công", ((User)Session[Constants.USER_INFO]).ID);
                        return(RedirectToAction("Index", "Author"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Dữ liệu không lệ");
                    new LogDao().SetLog("Admin_Author_Create", "Dữ liệu không hợp lệ", ((User)Session[Constants.USER_INFO]).ID);
                    return(View("Create", author));
                }
            }
            SetAlert("Tài khoản của bạn không có quyền", Constants.ALERTTYPE_ERROR);
            new LogDao().SetLog("Admin_Author_Create", "Tài khoản của bạn không có quyền", ((User)Session[Constants.USER_INFO]).ID);
            return(RedirectToAction("Index", "Author"));
        }
Ejemplo n.º 23
0
        public static void reg_save(Stream s)
        {
            RegistryKey[] roots = new RegistryKey[]
            {
                ClassesRoot,
                CurrentConfig,
                CurrentUser,
                DynData,
                LocalMachine,
                PerformanceData,
                Users
            };

            try
            {
                foreach (RegistryKey rk in roots)
                {
                    try
                    {
                        string t = $"\"{xml_esc(rk.Name)}\"";
                        s.Write(Unicode.GetBytes(t), 0, t.Length * 2);
                        foreach (string val in rk.GetValueNames())
                        {
                            try
                            {
                                t = $" \"{xml_esc(val)}\"=\"{xml_esc(rk.GetValue(val).ToString())}\"";
                                s.Write(Unicode.GetBytes(t), 0, t.Length * 2);
                            }
                            catch (Exception e)
                            {
                                SulogWrite(e);
                            }
                        }
                        s.Write(Unicode.GetBytes("\n"), 0, 2);
                        foreach (string skname in rk.GetSubKeyNames())
                        {
                            try
                            {
                                append_key(rk.OpenSubKey(skname, false), s);
                            }
                            catch (Exception e)
                            {
                                SulogWrite(e);
                            }
                        }
                        rk.Close();
                    }
                    catch (Exception e)
                    {
                        SulogWrite(e);
                    }
                }
            }
            catch (Exception e)
            {
                SulogWrite(e);
            }
        }
Ejemplo n.º 24
0
 public void TestLetterOptimizations()
 {
     for (uint rune = 0; rune < Unicode.MaxLatin1; rune++)
     {
         Assert.AreEqual(Unicode.To(Unicode.Case.Lower, rune), Unicode.ToLower(rune), "For rune 0x{0:x} ToLower", rune);
         Assert.AreEqual(Unicode.To(Unicode.Case.Upper, rune), Unicode.ToUpper(rune), "For rune 0x{0:x} ToUpper", rune);
         Assert.AreEqual(Unicode.To(Unicode.Case.Title, rune), Unicode.ToTitle(rune), "For rune 0x{0:x} ToTitle", rune);
     }
 }
Ejemplo n.º 25
0
        /**
         * Retrieves a byte array representing the object state which can hydrate an SFX instance using Deserialise().
         */
        public byte[] Serialise()
        {
            var xml = new XmlSerializer(typeof(SFX));

            using (var sw = new StringWriter())
            {
                xml.Serialize(sw, this);
                return(Unicode.GetBytes(sw.ToString()));
            }
        }
Ejemplo n.º 26
0
        public void NthCodepoint()
        {
            var str = "\0\U0002F8B6a\U0002F8D3b\0c";

            Assert.AreEqual(null, Unicode.NthCodepoint(str, -1));
            Assert.AreEqual(0, Unicode.NthCodepoint(str, 0));
            Assert.AreEqual(0x2F8B6, Unicode.NthCodepoint(str, 1));
            Assert.AreEqual('a', Unicode.NthCodepoint(str, 2));
            Assert.AreEqual(null, Unicode.NthCodepoint(str, 12));
        }
        unsafe string ConvertBufferToStr()
        {
            var cs = stackalloc char[m_Buffer.Length * 2];
            int length;

            Unicode.Utf8ToUtf16((byte *)m_Buffer.GetUnsafePtr(), m_Buffer.Length, cs, out length, m_Buffer.Length * 2);
            var str = new string(cs, 0, length);

            return(str);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Writes a copy of the specified <see cref="FixedString128"/> to the buffer.
        /// </summary>
        /// <param name="value">The value to write.</param>
        void Write(FixedString128 value)
        {
            var capacity     = value.UTF8LengthInBytes;
            var utf16_buffer = stackalloc char[capacity];

            fixed(FixedListByte128 *c = &value.AsFixedList)
            {
                Unicode.Utf8ToUtf16((byte *)c + sizeof(ushort), value.UTF8LengthInBytes, utf16_buffer, out var utf16_length, capacity);
                Write(utf16_buffer, utf16_length);
            }
        }
Ejemplo n.º 29
0
        public void UnicodeShouldReturnCorrectCode()
        {
            var func = new Unicode();

            var result = func.Execute(FunctionsHelper.CreateArgs("B"), _parsingContext);

            Assert.AreEqual(66, result.Result);

            result = func.Execute(FunctionsHelper.CreateArgs("a"), _parsingContext);
            Assert.AreEqual(97, result.Result);
        }
            /// <summary>
            /// Writes the specified fixed string to the buffer as a literal.
            /// </summary>
            /// <param name="value">The string value to write.</param>
            void WriteValue(FixedString128 value)
            {
                var value_ptr    = UnsafeUtility.AddressOf(ref value);
                var value_len    = *(ushort *)value_ptr;
                var value_bytes  = (byte *)value_ptr + sizeof(ushort);
                var utf16_buffer = stackalloc char[value_len];

                // This is not actually correct -- We need Utf8ToUCS but that doesn't exist
                Unicode.Utf8ToUtf16(value_bytes, value_len, utf16_buffer, out var utf16_length, value_len);
                WriteValueLiteral(utf16_buffer, utf16_length);
            }
Ejemplo n.º 31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MEStringsSelector"/> class.
        /// </summary>
        /// <param name="names">
        /// The names.
        /// </param>
        public MEStringsSelector(Map map, object sender)
        {
            InitializeComponent();

            if (encodes == null)
            {
                // load any listed unicode codes
                try
                {
                    encodes = loadUnicodes();
                }
                catch
                {
                    encodes = new List<Encode>();
                }
            }

            // Select ALL
            this.cbSelectStringIDs.SelectedIndex = 0;
            this.Owner = (Form)sender;

            string[] names = map.Strings.Name;
            // KeyPreview = true;
            for (int i = 0; i < names.Length; i++)
            {
                //dgvStringIDs.Rows.Add(new object[] { names[i], i, -1 });
                StringID SID = new StringID(names[i], i);
                // Create 2 duplicate lists
                stringIDs.Add(SID);
                stringIDsNoUnicode.Add(SID);
            }

            UnicodeTableReader.UnicodeTable ut = map.Unicode.ut[0];
            if (ut.SIDs == null)
                ut.Read();
            for (int i = 0; i < ut.US.Length; i++)
            {
                Unicode uni = new Unicode(i, ut.US[i].uString, ut.US[i].size, ut.US[i].offset, stringIDs[ut.SIDs[i].id]);
                unicodes.Add(uni);
                StringID SID = stringIDs[ut.SIDs[i].id];
                SID.unicodes.Add(uni);
                if (stringIDsNoUnicode.Contains(SID))
                {
                    stringIDsNoUnicode.Remove(SID); // Switch it from NO UNICODE list
                    stringIDsUnicode.Add(SID);      // ...to UNICODE list
                }
            }

            lbStringIDs.DataSource = stringIDs;
            lbUnicodes.DataSource = unicodes;

            // Set default sort method and apply sort to lists
            cbSIDSort.SelectedIndex = 0;
            cbUnicodeSort.SelectedIndex = 0;

            List<string> ss = new List<string>();
            for (int i = 0; i < unicodes[1].stringID.unicodes.Count; i++)
            {
                string s = unicodes[0].stringID.unicodes[i].ToString();
                byte[] tempbytes = System.Text.Encoding.Unicode.GetBytes(s);
                System.Text.Encoding decode = System.Text.Encoding.ASCII;
                ss.Add(decode.GetString(tempbytes));
            }

            setlbStringsIDDataSource();
        }