public HttpResponseMessage QrCode(string id) { if (id == null) throw new ArgumentNullException("id"); if (!ValidUserIdRegex.IsMatch(id)) { return new HttpResponseMessage(HttpStatusCode.BadRequest); } const int MODULE_SIZE = 12; GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(MODULE_SIZE, QuietZoneModules.Zero)); QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.L); string content = id; QrCode qrCode = qrEncoder.Encode(content); MemoryStream rendered = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Gif, rendered); HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK); responseMessage.Content = new ByteArrayContent(rendered.ToArray()); responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/gif"); return responseMessage; }
public void generar(Compra compra) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = qrEncoder.Encode(compra.Id.ToString()); Renderer renderer = new Renderer(5, Brushes.Black, Brushes.White); renderer.CreateImageFile(qrCode.Matrix, "c:/Qr" + compra.Id.ToString() + ".png", ImageFormat.Png); }
public Image DrawQRCode(int qrImageSize, ImageFormat imgFormat) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = qrEncoder.Encode(this.BarCodeValue); GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(qrImageSize, QuietZoneModules.Two), Brushes.Black, Brushes.White); MemoryStream stream = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, imgFormat, stream); return Image.FromStream(stream); }
public string generarQR(string codigo) { var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); var qrCode = qrEncoder.Encode(codigo); var renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); string path = AppDomain.CurrentDomain.BaseDirectory + "tmp\\"+ codigo +"QR.png"; using (var stream = new FileStream(path, FileMode.Create)) renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream); return codigo+"QR.png"; }
public static void RunSample3() { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = qrEncoder.Encode("Hello World!"); GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); using (FileStream stream = new FileStream(@"c:\temp\HelloWorld.png", FileMode.Create)) { renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream); } }
public Image GenerateQRCode(QRCodeParameters param) { if (param == null) throw new ArgumentNullException(); QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.L); QrCode qrCode = encoder.Encode(param.Text); GraphicsRenderer gRenderer = new GraphicsRenderer(new FixedModuleSize(param.Size, QuietZoneModules.Two), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); gRenderer.WriteToStream(qrCode.Matrix, param.ImageFormat, ms); return Image.FromStream(ms); }
public FileContentResult Show(Guid id) { QrEncoder enc = new QrEncoder(); QrCode code = enc.Encode(GetUrl()); Renderer renderer = new Renderer(5); Image image = new Bitmap(256,256); using (Graphics graphics = Graphics.FromImage(image)) renderer.Draw(graphics, code.Matrix); byte[] imageByte = imageToByteArray(image); string contentType = "image/png"; return File(imageByte, contentType); }
public static void GenerateQR(string encodeString, string venueName, string branding) { //Ask the user for the path where the QR pdf file will be stored. If canceled, return and do nothing. string filePath = GetSaveFilePath(); if (filePath.Equals("")) return; QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode code = encoder.Encode(encodeString); Renderer renderer = new Renderer(25, System.Drawing.Brushes.Black, System.Drawing.Brushes.White); renderer.CreateImageFile(code.Matrix, IMAGE_NAME, ImageFormat.Png); PrintToPDF(venueName, branding, filePath); }
public recieve_litecoin() { InitializeComponent(); ILitecoinService litecoinService = new LitecoinService(); string a = litecoinService.GetNewAddress(); address_textBox.Text = a; Gma.QrCodeNet.Encoding.QrEncoder Encoder = new Gma.QrCodeNet.Encoding.QrEncoder(Gma.QrCodeNet.Encoding.ErrorCorrectionLevel.H); Gma.QrCodeNet.Encoding.QrCode Code = Encoder.Encode(a); Bitmap TempBMP = new Bitmap(Code.Matrix.Width, Code.Matrix.Height); for (int X = 0; X <= (Code.Matrix.Width) - 1; X++) { for (int Y = 0; Y <= (Code.Matrix.Height) - 1; Y++) { if (Code.Matrix.InternalArray[X, Y]) { TempBMP.SetPixel(X, Y, System.Drawing.Color.Black); } else { TempBMP.SetPixel(X, Y, System.Drawing.Color.White); } } } //TempBMP.Size abc = new System.Drawing.Size(120,120); //Console.Write(TempBMP); //ictureBox.Image.Size =new Size(600, 700); //empBMP.Size = new Size(TempBMP.Height,TempBMP.Width); pictureBox.Size = new Size(100, 75); // pictureBox.Image = TempBMP; var imageTemp = new Bitmap(TempBMP); var image = new Bitmap(imageTemp, new System.Drawing.Size(new System.Drawing.Point(100, 75))); //image.Save("file.bmp", ImageFormat.Bmp); pictureBox.Image = image; //pictureBox.BorderStyle = BorderStyle.FixedSingle; }
/// <summary> /// Generates an img tag with a data uri encoded image of the QR code from the content given. /// </summary> /// <param name="html"></param> /// <param name="content"></param> /// <returns></returns> public static IHtmlString QRCode(this HtmlHelper html, string content) { QrEncoder enc = new QrEncoder(ErrorCorrectionLevel.H); var code = enc.Encode(content); GraphicsRenderer r = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); using (MemoryStream ms = new MemoryStream()) { r.WriteToStream(code.Matrix, ImageFormat.Png, ms); byte[] image = ms.ToArray(); //otpauth://totp/MY_APP_LABEL?secret={0} return html.Raw(string.Format(@"<img src=""data:image/png;base64,{0}"" alt=""{1}"" />", Convert.ToBase64String(image), content)); } }
/// <summary> /// Generates an img tag with a data uri encoded image of the QR code from the content given. /// </summary> /// <param name="html"></param> /// <param name="content"></param> /// <returns></returns> public static IHtmlString QRCode(this HtmlHelper html, string content) { QrEncoder enc = new QrEncoder(ErrorCorrectionLevel.H); var code = enc.Encode(content); Renderer r = new Renderer(5, Brushes.Black, Brushes.White); using (MemoryStream ms = new MemoryStream()) { r.WriteToStream(code.Matrix, ms, ImageFormat.Png); byte[] image = ms.ToArray(); return html.Raw(string.Format(@"<img src=""data:image/png;base64,{0}"" alt=""{1}"" />", Convert.ToBase64String(image), content)); } }
private void btnShowQRCode_Click(object sender, EventArgs e) { var qrGenerator = new QrEncoder(); var qrCode = qrGenerator.Encode(_password); var gRenderer = new GraphicsRenderer( new FixedModuleSize(6, QuietZoneModules.Two)); using (var ms = new MemoryStream()) { gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); using (pbQrCode.Image) { pbQrCode.Image = new Bitmap(ms); } } }
/// <summary> /// Gets the QR code containing the data of the network component. /// </summary> /// <returns>The QR code image.</returns> public Bitmap GetQRCode( ) { QrEncoder qrEncoder = new QrEncoder( ErrorCorrectionLevel.H ); byte[ ] ipBytes = IP.GetAddressBytes( ); QrCode qrCode = qrEncoder.Encode( $"{string.Join( ",", ipBytes )},{Port}" ); const int moduleSizeInPixels = 25; GraphicsRenderer renderer = new GraphicsRenderer( new FixedModuleSize( moduleSizeInPixels, QuietZoneModules.Two ), Brushes.Black, Brushes.White ); DrawingSize dSize = renderer.SizeCalculator.GetSize( qrCode.Matrix.Width ); Bitmap bmp = new Bitmap( dSize.CodeWidth, dSize.CodeWidth ); using ( Graphics graphics = Graphics.FromImage( bmp ) ) renderer.Draw( graphics, qrCode.Matrix ); return bmp; }
public void GenerateQrCodesForIds(string directory, IEnumerable<string> items) { QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M); GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); int index = 0; foreach (var item in items) { QrCode qrCode = encoder.Encode(item); using (FileStream stream = new FileStream(string.Format("{0}\\{1}.png", directory, index), FileMode.Create)) { renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream); } index++; } }
public static void RunSample1() { Console.Write(@"Type some text to QR code: "); string sampleText = Console.ReadLine(); QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = qrEncoder.Encode(sampleText); for (int j = 0; j < qrCode.Matrix.Width; j++) { for (int i = 0; i < qrCode.Matrix.Width; i++) { char charToPrint = qrCode.Matrix[i, j] ? '█' : ' '; Console.Write(charToPrint); } Console.WriteLine(); } Console.WriteLine(@"Press any key to quit."); Console.ReadKey(); }
public static void RunSample2() { const string helloWorld = "Hello World!"; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = qrEncoder.Encode(helloWorld); const int moduleSizeInPixels = 5; GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(moduleSizeInPixels, QuietZoneModules.Two), Brushes.Black, Brushes.White); Panel panel = new Panel(); Point padding = new Point(10, 16); DrawingSize dSize = renderer.SizeCalculator.GetSize(qrCode.Matrix.Width); panel.AutoSize = false; panel.Size = new Size(dSize.CodeWidth, dSize.CodeWidth) + new Size(2*padding.X, 2*padding.Y); using (Graphics graphics = panel.CreateGraphics()) { renderer.Draw(graphics, qrCode.Matrix, padding); } }
public ActionResult EnableGoogleAuthentication() { var secretKey = Utilities.GenerateOTPKey(); var content = string.Format("otpauth://totp/{0}?secret={1}", "DotPay:" + this.CurrentUser.LoginName, secretKey); QrEncoder enc = new QrEncoder(ErrorCorrectionLevel.H); var code = enc.Encode(content); var imageData = string.Empty; GraphicsRenderer r = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); using (MemoryStream ms = new MemoryStream()) { r.WriteToStream(code.Matrix, ImageFormat.Png, ms); byte[] image = ms.ToArray(); //otpauth://totp/MY_APP_LABEL?secret={0} imageData = Convert.ToBase64String(image); //return html.Raw(string.Format(@"<img src=""data:image/png;base64,{0}"" alt=""{1}"" />", Convert.ToBase64String(image), content)); } var result = FCJsonResult.CreateFailResult(Language.LangHelpers.Lang("Unable to update your nick name. Please try again.")); return Json(new { Code = 1, @ImageData = imageData, SecretKey = secretKey }); }
private void btnAceptar_Click(object sender, EventArgs e) { int existeNullCodeQR = 0; fecha = ""; fechafin = ""; cnx = new SqlConnection(cdn); cmd = new SqlCommand(); cmd.Connection = cnx; CalculoNomina.Core.NominaHelper nh = new CalculoNomina.Core.NominaHelper(); nh.Command = cmd; for (int i = 0; i < lstvPeriodos.SelectedItems.Count; i++) { fecha = lstvPeriodos.SelectedItems[i].Text; fechafin = lstvPeriodos.SelectedItems[i].SubItems[1].Text; } try { cnx.Open(); existeNullCodeQR = nh.existeNullQR(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date); cnx.Close(); } catch (Exception error) { MessageBox.Show("Error: Al obtener existencia de nulos Code QR. " + error.Message, "Error"); cnx.Dispose(); return; } if (existeNullCodeQR != 0) { List<CalculoNomina.Core.CodigoBidimensional> lstXml = new List<CalculoNomina.Core.CodigoBidimensional>(); try { cnx.Open(); lstXml = nh.obtenerListaQr(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date); cnx.Close(); } catch (Exception error) { MessageBox.Show("Error: Al obtener el listado de XMLs." + error.Message, "Error"); cnx.Dispose(); return; } string codigoQR = ""; string[] valores = null; string numero = ""; string vEntero = ""; string vDecimal = ""; for (int i = 0; i < lstXml.Count; i++) { numero = lstXml[i].tt.ToString(); valores = numero.Split('.'); vEntero = valores[0]; vDecimal = valores[1]; codigoQR = string.Format("?re={0}&rr={1}&tt={2}.{3}&id={4}", lstXml[i].re, lstXml[i].rr, vEntero.PadLeft(10, '0'), vDecimal.PadRight(6, '0'), lstXml[i].uuid); var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); var qrCode = qrEncoder.Encode(codigoQR); var renderer = new GraphicsRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Brushes.Black, Brushes.White); using (var stream = new FileStream(lstXml[i].uuid + ".png", FileMode.Create)) renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream); Bitmap bmp = new Bitmap(lstXml[i].uuid + ".png"); Byte[] qr = GLOBALES.IMAGEN_BYTES(bmp); bmp.Dispose(); File.Delete(lstXml[i].uuid + ".png"); try { cnx.Open(); nh.actualizaXml(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date, lstXml[i].idtrabajador, qr); cnx.Close(); } catch (Exception) { MessageBox.Show("Error: Al actualizar el código QR.", "Error"); cnx.Dispose(); return; } } } if (todos) { for (int i = 0; i < lstvPeriodos.SelectedItems.Count; i++) fecha = lstvPeriodos.SelectedItems[i].Text; idEmpleados = ""; frmVisorReportes vr = new frmVisorReportes(); vr._tipoNomina = (cmbTipoNomina.SelectedIndex == 0 ? GLOBALES.NORMAL : GLOBALES.EXTRAORDINARIO_NORMAL); vr._departamentos = idDepartamentos; vr._empleados = idEmpleados; vr._todos = todos; vr._noReporte = 10; vr._inicioPeriodo = DateTime.Parse(fecha).Date; vr._periodo = periodo; vr.Show(); } else { idEmpleados = ""; for (int i = 0; i < lstvEmpleados.Items.Count; i++) { if (lstvEmpleados.Items[i].Checked) idEmpleados += lstvEmpleados.Items[i].Text + ","; } fecha = ""; if (idEmpleados != "") { for (int i = 0; i < lstvPeriodos.SelectedItems.Count; i++) fecha = lstvPeriodos.SelectedItems[i].Text; idEmpleados = idEmpleados.Substring(0, idEmpleados.Length - 1); frmVisorReportes vr = new frmVisorReportes(); vr._tipoNomina = (cmbTipoNomina.SelectedIndex == 0 ? GLOBALES.NORMAL : GLOBALES.EXTRAORDINARIO_NORMAL); vr._departamentos = idDepartamentos; vr._empleados = idEmpleados; vr._todos = todos; vr._noReporte = 10; vr._periodo = periodo; vr._inicioPeriodo = DateTime.Parse(fecha).Date; vr.Show(); } } }
/// <summary> /// Post process payment (used by payment gateways that require redirecting to a third-party URL) /// </summary> /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param> public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest) { var order = postProcessPaymentRequest.Order; const string paymenturl = "https://api.mch.weixin.qq.com/pay/unifiedorder"; var spbillCreateIp = _webHelper.GetCurrentIpAddress(); var notifyUrl = _webHelper.GetStoreLocation(false) + "Order/Notify"; var paras = new SortedDictionary<string, string>() { {"body", "测试商品"}, {"attach", "测试商品"}, {"out_trade_no", order.TradeNo}, {"total_fee", (order.OrderTotal*100).ToString(".")}, {"time_start", DateTime.Now.ToString("yyyyMMddHHmmss")}, {"time_expire", DateTime.Now.AddMinutes(5).ToString("yyyyMMddHHmmss")}, {"goods_tag", "商品标记"}, {"trade_type", "NATIVE"}, {"product_id", order.Id.ToString()}, {"appid", Appid}, {"mch_id", MchId}, {"spbill_create_ip", spbillCreateIp}, {"nonce_str", CommonHelper.GenerateRandomDigitCode(16)}, {"notify_url", notifyUrl} }; using (var client = new HttpClient()) { var sign = MakeSign(paras); paras.Add("sign", sign); var requestxml = RequestXml(paras); var httpContent = new StringContent(requestxml, Encoding.UTF8, "application/xml"); var result = client.PostAsync(paymenturl, httpContent).Result; using (var responsestream = result.Content.ReadAsStreamAsync().Result) { var serializer = new XmlSerializer(typeof(WebCharReponse)); var response = serializer.Deserialize(responsestream) as WebCharReponse; if (response == null || response.ResultCode == "FAIL") return; var weburl = response.CodeUrl; var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); var qrCode = qrEncoder.Encode(weburl); var renderer = new GraphicsRenderer(new FixedCodeSize(200, QuietZoneModules.Zero)); _httpContext.Response.ContentType = "image/jpeg"; renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, _httpContext.Response.OutputStream); _httpContext.Response.End(); } } }
//[OutputCache(Duration = 60 * 60 * 24, Location = System.Web.UI.OutputCacheLocation.Downstream)] public async Task<ActionResult> QR(string slug, int width=8) { QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.L); using (var db = new SportDataContext()) { var ev = await EventService.GetEvent(slug, db); if (ev == null) return HttpNotFound(); var url = "http://afspb.org.ru/timeline/"; if(ev.Season!=2014) url += ev.Season + "/"; url += ev.Slug + "/Guide"; var qrCode = encoder.Encode(url); GraphicsRenderer dRenderer = new GraphicsRenderer( new FixedModuleSize(width, QuietZoneModules.Two), Brushes.Black, Brushes.White); using(var ms = new MemoryStream()) { dRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); return File(ms.ToArray(), "image/png"); } } }
private void writeQR(String url ,String fileName) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = qrEncoder.Encode(url); GraphicsRenderer gRender = new GraphicsRenderer(new FixedModuleSize(30, QuietZoneModules.Four)); BitMatrix matrix = qrCode.Matrix; using (FileStream stream = new FileStream(fileName, FileMode.Create)) { gRender.WriteToStream(matrix, ImageFormat.Png, stream, new System.Drawing.Point(600, 600)); } }
private void btnAceptar_Click(object sender, EventArgs e) { if (!_ReportePreNomina) { if (noReporte != 6 && noReporte != 9) { if (noReporte == 8) { int existeNullCodeQR = 0; cnx = new SqlConnection(cdn); cmd = new SqlCommand(); cmd.Connection = cnx; nh = new CalculoNomina.Core.NominaHelper(); nh.Command = cmd; #region EXISTENCIA DE NULOS EN TABLA xmlCabecera try { cnx.Open(); existeNullCodeQR = nh.existeNullQR(GLOBALES.IDEMPRESA, dtpInicioPeriodo.Value.Date, dtpFinPeriodo.Value.Date); cnx.Close(); } catch (Exception error) { MessageBox.Show("Error: Al obtener existencia de nulos Code QR." + error.Message, "Error"); cnx.Dispose(); return; } #endregion #region GENERACION DE CODIGO QR SI EXISTEN NULOS if (existeNullCodeQR != 0) { List<CalculoNomina.Core.CodigoBidimensional> lstXml = new List<CalculoNomina.Core.CodigoBidimensional>(); try { cnx.Open(); lstXml = nh.obtenerListaQr(GLOBALES.IDEMPRESA, dtpInicioPeriodo.Value.Date, dtpFinPeriodo.Value.Date); cnx.Close(); } catch (Exception error) { MessageBox.Show("Error: Al obtener el listado de los XML." + error.Message, "Error"); cnx.Dispose(); return; } string codigoQR = ""; string[] valores = null; string numero = ""; string vEntero = ""; string vDecimal = ""; for (int i = 0; i < lstXml.Count; i++) { numero = lstXml[i].tt.ToString(); valores = numero.Split('.'); vEntero = valores[0]; vDecimal = valores[1]; codigoQR = string.Format("?re={0}&rr={1}&tt={2}.{3}&id={4}", lstXml[i].re, lstXml[i].rr, vEntero.PadLeft(10, '0'), vDecimal.PadRight(6, '0'), lstXml[i].uuid); var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); var qrCode = qrEncoder.Encode(codigoQR); var renderer = new GraphicsRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Brushes.Black, Brushes.White); using (var stream = new FileStream(lstXml[i].uuid + ".png", FileMode.Create)) renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream); Bitmap bmp = new Bitmap(lstXml[i].uuid + ".png"); Byte[] qr = GLOBALES.IMAGEN_BYTES(bmp); bmp.Dispose(); File.Delete(lstXml[i].uuid + ".png"); try { cnx.Open(); nh.actualizaXml(GLOBALES.IDEMPRESA, dtpInicioPeriodo.Value.Date, dtpFinPeriodo.Value.Date, lstXml[i].idtrabajador, qr); cnx.Close(); } catch (Exception) { MessageBox.Show("Error: Al actualizar el código QR.", "Error"); cnx.Dispose(); return; } } } #endregion } frmVisorReportes vr = new frmVisorReportes(); vr._inicioPeriodo = dtpInicioPeriodo.Value; vr._finPeriodo = dtpFinPeriodo.Value; if (_ReportePreNomina) vr._tipoNomina = _tipoNomina; else vr._tipoNomina = tipoNomina; vr._noReporte = noReporte; vr._deptoInicio = int.Parse(cmbDeptoInicial.SelectedValue.ToString()); vr._deptoFin = int.Parse(cmbDeptoFinal.SelectedValue.ToString()); vr._empleadoInicio = int.Parse(cmbEmpleadoInicial.SelectedValue.ToString()); vr._empleadoFin = int.Parse(cmbEmpleadoFinal.SelectedValue.ToString()); vr._netoCero = netocero; vr._orden = orden; vr._periodo = periodo; vr.Show(); } else { if (noReporte == 6) excelTabular(); if (noReporte == 9) excelGravadosExentos(); } } else { int empleadoInicial = 0, empleadoFinal = 0; if (_noReporte == 9 || _noReporte == 1) { empleadoInicial = int.Parse(cmbEmpleadoInicial.SelectedValue.ToString()); empleadoFinal = int.Parse(cmbEmpleadoFinal.SelectedValue.ToString()); } if (OnReporte != null) OnReporte(netocero, orden, _noReporte, empleadoInicial, empleadoFinal); } }
public void PrintQrCode(string qrCodeData, int size, int ec) { if (string.IsNullOrWhiteSpace(qrCodeData)) return; var space = GetSpace(qrCodeData); qrCodeData = qrCodeData.TrimStart(); if (size == 0) size = 6; else size = (size * 2) + 1; if (ec > 0) ec--; var qrEncoder = new QrEncoder((ErrorCorrectionLevel)ec); var qrCode = qrEncoder.Encode(qrCodeData); var renderer = new GraphicsRenderer(new FixedModuleSize(size, QuietZoneModules.Zero), Brushes.Black, Brushes.White); using (var stream = new MemoryStream()) { renderer.WriteToStream(qrCode.Matrix, ImageFormat.Bmp, stream); PrintBitmap((Bitmap)Image.FromStream(stream), space); } }
private void workerEnvio_DoWork(object sender, DoWorkEventArgs e) { int existeNullCodeQR = 0; cnx = new SqlConnection(cdn); cmd = new SqlCommand(); cmd.Connection = cnx; CalculoNomina.Core.NominaHelper nh = new CalculoNomina.Core.NominaHelper(); nh.Command = cmd; workerEnvio.ReportProgress(0, "Generando códigos QR."); try { cnx.Open(); existeNullCodeQR = nh.existeNullQR(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date); cnx.Close(); } catch (Exception error) { MessageBox.Show("Error: Al obtener existencia de nulos Code QR." + error.Message, "Error"); cnx.Dispose(); return; } if (existeNullCodeQR != 0) { List<CalculoNomina.Core.CodigoBidimensional> lstQR = new List<CalculoNomina.Core.CodigoBidimensional>(); try { cnx.Open(); lstQR = nh.obtenerListaQr(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date); cnx.Close(); } catch (Exception error) { MessageBox.Show("Error: Al obtener el listado de los XML." + error.Message, "Error"); cnx.Dispose(); return; } string codigoQR = ""; string[] valores = null; string numero = ""; string vEntero = ""; string vDecimal = ""; for (int i = 0; i < lstQR.Count; i++) { numero = lstQR[i].tt.ToString(); valores = numero.Split('.'); vEntero = valores[0]; vDecimal = valores[1]; codigoQR = string.Format("?re={0}&rr={1}&tt={2}.{3}&id={4}", lstQR[i].re, lstQR[i].rr, vEntero.PadLeft(10, '0'), vDecimal.PadRight(6, '0'), lstQR[i].uuid); var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); var qrCode = qrEncoder.Encode(codigoQR); var renderer = new GraphicsRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Brushes.Black, Brushes.White); using (var stream = new FileStream(lstQR[i].uuid + ".png", FileMode.Create)) renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream); Bitmap bmp = new Bitmap(lstQR[i].uuid + ".png"); Byte[] qr = GLOBALES.IMAGEN_BYTES(bmp); bmp.Dispose(); File.Delete(lstQR[i].uuid + ".png"); try { cnx.Open(); nh.actualizaXml(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date, lstQR[i].idtrabajador, qr); cnx.Close(); } catch (Exception) { MessageBox.Show("Error: Al actualizar el código QR.", "Error"); cnx.Dispose(); return; } } } int existeRecibo = 0; if (fecha != "") { for (int i = 0; i < dgvEmpleados.Rows.Count; i++) { try { cnx.Open(); existeRecibo = (int)nh.existeXMLTrabajador(GLOBALES.IDEMPRESA, int.Parse(dgvEmpleados.Rows[i].Cells["idtrabajador"].Value.ToString()), DateTime.Parse(fecha).Date); cnx.Close(); } catch (Exception) { MessageBox.Show("Error: Al obtener existencia del XML", "Error"); cnx.Dispose(); return; } if (existeRecibo != 0) { dsReportes.NominaRecibosDataTable dtImpresionNomina = new dsReportes.NominaRecibosDataTable(); SqlDataAdapter daImpresionNomina = new SqlDataAdapter(); cmd.CommandText = "exec stp_rptNominaImpresionTrabajador @idempresa, @fechainicio, @tiponomina, @idtrabajador, @periodo"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("idempresa", GLOBALES.IDEMPRESA); cmd.Parameters.AddWithValue("fechainicio", DateTime.Parse(fecha).Date); cmd.Parameters.AddWithValue("tiponomina", tipoNomina); cmd.Parameters.AddWithValue("idtrabajador", int.Parse(dgvEmpleados.Rows[i].Cells["idtrabajador"].Value.ToString())); cmd.Parameters.AddWithValue("periodo", periodo); cmd.CommandTimeout = 300; daImpresionNomina.SelectCommand = cmd; daImpresionNomina.Fill(dtImpresionNomina); ReportDataSource rd = new ReportDataSource(); rd.Value = dtImpresionNomina; rd.Name = "dsNominaRecibo"; Visor.LocalReport.DataSources.Clear(); Visor.LocalReport.DataSources.Add(rd); Visor.LocalReport.ReportEmbeddedResource = "rptNominaRecibos.rdlc"; Visor.LocalReport.ReportPath = @"rptNominaRecibos.rdlc"; Warning[] warnings; string[] streamids; string mimeType; string encoding; string extension; byte[] bytes = Visor.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings); if (!Directory.Exists(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString())) Directory.CreateDirectory(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString()); using (FileStream fs = new FileStream(string.Format(@"{0}\{1}.{2}", ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString(), dgvEmpleados.Rows[i].Cells["nombrecompleto"].Value.ToString() + "_" + DateTime.Parse(fecha).ToString("yyyyMMdd"), "pdf"), FileMode.Create)) { fs.Write(bytes, 0, bytes.Length); fs.Flush(); fs.Close(); fs.Dispose(); } List<CalculoNomina.Core.XmlCabecera> lstXml = new List<CalculoNomina.Core.XmlCabecera>(); try { cnx.Open(); lstXml = nh.obtenerXmlTrabajador(GLOBALES.IDEMPRESA, int.Parse(dgvEmpleados.Rows[i].Cells["idtrabajador"].Value.ToString()), DateTime.Parse(fecha).Date); cnx.Close(); } catch (Exception) { MessageBox.Show("Error: Al obtener el XML del Trabajador", "Error"); cnx.Dispose(); return; } using (StreamWriter sw = new StreamWriter(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString() + "\\" + dgvEmpleados.Rows[i].Cells["nombrecompleto"].Value.ToString() + "_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + ".xml")) { sw.WriteLine(lstXml[0].xml); } workerEnvio.ReportProgress(i, "Recibo generado."); } else { workerEnvio.ReportProgress(i, "Recibo no existe."); } } try { using (ZipFile zip = new ZipFile()) { if (File.Exists(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip")) File.Delete(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip"); zip.AddDirectory(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString() + "\\"); zip.Save(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip"); } } catch (Exception) { MessageBox.Show("Error: Al crear el archivo comprimido.", "Error"); } MailMessage email = new MailMessage(); SmtpClient smtp = new SmtpClient(); Attachment comprimido = new Attachment(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip"); email.IsBodyHtml = true; email.From = new MailAddress(correoEnvio, "Recibos electrónicos de nómina"); email.To.Add(txtCorreoElectronico.Text); email.Subject = "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd"); email.Body = "Correo automatico enviado por el sistema de administración de nómina. \r\n \r\n No responder."; email.Priority = MailPriority.Normal; email.Attachments.Add(comprimido); smtp.Host = servidorEnvio; smtp.Port = puertoEnvio; smtp.EnableSsl = usaSSL; smtp.Credentials = new NetworkCredential(correoEnvio, passwordEnvio); try { workerEnvio.ReportProgress(0, "Enviando recibos de nómina"); smtp.Send(email); smtp.Dispose(); comprimido.Dispose(); } catch (Exception msg) { MessageBox.Show("Error al enviar el correo: " + msg.Message, "Error"); } } }
public void PrintQrCode(string qrCodeData) { var fileName = LocalSettings.DocumentPath + "\\qr.bmp"; var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); var qrCode = qrEncoder.Encode(qrCodeData); var renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); using (var stream = new FileStream(fileName, FileMode.Create)) { renderer.WriteToStream(qrCode.Matrix, ImageFormat.Bmp, stream); } PrintBitmap(fileName); }
private void button1_Click(object sender, EventArgs e) { string makefile = HKLibrary.UTIL.HKFileHelper.GetCurrentDirectory(); string sDirPath; sDirPath = makefile + "\\data"; DirectoryInfo di = new DirectoryInfo(sDirPath); if (di.Exists == false) { di.Create(); } string PinCode = "41302903000002"; makefile = makefile + "\\data\\"+PinCode+".png"; Int32 OrderSeq = 406359; string folderName = Convert.ToString(OrderSeq); string ftpfileName = folderName + "/" + PinCode + ".jpg"; string ftpBasicPath = "/var/www/IMAGE/Web/upload/order/barcode"; //string ftpBasicPath = "/var/www/IMAGE/Web/upload/order/qrcode/"; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = qrEncoder.Encode(PinCode); var renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); var image = new Bitmap(Image.FromStream(ms), new Size(new Point(200, 200))); image.Save(makefile, ImageFormat.Png); Tamir.SharpSsh.Sftp sftp; sftp = new Tamir.SharpSsh.Sftp("ledev.leisureq.co.kr", "lion", "gkffl1!"); sftp.Connect(10004); ArrayList res = sftp.GetFileList("/"); sftp.Mkdir(ftpBasicPath + "/" + folderName+ "/"); sftp.Put(makefile, ftpBasicPath + "/" + ftpfileName); sftp.Close(); //BarcodeLib.Barcode b = new BarcodeLib.Barcode(); //b.Encode(BarcodeLib.TYPE.CODE128, PinCode); //b.SaveImage(makefile, BarcodeLib.SaveTypes.JPG); /* string date = "2015-05-20 17:16:44"; string[] datePartPath = new string[4]; DateTime dt = Convert.ToDateTime(date); datePartPath[0] = dt.ToString("yyyy"); datePartPath[1] = dt.ToString("MM"); datePartPath[2] = dt.ToString("dd"); datePartPath[3] = Convert.ToString(OrderSeq); for(Int32 i =0; i<datePartPath.Length; i++){ ftpBasicPath = ftpBasicPath + "/" + datePartPath[i]; } comwls.image_01_FileMake(ftpBasicPath); */ string ftpUri = "sftp://ledev.leisureq.co.kr:10004/"+ ftpBasicPath + folderName; HKLibrary.comwls.comwls.image_01_FileMake(ftpBasicPath + folderName); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri); request.Method = WebRequestMethods.Ftp.MakeDirectory; //request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("lion", "gkffl1!"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); /* string ftpUri = "ftp://121.78.127.40:21/" + ftpBasicPath + folderName; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri); request.Method = WebRequestMethods.Ftp.MakeDirectory; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("infobay", "info9887"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); ftpUri = "ftp://121.78.127.40:21/" + ftpBasicPath + ftpfileName; request = (FtpWebRequest)WebRequest.Create(ftpUri); request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("infobay", "info9887"); byte[] fileContents = File.ReadAllBytes(makefile); request.ContentLength = fileContents.Length; request.UsePassive = true; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); response = (FtpWebResponse)request.GetResponse(); response.Close(); //sftp.ConnectTimeoutMs = 15000; //sftp.IdleTimeoutMs = 15000; //string hostname = "ftp://ledev.leisureq.co.kr:10004/"; //bool success = sftp.Connect(hostname, 10004); */ }
private void draw_qr(string qr_value) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = qrEncoder.Encode(qr_value); int padding = 2; double module_size = (double)(pictureBox_qr.Width) / (double)(qrCode.Matrix.Width + 2*padding); int moduleSizeInPixels = (int)Math.Floor(module_size); Renderer renderer = new Renderer(moduleSizeInPixels, Brushes.Black, Brushes.White); renderer.QuietZoneModules = (QuietZoneModules)padding; Size qrCodeSize = renderer.Measure(qrCode.Matrix.Width); reset_qr_display(); using (Graphics graphics = Graphics.FromImage(pictureBox_qr.Image)) { renderer.Draw(graphics, qrCode.Matrix); } pictureBox_qr.Refresh(); }
Image GetQRCode(string value) { QrEncoder enc = new QrEncoder(); QrCode code = enc.Encode(value); Renderer renderer = new Renderer(5); Image image = new Bitmap(256, 256); using (Graphics graphics = Graphics.FromImage(image)) renderer.Draw(graphics, code.Matrix); return image; }
public static Bitmap Draw(string barcodeText, Bitmap background, Rectangle destRect) { int x = destRect.X; int y = destRect.Y; int width = destRect.Width; int height = destRect.Height; if (x + width >= background.Width || y + height >= background.Height) { throw new QRBaException(ErrorConstants.Out_Of_Range); } var encoder = new QrEncoder(ErrorCorrectionLevel.M); var code = encoder.Encode(barcodeText); if (width < code.Matrix.Width * 2 || height < code.Matrix.Height * 2) { throw new QRBaException(ErrorConstants.Window_Too_Small); } byte[,] map = Calculate(code, background.Width, background.Height, new Rectangle(x, y, width, height)); for (int i = 0; i < background.Width; i++) { for (int j = 0; j < background.Height; j++) { var c = background.GetPixel(i, j); if (map[i, j] == (byte)ColorType.Dark) { background.SetPixel(i, j, Darker(c)); } else if (map[i, j] == (byte)ColorType.Light) { background.SetPixel(i, j, Lighter(c)); } } } return background; }
private void Encode_text() { try { var qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); var qrCode = qrEncoder.Encode(en_txt.Text); MemoryStream ms = new MemoryStream(); var renderer = new GraphicsRenderer(new FixedCodeSize(200, QuietZoneModules.Zero), Brushes.Black, Brushes.White); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg,ms); en_bmp = new Bitmap(ms); //bm.Save(Application.StartupPath + "//ss.jpg", ImageFormat.Jpeg); Qr_img.Image = en_bmp; getSliderBack_flag = true; } catch (Exception) { } }
/// <summary> /// 生成二维码 /// </summary> /// <param name="code">字符串</param> /// <param name="eSize">二维码尺寸</param> /// <param name="img">小图</param> /// <param name="iSize">小图尺寸</param> /// <param name="bColor">二维码背景颜色</param> /// <param name="fColor">二维码颜色</param> /// <returns></returns> public static Image GetQrcode(string code, int eSize, Image img, int iSize, Brush bColor, Brush fColor) { var qrcoder = new QrEncoder(ErrorCorrectionLevel.H); var qrCode = qrcoder.Encode(code); var render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Four), fColor, bColor); using (Stream stream = new MemoryStream()) { eSize = eSize > 0 ? eSize : 200; render.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream, new Point(10, 10)); var be = new Bitmap(stream); be = ResizeImage(be, eSize, eSize); Graphics ge = Graphics.FromImage(be); if (img != null) { iSize = iSize > 0 ? iSize : 50; img = ResizeImage(img, iSize, iSize); //小图白色边框 var bi = new Bitmap(iSize + 10, iSize + 10); Graphics gi = Graphics.FromImage(bi); gi.Clear(Color.White); gi.DrawImage(img, 5, 5, iSize, iSize); //将小图插入到二维码图片中 ge.DrawImage(bi, (eSize - iSize) / 2, (eSize - iSize) / 2, iSize, iSize); } return be; } }