예제 #1
0
        /// <summary>
        /// Metodo                  :InsertarAuditoria
        /// Propósito               :Permite insertar datos de auditoria al momento de loguear usuario
        /// Retorno                 :N/A
        /// Notas                   :N/A
        /// Autor                   :OCR - Orlando Carril R.
        /// Fecha/Hora de Creación  :04/10/2012
        /// Modificado              :N/A
        /// Fecha/Hora Modificación :N/A
        /// </summary>
        /// <param name="objUsuario"></param>
        /// <returns objReturnaValor></returns>
        public int InsertAuditoria(BEAuditoria objAuditoria)
        {
            SeguridadData objSeguridadDataNx = null;
            int           numVeces           = 0;

            try
            {
                objSeguridadDataNx = new SeguridadData();
                numVeces           = objSeguridadDataNx.InsertarAuditoria(objAuditoria);
            }
            catch (Exception ex)
            {
                HelpLogging.Write(TraceLevel.Error, string.Concat(this.GetType().Name, ".", MethodBase.GetCurrentMethod().Name), ex, objAuditoria.desLogin);
                numVeces = -1;
            }
            finally
            {
                if (objSeguridadDataNx != null)
                {
                    objSeguridadDataNx.Dispose();
                    objSeguridadDataNx = null;
                }
            }
            return(numVeces);
        }
예제 #2
0
        async public void CreateAndConfigureAsync(int pcodEmpresa, string pUserLogin)
        {
            try
            {
                CloudStorageAccount storageAccount = StorageUtils.StorageAccount;

                // Create a blob client and retrieve reference to images container
                CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container  = blobClient.GetContainerReference("DOCUMENTOS");

                // Create the "images" container if it doesn't already exist.
                if (await container.CreateIfNotExistsAsync())
                {
                    // Enable public access on the newly created "images" container
                    await container.SetPermissionsAsync(new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    });

                    HelpLogging.Write(TraceLevel.Info, this.GetType().Name + '.' + MethodBase.GetCurrentMethod().Name,
                                      "Creó con éxito el Blob Storage Images Container y lo hizo público", pUserLogin, pcodEmpresa.ToString());
                }
            }
            catch (Exception ex)
            {
                HelpLogging.Write(TraceLevel.Error, this.GetType().Name + '.' + MethodBase.GetCurrentMethod().Name,
                                  ex, pUserLogin, pcodEmpresa.ToString());
                throw new Exception("Error al crear o configurar el contenedor de imágenes en el Servicio de almacenamiento de blobs");
            }
        }
예제 #3
0
        /// <summary>
        /// Almacena el registro de una ENTIDAD de registro de Tipo ProductoKardexAux
        /// En la BASE de DATO la Tabla : [Produccion.ProductoExistenciasKardex]
        /// <summary>
        /// <param name="productoKardex"></param>
        /// <returns></returns>
        public ReturnValor Insert(ProductoKardexAux productoKardex)
        {
            ReturnValor objReturnValor = new ReturnValor();

            try
            {
                //using (TransactionScope tx = new TransactionScope(TransactionScopeOption.Required))
                //{
                objReturnValor.codRetorno = objProductoKardexData.Insert(productoKardex);
                if (objReturnValor.codRetorno > 0)
                {
                    objReturnValor.Message = HelpEventos.MessageEvento(HelpEventos.Process.NEW);
                    objReturnValor.Exitosa = true;
                    //tx.Complete();
                }
                else
                {
                    objReturnValor.Message = HelpMessages.KARDEX_NoRegistrado;
                }
                //}
            }
            catch (Exception ex)
            {
                HelpLogging.Write(TraceLevel.Error, string.Concat(this.GetType().Name, ".", MethodBase.GetCurrentMethod().Name), ex, productoKardex.segUsuarioEdita);
                objReturnValor = HelpException.mTraerMensaje(ex);
            }
            return(objReturnValor);
        }
예제 #4
0
        async public Task <string> UploadFileAsync(HttpPostedFileBase FileToUpload, string NombreArchivo, string Contenedor)
        {
            if (FileToUpload == null || FileToUpload.ContentLength == 0)
            {
                return(null);
            }
            string    fullPath = null;
            Stopwatch timespan = Stopwatch.StartNew();

            try
            {
                CloudStorageAccount storageAccount = StorageUtils.StorageAccount;

                // Create the blob client and reference the container
                CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container  = blobClient.GetContainerReference(Contenedor);

                // Upload image to Blob Storage
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(NombreArchivo);
                blockBlob.Properties.ContentType = FileToUpload.ContentType;
                await blockBlob.UploadFromStreamAsync((FileToUpload.InputStream));

                fullPath = blockBlob.Uri.ToString();
                timespan.Stop();
            }
            catch (Exception ex)
            {
                HelpLogging.Write(TraceLevel.Error, string.Concat(this.GetType().Name, ".UploadFileAsync", "Error upload file blob to storage"), ex);
                return(string.Empty);
            }
            return(fullPath);
        }
예제 #5
0
        protected OperationResult Warning(string pclass, string pmethod, OperationResult message, string pUser = "", int pIdEmpresa = 0)
        {
            string strOrigen = string.Concat(pclass, ".", pmethod);

            HelpLogging.Write(TraceLevel.Warning, strOrigen, message.brokenRulesCollection[0].description, pUser, pIdEmpresa.ToString());
            var operationResult = message;

            operationResult.isValid = false;

            return(operationResult);
        }
예제 #6
0
        public static string[] LeerRepuestaCDR(string pRutaEnvioSUNAT, string pNomFileSUNAT, string pNumRUC, bool pLecturaFileZip)
        {
            string mensajeRpta     = "";
            string mensajeRptaNota = "";
            string fileZiped       = "";

            string[]            datos             = new string[6];
            Nullable <DateTime> fechaCreateFile   = null;
            Nullable <DateTime> fechaModifiedFile = null;

            try
            {
                int PosicionFile = pLecturaFileZip ? 0 : 1;
                using (ZipArchive zip = ZipFile.Open(pRutaEnvioSUNAT, ZipArchiveMode.Read))
                {
                    ZipArchiveEntry zentry = null;
                    fileZiped = zip.Entries[PosicionFile].ToString();
                    zentry    = zip.GetEntry(fileZiped);
                    XmlDocument xd = new XmlDocument();
                    xd.Load(zentry.Open());
                    XmlNodeList xnl = xd.GetElementsByTagName("cbc:Description");
                    foreach (XmlElement item in xnl)
                    {
                        mensajeRpta = item.InnerText;
                    }

                    XmlNodeList xnlNota = xd.GetElementsByTagName("cbc:Note");
                    foreach (XmlElement item in xnlNota)
                    {
                        mensajeRptaNota = item.InnerText;
                    }
                }
                fechaCreateFile   = File.GetCreationTime(pRutaEnvioSUNAT);
                fechaModifiedFile = File.GetLastWriteTime(pRutaEnvioSUNAT);
            }
            catch (Exception ex)
            {
                HelpLogging.Write(TraceLevel.Info, string.Concat("HelpSUNAT.", MethodBase.GetCurrentMethod().Name),
                                  string.Concat("pRutaEnvioSUNAT.: ", pRutaEnvioSUNAT, "ex.Message ERROR: ", ex.Message), pNumRUC, pNumRUC);
            }
            datos[0] = mensajeRpta;
            datos[1] = fileZiped;
            datos[2] = pNomFileSUNAT;
            datos[3] = fechaCreateFile.HasValue ? fechaCreateFile.Value.ToString("dd/MM/yyyy HH:mm:ss",
                                                                                 CultureInfo.CreateSpecificCulture("es-PE")) : string.Empty;
            datos[4] = fechaModifiedFile.HasValue ? fechaModifiedFile.Value.ToString("dd/MM/yyyy HH:mm:ss",
                                                                                     CultureInfo.CreateSpecificCulture("es-PE")) : string.Empty;
            datos[5] = string.IsNullOrEmpty(mensajeRptaNota) ? "-" : mensajeRptaNota;
            return(datos);
        }
예제 #7
0
        protected OperationResult Error(string pClass, string pMethod, Exception ex, string pUser = "", string pIdEmpresa = "0")
        {
            string strOrigen = string.Concat(pClass, ".", pMethod);

            HelpLogging.Write(TraceLevel.Error, strOrigen, ex, pUser, pIdEmpresa);
            var operationResult = new OperationResult();

            operationResult.isValid = false;
            operationResult.brokenRulesCollection.Add(new BrokenRule
            {
                description = WebConstants.ErroresEjecucion.FirstOrDefault(x => x.Key == 1001).Value,
                severity    = RuleSeverity.Error
            });
            return(operationResult);
        }
예제 #8
0
        protected OperationResult Warning(string pclass, string pmethod, string message, string pUser = "", int pIdEmpresa = 0)
        {
            string strOrigen = string.Concat(pclass, ".", pmethod);

            HelpLogging.Write(TraceLevel.Warning, strOrigen, message, pUser, pIdEmpresa.ToString());
            var operationResult = new OperationResult();

            operationResult.isValid = false;
            operationResult.brokenRulesCollection.Add(new BrokenRule
            {
                description = message,
                severity    = RuleSeverity.Warning
            });
            return(operationResult);
        }
예제 #9
0
        public Stream GetSizeFileUrl(string URL, int pcodEmpresa, string pUserLogin, out int ReturnaTotalKb)
        {
            HttpWebRequest request = ((HttpWebRequest)WebRequest.Create(URL));
            Stream         StreamArchivo;
            int            totalBytes = 0;

            try
            {
                HttpWebResponse response = ((HttpWebResponse)request.GetResponse());
                using (StreamArchivo = response.GetResponseStream())
                {
                    using (Stream stream = StreamArchivo)
                    {
                        byte[] b = null;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            int count = 0;
                            do
                            {
                                byte[] buf = new byte[1024];
                                count = stream.Read(buf, 0, 1024);
                                ms.Write(buf, 0, count);
                                totalBytes += count;
                            }while (stream.CanRead && count > 0);
                            b          = ms.ToArray();
                            totalBytes = ms.ReadByte();
                        }
                        totalBytes = StreamArchivo.Read(b, 0, (int)b.Length);
                        totalBytes = stream.Read(b, 0, (int)b.Length);
                        int tota = stream.ReadByte();
                        totalBytes = (int)b.Length;
                    }
                }
            }
            catch (Exception ex)
            {
                HelpLogging.Write(TraceLevel.Error, this.GetType().Name + '.' + MethodBase.GetCurrentMethod().Name,
                                  ex, pUserLogin, pcodEmpresa.ToString());
                ReturnaTotalKb = totalBytes;
                return(null);
            }

            ReturnaTotalKb = totalBytes;

            return(StreamArchivo);
        }
예제 #10
0
        private OperationResult ValidarAccesoUsuarioSistemaEmpresa(BEUsuarioValidoResponse objUsuarioValidado, string pKeySistema)
        {
            var operationResult = new OperationResult();

            operationResult.isValid = false;
            if (string.IsNullOrEmpty(objUsuarioValidado.codEmpresaNombre) && objUsuarioValidado.codEmpleado != "EXT")
            {
                operationResult.brokenRulesCollection.Add(new BrokenRule
                {
                    description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2006).Value,
                    severity    = RuleSeverity.Warning
                });
                return(operationResult);
            }
            else if (string.IsNullOrEmpty(objUsuarioValidado.codSistemaNombre))
            {
                operationResult.brokenRulesCollection.Add(new BrokenRule
                {
                    description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2007).Value,
                    severity    = RuleSeverity.Warning
                });
                return(operationResult);
            }
            else if (string.IsNullOrEmpty(objUsuarioValidado.codRolNombre))
            {
                operationResult.brokenRulesCollection.Add(new BrokenRule
                {
                    description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2008).Value,
                    severity    = RuleSeverity.Warning
                });
                return(operationResult);
            }

            //Validar si esta asignado a una empresa
            //365A01B7-6C8E-460E-90F4-29C52D6CADD7|1|Sistema SIS|10181980325,
            //0E48ADC1-21B7-465B-858E-F3A3C608CEB1|2|Sistema GC|10181980327
            bool     blnEmpresaEsValido = false;
            string   strEmpresa         = string.Empty;
            string   strnumRUC          = string.Empty;
            DateTime?fecLicenciaVenc    = null;
            int      numCodigoError     = 0;

            if (objUsuarioValidado.codEmpleado != "EXT")
            {
                //HelpLogging.Write(TraceLevel.Warning, string.Concat(GetType().Name, ".", MethodBase.GetCurrentMethod().Name),
                //                  objUsuarioValidado.codEmpresaNombre,
                //                  string.Format("Empresa:[{0}], Usuario:[{1}]", "00", objUsuarioValidado.desLogin));

                string[] arrEmpresas = objUsuarioValidado.codEmpresaNombre.Split(',');
                foreach (string itemEmpresa in arrEmpresas)
                {
                    string[] arrDatoEmpresa = itemEmpresa.Split('|');

                    //HelpLogging.Write(TraceLevel.Info, string.Concat(GetType().Name,".", MethodBase.GetCurrentMethod().Name),
                    //              string.Format("arrDatoEmpresa[{0}].Trim() == pKeySistema({1})", arrDatoEmpresa[0].Trim(), pKeySistema),
                    //              string.Format("Empresa:[{0}], Usuario:[{1}]", "00", objUsuarioValidado.desLogin));

                    if (arrDatoEmpresa[0].Trim() == pKeySistema)
                    {
                        //HelpLogging.Write(TraceLevel.Info, string.Concat(GetType().Name, ".", MethodBase.GetCurrentMethod().Name),
                        //          string.Format("ConvertYYYYMMDDToDate:[ {0} ] == DateTime.Now=[ {1} ]", HelpTime.ConvertYYYYMMDDToDate(arrDatoEmpresa[1].Trim()),
                        //                                                                                 DateTime.Now.AddHours(GlobalSettings.GetDEFAULT_HorasFechaActualCloud())),
                        //          string.Format("Empresa:[{0}], Usuario:[{1}]", "00", objUsuarioValidado.desLogin));

                        if (HelpTime.ConvertYYYYMMDDToDate(arrDatoEmpresa[1].Trim()) > DateTime.Now.AddHours(GlobalSettings.GetDEFAULT_HorasFechaActualCloud()))
                        {
                            blnEmpresaEsValido            = true;
                            numCodigoError                = 0;
                            objUsuarioValidado.codEmpresa = Extensors.CheckInt(arrDatoEmpresa[2]);
                            strEmpresa = arrDatoEmpresa[3].Trim();
                            strnumRUC  = arrDatoEmpresa[4].Trim();
                            break;
                        }
                        else
                        {
                            numCodigoError  = 2011;
                            strEmpresa      = arrDatoEmpresa[3].Trim();
                            fecLicenciaVenc = HelpTime.ConvertYYYYMMDDToDate(arrDatoEmpresa[1].Trim());
                            HelpLogging.Write(TraceLevel.Warning, string.Concat(GetType().Name, ".", MethodBase.GetCurrentMethod().Name),
                                              string.Format("numCodigoError:[ {0} ] == DateTime.Now=[ {1} ]", numCodigoError,
                                                            DateTime.Now.AddHours(GlobalSettings.GetDEFAULT_HorasFechaActualCloud())),
                                              string.Format("Empresa:[{0}], Usuario:[{1}]", "00", objUsuarioValidado.desLogin));
                            break;
                        }
                    }
                    else
                    {
                        numCodigoError = 2010;
                        HelpLogging.Write(TraceLevel.Warning, string.Concat(GetType().Name, MethodBase.GetCurrentMethod().Name),
                                          string.Format("numCodigoError:[ {0} ] == DateTime.Now=[ {1} ]", numCodigoError,
                                                        DateTime.Now.AddHours(GlobalSettings.GetDEFAULT_HorasFechaActualCloud())),
                                          string.Format("Empresa:[{0}], Usuario:[{1}]", "00", objUsuarioValidado.desLogin));
                    }
                }

                if (!blnEmpresaEsValido)
                {
                    if (numCodigoError == 2011)
                    {
                        operationResult.brokenRulesCollection.Add(new BrokenRule
                        {
                            description = string.Format(WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == numCodigoError).Value,
                                                        strEmpresa, fecLicenciaVenc.Value.ToShortDateString()),
                            severity = RuleSeverity.Warning
                        });
                    }
                    else
                    {
                        operationResult.brokenRulesCollection.Add(new BrokenRule
                        {
                            description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == numCodigoError).Value,
                            severity    = RuleSeverity.Warning
                        });
                    }
                    return(operationResult);
                }

                objUsuarioValidado.codEmpresaNombre = strEmpresa;
                objUsuarioValidado.numRUC           = strnumRUC;
            }

            //Validar si esta asignado al sistema
            //365A01B7-6C8E-460E-90F4-29C52D6CADD7|1|Sistema SIS,
            //0E48ADC1-21B7-465B-858E-F3A3C608CEB1|2|Sistema GC
            bool   blnSistemaEsValido = false;
            string strSistema         = string.Empty;

            string[] arrSistemas = objUsuarioValidado.codSistemaNombre.Split(',');
            foreach (string itemSistema in arrSistemas)
            {
                string[] strValoresSistema = itemSistema.Split('|');
                if (strValoresSistema[0].Trim() == pKeySistema)
                {
                    strSistema = strValoresSistema[2].Trim();
                    objUsuarioValidado.codSistema = strValoresSistema[1].Trim();
                    blnSistemaEsValido            = true;
                    break;
                }
            }
            if (!blnSistemaEsValido)
            {
                operationResult.brokenRulesCollection.Add(new BrokenRule
                {
                    description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2009).Value,
                    severity    = RuleSeverity.Warning
                });
                return(operationResult);
            }
            objUsuarioValidado.codSistemaNombre = strSistema;
            //Validar si esta asignado a un rol
            //365A01B7-6C8E-460E-90F4-29C52D6CADD7|1|Administrador,
            //0E48ADC1-21B7-465B-858E-F3A3C608CEB1|15|Administrador
            bool   blnUsuarioEsValido = false;
            string strRol             = string.Empty;

            string[] arrRolesUsuario = objUsuarioValidado.codRolNombre.Split(',');
            foreach (string itemRolesUsuario in arrRolesUsuario)
            {
                string[] strValoresRolesUsuario = itemRolesUsuario.Split('|');
                if (strValoresRolesUsuario[0].Trim() == pKeySistema)
                {
                    strRol = strValoresRolesUsuario[2].Trim();
                    objUsuarioValidado.codRol = strValoresRolesUsuario[1].Trim();
                    blnUsuarioEsValido        = true;
                    break;
                }
            }
            if (!blnUsuarioEsValido)
            {
                operationResult.brokenRulesCollection.Add(new BrokenRule
                {
                    description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2012).Value,
                    severity    = RuleSeverity.Warning
                });
                return(operationResult);
            }

            objUsuarioValidado.codRolNombre = strRol;
            operationResult.isValid         = true;
            return(operationResult);
        }
예제 #11
0
        public static string ProcessRequest(string url, string method, byte[] byteData, string contentType,
                                            Dictionary <string, string> requestHeaders,
                                            string credentialUserName,
                                            string credentialPassword,
                                            int requestTimeout,
                                            ref bool hasErrors)
        {
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

            hasErrors = false;
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            if (requestTimeout >= 0)
            {
                myHttpWebRequest.Timeout          = requestTimeout;
                myHttpWebRequest.ContinueTimeout  = requestTimeout;
                myHttpWebRequest.ReadWriteTimeout = requestTimeout;
            }
            else
            {
                myHttpWebRequest.Timeout = System.Threading.Timeout.Infinite;
            }

            myHttpWebRequest.Method = method;

            if (!string.IsNullOrWhiteSpace(credentialUserName) && !string.IsNullOrWhiteSpace(credentialPassword))
            {
                myHttpWebRequest.Credentials = new NetworkCredential(credentialUserName, credentialPassword);
            }
            if (!string.IsNullOrWhiteSpace(contentType))
            {
                myHttpWebRequest.ContentType = contentType;
            }
            if (requestHeaders != null)
            {
                foreach (KeyValuePair <string, string> requestHeader in requestHeaders)
                {
                    myHttpWebRequest.Headers.Add(requestHeader.Key, requestHeader.Value);
                }
            }

            if ((method.ToLower() == WebConstants.METHOD_POST.ToLower() ||
                 method.ToLower() == WebConstants.METHOD_PUT.ToLower()) &&
                byteData != null)
            {
                myHttpWebRequest.ContentLength = byteData.Length;

                using (Stream requestStream = myHttpWebRequest.GetRequestStream())
                {
                    requestStream.Write(byteData, 0, byteData.Length);
                }
            }

            try
            {
                if (requestHeaders != null)
                {
                    foreach (KeyValuePair <string, string> requestHeader in requestHeaders)
                    {
                        string[] valorExist = myHttpWebRequest.Headers.GetValues(requestHeader.Key);
                        if (valorExist != null)
                        {
                            if (valorExist.Length > 0)
                            {
                                continue;
                            }
                        }

                        myHttpWebRequest.Headers.Add(requestHeader.Key, requestHeader.Value);
                    }
                }

                using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse())
                {
                    using (Stream responseStream = myHttpWebResponse.GetResponseStream())
                    {
                        if (responseStream == null)
                        {
                            return(null);
                        }
                        using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.UTF8))
                        {
                            return(myStreamReader.ReadToEnd());
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                HttpWebResponse resp    = ex.Response as HttpWebResponse;
                StreamReader    reader  = new StreamReader(resp.GetResponseStream());
                string          respStr = reader.ReadToEnd();
                reader.Close();
                if (string.IsNullOrEmpty(respStr))
                {
                    respStr = ex.Message;
                }

                HelpLogging.Write(TraceLevel.Error, string.Concat("HelpWebUtils.", MethodBase.GetCurrentMethod().Name), ex);
                hasErrors = true;
                return(respStr);
            }
            catch (OutOfMemoryException ex)
            {
                HelpLogging.Write(TraceLevel.Error, string.Concat("HelpWebUtils.", MethodBase.GetCurrentMethod().Name), ex);
                hasErrors = true;
                return(null);
            }
            catch (IOException ex)
            {
                HelpLogging.Write(TraceLevel.Error, string.Concat("HelpWebUtils.", MethodBase.GetCurrentMethod().Name), ex);
                hasErrors = true;
                return(null);
            }
            catch (Exception ex)
            {
                HelpLogging.Write(TraceLevel.Error, string.Concat("HelpWebUtils.", MethodBase.GetCurrentMethod().Name), ex);
                throw;
            }
        }
예제 #12
0
        public static async Task <OperationResult> ProcessHttpClientRequest(object pContent, string pMetodo, string pMediaType, Uri pURLWS)
        {
            OperationResult rptaResponse = new OperationResult();

            try
            {
                using (var client = new HttpClient())
                {
                    HttpContent content = new StringContent(JsonConvert.SerializeObject(pContent),
                                                            Encoding.UTF8,
                                                            pMediaType);
                    var metodo = HttpMethod.Get;
                    switch (pMetodo.ToUpper())
                    {
                    case WebConstants.METHOD_POST:
                        metodo = HttpMethod.Post;
                        break;

                    case WebConstants.METHOD_PUT:
                        metodo = HttpMethod.Put;
                        break;

                    case WebConstants.METHOD_DELETE:
                        metodo = HttpMethod.Delete;
                        break;
                    }

                    HttpRequestMessage request = new HttpRequestMessage
                    {
                        Method     = metodo,
                        RequestUri = pURLWS,
                        Content    = content,
                    };

                    HttpResponseMessage result = await client.SendAsync(request);

                    var responseBody = await result.Content.ReadAsStringAsync();

                    rptaResponse.isValid = result.IsSuccessStatusCode;
                    rptaResponse.data    = responseBody;

                    if (!result.IsSuccessStatusCode)
                    {
                        ResponseHttpClient jsonResul = JsonConvert.DeserializeObject <ResponseHttpClient>(responseBody);
                        rptaResponse.brokenRulesCollection.Add(new BrokenRule
                        {
                            description = jsonResul.Message,
                            severity    = RuleSeverity.Error,
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                HelpLogging.Write(TraceLevel.Error, string.Concat("ProcessHttpClientRequest.", MethodBase.GetCurrentMethod().Name), ex);
                rptaResponse.brokenRulesCollection.Add(new BrokenRule
                {
                    description = ex.Message,
                    severity    = RuleSeverity.Error,
                });
            }
            return(rptaResponse);
        }
예제 #13
0
        public static Bitmap GenerarCodigoQR(string pEmisorRUC,
                                             string Tipocomprobante,
                                             string Numeracion,
                                             string SumatoriaIGV,
                                             string ImporteTotalVenta,
                                             string FechaEmision,
                                             string TipoDocumentoAdquirente,
                                             string NumeroDocumentoAdquirente,
                                             string CodigoHash,
                                             bool pSaveImgQR,
                                             string pPathFileName,
                                             string pUserLogin,
                                             out string pMessajeError)
        {
            pMessajeError = string.Empty;
            Bitmap result = null;

            try
            {
                QrCodeEncodingOptions options = new QrCodeEncodingOptions();
                options = new QrCodeEncodingOptions
                {
                    DisableECI   = true,
                    CharacterSet = "UTF-8",
                    Width        = 250,
                    Height       = 250,
                };
                var writer = new BarcodeWriter();
                writer.Format  = BarcodeFormat.QR_CODE;
                writer.Options = options;

                if (String.IsNullOrWhiteSpace(pEmisorRUC) || String.IsNullOrEmpty(Tipocomprobante) || String.IsNullOrEmpty(Numeracion) ||
                    String.IsNullOrWhiteSpace(SumatoriaIGV) || String.IsNullOrEmpty(ImporteTotalVenta) || String.IsNullOrEmpty(FechaEmision) ||
                    String.IsNullOrWhiteSpace(ImporteTotalVenta) || String.IsNullOrWhiteSpace(FechaEmision) || String.IsNullOrWhiteSpace(TipoDocumentoAdquirente) ||
                    String.IsNullOrWhiteSpace(NumeroDocumentoAdquirente) || String.IsNullOrWhiteSpace(CodigoHash))
                {
                    pMessajeError = "Debe proporcionar todos los parametros para la generación del QR.";
                }
                else
                {
                    string codigo = string.Concat(pEmisorRUC, "|",
                                                  Tipocomprobante, "|",
                                                  Numeracion, "|",
                                                  SumatoriaIGV, "|",
                                                  ImporteTotalVenta, "|",
                                                  FechaEmision, "|",
                                                  TipoDocumentoAdquirente, "|",
                                                  NumeroDocumentoAdquirente, "|",
                                                  CodigoHash);


                    var qr = new ZXing.BarcodeWriter();
                    qr.Options = options;
                    qr.Format  = ZXing.BarcodeFormat.QR_CODE;
                    result     = new Bitmap(qr.Write(codigo.Trim())); //Generar QR

                    /*
                     * GRABAR LA IMAGEN QR
                     */
                    if (pSaveImgQR)
                    {
                        try
                        {
                            result.Save(pPathFileName, ImageFormat.Png);
                        }
                        catch (Exception ex)
                        {
                            HelpLogging.Write(TraceLevel.Error, string.Concat(pEmisorRUC + "." + MethodBase.GetCurrentMethod().Name), ex,
                                              pEmisorRUC);
                            pMessajeError = "Error interno.";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HelpException.mTraerMensaje(ex, false, string.Concat("HelpSUNAT.", MethodBase.GetCurrentMethod().Name), pUserLogin, pEmisorRUC);
            }
            return(result);
        }