Пример #1
0
            private void ExecuteNewGameCommand(byte[] commandParameters)
            {
                int height     = commandParameters[0];
                int width      = commandParameters[1];
                int minesCount = commandParameters[2];
                int x          = commandParameters[3];
                int y          = commandParameters[4];
                NewGameEventArgs e;

                if (commandParameters.Length == 9)//Seed is sent
                {
                    byte[] seedBytes = new byte[4];
                    commandParameters.CopyTo(seedBytes, 3);
                    int seed = ByteArrayConverter.ToInt32(seedBytes);
                    model.NewGame(height, width, minesCount, seed);
                    e = new NewGameEventArgs(height, width, minesCount, seed);
                }
                else//Seed is not sent
                {
                    model.NewGame(height, width, minesCount);
                    e = new NewGameEventArgs(height, width, minesCount);
                }

                model.OnNewGame(e);
                List <Sector>          initialList = model.RevealSector(x, y);
                RevealSectorsEventArgs ee          = new RevealSectorsEventArgs(initialList);

                model.OnRevealSectors(ee);
            }
Пример #2
0
        private string GetSha256Hash_BigFile(Stream fileStream)
        {
            string result = string.Empty;

            using (SHA256Managed hashAlgorithm = new SHA256Managed())
            {
                long bytesToHash = fileStream.Length;

                byte[] buffer     = new byte[bigChunkSize];
                int    sizeToRead = buffer.Length;
                while (bytesToHash > 0)
                {
                    if (bytesToHash < (long)sizeToRead)
                    {
                        sizeToRead = (int)bytesToHash;
                    }

                    int bytesRead = fileStream.ReadAsync(buffer, 0, sizeToRead, CancellationHelper.GetCancellationToken()).Result;
                    CancellationHelper.ThrowIfCancelled();
                    hashAlgorithm.TransformBlock(buffer, 0, bytesRead, null, 0);
                    bytesToHash -= (long)bytesRead;
                    if (bytesRead == 0)
                    {
                        throw new InvalidOperationException("Unexpected end of stream");
                        // or break;
                    }
                }
                hashAlgorithm.TransformFinalBlock(buffer, 0, 0);
                buffer = null;
                result = ByteArrayConverter.ToHexString(hashAlgorithm.Hash);
            }

            return(result);
        }
Пример #3
0
        internal void PersistMeTo(IFileSystemInterface fsi)
        {
            var sizeOfLong = OdbType.Long.Size;
            var sizeOfInt  = OdbType.Integer.Size;

            // build the full byte array to write once
            var bytes = new byte[sizeOfLong + sizeOfInt + _size];

            var bytesOfPosition = ByteArrayConverter.LongToByteArray(_position);
            var bytesOfSize     = ByteArrayConverter.IntToByteArray(_size);

            for (var i = 0; i < sizeOfLong; i++)
            {
                bytes[i] = bytesOfPosition[i];
            }

            var offset = sizeOfLong;

            for (var i = 0; i < sizeOfInt; i++)
            {
                bytes[offset] = bytesOfSize[i];
                offset++;
            }

            foreach (var tmp in _listOfBytes)
            {
                Buffer.BlockCopy(tmp, 0, bytes, offset, tmp.Length);
                offset += tmp.Length;
            }

            fsi.WriteBytes(bytes, false);
        }
Пример #4
0
        public async Task <ActionMessage> UpdateAsync(AccountDetailsModel model, List <IFormFile> userImage)
        {
            ActionMessage response = new ActionMessage();

            User user = await userManager.FindByIdAsync(model.UserId);

            bool exists = userManager.Users.Where(x => x.Id != model.UserId && x.UserName == model.UserName).Any();

            if (exists)
            {
                response.Error = $"Update Failed!!! Username {model.UserName} aleready exists ";
                return(response);
            }

            byte[] image = await ByteArrayConverter.ConvertImageToByteArrayAsync(userImage);

            if (user != null)
            {
                user.Email     = model.Email;
                user.UserName  = model.UserName;
                user.UserImage = image;

                IdentityResult result = await userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    response.Message = "Update Successful";
                }
            }
            else
            {
                response.Error = "Update Failed";
            }
            return(response);
        }
Пример #5
0
        public async Task <IActionResult> EmailValidation(EmailValidationDto model)
        {
            if (ModelState.IsValid)
            {
                //Console.WriteLine(model.Email + "," + model.Code);
                HttpContext.Session.TryGetValue(HttpContext.Session.Id,
                                                out byte[] _code);
                if (_code == null || _code.Length == 0)
                {
                    return(View(model));
                }
                var code = ByteArrayConverter.ToString(_code);
                if (code != model.Code)
                {
                    ModelState.AddModelError("Code", "验证码错误");
                    return(View(model));
                }

                var user = await _userManager.FindByEmailAsync(model.Email);

                await _signInManager.SignInAsync(user, false);

                return(RedirectToAction("ChangePassword"));
            }
            return(View(model));
        }
        static NServiceBusXmlMessageSerializer()
        {
            XmlSerializer = new Lazy <JsonSerializer>(() => JsonSerializer.Create(XmlSerializerSettings));

            ByteArrayConverter       = new ByteArrayConverter();
            MessageDataJsonConverter = new MessageDataJsonConverter();
            StringDecimalConverter   = new StringDecimalConverter();

            DefaultContractResolver serializerContractResolver =
                new JsonContractResolver(ByteArrayConverter, MessageDataJsonConverter, StringDecimalConverter)
            {
                NamingStrategy = new DefaultNamingStrategy()
            };

            SerializerSettings = new JsonSerializerSettings
            {
                NullValueHandling      = NullValueHandling.Ignore,
                DefaultValueHandling   = DefaultValueHandling.Ignore,
                MissingMemberHandling  = MissingMemberHandling.Ignore,
                ObjectCreationHandling = ObjectCreationHandling.Auto,
                ConstructorHandling    = ConstructorHandling.AllowNonPublicDefaultConstructor,
                ContractResolver       = serializerContractResolver,
                TypeNameHandling       = TypeNameHandling.None,
                DateParseHandling      = DateParseHandling.None,
                DateTimeZoneHandling   = DateTimeZoneHandling.RoundtripKind
            };

            _serializer = new Lazy <JsonSerializer>(() => JsonSerializer.Create(SerializerSettings));
        }
        public void WhenConverting_FromByteArrayToString_ReturnsCorrectValues()
        {
            var testCases = new[]
            {
                new
                {
                    Options    = ByteArrayConverterOptions.Hexadecimal | ByteArrayConverterOptions.HexInclude0x,
                    Expected   = new[] { "0xDEAD", "0xB33FBEEF", "0xEA5EEA5EEA5E", "0xCA75CA75CA75CA75" },
                    FieldBytes = new []
                    {
                        new byte[] { 0xDE, 0xAD },
                        new byte[] { 0xB3, 0x3F, 0xBE, 0xEF },
                        new byte[] { 0xEA, 0x5E, 0xEA, 0x5E, 0xEA, 0x5E },
                        new byte[] { 0xCA, 0x75, 0xCA, 0x75, 0xCA, 0x75, 0xCA, 0x75 }
                    }
                },
                new
                {
                    Options    = ByteArrayConverterOptions.Hexadecimal | ByteArrayConverterOptions.HexDashes,
                    Expected   = new[] { "DE-AD", "B3-3F-BE-EF", "EA-5E-EA-5E-EA-5E", "CA-75-CA-75-CA-75-CA-75" },
                    FieldBytes = new []
                    {
                        new byte[] { 0xDE, 0xAD },
                        new byte[] { 0xB3, 0x3F, 0xBE, 0xEF },
                        new byte[] { 0xEA, 0x5E, 0xEA, 0x5E, 0xEA, 0x5E },
                        new byte[] { 0xCA, 0x75, 0xCA, 0x75, 0xCA, 0x75, 0xCA, 0x75 }
                    }
                },
                new
                {
                    Options  = ByteArrayConverterOptions.Base64,
                    Expected = new []
                    {
                        Convert.ToBase64String(new byte[] { 0xDE, 0xAD }),
                        Convert.ToBase64String(new byte[] { 0xB3, 0x3F, 0xBE, 0xEF }),
                        Convert.ToBase64String(new byte[] { 0xEA, 0x5E, 0xEA, 0x5E, 0xEA, 0x5E }),
                        Convert.ToBase64String(new byte[] { 0xCA, 0x75, 0xCA, 0x75, 0xCA, 0x75, 0xCA, 0x75 })
                    },
                    FieldBytes = new []
                    {
                        new byte[] { 0xDE, 0xAD },
                        new byte[] { 0xB3, 0x3F, 0xBE, 0xEF },
                        new byte[] { 0xEA, 0x5E, 0xEA, 0x5E, 0xEA, 0x5E },
                        new byte[] { 0xCA, 0x75, 0xCA, 0x75, 0xCA, 0x75, 0xCA, 0x75 }
                    }
                }
            };

            foreach (var t in testCases)
            {
                var converter = new ByteArrayConverter(t.Options);
                foreach (var f in t.Expected.Zip(t.FieldBytes, (expected, test) => new { test, expected }))
                {
                    var actual = converter.ConvertToString(f.test, null, null);

                    Assert.AreEqual(actual, f.expected);
                }
            }
        }
Пример #8
0
        public void SendEmail(string email)
        {
            var code = Guid.NewGuid().ToString().Substring(0, 5);

            HttpContext.Session.Set(HttpContext.Session.Id,
                                    ByteArrayConverter.ToByteArray(code));
            EmailHelper.SendEmail(email, code);
        }
Пример #9
0
        public virtual void TestBigDecimal6()
        {
            var bd1 = new Decimal(0.000000000000000123456789);
            var b2  = ByteArrayConverter.DecimalToByteArray(bd1);
            var bd2 = ByteArrayConverter.ByteArrayToDecimal(b2);

            AssertEquals(bd1, bd2);
        }
Пример #10
0
        public virtual void TestString()
        {
            var s  = "test1";
            var b2 = ByteArrayConverter.StringToByteArray(s, -1);
            var s2 = ByteArrayConverter.ByteArrayToString(b2);

            AssertEquals(s, s2);
        }
Пример #11
0
        public virtual void TestInt()
        {
            var l1 = 785412;
            var b  = ByteArrayConverter.IntToByteArray(l1);
            var l2 = ByteArrayConverter.ByteArrayToInt(b);

            AssertEquals(l1, l2);
        }
Пример #12
0
        public virtual void TestFloat()
        {
            var l1 = (float)785412.4875;
            var b2 = ByteArrayConverter.FloatToByteArray(l1);
            var l2 = ByteArrayConverter.ByteArrayToFloat(b2);

            AssertEquals(l1, l2, 0);
        }
Пример #13
0
        public virtual void TestDouble()
        {
            var l1 = 785412.4875;
            var b2 = ByteArrayConverter.DoubleToByteArray(l1);
            var l2 = ByteArrayConverter.ByteArrayToDouble(b2);

            AssertEquals(l1, l2, 0);
        }
Пример #14
0
            protected byte[] GenerateNewGameParameters(int height, int width, int minesCount, int seed)
            {
                List <byte> result = new List <byte>(GenerateNewGameParameters(height, width, minesCount));

                result.AddRange(ByteArrayConverter.ToArrayOfBytes(seed, 4));

                return(result.ToArray());
            }
Пример #15
0
        public virtual void TestChar()
        {
            var c  = '\u00E1';
            var b2 = ByteArrayConverter.CharToByteArray(c);
            var c1 = ByteArrayConverter.ByteArrayToChar(b2);

            AssertEquals(c, c1);
        }
        public void It_should_convert_double_to_binary_and_from_binary_to_double_with_the_success()
        {
            const double value = 1.2345678910111213141516171d;

            var byteArray      = ByteArrayConverter.DoubleToByteArray(value);
            var convertedValue = ByteArrayConverter.ByteArrayToDouble(byteArray);

            Assert.That(convertedValue, Is.EqualTo(value));
        }
        public void It_should_convert_datetime_to_binary_and_from_datetime_to_bool_with_the_success()
        {
            var value = new DateTime(1988, 8, 6);

            var byteArray      = ByteArrayConverter.DateToByteArray(value);
            var convertedValue = ByteArrayConverter.ByteArrayToDate(byteArray);

            Assert.That(convertedValue, Is.EqualTo(value));
        }
        public void It_should_convert_string_to_binary_and_from_binary_to_string_with_success()
        {
            const string name = "Magdalena Płatek-Spólnik";

            var byteArray      = ByteArrayConverter.StringToByteArray(name, -1);
            var convertedValue = ByteArrayConverter.ByteArrayToString(byteArray);

            Assert.That(convertedValue, Is.EqualTo(name));
        }
        public void It_should_convert_decimal_to_binary_and_from_binary_to_decimal_with_the_success()
        {
            const decimal value = 1.23456789101112131415161718192021222324252627282930m;

            var byteArray      = ByteArrayConverter.DecimalToByteArray(value);
            var convertedValue = ByteArrayConverter.ByteArrayToDecimal(byteArray);

            Assert.That(convertedValue, Is.EqualTo(value));
        }
        public void It_should_convert_char_to_binary_and_from_binary_to_char_with_the_success()
        {
            const char value = 'c';

            var byteArray      = ByteArrayConverter.CharToByteArray(value);
            var convertedValue = ByteArrayConverter.ByteArrayToChar(byteArray);

            Assert.That(convertedValue, Is.EqualTo(value));
        }
        public void It_should_convert_short_to_binary_and_from_binary_to_short_with_the_success()
        {
            const short value = 12345;

            var byteArray      = ByteArrayConverter.ShortToByteArray(value);
            var convertedValue = ByteArrayConverter.ByteArrayToShort(byteArray);

            Assert.That(convertedValue, Is.EqualTo(value));
        }
        public void It_should_convert_long_to_binary_and_from_binary_to_long_with_the_success()
        {
            const long value = 1234567891011121314L;

            var byteArray      = ByteArrayConverter.LongToByteArray(value);
            var convertedValue = ByteArrayConverter.ByteArrayToLong(byteArray);

            Assert.That(convertedValue, Is.EqualTo(value));
        }
        public void It_should_convert_float_to_binary_and_from_binary_to_float_with_the_success()
        {
            const float value = 1.2345678910111213141516171f;

            var byteArray      = ByteArrayConverter.FloatToByteArray(value);
            var convertedValue = ByteArrayConverter.ByteArrayToFloat(byteArray);

            Assert.That(convertedValue, Is.EqualTo(value));
        }
        public void It_should_convert_bool_to_binary_and_from_binary_to_bool_with_the_success()
        {
            const bool value = true;

            var byteArray      = ByteArrayConverter.BooleanToByteArray(value);
            var convertedValue = ByteArrayConverter.ByteArrayToBoolean(byteArray);

            Assert.That(convertedValue, Is.EqualTo(value));
        }
Пример #25
0
        public void FromByteArray()
        {
            var converter = new ByteArrayConverter();
            var result    = converter.Convert(new byte[] { 55, 66, 77 });

            Assert.AreEqual(3, (result as byte[])?.Length);
            Assert.AreEqual(55, (result as byte[])[0]);
            Assert.AreEqual(66, (result as byte[])[1]);
            Assert.AreEqual(77, (result as byte[])[2]);
        }
        public void CanSerializeAndDeserialize()
        {
            byte[] value = Encoding.UTF8.GetBytes("lorem ipsum");
            ByteArrayConverter converter = new ByteArrayConverter();
            byte[] bytes = converter.Serialize(value);

            byte[] valueFromBytes = converter.Deserialize(bytes);
            
            Assert.Equal(valueFromBytes, value);
        }
Пример #27
0
        public void Direct_null()
        {
            ByteArrayConverter converter  = new ByteArrayConverter();
            StringBuilder      sb         = new StringBuilder();
            JsonSerializer     serializer = new JsonSerializer();

            serializer.Converters.Add(converter);
            converter.WriteJson(
                new JsonTextWriter(new StringWriter(sb)), null, serializer);
            sb.ToString().Should().Be("null");
        }
Пример #28
0
        public virtual void TestBoolean()
        {
            var b1 = true;
            var b2 = ByteArrayConverter.BooleanToByteArray(b1);
            var b3 = ByteArrayConverter.ByteArrayToBoolean(b2, 0);

            AssertEquals(b1, b3);
            b1 = false;
            b2 = ByteArrayConverter.BooleanToByteArray(b1);
            b3 = ByteArrayConverter.ByteArrayToBoolean(b2, 0);
            AssertEquals(b1, b3);
        }
Пример #29
0
        public async Task <IActionResult> AddImage(RecipeAddImageView recipe, List <IFormFile> recipeImage)
        {
            if (ModelState.IsValid)
            {
                byte[] image = await ByteArrayConverter.ConvertImageToByteArrayAsync(recipeImage);

                var recipeDb = recipeService.GetById(recipe.Id);
                recipeDb.RecipeImage = image;

                recipeService.Update(recipeDb);
            }

            return(View(recipe));
        }
Пример #30
0
        public virtual void TestStringGetBytesWithoutEncoding()
        {
            var test = "How are you my friend?";
            var size = 1000000;
            var t0   = OdbTime.GetCurrentTimeInMs();

            // Execute with encoding
            for (var i = 0; i < size; i++)
            {
                ByteArrayConverter.StringToByteArray(test, -1);
            }
            var t1 = OdbTime.GetCurrentTimeInMs();

            Println("With Encoding=" + (t1 - t0));
        }
Пример #31
0
        public virtual void TestLong()
        {
            long l1 = 785412;
            var  b  = ByteArrayConverter.LongToByteArray(l1);
            var  l2 = ByteArrayConverter.ByteArrayToLong(b);

            AssertEquals(l1, l2);
            l1 = long.MaxValue;
            b  = ByteArrayConverter.LongToByteArray(l1);
            l2 = ByteArrayConverter.ByteArrayToLong(b);
            AssertEquals(l1, l2);
            l1 = long.MinValue;
            b  = ByteArrayConverter.LongToByteArray(l1);
            l2 = ByteArrayConverter.ByteArrayToLong(b);
            AssertEquals(l1, l2);
        }
        private void CreateObservation()
        {
            ServiceObservation.Observation newObs = new ServiceObservation.Observation();

            int tmp = 0;
            if (Int32.TryParse(_weight, out tmp)) {
                newObs.Weight = tmp;
            }

            if (Int32.TryParse(_bloodPressure, out tmp)) {
                newObs.BloodPressure = tmp;
            }

            if (_comment != null) {
                newObs.Comment = _comment;
            }

            if (_arrayPrescription != null) {
                newObs.Prescription = _arrayPrescription.ToArray();
            }

            if (_listDisplayedImages != null && _listDisplayedImages.Count != 0)
            {
                /// Le nombre d'images voulues utile pour creer le tableau statique
                int finalSize = _listDisplayedImages.Count;

                /// Le tableau d'images final
                byte[][] finalArrayImages = new byte[finalSize][];

                ///Pour convertir nos images en byte[]
                ByteArrayConverter cv = new ByteArrayConverter();

                for (int i = 0; i < finalSize; i++)
                {
                    byte[] convertedImg = (byte[])cv.ConvertBack(_listDisplayedImages.ElementAt(i), null, null, null);
                    finalArrayImages[i] = convertedImg;
                }
                newObs.Pictures = finalArrayImages;

                newObs.Date = DateTime.Now;
            }

            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += new DoWorkEventHandler((object s, DoWorkEventArgs e) =>
            {
                ServiceObservation.ServiceObservationClient observService = new ServiceObservation.ServiceObservationClient();
                e.Result = observService.AddObservation(_idPatient, newObs);
            });

            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((object s, RunWorkerCompletedEventArgs e) =>
            {
                WaitingMessage = "";
                if (e.Cancelled)
                {
                    WaitingMessage = "L'opération a été annulée.";
                }
                if (e.Error != null)
                {
                    WaitingMessage = "Erreur lors de la création : " + e.Error.Message;
                }
                bool? resWebService = e.Result as bool?;
                if (resWebService.HasValue && resWebService.Value)
                {
                    View.PatientBrowserView window = new View.PatientBrowserView();
                    ViewModel.PatientBrowserViewModel vm = new PatientBrowserViewModel(window);
                    window.DataContext = vm;

                    _ns = NavigationService.GetNavigationService(_linkedView);
                    _ns.Navigate(window);
                }
                else {
                    WaitingMessage = "Erreur côté serveur lors de la création. Veuillez recommencer";
                }

            });

            worker.RunWorkerAsync();
            WaitingMessage = "Ajout de l'observation en cours";
        }
Пример #33
0
        private void SelectImage()
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "Images Files (*.jpg)|*.jpg";
            ///
            // Peut-etre informer l'utilisateur que les images ne doivent pas depasser 128*128
            ///

            openFileDialog1.FileOk += new CancelEventHandler((object s, CancelEventArgs e) =>
            {
                Imagepath = openFileDialog1.FileName;
                BitmapImage bitimg = new BitmapImage(new Uri(Imagepath));
                Imagesrc = bitimg;
                ByteArrayConverter cv = new ByteArrayConverter();
                _imagebyte = (byte[]) cv.ConvertBack(bitimg, null, null, null);
            });
            openFileDialog1.ShowDialog();
        }