clsPep.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Data;
6 using System.Diagnostics;
7 using System.Windows.Forms;
8 using System.IO;
9 using sage.ew.db;
10 using sage.ew.global;
11 using sage.ew.ewbase;
12 using sage.ew.interficies;
13 
14 
15 namespace sage.ew.pep
16 {
20  public static class PEP
21  {
22 
23  // Para poder introducir comillas dobles dentro de cadenas
24  const string COMILLAS = "\"";
25 
26  #region PROPIEDADES
27 
28  // Ruta completa del ejecutable principal de la aplicación
29  private static string _cMainEXEFileName = "";
30 
31  // Identificación del usuario o “00” para no configurar por usuario
32  private static string _cUserId = ""; // S'ha decidit no distingir entre els diferent usuaris d'EW. Un genèric.
33 
34  // Idetificador único del cliente (IDSage o similar)
35  private static string _cCustomerId = ""; //ALLTRIM(loCodCom.SageID)
36 
37  //* SSB / ACC / SMB
38  private static string _cDivision = "";
39 
40  // Identificador único para la instalación y aplicación (opcional)
41  private static string _cLicensePlate = "";
42 
43  // Fecha de la última sincronización
44  private static DateTime _dFechaSincro = DateTime.MinValue; // TTOD(loCodCom.PepSincro)
45 
46  // Nombre y versión de la aplicación
47  private static string _cApplicationNameAndVersion = ""; // ALLTRIM(loCodCom.ProductName) +" "+ ALLTRIM(loCodCom.Version)
48 
49  // 0 = Adherido 1 = No adherido 2 = Sin selección
50  private static int _nValue = 2; //_Comprobar_Adhesion(loCodCom.PepValue, tlForzar)
51 
53  //private static string _cFormName = "";
54 
56  //private static string _cUserInterfaceSource = "";
57 
59  //private static string _cVolumeCategory = "";
60 
62  //private static decimal _nValumeAmmount = 0;
63 
65  //private static string _cDirectoryForConfigFiles = "";
66 
67  // Para saber si estamos en sage50 (PE-103025)
68  private static bool _lSage50 = false;
69 
70  // Nombre del ejecutable relacionado (PE-103025)
71  private static string _cAppName = "sagetpv";
72 
73  // Datatable con los controles a tener en cuenta (PE-103025)
74  private static DataTable _dtControles = null;
75 
76  #endregion PROPIEDADES
77 
78 
79  #region CONSTRUCTORES
80 
84  static PEP()
85  {
86  _Inicializar(); // PE-103025
87  }
88 
89  #endregion CONSTRUCTORES
90 
91 
92  #region METODOS PRIVADOS
93 
98  private static DataTable Obtener_Controles()
99  {
100  DataTable ldtControles = new DataTable();
101 
102  string lcSql = "SELECT clase, MAX(libreria) as libreria, MAX(nombre) as nombre FROM "+DB.SQLDatabase("COMUNES","OBJETOS");
103  if (_lSage50)
104  {
105  lcSql += " WHERE s50 = " + DB.SQLString(_lSage50);
106  }
107  lcSql += " GROUP BY clase";
108 
109  DB.SQLExec(lcSql, ref ldtControles);
110 
111  // Poner el nombre de los controles en minúsculas
112  foreach (DataRow loFila in ldtControles.Rows)
113  {
114  loFila["clase"] = loFila["clase"].ToString().ToLower().Trim();
115  }
116  ldtControles.PrimaryKey = new DataColumn[] { ldtControles.Columns["clase"] };
117 
118  return ldtControles;
119  }
120 
121 
128  private static bool Execute_pep(string tcParams, bool tlSincron=false)
129  {
130  bool llOk = false;
131  string lcParams = "", lcRutaExe="";
132 
133  //*!* Parámetros disponibles para la ejecución de Sage.PEP.Exe:
134  //*!*
135  //*!* <MainEXEFileName>: Ruta completa del ejecutable principal de la aplicación
136  //*!* <UserId>: Identificación del usuario o “00” para no configurar por usuario
137  //*!* <CustomerId>: Idetificador único del cliente (IDSage o similar)
138  //*!* <Division>: SSB / ACC / SMB
139  //*!* <FormName>: Nombre del módulo funcional
140  //*!* <UserInterfaceSource>: Elemento de la interfaz de usuario (Toolbar, MainMenu, VerticalMenu, …)
141  //*!* <ApplicationNameAndVersion>: Nombre y versión de la aplicación
142  //*!* <Value>:0 ? Adherido 1 ? No aherido 2 ? Sin selección
143  //*!* <VolumeCategory>: Nombre de la categoría para el envío de información de volumen
144  //*!* <ValumeAmmount>: Cantidad asociada a la categoría anterior para el envío de información de volumen
145  //*!* <DirectoryForConfigFiles>: Directorio que contiene los ficheros configuración de la adhesión al Programa de Mejora de cada cliente. (opcional)
146  //*!* <LicensePlate>: Identificador único para la instalación y aplicación (opcional)
147  //*!*
148  //*!* Ejemplos ejecución:
149  //*!* Sage.PEP.exe -EXE="C:\GrupoSP\CON2012\Contabilidad.exe" -USER=02 -FORM="Gestión de asientos" -UISOURCE="Toolbar" -DIVISION="ACC" -CUSTOMERID="Pepito" -VERSION="ContaPlus 2013 R2"
150  //*!* Sage.PEP.exe -EXE="C:\GrupoSP\NOM2012\Nominas.exe" -USER=05 -EULA
151 
152  //*!* OJO, VALOR tiene que ser uno de los valores devueltos por la llamada -ISJOINED
153  //*!* Sage.PEP.exe -EXE="C:\GrupoSP\GES2012\EXE\Gestion.exe" -USER=88 -VALUE=3 -SAVEEULA
154 
155 
156  // Únicamente enviamos información en caso de estar en ejecutable
157  if (!Convert.ToBoolean(EW_GLOBAL._GetVariable("wl_EsEjecutable")))
158  return true;
159 
160  // En licencias internas de pruebas no enviar información (PE-103025)
161  if (LICENCIAS._EsLicenciaParaPruebas)
162  return true;
163 
164  // En licencias de DEMO no enviar información (Task 110943)
165  if (LICENCIAS._Demo)
166  return true;
167 
168  // Obtener todos los parámetros para la ejecución de sage.PEP.exe
169  lcParams = "-EXE=" + COMILLAS + _cMainEXEFileName.Trim() + COMILLAS + " -USER=" + _cUserId + " -LICENSEPLATE=" + COMILLAS + _cLicensePlate + COMILLAS + " " + tcParams;
170 
171  // Ruta del ejecutable sage.PEP.exe
172  lcRutaExe = Path.Combine(EW_GLOBAL._GetVariable("wc_PathInicio").ToString(), @"librerias\Sage.PEP.exe");
173 
174  // Preparar proceso
175  Process loProcess = new Process();
176  ProcessStartInfo loExePep = new ProcessStartInfo(lcRutaExe);
177  loExePep.Arguments = lcParams;
178  loProcess.StartInfo = loExePep;
179 
180  try
181  {
182  llOk = loProcess.Start();
183  if (tlSincron)
184  loProcess.WaitForExit();
185  }
186  catch (Exception loEx)
187  {
188  DB.Registrar_Error(loEx); //Registramos excepción
189  llOk = false;
190  MessageBox.Show("Se ha detectado alguna incidencia en la ejecución del PEP Service."+Environment.NewLine+loEx.Message,"Pep Service",MessageBoxButtons.OK,MessageBoxIcon.Error);
191  }
192 
193  return llOk;
194  }
195 
202  private static bool Enviar_Opcion(string tcNombreOpcion, bool tlEdicion)
203  {
204  bool llOk = false;
205  string lcParams = "",lcModulo="";
206 
207  // En licencias internas de pruebas no enviar información (PE-103025)
208  if (LICENCIAS._EsLicenciaParaPruebas)
209  return true;
210 
211  // En licencias de DEMO no enviar información (Task 110943)
212  if (LICENCIAS._Demo)
213  return true;
214 
215  // Comprobar si está adherido
216  if (_nValue != 0)
217  return true;
218 
219  // Si estamos editando un pefil no hay que enviar información (PE-103025)
220  if (EW_GLOBAL._EdicionPerfiles && !tlEdicion)
221  return true;
222 
223  // Bug 138639
224  tcNombreOpcion = LimpiarDatosBasura(tcNombreOpcion);
225 
226 
227  // Módulo desde donde se ha llamado la opción
228  lcModulo = Convert.ToString(EW_GLOBAL._GetVariable("wc_modulo")).ToLower().Trim();
229 
230  // Opción a enviar
231  tcNombreOpcion = _cAppName +"_"+tcNombreOpcion;
232 
233  //* Sage.PEP.exe -EXE=<MainEXEFileName> -USER=<UserId> -CUSTOMERID=<CustomerId>
234  //* [-CONFIGFILESDIR=<DirectoryForConfigFiles>] [-LICENSEPLATE=<LicensePlate>]
235  //* -DIVISION=<Division> -FORM=<FormName> -UISOURCE=<UserInterfaceSource>
236  //* -VERSION=<ApplicationNameAndVersion>
237 
238  lcParams = " -CUSTOMERID=" + COMILLAS + _cCustomerId + COMILLAS +
239  " -DIVISION=" + COMILLAS + _cDivision + COMILLAS +
240  " -FORM=" + COMILLAS + tcNombreOpcion + COMILLAS +
241  " -UISOURCE=" + COMILLAS + lcModulo + COMILLAS +
242  " -VERSION=" + COMILLAS + _cApplicationNameAndVersion + COMILLAS;
243 
244  llOk = Execute_pep(lcParams);
245 
246  return llOk;
247  }
248 
254  private static string LimpiarDatosBasura(string tcNombreOpcion)
255  {
256  tcNombreOpcion = QuitarLiteral(tcNombreOpcion, "(sólolectura)");
257  tcNombreOpcion = QuitarLiteral(tcNombreOpcion, "(bajasuscripción)");
258  tcNombreOpcion = QuitarLiteral(tcNombreOpcion, "(sql_log)");
259 
260  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "browser_listadodeplanesanalíticosdelacuentacontable");
261  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmobserv_observacionesdelcliente");
262 
263  if (tcNombreOpcion.Contains("frmdoccompra"))
264  {
265  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmdoccompraalbaran");
266  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmdoccompradeposito");
267  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmdoccomprafactura");
268  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmdoccomprapedido");
269  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmdoccomprapropuesta");
270  }
271 
272  if (tcNombreOpcion.Contains("frmdocventa"))
273  {
274  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmdocventaalbaran");
275  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmdocventadeposito");
276  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmdocventafra");
277  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmdocventaped");
278  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmdocventapresupuesto");
279  tcNombreOpcion = RecortarHastaLiteral(tcNombreOpcion, "frmdocventatpv");
280  }
281 
282  return tcNombreOpcion;
283  }
284 
291  private static string QuitarLiteral(string tcNombreOpcion, string tcLiteral)
292  {
293  if (tcNombreOpcion.Contains(tcLiteral))
294  tcNombreOpcion = tcNombreOpcion.Replace(tcLiteral, "");
295 
296  return tcNombreOpcion;
297  }
298 
305  private static string RecortarHastaLiteral(string tcNombreOpcion, string tcLiteral)
306  {
307  if (tcNombreOpcion.Contains(tcLiteral))
308  {
309  int lnPos = tcNombreOpcion.IndexOf(tcLiteral);
310  if (lnPos >= 0)
311  {
312  lnPos = lnPos + tcLiteral.Length;
313  tcNombreOpcion = tcNombreOpcion.Substring(0, lnPos);
314  }
315  }
316 
317  return tcNombreOpcion;
318  }
319 
320  #endregion METODOS PRIVADOS
321 
322 
323  #region METODOS PUBLICOS
324 
328  public static void _Inicializar()
329  {
330  // Únicamente enviamos información en caso de estar en ejecutable
331  if (!Convert.ToBoolean(EW_GLOBAL._GetVariable("wl_EsEjecutable")))
332  return;
333 
334  // En licencias internas de pruebas no enviar información (PE-103025)
335  if (LICENCIAS._EsLicenciaParaPruebas)
336  return;
337 
338  // En licencias de DEMO no enviar información (Task 110943)
339  if (LICENCIAS._Demo)
340  return;
341 
342  // Estamos en sage50? (PE-103025)
343  _lSage50 = Convert.ToBoolean(EW_GLOBAL._GetVariable("wl_Sage50"));
344  _cAppName = (_lSage50 ? "sage50" : "sagetpv");
345 
346  // Task 110943. Si en el fichero sagelic existe el atributo "internal.user" con el valor "yes", NO se enviará información a google analytics
347  if (_lSage50)
348  {
349  object loInternal = LICENCIAS._ObtenerAtributoSagelic("internal.user");
350  if (loInternal != null && Convert.ToString(loInternal).ToLower().Trim() == "yes")
351  return;
352  }
353 
354  // Obtener registro CODCOM
355  object loObj = null;
356  Dictionary<string, object> loDicCodCom = DB.SQLREGValor("codcom", "1", "1", "comunes");
357  if (loDicCodCom.Count <= 0)
358  return;
359 
360  // Establecer el valor para las propiedades necesarias
361  _cMainEXEFileName = Path.Combine(EW_GLOBAL._GetVariable("wc_PathInicio").ToString(), (_lSage50 ? "Sage50.exe" : "Eurowin.exe")); // PE-103025
362  _cUserId = "00";
363  _cDivision = "SSB"; // Task 110943
364  _cLicensePlate = EW_GLOBAL._GetVariable("wc_ewlicencia").ToString();
365 
366  loObj = null;
367  if (loDicCodCom.TryGetValue("sageid", out loObj))
368  _cCustomerId = loObj.ToString().Trim();
369 
370  // PE-79928. Este campo no se utiliza desde .NET
371  //loObj = null;
372  //if (loDicCodCom.TryGetValue("pepsincro", out loObj))
373  // this._dFechaSincro = Convert.ToDateTime(loObj).Date;
374 
375  loObj = null;
376  if (loDicCodCom.TryGetValue("productname", out loObj))
377  _cApplicationNameAndVersion = loObj.ToString().Trim();
378 
379  loObj = null;
380  if (loDicCodCom.TryGetValue("version", out loObj))
381  _cApplicationNameAndVersion += " " + loDicCodCom["version"].ToString().Trim();
382 
383  loObj = null;
384  if (loDicCodCom.TryGetValue("pepvalue", out loObj))
385  _nValue = Convert.ToInt32(loObj);
386 
387  if (_Login())
388  {
389  // PE-103025. Obtener datatable con todos los objetos a tener en cuenta
390  _dtControles = Obtener_Controles();
391  }
392  }
393 
394 
399  public static bool _Login()
400  {
401  bool llOk = false;
402 
403  // Sage.PEP.exe -EXE=<MainEXEFileName> -USER=<UserId> -CUSTOMERID=<CustomerId>
404  // [-CONFIGFILESDIR=<DirectoryForConfigFiles>] [-LICENSEPLATE=<LicensePlate>]
405  // -VERSION=<ApplicationNameAndVersion> -LOGIN
406 
407  string lcParams = " -VERSION=" + COMILLAS + _cApplicationNameAndVersion + COMILLAS + " "+
408  " -LOGIN";
409 
410  llOk = Execute_pep(lcParams);
411 
412  return llOk;
413  }
414 
415 
422  public static bool _Control(Control toControl, bool tlEdicion=false)
423  {
424  bool llOk = false;
425  string lcExcluir = "messageboxtactil,frmprincipal,frmlogin,btdocsalir";
426 
427  if (toControl == null)
428  return true;
429 
430  // Obtener el nombre del control
431  string lcNombreControl = toControl.Name.ToLower().Trim();
432  if (string.IsNullOrWhiteSpace(lcNombreControl))
433  return true;
434 
435  // Excluir controles
436  if (lcExcluir.Contains(lcNombreControl))
437  return true;
438 
439  // PE-103259. En caso que el control sea un checkbox y esté en el formulario de configuración de empresa se enviará la información tambien
440  if ((toControl is CheckBox) && toControl.FindForm() != null && (toControl.FindForm().Name.ToLower().Trim() == "frmempresa"))
441  {
442  lcNombreControl = "opcemp_" + (((CheckBox)toControl).Checked ? "marked" : "unmarked") + "_" + toControl.Text.ToLower().Replace(" ", "").Trim();
443  return Enviar_Opcion(lcNombreControl, false);
444  }
445 
446  //Task 103195
447  if ((toControl is CheckBox) && toControl.FindForm() != null && (toControl.FindForm().Name.ToLower().Trim() == "frmgruposemp") && lcNombreControl == "chkbackup")
448  {
449  lcNombreControl = "chkbackup_" + (((CheckBox)toControl).Checked ? "marked" : "unmarked") + "_" + toControl.Text.ToLower().Replace(" ", "").Trim();
450  return Enviar_Opcion(lcNombreControl, false);
451  }
452 
453  // Comprobar si se trata de un formulario, en ese caso enviar la información directamente
454  if (toControl is Form)
455  {
456  String lcText;
457 
458  lcText = (toControl is IFormBase) ? ((IFormBase)toControl)._ObtenerText(false) : toControl.Text;
459  lcText = lcText.ToLower().Trim().Replace(" ", "");
460 
461  return Enviar_Opcion(lcNombreControl + "_" + lcText, tlEdicion);
462  }
463 
464  // PE-105393: Si es un botón, miramos si tenemos definida la variable que nos dice si enviar o no la estadistica
465  if (toControl is Button && toControl.GetType().GetProperty("_GoogleAnalytics") != null && ((IGoogleAnalitics)toControl)._GoogleAnalytics)
466  {
467  return Enviar_Opcion(lcNombreControl + "_" + toControl.Text.ToLower().Trim().Replace(" ", ""), tlEdicion);
468  }
469 
470  // Comprobar que el control esté dentro de nuestra tabla OBJETOS
471  if (_dtControles != null && _dtControles.Rows.Count > 0)
472  {
473  llOk = (_dtControles.Rows.Find(lcNombreControl) != null);
474  }
475 
476  // Enviar información
477  if (llOk)
478  return Enviar_Opcion(lcNombreControl,tlEdicion);
479  else
480  return false;
481  }
482 
483 
490  public static bool _Opcion(string tcOpcion, bool tlEdicion=false)
491  {
492  if (string.IsNullOrWhiteSpace(tcOpcion))
493  return true;
494 
495  return Enviar_Opcion(tcOpcion,tlEdicion);
496  }
497 
498  #endregion METODOS PUBLICOS
499  }
500 }
Interface para formularios que deriven de FormBase
Definition: IFormBase.cs:12
Interfaz para Google Analitics