Ejemplo n.º 1
0
        public void Decode64Test()
        {
            EncodingService encodingService = new EncodingService();
            string          test1           = encodingService.Decode64(base64After);

            Assert.AreEqual(base64Original, test1);
        }
Ejemplo n.º 2
0
        public ActionResult Create(Usuarios u)
        {
            var algo            = this.repo.ComboRolUsuario();
            var encodingService = new EncodingService();


            if (!ModelState.IsValid)
            {
                List <SelectListItem> listaDePerfiles = new List <SelectListItem>();
                foreach (var item in algo)
                {
                    SelectListItem Perfil = new SelectListItem()
                    {
                        Value = item.Key.ToString(),
                        Text  = item.Value
                    };
                    listaDePerfiles.Add(Perfil);
                }
                ViewBag.ListaPerfiles = new List <SelectListItem>();
                ViewBag.ListaPerfiles = listaDePerfiles;
                return(View(u));
            }
            u.Perfil   = algo.ContainsKey(u.DIR) ? algo[u.DIR] : null;
            u.Password = encodingService.SHA256(u.Password);

            this.repo.InsertarUsuarios(u);
            return(RedirectToAction("Usuarios"));
        }
Ejemplo n.º 3
0
            static async Task ProcessInvoiceMessagesAsync(Message message, CancellationToken token)
            {
                var json  = EncodingService.Base64Decode(message.Body);
                var trans = EncodingService.DecodeJson <OnlineTransaction>(json);

                // Random delay of at least a second
                var rnd = new Random(Environment.TickCount);
                await Task.Delay((int)(1000 + 1000 * rnd.NextDouble()));

                // Process the message.
                //Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{json}");
                Console.WriteLine(DateTime.Now.ToString() + ": Invoice Received");

                // Process the invoice
                trans.ProcessedTimeUTC = DateTime.UtcNow;
                trans.Processed        = true;
                // Persist to SQL
                await SaveTransactionAsync(trans, json);

                // Complete the message so that it is not received again.
                // This can be done only if the subscriptionClient is created in ReceiveMode.PeekLock mode (which is the default).
                await invoiceSubscriptionClient.CompleteAsync(message.SystemProperties.LockToken);

                // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed.
                // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
                // to avoid unnecessary exceptions.
            }
Ejemplo n.º 4
0
        public async Task <IActionResult> Create(Usuarios cl)
        {
            EncodingService encodingService = new EncodingService();
            string          token           = HttpContext.Session.GetString("TOKEN");

            var listausuarios = await this.repo.GetUsuariosAsync();

            List <SelectListItem> listaPerfiles = new List <SelectListItem>();

            foreach (var item in listausuarios)
            {
                SelectListItem selList = new SelectListItem()
                {
                    Value = item.DIR.ToString(), Text = item.Perfil
                };
                if (!listaPerfiles.Any(x => x.Value == selList.Value && x.Text == selList.Text))
                {
                    listaPerfiles.Add(selList);
                }
            }
            if (!ModelState.IsValid)
            {
                ViewBag.ListaPerfiles = listaPerfiles;
                return(View(cl));
            }

            cl.Perfil   = listaPerfiles.Any(x => x.Value == cl.DIR.ToString()) ? listaPerfiles.Where(x => x.Value == cl.DIR.ToString()).Select(x => x.Text).FirstOrDefault() : null;
            cl.Password = encodingService.SHA256(cl.Password);

            await this.repo.InsertarUsuarioAsync(cl, token);


            return(RedirectToAction("Usuarios"));
        }
Ejemplo n.º 5
0
        public void Verify_CohortReference_Is_Mapped()
        {
            EncodingService.Verify(x => x.Encode(It.IsAny <long>(), EncodingType.CohortReference), Times.Exactly(2));

            Assert.AreEqual("1_Encoded", GetCohortsWithEmployer(1).CohortReference);
            Assert.AreEqual("2_Encoded", GetCohortsWithEmployer(2).CohortReference);
        }
        private EuGatewayService CreateGatewayService(
            TemporaryExposureKeyRepository keysRepository,
            ISignatureService signatureService,
            IMapper autoMapper,
            IGatewayHttpClient gateWayHttpClient,
            IKeyFilter keyFilter,
            IGatewayWebContextReader webContextReader,
            IEFGSKeyStoreService storeService,
            ILogger <EuGatewayService> logger,
            EuGatewayConfig config)
        {
            var encodingService = new EncodingService();
            var epochConverter  = new EpochConverter();

            var gatewaySyncStateSettingsDao = new GatewaySyncStateSettingsDao(new SettingRepository(_dbContext));
            var settingsService             = new SettingsService(gatewaySyncStateSettingsDao);

            return(new EuGatewayService(
                       keysRepository,
                       signatureService,
                       encodingService,
                       keyFilter,
                       webContextReader,
                       autoMapper,
                       logger,
                       config,
                       settingsService,
                       epochConverter,
                       gateWayHttpClient,
                       storeService));
        }
Ejemplo n.º 7
0
        public void Verify_CohortReference_Is_Mapped()
        {
            EncodingService.Verify(x => x.Encode(It.IsAny <long>(), EncodingType.CohortReference), Times.Exactly(2));

            Assert.AreEqual("5_Encoded", GetCohortInReviewViewModel(5).CohortReference);
            Assert.AreEqual("6_Encoded", GetCohortInReviewViewModel(6).CohortReference);
        }
        public void Verify_CohortRefrence_Is_Mapped()
        {
            EncodingService.Verify(x => x.Encode(It.IsAny <long>(), EncodingType.CohortReference), Times.Exactly(2));

            Assert.AreEqual("2_Encoded", GetDraftCohortWithId(2).CohortReference);
            Assert.AreEqual("3_Encoded", GetDraftCohortWithId(3).CohortReference);
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            WorkflowEngine  workflowEngine;
            Video           video;
            CloudService    cloudService;
            EncodingService encodingService;
            Message         message;
            Database        database;

            video        = new Video();
            cloudService = new CloudService();
            var videoUpload = new VideoUploadActivity(video, cloudService);

            encodingService = new EncodingService();
            var prepareForEncoding = new PrepareForEncodingActivity(video, encodingService);

            message = new Message();
            var sendEmail = new SendEmailActivity(video, message);

            database = new Database();
            var changeDatabase = new ChangeDatabaseActivity(video, database);

            workflowEngine = new WorkflowEngine();
            workflowEngine.RegisterActivity(videoUpload);
            workflowEngine.RegisterActivity(prepareForEncoding);
            workflowEngine.RegisterActivity(sendEmail);
            workflowEngine.RegisterActivity(changeDatabase);

            workflowEngine.Run();
        }
Ejemplo n.º 10
0
        public static string GetSpriteFromJob(MultiGrfReader grf, Job job, PreviewHelper helper, string sprite, ViewIdTypes type)
        {
            switch (type)
            {
            case ViewIdTypes.Garment:
                return(GetSpritePathFromJob(grf, job, @"data\sprite\·Îºê\" + sprite + @"\" + helper.GenderString + "\\{0}_" + helper.GenderString, helper.Gender, null, sprite));

            case ViewIdTypes.Shield:
                return(GetSpritePathFromJob(grf, job, @"data\sprite\¹æÆÐ\{0}\{0}_" + helper.GenderString + sprite, helper.Gender, "¹æÆÐ", sprite));

            case ViewIdTypes.Weapon:
                return(GetSpritePathFromJob(grf, job, @"data\sprite\Àΰ£Á·\{0}\{0}_" + helper.GenderString + sprite, helper.Gender, "Àΰ£Á·", sprite));

            case ViewIdTypes.Headgear:
                return(EncodingService.FromAnyToDisplayEncoding(@"data\sprite\¾Ç¼¼»ç¸®\" + helper.GenderString + "\\" + EncodingService.FromAnyToDisplayEncoding(helper.GenderString + "_") + helper.PreviewSprite));

            case ViewIdTypes.Npc:
                if (helper.PreviewSprite != null && helper.PreviewSprite.EndsWith(".gr2", StringComparison.OrdinalIgnoreCase))
                {
                    return(EncodingService.FromAnyToDisplayEncoding(@"data\model\3dmob\" + helper.PreviewSprite));
                }

                return(EncodingService.FromAnyToDisplayEncoding(@"data\sprite\npc\" + helper.PreviewSprite));
            }

            return(null);
        }
Ejemplo n.º 11
0
        private async Task Encode()
        {
            string targetPath = FileSelectorService.GetSaveFile(DefaultArchiveExtension);

            if (string.IsNullOrEmpty(targetPath))
            {
                return;
            }

            Status = ViewModelStatus.Encoding;
            cts    = new CancellationTokenSource();
            try {
                EncodingStatistics statistics = await EncodingService.EncodeAsync(Path, targetPath, cts.Token, new DefaultProgressHandler(this));

                EncodingResult = new EncodingResultViewModel(statistics);
                Status         = ViewModelStatus.WaitForCommand | ViewModelStatus.EncodingFinished;
            }
            catch (OperationCanceledException) {
                StatusMessage = "Encoding Cancelled";
                Status        = ViewModelStatus.Cancelled;
            }
            catch {
                Status = ViewModelStatus.Error;
                throw;
            }
            finally {
                cts.Dispose();
            }
        }
        public void Verify_CohortRefrence_Is_Mapped()
        {
            EncodingService.Verify(x => x.Encode(It.IsAny <long>(), EncodingType.CohortReference), Times.Exactly(2));

            Assert.AreEqual("1_Encoded", GetCohortInTrainingProviderViewModel(1).CohortReference);
            Assert.AreEqual("2_Encoded", GetCohortInTrainingProviderViewModel(2).CohortReference);
        }
Ejemplo n.º 13
0
 private static bool _isShield(string sub)
 {
     if (sub == null)
     {
         return(false);
     }
     return(EncodingService.FromAnyTo(sub, EncodingService.Ansi) == "¹æÆÐ");
 }
Ejemplo n.º 14
0
        public void And_Encoded_Value_Is_Empty_String_Then_Throws_Exception(
            EncodingConfig config)
        {
            var encodingType    = EncodingType.AccountId;
            var encodingService = new EncodingService(config);

            Assert.Throws <ArgumentException>(() => encodingService.TryDecode("", encodingType, out var decodedValue));
        }
Ejemplo n.º 15
0
        private void _textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try {
                if (!_tab.ItemsEventsDisabled)
                {
                    DisplayableProperty <TKey, TValue> .ApplyCommand(_tab, _attribute, _textBox.Text);
                }

                try {
                    byte[] data = _tab.ProjectDatabase.MetaGrf.GetDataBuffered(EncodingService.FromAnyToDisplayEncoding(GrfPath.Combine(_grfPath1, _textBox.Text.ExpandString()) + _ext));

                    if (data != null)
                    {
                        WpfUtilities.TextBoxOk(_textBox);
                        _wrapper1.Image = ImageProvider.GetImage(data, _ext);
                        _wrapper1.Image.MakePinkTransparent();
                        _imageResource.Tag    = _textBox.Text;
                        _imageResource.Source = _wrapper1.Image.Cast <BitmapSource>();
                    }
                    else
                    {
                        WpfUtilities.TextBoxError(_textBox);
                        _wrapper1.Image       = null;
                        _imageResource.Source = null;
                    }
                }
                catch (ArgumentException) {
                    WpfUtilities.TextBoxError(_textBox);
                    _wrapper1.Image       = null;
                    _imageResource.Source = null;
                }

                try {
                    byte[] data2 = _tab.ProjectDatabase.MetaGrf.GetDataBuffered(EncodingService.FromAnyToDisplayEncoding(GrfPath.Combine(_grfPath2, _textBox.Text.ExpandString()) + _ext));

                    if (data2 != null)
                    {
                        _wrapper2.Image = ImageProvider.GetImage(data2, _ext);
                        _wrapper2.Image.MakePinkTransparent();
                        _imagePreview.Tag    = _textBox.Text;
                        _imagePreview.Source = _wrapper2.Image.Cast <BitmapSource>();
                        //_imagePreview.Source.Freeze();
                    }
                    else
                    {
                        _wrapper2.Image      = null;
                        _imagePreview.Source = null;
                    }
                }
                catch (ArgumentException) {
                    _wrapper2.Image      = null;
                    _imagePreview.Source = null;
                }
            }
            catch (Exception err) {
                ErrorHandler.HandleException(err);
            }
        }
Ejemplo n.º 16
0
        public void Base64()
        {
            var service = new EncodingService();
            var test    = "this is a string with numbers 123123";
            var base64  = service.Base64Encode(test);
            var text    = service.Base64Decode(base64);

            Assert.Equal(test, text);
        }
Ejemplo n.º 17
0
        public static void WriteEncodedLicensingDllHash()
        {
            IHashingProvider hashingProvider = new HashingProvider();
            IEncodingService encodingService = new EncodingService();

            string hash = hashingProvider.HashFile(Directory.GetCurrentDirectory() + "\\WaveTech.Scutex.Licensing.dll");

            Console.WriteLine(encodingService.Encode(hash));
        }
Ejemplo n.º 18
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            EncodingService encodingService = new EncodingService();

            cmbEncoding.ItemsSource = encodingService.AvailableCharSets;
            GetFilesInAssets();
            cmbEncoding.SelectedIndex = 0;
            cmbFiles.SelectedIndex    = 0;
        }
Ejemplo n.º 19
0
        public void DecodeTest()
        {
            IEncodingService service = new EncodingService();

            string test = service.Decode(encodedValue);

            Assert.IsNotNull(test);
            Assert.AreEqual(originalValue, test);
        }
        public EncodingController()
        {
            userId  = ConfigurationManager.AppSettings["encodingUserId"];
            userKey = ConfigurationManager.AppSettings["encodingApiKey"];
            apiUrl  = ConfigurationManager.AppSettings["encodingApiUrl"];
            string cloudHost = ConfigurationManager.AppSettings["cloudStorageHost"];

            pullLocation = cloudHost + "/" + ConfigurationManager.AppSettings["cloudContainerPrivate"] + "/";
            pushLocation = cloudHost + "/" + ConfigurationManager.AppSettings["cloudContainerPublic"] + "/";

            service = new EncodingService(userId, userKey, apiUrl);
        }
Ejemplo n.º 21
0
 public bool SetEncoding(int encoding)
 {
     try {
         EncodingService.SetDisplayEncoding(encoding);
         SdeAppConfiguration.EncodingCodepage = encoding;
         return(true);
     }
     catch (Exception err) {
         ErrorHandler.HandleException(err.Message, ErrorLevel.Critical);
         return(false);
     }
 }
Ejemplo n.º 22
0
        public async Task <IActionResult> Login(String usuario, String password)
        {
            if (string.IsNullOrEmpty(usuario) || string.IsNullOrEmpty(password))
            {
                ViewBag.Mensaje = "Usuario/Password incorrectos";
                return(View());
            }
            EncodingService encoding = new EncodingService();
            //BUSCAMOS EL TOKEN PARA COMPROBAR LAS CREDENCIALES
            //DEL EMPLEADO
            String token = await this.repo.GetToken(usuario, encoding.SHA256(password));

            //SI EL TOKEN ES NULL, NO TIENE CREDENCIALES
            if (token != null)
            {
                HttpContext.Session.SetString("TOKEN", token);//esta es la linea importante de acceso con la api
                //SI TENEMOS TOKEN, TENEMOS EMPLEADO
                //POR LO QUE PODEMOS RECUPERARLO DEL METODO PERFILEMPLEADO
                Usuarios empleado = await
                                    this.repo.PerfilEmpleado(token);

                //CREAMOS AL USUARIO PARA EL ENTORNO MVC DE CORE
                ClaimsIdentity identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
                //ALMACENAMOS EL ID DE EMPLEADO
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier
                                            , empleado.Login));
                identity.AddClaim(new Claim(ClaimTypes.Name, empleado.Apellido + ", " + empleado.Nombre));
                //GUARDAMOS TAMBIEN EL ROLE DEL EMPLEADO
                identity.AddClaim(new Claim(ClaimTypes.Role, empleado.Perfil));
                ClaimsPrincipal principal = new ClaimsPrincipal(identity);
                await HttpContext.SignInAsync
                    (CookieAuthenticationDefaults.AuthenticationScheme, principal
                    , new AuthenticationProperties
                {
                    IsPersistent = true
                    ,//DEBERIAMOS DAR EL MISMO TIEMPO DE SESSION QUE TOKEN
                    ExpiresUtc = DateTime.Now.AddMinutes(60)
                });

                //UNA VEZ QUE TENEMOS A NUESTRO EMPLEADO ALMACENADO
                //DEBEMOS ALMACENAR EL TOKEN EN SESSION PARA PODER REUTILIZARLO
                //EN OTROS METODOS DE LA APP

                //REDIRECCIONAMOS A UNA PAGINA DE INICIO PROTEGIDA
                return(RedirectToAction("Index", "BackHome"));
            }
            else
            {
                ViewBag.Mensaje = "Usuario/Password incorrectos";
                return(View());
            }
        }
Ejemplo n.º 23
0
        public static IEnumerable <string[]> GetElementsInt(byte[] data)
        {
            if (data != null)
            {
                using (StreamReader reader = SetAndLoadReader(data, EncodingService.DetectEncoding(data))) {
                    string[] elements = null;
                    int      ival;

                    while (!reader.EndOfStream)
                    {
                        string line = ReadNextLine(reader);

                        if (line == null)
                        {
                            continue;
                        }

                        string[] subElements = line.Split(new char[] { '#' });

                        if (subElements.Length <= 1)
                        {
                            continue;
                        }

                        if (elements != null)
                        {
                            if (Int32.TryParse(subElements[0], out ival))
                            {
                                yield return(elements);

                                elements = subElements;
                            }
                            else
                            {
                                elements[elements.Length - 1] = elements[elements.Length - 1].Trim(' ', '\t') == "" ? subElements[0] : elements[elements.Length - 1] + "\r\n" + subElements[0];
                                subElements = subElements.Skip(1).ToArray();
                                elements    = elements.Concat(subElements).ToArray();
                            }
                        }
                        else
                        {
                            elements = subElements;
                        }
                    }

                    if (elements != null && Int32.TryParse(elements[0], out ival))
                    {
                        yield return(elements);
                    }
                }
            }
        }
Ejemplo n.º 24
0
        public AuthorizationContextProviderTestsFixture SetInvalidDraftApprenticeshipId()
        {
            DraftApprenticeshipHashedId = "CCCC";

            var draftApprenticeshipId = DraftApprenticeshipId;

            RouteData.Values[RouteValueKeys.DraftApprenticeshipHashedId] = DraftApprenticeshipHashedId;

            RoutingFeature.Setup(f => f.RouteData).Returns(RouteData);
            EncodingService.Setup(h => h.TryDecode(DraftApprenticeshipHashedId, EncodingType.ApprenticeshipId, out draftApprenticeshipId)).Returns(false);

            return(this);
        }
Ejemplo n.º 25
0
        public AuthorizationContextProviderTestsFixture SetInvalidCohortId()
        {
            CohortReference = "BBB";

            var cohortId = CohortId;

            RouteData.Values[RouteValueKeys.CohortReference] = CohortReference;

            RoutingFeature.Setup(f => f.RouteData).Returns(RouteData);
            EncodingService.Setup(h => h.TryDecode(CohortReference, EncodingType.CohortReference, out cohortId)).Returns(false);

            return(this);
        }
        public AuthorizationContextProviderTestsFixture SetInvalidAccountLegalEntityId()
        {
            AccountLegalEntityPublicHashedId = "AAA";

            var accountLegalEntityId = 0L;

            RouteData.Values[RouteValueKeys.AccountLegalEntityPublicHashedId] = AccountLegalEntityPublicHashedId;

            RoutingFeature.Setup(f => f.RouteData).Returns(RouteData);
            EncodingService.Setup(h => h.TryDecode(AccountLegalEntityPublicHashedId, EncodingType.PublicAccountLegalEntityId, out accountLegalEntityId)).Returns(false);

            return(this);
        }
Ejemplo n.º 27
0
        public void ToBase64String_given_valid_data_should_return_base64_encoded_value()
        {
            // Arrange
            var expected     = "dXNlcm5hbWU6cGFzc3dvcmQ=";
            var textToEncode = "username:password";
            IEncodingService classUnderTest = new EncodingService();

            // Act
            var actual = classUnderTest.ToBase64String(textToEncode);

            // Assert
            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 28
0
        public Act GetBodySprite(Job job, string gender = "남")
        {
            var jobActionData = Grf.GetData(EncodingService.FromAnyToDisplayEncoding(@"data\sprite\인간족\몸통\" + gender + "\\" + job.GetSpriteName(Gender) + EncodingService.FromAnyToDisplayEncoding("_" + gender + ".act")));
            var jobSpriteData = Grf.GetData(EncodingService.FromAnyToDisplayEncoding(@"data\sprite\인간족\몸통\" + gender + "\\" + job.GetSpriteName(Gender) + EncodingService.FromAnyToDisplayEncoding("_" + gender + ".spr")));

            if (jobActionData == null || jobSpriteData == null)
            {
                AddError("resource error: sprite for job '" + job.Name + "' not found.");
                return(DefaultBodyReference);
            }

            return(new Act(jobActionData, new Spr(jobSpriteData)));
        }
Ejemplo n.º 29
0
        public void And_Encoded_Value_Is_Empty_String_Then_Throws_Exception(EncodingType encodingType, long expectedResult)
        {
            //Arrange
            var config             = EncodingConfigHelper.GenerateRandomConfig();
            var encodingTypeConfig = config.Encodings.Single(x => x.EncodingType == encodingType.ToString());
            var hashids            = new Hashids(encodingTypeConfig.Salt, encodingTypeConfig.MinHashLength, encodingTypeConfig.Alphabet);

            //Act
            var encodingService = new EncodingService(config);

            //Assert
            Assert.Throws <ArgumentException>(() => encodingService.Decode("", encodingType));
        }
Ejemplo n.º 30
0
        public AuthorizationContextProviderTestsFixture SetValidApprenticeshipId()
        {
            ApprenticeshipHashedId = "XYRZ";
            ApprenticeshipId       = 887;

            long decodedApprenticeshipId;

            RouteData.Values[RouteValueKeys.ApprenticeshipHashedId] = ApprenticeshipHashedId;

            RoutingFeature.Setup(f => f.RouteData).Returns(RouteData);
            EncodingService.Setup(h => h.TryDecode(ApprenticeshipHashedId, EncodingType.ApprenticeshipId, out decodedApprenticeshipId)).Returns(true);

            return(this);
        }