Example #1
0
        public ShareSold Sell(float shareValue, int year, string transactionId)
        {
            Guard.Against(this.State == Share.ShareState.Sold, "Share already Sold!");

            this.State = Share.ShareState.Sold;

            return(new ShareSold
            {
                Year = year,
                ShareValue = shareValue,
                ShareCost = this.Value,
                ExerciseCost = this.ExerciseCost,
                TransactionId = transactionId
            });
        }
Example #2
0
        public ShareVested Vest(string transactionId)
        {
            Guard.Against(this.State == Share.ShareState.Vested, "Share already vested!");
            Guard.Against(this.State == Share.ShareState.Sold, "Share already Sold!");

            this.State = Share.ShareState.Vested;

            return(new ShareVested
            {
                Year = this.VestedYear,
                ShareValue = this.Value,
                ExerciseCost = this.ExerciseCost,
                TransactionId = transactionId
            });
        }
Example #3
0
        /// <summary>
        /// Buscar o endereço para o CEP passado.
        /// </summary>
        /// <param name="cep">The cep.</param>
        /// <returns>System.Int32.</returns>
        public int BuscarPorCEP(string cep)
        {
            Guard.Against <ArgumentException>(cep.IsEmpty(), "CEP não pode ser vazio.");
            Guard.Against <ArgumentException>(!cep.IsCep(), "CEP inválido.");

            Resultados.Clear();

            var provider = GetProvider();
            var results  = provider.BuscarPorCEP(cep);

            Resultados.AddRange(results);

            OnBuscaEfetuada.Raise(this, EventArgs.Empty);
            return(Resultados.Count);
        }
        /// <summary>
        /// Assina o xml.
        /// </summary>
        /// <param name="doc">O Xml.</param>
        /// <param name="docElement">O elemento principal do xml a ser assinado.</param>
        /// <param name="infoElement">O elemento a ser assinado.</param>
        /// <param name="signAtribute">O atributo identificador do elemento a ser assinado.</param>
        /// <param name="certificado">O certificado.</param>
        /// <param name="comments">Se for <c>true</c> vai inserir a tag #withcomments no transform.</param>
        /// <param name="digest">Algoritmo usando para gerar o hash por padrão SHA1.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="ACBrDFeException">Erro ao efetuar assinatura digital.</exception>
        /// <exception cref="ACBrDFeException">Erro ao efetuar assinatura digital.</exception>
        public static void AssinarDocumento(XmlDocument doc, string docElement, string infoElement, string signAtribute,
                                            X509Certificate2 certificado, bool comments = false, SignDigest digest = SignDigest.SHA1)
        {
            Guard.Against <ArgumentNullException>(doc == null, "XmlDOcument não pode ser nulo.");
            Guard.Against <ArgumentException>(docElement.IsEmpty(), "docElement não pode ser nulo ou vazio.");

            var xmlDigitalSignature = GerarAssinatura(doc, infoElement, signAtribute, certificado, comments, digest);
            var xmlElement          = doc.GetElementsByTagName(docElement).Cast <XmlElement>().FirstOrDefault();

            Guard.Against <ACBrDFeException>(xmlElement == null, "Elemento principal não encontrado.");

            var element = doc.ImportNode(xmlDigitalSignature, true);

            xmlElement.AppendChild(element);
        }
        public IBusinessConfig <IUnityContainer, TBusinessProcess> ConfigureNCommon(Func <IUnityContainer, INCommonConfig> getNCommonConfig, bool updateIfExist = false)
        {
            Guard.Against <ArgumentNullException>(Container == null, "Ошибка определения конфигурации NCommon: не определен Unity контейнер");
            Guard.Against <ArgumentNullException>(getNCommonConfig == null, "Ошибка определения конфигурации NCommon: не определен метод получения конфигурации");
            //Guard.Against<ArgumentNullException>(NCommonConfigActions != null, "Ошибка определения конфигурации NCommon: конфигурация уже определена");
            //Guard.Against<ArgumentNullException>(!updateIfExist && (NCommonConfigGets != null || NCommonConfigActions != null), "Ошибка определения конфигурации NCommon: конфигурация уже определена");

            if (Container != null && Container.ExistsType <IUnitOfWorkScope>())//Если NCommon уже зарегистрирован, то регистрация отменяется
            {
                return(this);
            }

            NCommonConfigGets = getNCommonConfig;
            return(this);
        }
Example #6
0
        public static XElement[] SerializeChild(ICollection values, DFeCollectionAttribute tag, DFeItemAttribute[] itemTags, SerializerOptions options)
        {
            var childElements = new List <XElement>();

            foreach (var value in values)
            {
                var itemTag = itemTags.SingleOrDefault(x => x.Tipo == value.GetType());
                Guard.Against <ACBrDFeException>(itemTag == null, $"Item {value.GetType().Name} não presente na lista de itens.");

                var childElement = ObjectSerializer.Serialize(value, value.GetType(), itemTag.Name, itemTag.Namespace, options);
                childElements.Add(childElement);
            }

            return(childElements.ToArray());
        }
Example #7
0
        /// <summary>
        /// Cancela a venda relacionada a classe de cancelamento informada.
        /// </summary>
        /// <param name="cfeCanc">The cfe canc.</param>
        /// <returns>CancelamentoSatResposta.</returns>
        public CancelamentoSatResposta CancelarUltimaVenda(CFeCanc cfeCanc)
        {
            Guard.Against <ArgumentNullException>(cfeCanc.IsNull(), nameof(cfeCanc));

            var options = DFeSaveOptions.OmitDeclaration | DFeSaveOptions.DisableFormatting;

            if (Configuracoes.RemoverAcentos)
            {
                options |= DFeSaveOptions.RemoveAccents;
            }

            var dados = cfeCanc.GetXml(options);

            return(CancelarUltimaVenda(cfeCanc.InfCFe.ChCanc, dados));
        }
Example #8
0
        /// <summary>
        /// Retorna o provedor para o municipio nas configurações informadas.
        /// </summary>
        /// <param name="config">A configuração.</param>
        /// <returns>Provedor NFSe.</returns>
        public static ProviderBase GetProvider(ConfigNFSe config)
        {
            var municipio = Municipios.SingleOrDefault(x => x.Codigo == config.WebServices.CodigoMunicipio);

            Guard.Against <ACBrException>(municipio == null, "Provedor para esta cidade não implementado ou não especificado!");

            // ReSharper disable once PossibleNullReferenceException
            var providerType = Providers[municipio.Provedor];

            Guard.Against <ACBrException>(providerType == null, "Provedor não encontrado!");
            Guard.Against <ACBrException>(!CheckBaseType(providerType), "Classe base do provedor incorreta!");

            // ReSharper disable once AssignNullToNotNullAttribute
            return((ProviderBase)Activator.CreateInstance(providerType, config, municipio));
        }
        public IBusinessConfig <IUnityContainer, TBusinessProcess> ConfigureNCommonActions(Action <INCommonConfig> actions, bool updateIfExist = false)
        {
            Guard.Against <ArgumentNullException>(Container == null, "Ошибка определения конфигурации NCommon: не определен Unity контейнер");
            Guard.Against <ArgumentNullException>(actions == null, "Ошибка определения конфигурации NCommon: не определены действия конфигурации");
            Guard.Against <ArgumentNullException>(NCommonConfigGets != null, "Ошибка определения конфигурации NCommon: конфигурация уже определена");
            Guard.Against <ArgumentNullException>(!updateIfExist && NCommonConfigActions != null, "Ошибка определения конфигурации NCommon: конфигурация уже определена");

            if (Container != null && Container.ExistsType <IUnitOfWorkScope>())//Если NCommon уже зарегистрирован, то регистрация отменяется
            {
                return(this);
            }

            NCommonConfigActions = actions;
            return(this);
        }
Example #10
0
        public async Task <int> SaveThemeVariablesAsync(string themeName, int storeId, IDictionary <string, object> variables)
        {
            Guard.NotEmpty(themeName, nameof(themeName));
            Guard.Against <ArgumentException>(!_themeRegistry.ContainsTheme(themeName), "The theme '{0}' does not exist in the registry.".FormatInvariant(themeName));
            Guard.NotNull(variables, nameof(variables));

            if (!variables.Any())
            {
                return(0);
            }

            var manifest = _themeRegistry.GetThemeManifest(themeName);

            if (manifest == null)
            {
                throw new ArgumentException("Theme '{0}' does not exist".FormatInvariant(themeName), nameof(themeName));
            }

            // Get current for later restore on parse error
            var currentVars = await GetThemeVariablesAsync(themeName, storeId);

            // Save
            var result = await SaveThemeVariablesInternal(manifest, storeId, variables);

            if (result.TouchedVariablesCount > 0)
            {
                // Check for parsing error
                string error = await ValidateSassAsync(manifest, storeId);

                if (error.HasValue())
                {
                    // Restore previous vars
                    try
                    {
                        await DeleteThemeVariablesInternal(themeName, storeId, false);
                    }
                    finally
                    {
                        // We do it here to absolutely ensure that this gets called
                        await SaveThemeVariablesInternal(manifest, storeId, currentVars);
                    }

                    throw new ThemeValidationException(error, variables);
                }
            }

            return(result.TouchedVariablesCount);
        }
Example #11
0
 private Rank(int score, string shortName, string fullName, IEnumerable <string> additionalMappingValues = null)
 {
     Guard.Against(score < 2 && score > 14, "Score should be in range of 2 - 14");
     _score           = score;
     _shortName       = shortName;
     _fullName        = fullName;
     Ranks[shortName] = this;
     AllRanks.Add(this);
     if (additionalMappingValues != null)
     {
         foreach (var mappingValue in additionalMappingValues)
         {
             Ranks[mappingValue] = this;
         }
     }
 }
Example #12
0
        /// <summary>
        /// Fecha a operação com cartão ligando a chave do CFe à transação em cartão
        /// </summary>
        /// <returns>MFeIntegradorResp.</returns>
        public MFeSatResposta RespostaFiscal(int idFila, string chaveAcesso, string nsu,
                                             string numeroAprovacao, string bandeira, string adquirinte, string cnpj, string impressaofiscal, string numeroDocumento)
        {
            Guard.Against <ACBrException>(!Ativo, "Componente não está ativo.");

            IniciaComando($"RespostaFiscal({Sessao}, {sat.Config.ChaveAcessoValidador}, {idFila}, {chaveAcesso}, {nsu}, {numeroAprovacao}, {bandeira}," +
                          $"{adquirinte}, {cnpj}, {impressaofiscal}, {numeroDocumento})");

            var ret = sat.RespostaFiscal(Sessao, sat.Config.ChaveAcessoValidador, idFila, chaveAcesso, nsu, numeroAprovacao, bandeira,
                                         adquirinte, cnpj, impressaofiscal, numeroDocumento);

            var mfeResposta = FinalizaComando <MFeSatResposta>(ret.XmlRetorno);

            mfeResposta.XmlEnvio = ret.XmlEnvio;
            return(mfeResposta);
        }
        /// <summary>
        /// Creates the entity group as a child of <paramref name="parentGroupName"/>.
        /// </summary>
        /// <param name="parentGroupName">Name of the parent group.</param>
        /// <param name="usersGroupName">Name of the users group.</param>
        /// <returns></returns>
        public virtual EntitiesGroup CreateChildEntityGroupOf(string parentGroupName, string usersGroupName)
        {
            EntitiesGroup parent = GetEntitiesGroupByName(parentGroupName);

            Guard.Against <ArgumentException>(parent == null,
                                              "Parent users group '" + parentGroupName + "' does not exists");
            EntitiesGroup group = CreateEntitiesGroup(usersGroupName);

            group.Parent = parent;
            group.AllParents.AddAll(parent.AllParents);
            group.AllParents.Add(parent);
            parent.DirectChildren.Add(group);
            parent.AllChildren.Add(group);

            return(group);
        }
Example #14
0
        public static void SetAppSetting(this Configuration config, string setting, object value)
        {
            Guard.Against <ArgumentNullException>(config == null, nameof(config));
            Guard.Against <ArgumentNullException>(config.AppSettings == null, nameof(config.AppSettings));

            var valor = string.Format(CultureInfo.InvariantCulture, "{0}", value);

            if (config.AppSettings.Settings[setting]?.Value != null)
            {
                config.AppSettings.Settings[setting].Value = valor;
            }
            else
            {
                config.AppSettings.Settings.Add(setting, valor);
            }
        }
Example #15
0
        public BusinessOperationConfigCollection <TContainer> Update(string operationName, IBusinessOperationConfig <TContainer> operationConfig)
        {
            Guard.Against <ArgumentNullException>(string.IsNullOrEmpty(operationName), "Ошибка обновления конфигурации для стратегии: название конфигурации не может быть нулевым");
            Guard.Against <ArgumentNullException>(operationConfig == null, "Ошибка обновления конфигурации для стратегии: объект конфигурации не может быть нулевым");

            if (!this.ContainsKey(operationName))
            {
                base.Add(operationName, operationConfig);
            }
            else
            {
                base[operationName] = operationConfig;
            }

            return(this);
        }
Example #16
0
        public async Task <bool> UpdateAsync(MovieUpdateCommand command)
        {
            var movie = await _repository.SingleOrDefaultAsync(x => x.ID == command.ID, tracking : false);

            Guard.Against(movie, ErrorType.NotFound);

            var moviesCountByName = await _repository.CountAsync(x => x.Title.Equals(command.Title) && x.ID != command.ID);

            Guard.Against(moviesCountByName > 0, ErrorType.Duplicating);

            movie = _mapper.Map <Movie>(command);

            _repository.Update(movie);

            return(await CommitAsync() > 0);
        }
Example #17
0
        public static Guid ParseFromZBase32String(string base32)
        {
            Guard.IsNotNullNorEmpty(base32, nameof(base32));
            Guard.Against <ArgumentException>(base32.Length != ZBASE32_LENGTH,
                                              $"Invalid base32 string length, expected {ZBASE32_LENGTH}");

            try
            {
                var bytes = new ZBase32Encoder().Decode(base32);
                return(new Guid(bytes));
            }
            catch (ArgumentException e)
            {
                throw new ArgumentException($"Unable to parse ZBase32String '{base32}' to Guid", e);
            }
        }
Example #18
0
        /// <summary>
        /// Creates a new instance of <see cref="IUnitOfWork"/>.
        /// </summary>
        /// <returns>Instances of <see cref="EFUnitOfWork"/>.</returns>
        public IUnitOfWork Create()
        {
//#if DEBUG
            using (MiniProfiler.Current.Step("EFUnitOfWorkFactory.Create")) {
//#endif
                Guard.Against <InvalidOperationException>(
                    _resolver.ContextsRegistered == 0,
                    "No DbContext providers have been registered. You must register DbContext providers using " +
                    "the RegisterDbContextProvider method or use NCommon.Configure class to configure NCommon.EntityFramework " +
                    "using the EFConfiguration class and register DbContext instances using the WithDbContext method.");

                return(new EFUnitOfWork(_resolver));
//#if DEBUG
            }
//#endif
        }
Example #19
0
        public GasLogValidator(IEntityLookup lookupRepo, IDateTimeProvider dateTimeProvider) : base(lookupRepo)
        {
            Guard.Against <ArgumentNullException>(dateTimeProvider == null, nameof(dateTimeProvider));
            _dateTimeProvider = dateTimeProvider;

            RuleFor(l => l.AuthorId).Must(HasValidAuthor).WithMessage("Has valid author for GasLog");
            RuleFor(l => l.Date).NotNull().Must(HasValidDate).WithMessage("Gas log does not has valid date");
            RuleFor(l => l.Car).NotNull().WithMessage("Gas log must belongs to an automobile");
            RuleFor(l => l.Distance).Must((o, distance) => HasValidDistance2(distance, o.CurrentMeterReading)).WithMessage("Need has valid distance");
            RuleFor(l => l.CurrentMeterReading).Must((o, meter) => HasValidDistance2(o.Distance, meter)).WithMessage("Need has valid meter reading");
            RuleFor(l => l.Gas).Must(HasValidVolume).WithMessage("Need has valid gas volume");
            RuleFor(l => l.Price).Must(HasValidMoney).WithMessage("Need has valid Price");
            RuleFor(l => l.Station).Length(1, 1000).WithMessage("Need has gas station");
            RuleFor(l => l.CreateDate).Must(HasValidEarlyDate).WithMessage("Create date should not earlier then today");
            RuleForEach(l => l.Discounts).SetValidator(new GasDiscountInfoValidator(lookupRepo)).WithMessage("All valid GasDiscountInfo is required");
        }
Example #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="inputHtmlPath"></param>
        /// <param name="outputPdfPath"></param>
        /// <param name="paperSizeName">A0,A1,A2,A3,A4,A5,A6,A7,A8,A9,B0,B1,B10,B2,B3,B4,B5,B6,B7,B8,B9,C5E,Comm10E,DLE,Executive,Folio,Ledger,Legal,Letter,Tabloid</param>
        /// <param name="landscape"> </param>
        /// <param name="booketLayoutMethod"> </param>
        /// <param name="bookletPortion"></param>
        /// <param name="doWorkEventArgs"> </param>
        /// <param name="getIsLandscape"></param>
        public void MakePdf(string inputHtmlPath, string outputPdfPath, string paperSizeName, bool landscape, PublishModel.BookletLayoutMethod booketLayoutMethod, PublishModel.BookletPortions bookletPortion, DoWorkEventArgs doWorkEventArgs)
        {
            Guard.Against(Path.GetExtension(inputHtmlPath) != ".htm",
                          "wkhtmtopdf will croak if the input file doesn't have an htm extension.");

            MakeSimplePdf(inputHtmlPath, outputPdfPath, paperSizeName, landscape, doWorkEventArgs);
            if (doWorkEventArgs.Cancel || (doWorkEventArgs.Result != null && doWorkEventArgs.Result is Exception))
            {
                return;
            }
            if (bookletPortion != PublishModel.BookletPortions.AllPagesNoBooklet)
            {
                //remake the pdf by reording the pages (and sometimes rotating, shrinking, etc)
                MakeBooklet(outputPdfPath, paperSizeName, booketLayoutMethod);
            }
        }
Example #21
0
        /// <summary>
        /// Reads a property in the context of the message
        /// </summary>
        /// <typeparam name="TExpected">Expected type of the value</typeparam>
        /// <param name="message">BizTalk pipeline message</param>
        /// <param name="name">Name of the property</param>
        /// <param name="ns">Namespace of the property</param>
        /// <param name="isMandatory">Indication if it is mandatory for the property to be present</param>
        /// <returns>Value from the property, if present</returns>
        /// <exception cref="BizTalk.Extended.Core.Exceptions.ContextPropertyNotFoundException">Thrown when a mandatory property is not present</exception>
        public static TExpected ReadContextProperty <TExpected>(this IBaseMessage message, string name, string ns, bool isMandatory)
        {
            Guard.NotNull(message, "msg");
            Guard.Against(message.Context == null, "msg");
            Guard.NotNullOrEmpty(name, "name");
            Guard.NotNullOrEmpty(ns, "ns");

            object value = message.Context.Read(name, ns);

            if (value == null && isMandatory)
            {
                throw new ContextPropertyNotFoundException(name, ns);
            }

            return(ContextPropertySerializer.DeserializeFromContextPropertyValue <TExpected>(value));
        }
Example #22
0
        /// <summary>
        ///     Seleciona um certificado passando um array de bytes.
        /// </summary>
        /// <param name="certificado">O certificado.</param>
        /// <param name="senha">A senha.</param>
        /// <returns>X509Certificate2.</returns>
        /// <exception cref="System.Exception">Arquivo do Certificado digital não encontrado</exception>
        public static X509Certificate2 SelecionarCertificado(byte[] certificado, string senha = "")
        {
            Guard.Against <ArgumentNullException>(certificado == null, "O certificado não poder ser nulo");
            Guard.Against <ArgumentException>(certificado?.Length == 0, "Certificado com tamanho inválido");

            var secureString = new SecureString();

            foreach (var s in senha)
            {
                secureString.AppendChar(s);
            }

            var cert = new X509Certificate2(certificado, secureString);

            return(cert);
        }
Example #23
0
        /// <summary>
        /// Carrega o arquivo de cidades.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="clean">if set to <c>true</c> [clean].</param>
        public static void Load(Stream stream, bool clean = true)
        {
            Guard.Against <ArgumentException>(stream == null, "Arquivo de cidades não encontrado");

            using (var zip = new GZipStream(stream, CompressionMode.Decompress))
            {
                var formatter = new BinaryFormatter();
                var cidades   = (MunicipioNFSe[])formatter.Deserialize(zip);

                if (clean)
                {
                    Municipios.Clear();
                }
                Municipios.AddRange(cidades);
            }
        }
Example #24
0
        /// <summary>
        ///     Seleciona um certificado informando o caminho e a senha
        /// </summary>
        /// <param name="caminho">Caminho do certificado digital</param>
        /// <param name="senha">Senha do certificado</param>
        /// <returns>X509Certificate2</returns>
        /// <exception cref="VipException">Arquivo do Certificado digital não encontrado</exception>
        public static X509Certificate2 SelecionarCertificado(string caminho, string senha)
        {
            Guard.Against <ArgumentNullException>(caminho.IsNullOrEmpty(), "Caminho do arquivo não poder ser nulo ou vazio");
            Guard.Against <ArgumentException>(!File.Exists(caminho), "Arquivo do Certificado digital não encontrado");

            var secureString = new SecureString();

            foreach (var s in senha)
            {
                secureString.AppendChar(s);
            }

            var cert = new X509Certificate2(caminho, secureString);

            return(cert);
        }
Example #25
0
        /// <summary>
        /// Assina o CTe.
        /// </summary>
        /// <param name="certificado">The certificado.</param>
        /// <param name="saveOptions">The save options.</param>
        public void Assinar(X509Certificate2 certificado, DFeSaveOptions saveOptions)
        {
            Guard.Against <ArgumentNullException>(certificado == null, "Certificado não pode ser nulo.");

            if (InfCTe.Id.IsEmpty() || InfCTe.Id.Length < 44)
            {
                var chave = ChaveDFe.Gerar(InfCTe.Ide.CUF, InfCTe.Ide.DhEmi.DateTime,
                                           InfCTe.Emit.CNPJ, (int)InfCTe.Ide.Mod, InfCTe.Ide.Serie,
                                           InfCTe.Ide.NCT, InfCTe.Ide.TpEmis, InfCTe.Ide.CCT);

                InfCTe.Id      = $"CTe{chave.Chave}";
                InfCTe.Ide.CDV = chave.Digito;
            }

            AssinarDocumento(certificado, saveOptions, false, SignDigest.SHA1);
        }
        public Task RenewAsync(string key, AuthenticationTicket ticket)
        {
            Guard.Against <ArgumentNullException>(key.IsNull(), "RenewAsync - key can't be null");
            Guard.Against <ArgumentNullException>(ticket.IsNull(), "RenewAsync - ticket can't be null");

            var entry = this.store.FirstOrDefault(ent => ent.Key == key);

            if (entry.IsNotNull())
            {
                var oldValue = entry.Value;
                var json     = this.serializer.Serialize(ticket);
                this.store.TryUpdate(key, json, oldValue);
            }

            return(Task.FromResult(0));
        }
Example #27
0
        /// <summary>
        /// Envia pagamento ao MFe
        /// </summary>
        /// <returns>MFeIntegradorResp.</returns>
        public MFeSatResposta EnviarPagamento(string chaveRequisicao, string estabelecimento, string serialPOS, string cnpj, decimal icmsBase, decimal valorTotalVenda, string origemPagamento,
                                              bool habilitarMultiplosPagamentos = true, bool habilitarControleAntiFraude = false, string codigoMoeda = "BRL", bool emitirCupomNFCE = false)
        {
            Guard.Against <ACBrException>(!Ativo, "Componente não está ativo.");

            IniciaComando($"EnviarPagamento({Sessao}, {sat.Config.ChaveAcessoValidador}, {chaveRequisicao}, {estabelecimento} , {cnpj}, {icmsBase}, {valorTotalVenda}, {origemPagamento})" +
                          $"{habilitarMultiplosPagamentos}, {habilitarControleAntiFraude}, {codigoMoeda}, {emitirCupomNFCE})");

            var ret = sat.EnviarPagamento(Sessao, sat.Config.ChaveAcessoValidador, chaveRequisicao, estabelecimento, serialPOS, cnpj,
                                          icmsBase, valorTotalVenda, origemPagamento, habilitarMultiplosPagamentos, habilitarControleAntiFraude, codigoMoeda, emitirCupomNFCE);

            var mfeResposta = FinalizaComando <MFeSatResposta>(ret.XmlRetorno);

            mfeResposta.XmlEnvio = ret.XmlEnvio;
            return(mfeResposta);
        }
Example #28
0
        /// <summary>
        /// Enviar status do pagamento ao Validador - usado no roteiro TEF
        /// </summary>
        /// <returns>MFeIntegradorResp.</returns>
        public MFeSatResposta EnviarStatusPagamento(string codigoAutorizacao, string bin, string donoCartao,
                                                    string dataExpiracao, string instituicaoFinanceira, int parcelas, string codigoPagamento, decimal valorPagamento, int idFila, string tipo, int ultimosQuatroDigitos)
        {
            Guard.Against <ACBrException>(!Ativo, "Componente não está ativo.");

            IniciaComando($"EnviarStatusPagamento({Sessao}, {sat.Config.ChaveAcessoValidador}, {codigoAutorizacao}, {bin}, {donoCartao}, {dataExpiracao}, {instituicaoFinanceira}," +
                          $"{parcelas}, {codigoPagamento}, {valorPagamento}, {idFila}, {tipo}, {ultimosQuatroDigitos})");

            var ret = sat.EnviarStatusPagamento(Sessao, sat.Config.ChaveAcessoValidador, codigoAutorizacao, bin, donoCartao, dataExpiracao, instituicaoFinanceira, parcelas, codigoPagamento,
                                                valorPagamento, idFila, tipo, ultimosQuatroDigitos);

            var mfeResposta = FinalizaComando <MFeSatResposta>(ret.XmlRetorno);

            mfeResposta.XmlEnvio = ret.XmlEnvio;
            return(mfeResposta);
        }
Example #29
0
        public void Execute(OnDecryptMessage pipelineEvent)
        {
            var transportMessage = pipelineEvent.GetTransportMessage();

            if (!transportMessage.EncryptionEnabled())
            {
                return;
            }

            var algorithm =
                pipelineEvent.GetServiceBus().Configuration.FindEncryptionAlgorithm(transportMessage.EncryptionAlgorithm);

            Guard.Against <InvalidOperationException>(algorithm == null, string.Format(ESBResources.EncryptionAlgorithmException, transportMessage.CompressionAlgorithm));

            transportMessage.Message = algorithm.Decrypt(transportMessage.Message);
        }
Example #30
0
        public async Task <bool> UpdateAsync(UserUpdateCommand command)
        {
            var user = await _repository.SingleOrDefaultAsync(x => x.ID == command.ID, tracking : false);

            Guard.Against(user, ErrorType.NotFound);

            var userCountByUsername = await _repository.CountAsync(x => x.Username.Equals(command.Username) && x.ID != command.ID);

            Guard.Against(userCountByUsername > 0, ErrorType.Duplicating);

            user = _mapper.Map <User>(command);

            _repository.Update(user);

            return(await CommitAsync() > 0);
        }