clsImpresora.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using sage.ew.ewbase;
6 using sage.ew.db;
7 using sage.ew.tpv.Forms;
8 using System.IO;
9 using System.Windows.Forms;
10 using sage.ew.functions;
11 using System.Management;
12 
13 namespace sage.ew.tpv
14 {
18  public class Impresora : ewMante
19  {
20 
21  #region PROPIEDADES PUBLICAS
22 
26  public override string _Nombre
27  {
28  get
29  {
30  return base._Nombre;
31  }
32  set
33  {
34  if (value != base._Nombre) _Fichero._CambiaNombreImpresora(value);
35  base._Nombre = value;
36  }
37  }
41  public int _Tipo
42  {
43  get
44  {
45  if (_lisCampos.ContainsKey("TIPO"))
46  return Convert.ToInt32(_lisCampos["TIPO"]._NewVal.ToString());
47  else
48  return 0;
49  }
50  set
51  {
52  if (_lisCampos.ContainsKey("TIPO"))
53  {
54  _lisCampos["TIPO"]._NewVal = value;
55  _Exportar_Null();
56  }
57  }
58  }
59 
63  public string _Nombre_Puerto
64  {
65  get
66  {
67  if (_lisCampos.ContainsKey("NOMPORT"))
68  return _lisCampos["NOMPORT"]._NewVal.ToString();
69  else
70  return "";
71  }
72  set
73  {
74  if (_lisCampos.ContainsKey("NOMPORT"))
75  {
76  _lisCampos["NOMPORT"]._NewVal = value;
77  _Exportar_Null();
78  }
79  }
80  }
81 
85  public int _Longitud_Papel
86  {
87  get
88  {
89  if (_lisCampos.ContainsKey("SALT_LIN"))
90  return Convert.ToInt32(_lisCampos["SALT_LIN"]._NewVal.ToString());
91  else
92  return 0;
93  }
94  set
95  {
96  if (_lisCampos.ContainsKey("SALT_LIN"))
97  {
98  _lisCampos["SALT_LIN"]._NewVal = value;
99  _Exportar_Null();
100  }
101  }
102  }
103 
107  public bool _Compcajon
108  {
109  get
110  {
111  if (_lisCampos.ContainsKey("COMPCAJON"))
112  return Convert.ToBoolean(_lisCampos["COMPCAJON"]._NewVal);
113  else
114  return false;
115  }
116  set
117  {
118  if (_lisCampos.ContainsKey("COMPCAJON"))
119  {
120  _lisCampos["COMPCAJON"]._NewVal = value;
121  _Exportar_Null();
122  }
123  }
124  }
125 
129  public string _Abrir_Caja
130  {
131  get
132  {
133  if (_lisCampos.ContainsKey("ABRIR_CAJA"))
134  return _lisCampos["ABRIR_CAJA"]._NewVal.ToString();
135  else
136  return "";
137  }
138  set
139  {
140  if (_lisCampos.ContainsKey("ABRIR_CAJA"))
141  {
142  _lisCampos["ABRIR_CAJA"]._NewVal = value;
143  _Exportar_Null();
144  }
145  }
146  }
147 
151  public string _Cortar_Papel
152  {
153  get
154  {
155  if (_lisCampos.ContainsKey("CORTAR_PAP"))
156  return _lisCampos["CORTAR_PAP"]._NewVal.ToString();
157  else
158  return "";
159  }
160  set
161  {
162  if (_lisCampos.ContainsKey("CORTAR_PAP"))
163  {
164  _lisCampos["CORTAR_PAP"]._NewVal = value;
165  _Exportar_Null();
166  }
167  }
168  }
169 
170  //Campo virtual (lo gestiona la clase ewPrinterFile)
174  public string _Nombre_Local
175  {
176  get { return _Fichero._NombreLocal; }
177  set { _Fichero._NombreLocal = value; }
178  }
179  private string _cNombreLocal = string.Empty;
180 
181 
182  private ewPrinterFile _Fichero
183  {
184  get
185  {
186  if(_oFichero == null)
187  _oFichero = new ewPrinterFile(this);
188  return _oFichero;
189  }
190  set { _oFichero = value; }
191  }
192  private ewPrinterFile _oFichero = null;
193 
194  #endregion PROPIEDADES PUBLICAS
195 
196  #region CONSTRUCTORS
197 
201  public Impresora()
202  {
203  // Asignamos las propiedades para Familias
204  this._Clave = "Codigo";
205  this._DataBase = "TPV";
206  this._Tabla = "IMPRESOR";
207  this._TituloMantenimiento = "Mantenimiento de impresoras";
208  this._FormManteBaseType = typeof(tpv.Forms.frmImpresoras);
209 
210  this._Pantalla = "IMPRESOR"; // PARTE 88419
211  }
212 
213  #endregion CONSTRUCTORS
214 
215  #region Métodos públicos
216 
217 
222  public override bool _Save()
223  {
224  bool esperandoCodigo = (_Estado == _EstadosMantenimiento.EsperandoCodigo);
225  // PE-92530
226  bool llOk = base._Save();
227 
228  if (llOk && !esperandoCodigo) //=> esperando código dispara un save para la operación de new
229  llOk = _Fichero._WriteFile();
230 
231  // PE-103019. Crear los documentos de TPV
232  if (llOk)
233  {
234  // Sigui quin sigui l'estat, comprovem si existeixen els reports per a la impressora.
235  _Crear_Reports();
236  }
237 
238  return llOk;
239  }
240 
244  public override void _Load()
245  {
246  base._Load();
247 
248  //Inicializamos fichero
249  _Fichero = new ewPrinterFile(this);
250  }
251 
255  public override bool _Delete()
256  {
257  //2. En caso de DELETE se deberá comprobar que no exista en las siguientes tablas: TPV!CAJAS
258  // Hay 4 alias Impresora, impresora2, imp_coci e imp_resum
259 
260  bool llOk = true;
261  List<string> llisListaTablas = new List<string>();
262 
263  // Tablas del TPV
264  llisListaTablas.Clear();
265  llisListaTablas.Add("CAJAS");
266 
267 
268  llOk = llOk && !_Existen_Registros("TPV", llisListaTablas, "IMPRESORA");
269  llOk = llOk && !_Existen_Registros("TPV", llisListaTablas, "IMPRESORA2");
270  llOk = llOk && !_Existen_Registros("TPV", llisListaTablas, "IMP_COCI");
271  llOk = llOk && !_Existen_Registros("TPV", llisListaTablas, "IMP_RESUM");
272 
273  if (llOk)
274  return base._Delete();
275  else
276  this._Error_Message = "Este código de impresora está siendo utilizado en alguna caja de venta. No se puede borrar.";
277 
278  return llOk;
279  }
280 
285  public bool _Send_Abrir_Cajon()
286  {
287  string lcErrorMessage = string.Empty;
288  string lcImpresora = string.Empty;
289  bool llOk = true;
290 
291  lcImpresora = this._Nombre_Local; //Asigno el nombre local
292  if (string.IsNullOrWhiteSpace(lcImpresora)) lcImpresora = this._Nombre; //Si esta vacio lo cambio por el nombre
293  llOk = (!string.IsNullOrWhiteSpace(lcImpresora)); //Sino tengo ni nombre ni nombre local no hago nada.
294 
295  lcImpresora = FUNCTIONS._GetPrinterDriver(lcImpresora);
296 
297  if(string.IsNullOrWhiteSpace(this._Abrir_Caja))
298  {
299  lcErrorMessage = "No se ha definido el código para abrir el cajón.";
300  llOk = false;
301  }
302 
303  if (llOk && FUNCTIONS.SendStringToPrinter(lcImpresora, this._Abrir_Caja, ref lcErrorMessage)) return true;
304  else
305  {
306  this._Error_Message = lcErrorMessage;
307  return false;
308  }
309  }
310 
315  public bool _Send_Cortar_Papel()
316  {
317  string lcErrorMessage = string.Empty;
318  string lcImpresora = string.Empty;
319  bool llOk = true;
320 
321  lcImpresora = this._Nombre_Local; //Asigno el nombre local
322  if (string.IsNullOrWhiteSpace(lcImpresora)) lcImpresora = this._Nombre; //Si esta vacio lo cambio por el nombre
323  llOk = (!string.IsNullOrWhiteSpace(lcImpresora)); //Sino tengo ni nombre ni nombre local no hago nada.
324 
325  lcImpresora = FUNCTIONS._GetPrinterDriver(lcImpresora);
326 
327  if(llOk && string.IsNullOrWhiteSpace(this._Cortar_Papel))
328  {
329  lcErrorMessage = "No se ha definido el código para cortar el papel.";
330  llOk = false;
331  }
332 
333  if(llOk && FUNCTIONS.SendStringToPrinter(lcImpresora,this._Cortar_Papel, ref lcErrorMessage)) return true;
334  else
335  {
336  this._Error_Message = lcErrorMessage;
337  return false;
338  }
339  }
340 
341  #endregion Métodos públicos
342 
343 
344  #region Métodos privados
345 
346  // PE-103019. Crear tots el reports
347  private bool _Crear_Reports()
348  {
349  bool lbOk = true;
350 
351  _Crear_Report("TICKET");
352  _Crear_Report("COBRO");
353  _Crear_Report("COCINA");
354  _Crear_Report("ENTREGA");
355  _Crear_Report("IPAGOVAR");
356  _Crear_Report("TICKETPV");
357  _Crear_Report("IRETIROS");
358  _Crear_Report("IREPOSI");
359  _Crear_Report("VALE");
360  _Crear_Report("COMPROBA");
361  _Crear_Report("COMP_EMV");
362 
363  return lbOk;
364  }
365 
366  // PE-103019. Crear tots el reports
367  private bool _Crear_Report(string tcTipoDoc)
368  {
369  bool lbOk = true;
370 
371  string lcDefaultReport = "";
372  string lcReport = "";
373  string lcRutaReports = Path.Combine(global.EW_GLOBAL._GetVariable("wc_iniservidor").ToString(), @"MODULOS\TPV\REPORTS\DOCS_TPV\");
374 
375  // Tickets
376  lcReport = lcRutaReports + tcTipoDoc + _Codigo + ".FRX";
377 
378  if (!Directory.Exists(lcRutaReports)) Directory.CreateDirectory(lcRutaReports);
379 
380  if (!File.Exists(lcReport))
381  {
382  lcDefaultReport = lcRutaReports + tcTipoDoc + ".FRX";
383  if (File.Exists(lcDefaultReport))
384  {
385  File.Copy(lcDefaultReport, lcReport);
386 
387  lcDefaultReport = lcRutaReports + tcTipoDoc + ".FRT";
388  lcReport = lcRutaReports + tcTipoDoc + _Codigo + ".FRT";
389  if (File.Exists(lcDefaultReport))
390  {
391  File.Copy(lcDefaultReport, lcReport);
392  }
393  else
394  {
395  lbOk = false;
396  }
397  }
398  else
399  {
400  lbOk = false;
401  }
402 
403  if (!lbOk)
404  {
405  String[] lcFiles = Directory.GetFiles(lcRutaReports, tcTipoDoc + _Codigo + ".*");
406 
407  foreach(String lcFile in lcFiles)
408  {
409  try
410  {
411  // Esborro els reports a mitjes
412  File.Delete(lcFile);
413  }
414  catch
415  {
416 
417  }
418  }
419 
420  }
421  }
422 
423  return lbOk;
424  }
425 
426  #endregion Métodos privados
427 
428 
432  public class ewPrinterFile
433  {
437  private readonly Impresora _oImpresora = null;
438 
443  public ewPrinterFile(Impresora toImpresora)
444  {
445  _oImpresora = toImpresora;
446  }
447 
451  public string _NombreLocal
452  {
453  get { return _Get_NombreLocal(); }
454  set { _Set_NombreLocal(value); }
455  }
456  private string _cNombreLocal = string.Empty;
457 
458  #region fichero
459 
463  public string _NombreFichero
464  {
465  get { return (Path.Combine(_cPathFichero, _cSafeFileName)).Trim(); }
466  }
467 
471  protected string _cPathFichero = Convert.ToString(sage.ew.global.EW_GLOBAL._GetVariable("wc_PathInicio"));
472 
476  protected string _cSafeFileName = "EWPRNSET.INF";
477 
478  #endregion fichero
479 
483  private string _cTextoFichero = string.Empty;
484 
488  private string _cTextoFijo = string.Empty;
489 
493  private bool _lFicheroCargado = false;
494 
498  private Dictionary<string, string> _dicEquivalenciasImpresoras = new Dictionary<string, string>();
499 
503  private string _cEtiqueta = "[Printers]";
504 
509  private string _Get_NombreLocal()
510  {
511  if (!_lFicheroCargado) _ReadFile();
512 
513  if (_dicEquivalenciasImpresoras.ContainsKey(_oImpresora._Nombre.TrimEnd())) return _dicEquivalenciasImpresoras[_oImpresora._Nombre.TrimEnd()];
514  else return "";
515  }
516 
521  public void _CambiaNombreImpresora(string tcValor)
522  {
523  String lcClave;
524 
525  if (!_lFicheroCargado) _ReadFile();
526 
527  if (string.IsNullOrWhiteSpace(tcValor) || string.IsNullOrWhiteSpace(tcValor)) return;
528 
529  lcClave = _oImpresora._Nombre.TrimEnd();
530 
531  //Si tengo la clave, actualizo el valor
532  if (_dicEquivalenciasImpresoras.ContainsKey(lcClave))
533  {
534  _dicEquivalenciasImpresoras.Add(tcValor, _NombreLocal);
535  _dicEquivalenciasImpresoras.Remove(lcClave);
536  }
537  }
538 
543  private void _Set_NombreLocal(string tcValor)
544  {
545  if (!_lFicheroCargado) _ReadFile();
546 
547  if (string.IsNullOrWhiteSpace(_oImpresora._Nombre) || string.IsNullOrWhiteSpace(tcValor)) return;
548 
549  string lcClave = _oImpresora._Nombre.TrimEnd();
550 
551  //Si tengo la clave, actualizo el valor
552  if (_dicEquivalenciasImpresoras.ContainsKey(lcClave))
553  {
554  _dicEquivalenciasImpresoras[lcClave] = tcValor;
555  }
556  else //Sino la inserto
557  _dicEquivalenciasImpresoras.Add(lcClave, tcValor);
558  }
559 
563  public bool _WriteFile()
564  {
565  _lFicheroCargado = false; //Marco que trato de modificar el fichero
566 
567  if (!_Existe_Fichero()) return false;
568 
569  try
570  {
571  StreamWriter loStrmWrtr = new StreamWriter(_NombreFichero);
572 
573  //Monto el contenido que voy a grabar a fichero
574  _cTextoFichero = _cTextoFijo;
575 
576  //Por cada elemento del diccionario
577  foreach (KeyValuePair<string,string> loDicItem in _dicEquivalenciasImpresoras)
578  {
579  //lo concateno
580  _cTextoFichero += (loDicItem.Key + "=" + loDicItem.Value + Environment.NewLine);
581  }
582 
583  loStrmWrtr.WriteLine(_cTextoFichero);
584  loStrmWrtr.Close();
585  return true;
586  }
587  catch (Exception loEx)
588  {
589  functions.FUNCTIONS._MessageBox(loEx.Message, "Error grabando el fichero",
590  MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
591  return false;
592  }
593  }
594 
598  public void _ReadFile()
599  {
600  _lFicheroCargado = false;
601 
602  if (!_Existe_Fichero()) return;
603 
604  try
605  {
606  //Volco el contenido del fichero a un string
607  leerFichero();
608 
609  //Proceso el string
610  string lcImpresoras = string.Empty;
611 
612  //Si tengo la etiqueta
613  if (_cTextoFichero.Contains(_cEtiqueta))
614  {
615  //Vacio lo que pueda haber en el diccionario
616  _dicEquivalenciasImpresoras = new Dictionary<string, string>();
617 
618  //Parte fija: Grabo la parte fija la etiqueta y un salto de línea
619  _cTextoFijo = _cTextoFichero.Substring(0,(_cTextoFichero.IndexOf(_cEtiqueta) + _cEtiqueta.Length)) +Environment.NewLine;
620 
621  //Parte variable
622  lcImpresoras = _cTextoFichero.Substring((_cTextoFichero.IndexOf(_cEtiqueta) + _cEtiqueta.Length));
623 
624  if (!string.IsNullOrWhiteSpace(lcImpresoras))
625  {
626  string[] lcSeparador = new string[] { "\r\n" }; // Environment.NewLine
627  string[] laLineasImpresoras = lcImpresoras.Split(lcSeparador, StringSplitOptions.RemoveEmptyEntries); //Splito el bloque de impresoras en lineas
628 
629  if (laLineasImpresoras.Count() > 0)
630  {
631  //Monto un diccionario de impresoras
632  foreach (string lcImpresora in laLineasImpresoras)
633  {
634  string[] laDetalleImpresora = lcImpresora.Split('=');
635  if (laDetalleImpresora.Count() > 1)
636  {
637  if (_dicEquivalenciasImpresoras.ContainsKey(laDetalleImpresora[0])) //Si ya tengo la clave (no debería pasar nunca)
638  {
639  _dicEquivalenciasImpresoras[laDetalleImpresora[0]] = laDetalleImpresora[1]; //Actualizo el valor
640  }
641  else _dicEquivalenciasImpresoras.Add(laDetalleImpresora[0], laDetalleImpresora[1]); //Inserto la clave
642  }
643  }
644  }
645  }
646 
647  _lFicheroCargado = true;
648  }
649 
650 
651 
652  }
653  catch (Exception loEx)
654  {
655  functions.FUNCTIONS._MessageBox(loEx.Message, "Error leyendo el fichero",
656  MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
657  }
658  }
659 
664  private bool _Existe_Fichero()
665  {
666  bool llOk = false;
667 
668  try
669  {
670  //Verifico la existencia del directorio
671  if (!Directory.Exists(_cPathFichero) && (string.IsNullOrWhiteSpace(_cPathFichero) == false)) Directory.CreateDirectory(_cPathFichero); // PARTE 92408. Cuando creamos una impresora siempre sale error
672 
673  //Verifico la existencia del fichero
674  if (!File.Exists(_NombreFichero))
675  {
676  crearFichero();
677  }
678  else //El fichero existe, verifico que sea bueno
679  {
680  leerFichero();
681 
682  //Sino tengo la etiqueta => Fichero malo
683  if (!_cTextoFichero.Contains(_cEtiqueta))
684  {
685  reemplazarFichero();
686  }
687  }
688 
689  llOk = true;
690  }
691  catch (Exception loEx)
692  {
693  functions.FUNCTIONS._MessageBox(loEx.Message, "Operaciones previas con ficheros",
694  MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
695 
696  return false;
697  }
698 
699  return llOk;
700  }
701 
702  private void leerFichero()
703  {
704  //Volco el contenido del fichero a un string
705  StreamReader loStrmRdr = new StreamReader(_NombreFichero);
706  _cTextoFichero = loStrmRdr.ReadToEnd();
707  loStrmRdr.Close();
708  }
709 
710  private void reemplazarFichero()
711  {
712  File.Delete(_NombreFichero); //Borro el fichero que no tiene la etiqueta
713  crearFichero(); //Vuelvo a crear el fichero
714  }
715 
716  private void crearFichero()
717  {
718  //Sino existe trato de crearlo
719  using (FileStream loFS = File.Create(_NombreFichero))
720  {
721  //Monto las líneas
722  // --- Fox legacy text ---
723  List<Byte[]> llisLineas = new List<byte[]>();
724  llisLineas.Add(new UTF8Encoding(true).GetBytes(";" + Environment.NewLine));
725  llisLineas.Add(new UTF8Encoding(true).GetBytes("; EWPRNSET.INF -- NO CANVIAR" + Environment.NewLine));
726  llisLineas.Add(new UTF8Encoding(true).GetBytes(";" + Environment.NewLine));
727  llisLineas.Add(new UTF8Encoding(true).GetBytes("; En aquest fitxer es guarden les equivalencies d'impressores de TPV." + Environment.NewLine));
728  llisLineas.Add(new UTF8Encoding(true).GetBytes("; Des de la pantalla d'impressores de TPV es pot seleccionar la impressora" + Environment.NewLine));
729  llisLineas.Add(new UTF8Encoding(true).GetBytes("; local que correspondria a la impressora de TPV." + Environment.NewLine));
730  llisLineas.Add(new UTF8Encoding(true).GetBytes("; Amb això se soluciona el problema de que el terminal que te endollada la" + Environment.NewLine));
731  llisLineas.Add(new UTF8Encoding(true).GetBytes("; impressora no imprimeixi amb el registre de Impressores de TPV que utilitzen" + Environment.NewLine));
732  llisLineas.Add(new UTF8Encoding(true).GetBytes("; els altres terminals." + Environment.NewLine));
733  llisLineas.Add(new UTF8Encoding(true).GetBytes(";" + Environment.NewLine));
734  llisLineas.Add(new UTF8Encoding(true).GetBytes("[Printers]" + Environment.NewLine));
735 
736  //Escribo las líneas en el fichero
737  foreach (Byte[] loLinea in llisLineas)
738  {
739  loFS.Write(loLinea, 0, loLinea.Length);
740  }
741 
742  //Cierro el fichero
743  loFS.Close();
744  }
745  }
746  }
747 
753  public static string _ObtenerPuerto(String lcPrinter)
754  {
755 
756  String lcQuery, lcPrinterName, lcPort = ""; ;
757 
758  lcPrinterName = lcPrinter.Contains(@"\") ? lcPrinter.Substring(lcPrinter.LastIndexOf(@"\") + 1) : lcPrinter;
759  lcQuery = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", lcPrinterName);
760 
761  using (ManagementObjectSearcher loSearcher = new ManagementObjectSearcher(lcQuery))
762  using (ManagementObjectCollection loCol = loSearcher.Get())
763  {
764  try
765  {
766  foreach (ManagementObject printer in loCol)
767  {
768  lcPrinterName = Convert.ToString(printer.GetPropertyValue("Name"));
769  if (lcPrinterName == lcPrinter) lcPort = Convert.ToString(printer.GetPropertyValue("PortName"));
770  }
771  }
772  catch
773  {
774 
775  }
776  }
777 
778  return lcPort;
779  }
780  }
781 }
Clase de negocio base para mantenimientos
Definition: clsEwBase.cs:1643
bool _Send_Cortar_Papel()
Función que manda a la impresora el código de cortar papel
override bool _Save()
Override del método _Save
bool _Send_Abrir_Cajon()
Función que manda a la impresora el código de abrir el cajón
static string _ObtenerPuerto(String lcPrinter)
Bug 113424 Obtener puerto de impresora
void _CambiaNombreImpresora(string tcValor)
Establece el nombre local para la impresora
bool _WriteFile()
Función que escribe en el fichero
void _ReadFile()
Función que recupara el contenido del fichero
Clase EW_GLOBAL para gestionar las variables públicas de Eurowin, variables de empresa, variables de anchuras de campo, variables de mascaras, etc.
Definition: EW_GLOBAL.cs:46
Clase de impresoras
Definition: clsImpresora.cs:18
Clase auxiliar para gestionar el fichero EWPRNSET
override bool _Delete()
Método para eliminar impresoras
virtual string _Nombre
Campo nombre del mantenimiento. En este hay que basar los demás campos en las clases heredadas ...
Definition: clsEwBase.cs:2655
Impresora()
Constructor por fefecto
_EstadosMantenimiento
Declaro un enum para los estados del mantenimiento.
Definition: clsEwBase.cs:1671
ewPrinterFile(Impresora toImpresora)
Constructor con parámetros
override void _Load()
Override del método _Load