OnlyNumbers() public static method

Remove caracteres não-numéricos e retorna.
public static OnlyNumbers ( object text ) : object
text object valor a ser convertido
return object
Esempio n. 1
0
File: CNPJ.cs Progetto: Klegy/uninfe
        /// <summary>
        /// valida o CNPJ
        /// </summary>
        /// <param name="cnpj"></param>
        /// <returns>true se for um CNPJ válido</returns>
        public static bool Validate(string cnpj)
        {
            if (string.IsNullOrEmpty(cnpj))
            {
                return(false);
            }

            cnpj = Functions.OnlyNumbers(cnpj, "-.,/").ToString();

            try
            {
                #region Valida

                string Cnpj_1   = cnpj.Substring(0, 12);
                string Cnpj_2   = cnpj.Substring(cnpj.Length - 2);
                string Mult     = "543298765432";
                string Controle = String.Empty;
                int    Soma     = 0;
                int    Digito   = 0;

                for (int j = 1; j < 3; j++)
                {
                    Soma = 0;

                    for (int i = 0; i < 12; i++)
                    {
                        Soma += int.Parse(Cnpj_1.Substring(i, 1)) * int.Parse(Mult.Substring(i, 1));
                    }

                    if (j == 2)
                    {
                        Soma += (2 * Digito);
                    }
                    Digito = ((Soma * 10) % 11);
                    if (Digito == 10)
                    {
                        Digito = 0;
                    }
                    Controle = Controle + Digito.ToString();
                    Mult     = "654329876543";
                }

                if (Controle != Cnpj_2)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
                #endregion Valida
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 2
0
File: CEI.cs Progetto: Klegy/uninfe
        /// <summary>
        /// Validar o Cadastro Específico do INSS
        /// </summary>
        /// <param name="cei">Número do cadastro específico do INSS a ser validado</param>
        /// <returns></returns>
        public static bool Validate(string cei)
        {
            cei = Functions.OnlyNumbers(cei, "./").ToString();

            if (String.IsNullOrEmpty(cei) || cei.Length < 12)
            {
                return(false);
            }

            var peso = "74185216374";
            var soma = 0;

            //Faz um for para multiplicar os números do CEI digitado pelos números do peso.
            //E somar o total de cada número multiplicado.
            for (int i = 1; i < 12; i++)
            {
                int fator = Convert.ToInt32(peso.Substring(i - 1, 1));
                int valor = Convert.ToInt32(cei.Substring(i - 1, 1));
                soma += (fator * valor);
            }

            //Pega o length do resultado da soma e desconta 2 para pegar somente a dezena.
            int definirDezena = soma.ToString().Length - 2;

            //pega a dezena
            int dezena = Convert.ToInt32(soma.ToString().Substring(definirDezena));

            //pega o algarismo da dezena
            int algarismoDezena = Convert.ToInt32(dezena.ToString().Substring(0, 1));

            //pega o algarismo da unidade
            int algarismoUnidade = Convert.ToInt32(soma) - (Convert.ToInt32((soma / 10)) * 10);

            //soma o algarismo da dezena com o algarismo da unidade.
            soma = Convert.ToInt32(algarismoDezena) + algarismoUnidade;

            //unidade da soma
            int unidadeSoma = Convert.ToInt32(soma.ToString().Substring(soma.ToString().Length - 1));

            int digitoEncontrado = 10 - unidadeSoma;

            int definirDigitoEncontrado = Convert.ToInt32(digitoEncontrado.ToString().Length - 1);

            int unidadeDigitoEncontrado = Convert.ToInt32(digitoEncontrado.ToString().Substring(definirDigitoEncontrado));

            //pega o dígito (último número) do cei digitado.
            int digitoCEI = Convert.ToInt32(cei.Substring(11));

            if (digitoCEI != unidadeDigitoEncontrado)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Esempio n. 3
0
File: CEI.cs Progetto: Klegy/uninfe
        private string Format(string cei)
        {
            if (String.IsNullOrEmpty(cei))
            {
                return("__.___.____/__");
            }

            cei = Functions.OnlyNumbers(cei, "./").ToString();

            return(Convert.ToInt64(cei).ToString(@"00\.000\.0000\/00"));
        }
Esempio n. 4
0
        /// <summary>
        /// Formatar o CPF
        /// </summary>
        /// <param name="cpf">CPF a ser formatado</param>
        /// <returns></returns>
        public string Format(string cpf)
        {
            if (string.IsNullOrEmpty(cpf))
            {
                return("___.___.___-__");
            }

            cpf = Functions.OnlyNumbers(cpf, "-.").ToString();

            return(Convert.ToInt64(cpf).ToString(@"000\.000\.000-00"));
        }
Esempio n. 5
0
        /// <summary>
        /// formata o CNPJ
        /// </summary>
        /// <param name="cnpj">valor a ser formatado</param>
        /// <returns></returns>
        public static string FormatCNPJ(string cnpj)
        {
            string             ret = "";
            MaskedTextProvider mascara;

            cnpj = Functions.OnlyNumbers(cnpj, "-.,/").ToString();
            //cnpj
            //##.###.###/####-##
            mascara = new MaskedTextProvider(@"00\.000\.000/0000-00");
            mascara.Set(cnpj);
            ret = mascara.ToString();
            return(ret);
        }
Esempio n. 6
0
        private CNPJ(string cnpj)
        {
            if (cnpj.Length == 0)
            {
                return;
            }

            cnpj = Functions.OnlyNumbers(cnpj, ".,-/").ToString();
            if (CNPJ.Validate(cnpj) == false)
            {
                throw new ExceptionCNPJInvalido(cnpj);
            }
            this.mValue = cnpj;
        }
Esempio n. 7
0
        /// <summary>
        /// Construtor do objeto CPF
        /// </summary>
        /// <param name="value">CPF informado</param>
        private CPF(string value)
        {
            if (value.Length == 0)
            {
                return;
            }

            value = Functions.OnlyNumbers(value, ".-").ToString();

            if (!Validate(value))
            {
                throw new ExceptionCPFInvalido(value);
            }

            _value = value;
        }
Esempio n. 8
0
        private static bool LoadArqXMLWebService(string filenameWS, string subfolder)
        {
            bool salvaXmlLocal = false;

            if (File.Exists(filenameWS))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filenameWS);
                XmlNodeList estadoList = doc.GetElementsByTagName(NFeStrConstants.Estado);
                foreach (XmlNode estadoNode in estadoList)
                {
                    XmlElement estadoElemento = (XmlElement)estadoNode;
                    if (estadoElemento.Attributes.Count > 0)
                    {
                        if (estadoElemento.Attributes[TpcnResources.UF.ToString()].Value != "XX")
                        {
                            int ID = Convert.ToInt32("0" + Functions.OnlyNumbers(estadoElemento.Attributes[TpcnResources.ID.ToString()].Value));
                            if (ID == 0)
                            {
                                continue;
                            }
                            string Nome = estadoElemento.Attributes[NFeStrConstants.Nome].Value;
                            string UF   = estadoElemento.Attributes[TpcnResources.UF.ToString()].Value;

                            /// danasa 1-2012
                            ///
                            /// verifica se o ID já está na lista
                            /// isto previne que no xml de configuracao tenha duplicidade e evita derrubar o programa
                            ///
                            var ci = (from i in webServicesList where i.ID == ID select i).FirstOrDefault();
                            if (ci == null)
                            {
                                webServices wsItem = new webServices(ID, Nome, UF);
                                XmlNodeList urlList;

                                urlList = estadoElemento.GetElementsByTagName(NFe.Components.NFeStrConstants.LocalHomologacao);
                                if (urlList.Count > 0)
                                {
                                    PreencheURLw(wsItem.LocalHomologacao,
                                                 NFe.Components.NFeStrConstants.LocalHomologacao,
                                                 urlList.Item(0).OuterXml,
                                                 UF,
                                                 subfolder);
                                }

                                urlList = estadoElemento.GetElementsByTagName(NFe.Components.NFeStrConstants.LocalProducao);
                                if (urlList.Count > 0)
                                {
                                    PreencheURLw(wsItem.LocalProducao,
                                                 NFe.Components.NFeStrConstants.LocalProducao,
                                                 urlList.Item(0).OuterXml,
                                                 UF,
                                                 subfolder);
                                }

                                webServicesList.Add(wsItem);
                            }
                            // danasa 1-2012
                            if (estadoElemento.HasAttribute(NFeStrConstants.Padrao))
                            {
                                try
                                {
                                    string padrao = estadoElemento.Attributes[NFeStrConstants.Padrao].Value;
                                    if (!padrao.Equals(PadroesNFSe.NaoIdentificado.ToString(), StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        var cc = (from i in Propriedade.Municipios
                                                  where i.CodigoMunicipio == ID
                                                  select i).FirstOrDefault();
                                        if (cc == null)
                                        {
                                            Propriedade.Municipios.Add(new Municipio(ID, UF, Nome, WebServiceNFSe.GetPadraoFromString(padrao)));
                                            salvaXmlLocal = true;
                                        }
                                        else
                                        {
                                            if (!cc.PadraoStr.Equals(padrao) || !cc.UF.Equals(UF) || !cc.Nome.Equals(Nome, StringComparison.InvariantCultureIgnoreCase))
                                            {
                                                cc.Padrao     = WebServiceNFSe.GetPadraoFromString(padrao);
                                                cc.Nome       = Nome;
                                                cc.UF         = UF;
                                                salvaXmlLocal = true;
                                            }
                                        }
                                    }
                                }
                                catch { }
                            }
                            // danasa 1-2012
                        }
                    }
                }
            }
            return(salvaXmlLocal);
        }
Esempio n. 9
0
        /// <summary>
        /// Carrega a lista de webservices definidos no arquivo WebService.XML
        /// </summary>
        public static bool CarregaWebServicesList()
        {
            bool atualizaWSDL = false;

            if (webServicesList == null)
            {
                webServicesList        = new List <webServices>();
                Propriedade.Municipios = null;
                Propriedade.Municipios = new List <Municipio>();

                XmlDocument doc = new XmlDocument();
                /// danasa 1-2012
                if (File.Exists(Propriedade.NomeArqXMLMunicipios))
                {
                    doc.Load(Propriedade.NomeArqXMLMunicipios);
                    XmlNodeList estadoList = doc.GetElementsByTagName(NFe.Components.NFeStrConstants.Registro);
                    foreach (XmlNode registroNode in estadoList)
                    {
                        XmlElement registroElemento = (XmlElement)registroNode;
                        if (registroElemento.Attributes.Count > 0)
                        {
                            int    IDmunicipio = Convert.ToInt32("0" + Functions.OnlyNumbers(registroElemento.Attributes[TpcnResources.ID.ToString()].Value));
                            string Nome        = registroElemento.Attributes[NFeStrConstants.Nome].Value;
                            string Padrao      = registroElemento.Attributes[NFeStrConstants.Padrao].Value;
                            string UF          = Functions.CodigoParaUF(Convert.ToInt32(IDmunicipio.ToString().Substring(0, 2)));

                            ///
                            /// danasa 9-2013
                            /// verifica se o 'novo' padrao existe, nao existindo retorna para atualizar os wsdl's dele
                            string dirSchemas = Path.Combine(Propriedade.PastaExecutavel, "NFse\\schemas\\NFSe\\" + Padrao);
                            if (!Directory.Exists(dirSchemas))
                            {
                                atualizaWSDL = true;
                            }
                            PadroesNFSe pdr = WebServiceNFSe.GetPadraoFromString(Padrao);

                            string urlsH = WebServiceNFSe.WebServicesHomologacao(ref pdr, IDmunicipio);
                            string urlsP = WebServiceNFSe.WebServicesProducao(ref pdr, IDmunicipio);

                            if (!string.IsNullOrEmpty(urlsH) || !string.IsNullOrEmpty(urlsP))
                            {
                                var ci = (from i in webServicesList where i.ID == IDmunicipio select i).FirstOrDefault();
                                if (ci == null)
                                {
                                    webServices wsItem = new webServices(IDmunicipio, Nome, UF);

                                    PreencheURLw(wsItem.LocalHomologacao,
                                                 NFe.Components.NFeStrConstants.LocalHomologacao,
                                                 urlsH,
                                                 "",
                                                 "NFse\\");
                                    PreencheURLw(wsItem.LocalProducao,
                                                 NFe.Components.NFeStrConstants.LocalProducao,
                                                 urlsP,
                                                 "",
                                                 "NFse\\");
                                    webServicesList.Add(wsItem);
                                }
                            }
                            ///
                            /// adiciona na lista que será usada na manutencao
                            ///
                            Propriedade.Municipios.Add(new Municipio(IDmunicipio, UF, Nome, pdr));
                        }
                    }
                }
                /// danasa 1-2012

                bool salvaXmlLocal = false;
                LoadArqXMLWebService(Propriedade.NomeArqXMLWebService_NFe, "NFe\\");
                salvaXmlLocal = LoadArqXMLWebService(Propriedade.NomeArqXMLWebService_NFSe, "NFse\\");

                if (salvaXmlLocal)
                {
                    WebServiceNFSe.SalvarXMLMunicipios(null, null, 0, null, false);
                }
            }
            return(atualizaWSDL);
        }
Esempio n. 10
0
 /// <summary>
 /// gravação de dados
 /// </summary>
 /// <param name="provider">CurrentCulture</param>
 /// <returns>somente os números</returns>
 public string ToString(IFormatProvider provider)
 {
     return(Functions.OnlyNumbers(mValue, ".,-").ToString());
 }
Esempio n. 11
0
File: CEI.cs Progetto: Klegy/uninfe
 public string ToString(IFormatProvider provider)
 {
     return(Functions.OnlyNumbers(_cei, "./").ToString());
 }
Esempio n. 12
0
        /// <summary>
        /// Analisa o CPF informado e verifica se é válido
        /// </summary>
        /// <param name="cpf">CPF informado</param>
        /// <param name="allowNullOrEmpty">Se true, permite nulo e branco</param>
        /// <returns></returns>
        public static bool Validate(string cpf, bool allowNullOrEmpty = true)
        {
            cpf = Functions.OnlyNumbers(cpf, "/.-").ToString();
            if (String.IsNullOrEmpty(cpf) && allowNullOrEmpty)
            {
                return(true);
            }
            if (string.IsNullOrEmpty(cpf) || cpf.Length < 11)
            {
                return(false);
            }

            //Se todos os números forem iguais, isso indica que o CPF é inválido
            int result = CountChars(cpf, Convert.ToChar(cpf.Substring(0, 1)));

            if (result == 11)
            {
                return(allowNullOrEmpty);
            }

            try
            {
                #region valida

                int[] multiplicador1 = new int[9] {
                    10, 9, 8, 7, 6, 5, 4, 3, 2
                };
                int[] multiplicador2 = new int[10] {
                    11, 10, 9, 8, 7, 6, 5, 4, 3, 2
                };
                string tempCpf;
                string digito;
                int    soma;
                int    resto;

                cpf = cpf.Trim();
                cpf = cpf.Replace(".", "").Replace("-", "");

                if (cpf.Length != 11)
                {
                    return(false);
                }

                tempCpf = cpf.Substring(0, 9);
                soma    = 0;
                for (int i = 0; i < 9; i++)
                {
                    soma += int.Parse(tempCpf[i].ToString()) * multiplicador1[i];
                }

                resto = soma % 11;
                if (resto < 2)
                {
                    resto = 0;
                }
                else
                {
                    resto = 11 - resto;
                }

                digito = resto.ToString();

                tempCpf = tempCpf + digito;

                soma = 0;
                for (int i = 0; i < 10; i++)
                {
                    soma += int.Parse(tempCpf[i].ToString()) * multiplicador2[i];
                }

                resto = soma % 11;
                if (resto < 2)
                {
                    resto = 0;
                }
                else
                {
                    resto = 11 - resto;
                }

                digito = digito + resto.ToString();

                return(cpf.EndsWith(digito));

                #endregion valida
            }
            catch
            {
                return(false);
            }
        }