main_s50.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.IO;
6 using System.Data;
7 using sage.ew.functions;
8 using System.Xml;
9 using sage.ew.db;
10 using System.Diagnostics;
11 using sage.ew.global;
12 using System.Runtime.InteropServices;
13 using System.Windows.Forms;
14 using sage.ew.ewbase;
15 using sage.ew.ewbase.Forms;
16 using sage.ew.reports;
17 using System.Threading.Tasks;
18 using System.Reflection;
19 using sage.ew.empresa;
20 using System.Globalization;
21 using sage.ew.formul.Classes;
23 using sage.ew.functions.Clases;
24 using Sage.ES.S50.Addons;
26 using sage._50.Clases;
27 
28 namespace sage._50
29 {
33  public static class main_s50
34  {
35  // Variables privadas
36  private static string _cRutaServ = "";
37  private static string _cComunes = "";
38  private static string _cOdbc = "";
39  private static string _cIp = "";
40  private static string _cUser = "";
41  private static string _cPassword = "";
42  private static string lcNameProd = Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto"));
43  private static bool _lExternal_Entry = false; //PE-105614
44  private static bool _lSemaforoConfigBak = false;
45 
46  public delegate void _OnReportProgressHandLer(InfoProgresBar e);
47 
48  public static event _OnReportProgressHandLer _OnReportProgress;
49 
53  public static bool _lEjecucionDesdeProyecto = false;
54 
58  public static bool _lEsEjecutable = false;
59 
63  public static Dictionary<string, RegCfgCliSrv> _oCfgCliSrv = new Dictionary<string, RegCfgCliSrv>();
64 
68  public static string _cPathInicio = "";
69 
73  public static Forms.frmSplash _frmSplash;
74 
78  public static string _ErrorString = "";
79 
83  public static bool _External_Entry
84  {
85  get { return _lExternal_Entry; }
86  }
87 
91  private const int CACHE_EXPIRATION = 2;
92 
96  private static readonly string SQL_MINIMUM_VERSION = "12";
97 
102  public static bool _main_Sage_50()
103  {
104  bool lbValidar = true;
105  string lcMensajeErrorSO = "";
106 
107  EW_GLOBAL.ValorEnClave_VarGlob("wl_sage50", true); // Bug 125014 // PE-97745
108 
109  //Activo una cache de 2 minutos
110  DB._SetTimeCacheTo(CACHE_EXPIRATION);
111 
112  //PE-105131 Validaciones de versión de sistema operativo
113  LoadingLog(5, tcText:"Requisitos de sistema operativo");
114  if (!FUNCTIONS._RequisitosVersionSO(out lcMensajeErrorSO))
115  {
116  ew.functions.AutoClosingMessageBox._Show(lcMensajeErrorSO, "Requisitos de sistema operativo", 120000);
117  }
118 
119  //PE-105131
120  LoadingLog(10, tcText: "Validaciones de entorno");
121  //Bug 140957 Validaciones de entorno (formato fechas)
122  if (!validacionesEntornoCorrectas(out string lcMensajeError))
123  {
124  DB.Registrar_Traza("main_s50.cs,_Validacion_Entorno_Fallida"); // PE-104002
125  _ErrorString = lcMensajeError;
126  return false; //Fuerzo el retorno para que no siga con la carga
127  }
128 
129  LoadingLog(20, "_Validar_ConfigINI", "Validando config.ini");
130  lbValidar = _Validar_ConfigINI(Program._cGrupoParametro); //Task 195376: Añadimos la opción de especificar un grupo de arranque. por defecto vacío para que utilice el del config.ini
131 
132  if (lbValidar)
133  {
134  LoadingLog(30, "_Validar_CfgCliSrv", "Validando cfgclisrv.xml");
135  lbValidar = _Validar_CfgCliSrv();
136  }
137 
138  if (lbValidar && !_lEjecucionDesdeProyecto)
139  {
140  LoadingLog(30, "_Validar_Eurowin", "Validando EW");
141  lbValidar = _Validar_Eurowin();
142  }
143 
144  // Task 143679
145  if (lbValidar)
146  {
147  LoadingLog(40, "_Cargar_Licencia", "Comprobando licencia");
148  lbValidar = _Cargar_Licencia();
149  }
150 
151  if (lbValidar)
152  {
153  LoadingLog(50, "_Registrar_Dependencias_Injector", "Registrando dependencias");
154 
155  Stopwatch sw = Stopwatch.StartNew();
156  //Registramos las dependencias
157  RegisterTypesDependencyInjector();
158  //DependencyInjector.Instance.RegisterTypes(RegisterType.Addons, true);
159  Trace.WriteLine($"Tiempo para carga de dependencias de addons; {sw.ElapsedMilliseconds}");
160 
161  LoadingLog(50, "_Cargar_Globales", "Cargando diccionarios");
162  lbValidar = _Cargar_Globales();
163  }
164 
165  //Carga dinamica de librerias para reports (Sage.ES.S50c.Reports)
166  if (lbValidar)
167  {
168  LoadingLog(60, "_Cargar_LibreriasReports", "Cargando librerias SageReports");
169  _Cargar_LibreriasReports();
170 
171  //PE-103639
172  LoadingLog(70, "_RegistrerSageReport", "Registrando SageReports");
173  _RegistrerSageReport();
174 
175  //PE-103966 - Registar notificaciones
176  LoadingLog(80, "_RegistrerSageReport", "Registrando notificationes");
177  _RegisterNotifications();
178 
179 
180  LoadingLog(90, tcText:"Evaluar y registrar versión de motor Sql");
181  //Task 144713 => Evaluar y registrar versión de motor Sql
182  FUNCTIONS.EvaluarRequisitosMotorBaseDeDatos(SQL_MINIMUM_VERSION, tnDiasEntreNotificaciones: 7, tlGuardarRegistroNotificacion: true);
183 
184  //Bug 156806 - Revisar Live Update
185  LoadingLog(100, "_LiveUpdate", "Revisando Live Update");
186  RevisarLiveUpdate();
187 
188  // Definimos objeto para capturar mensajes de Windows
189  DB.Registrar_Traza("main_s50,ew_MessageFilters"); // PE-104002
191  Application.AddMessageFilter(lst);
192 
193  LoadingLog(100, tcTextCentral: "Cargando entorno ... ");
194  }
195 
196  return lbValidar;
197  }
198 
199  private static void LoadingLog(int tnProcess, string tcName = "", string tcText = "", string tcTextCentral = "")
200  {
201  if (!string.IsNullOrEmpty(tcText) || !string.IsNullOrEmpty(tcTextCentral)) _OnReportProgress?.Invoke(new InfoProgresBar(tnProcess, 100, tcText, tcTextCentral));
202  if (!string.IsNullOrEmpty(tcName)) DB.Registrar_Traza($"main_s50,{tcName}");
203  }
204 
205  private static bool validacionesEntornoCorrectas(out string lcMensajeError)
206  {
207  lcMensajeError = "";
208  bool entornoCorrecto = true;
209 
210  //Validamos formato de fechas
211  if (!FormatoFechasValido())
212  {
213  entornoCorrecto = false;
214  lcMensajeError = lcMensajeError += "Para poder trabajar con "+ lcNameProd+" debe tener configurado el formato de fecha de la forma día/mes/año" + Environment.NewLine;
215  }
216 
217  return entornoCorrecto;
218  }
219 
224  private static bool FormatoFechasValido()
225  {
226  bool formatoCorrecto = false;
227  //string formato = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern.ToUpper();
228  string formato = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToUpper(); //Bug 142594 => En Windows ingleses la cultura de UI no cumple
229 
230  //Se hacen varias pruebas y el único formato que hace fallar la aplicación (que sepamos) incumple empezar por el día.
231  if (formato.StartsWith("D") && formato.EndsWith("Y"))
232  {
233  formatoCorrecto = true;
234  }
235  return formatoCorrecto;
236  }
237 
245  public static bool _main_Sage_50_External_Entry(string tcRutaPathInicio, string tcComunes = "", string tcEmpresa = "")
246  {
247 #if DEBUG
248  sage.ew.db.DB.Escribir_En_Log_Error(sage.ew.db.DB.Modo_Registro.Registro_Consulta, null, "Entrando en _main_Sage_50_External_Entry. Ruta path inicio -> " + tcRutaPathInicio);
249 #endif
250  bool lbValidar = true;
251  EW_GLOBAL.ValorEnClave_VarGlob("wl_sage50", true); // Bug 125014 // PE-97745
252 
253  _lExternal_Entry = true; //PE-105614
255 
256  if (string.IsNullOrWhiteSpace(tcRutaPathInicio))
257  return false;
258 
259  if (!Directory.Exists(tcRutaPathInicio))
260  return false;
261 
262  string lcEmpAnt = Convert.ToString(EW_GLOBAL._GetVariable("wc_empresa"));
263  string lcComunesAnt = DB.DbComunes;
264 
265  _cPathInicio = tcRutaPathInicio;
266  lbValidar = _Validar_ConfigINI(tcComunes); //PE-104599
267 
268  lbValidar = lbValidar && _Validar_CfgCliSrv(tcComunes);
269 
270  if (lbValidar)
271  _frmSplash = new Forms.frmSplash();
272 
273  //Registramos las dependencias
274  RegisterTypesDependencyInjector();
275 
276  lbValidar = lbValidar && _Cargar_Globales(tcEmpresa); //PE-104599
277  bool cargaraddonsuccess = AddonsController.Instance.AddonsManager._CargarAddons_WaitAll();
278 
279  // CCR 209318 - Si se cambia de grupo o de empresa, tenemos que actualizar la empresa
280  // CCR 164862 - Cuando se cargaba un documento de venta por reflection en el método Iva_Portes() de docsven,
281  // se producía un error porque EW_GLOBAL._Empresa era nulo
282  if (lbValidar && (EW_GLOBAL._Empresa == null || lcComunesAnt != DB.DbComunes || lcEmpAnt != Convert.ToString(EW_GLOBAL._GetVariable("wc_empresa"))))
283  EW_GLOBAL._Empresa = new Empresa(Convert.ToString(EW_GLOBAL._GetVariable("wc_empresa")));
284 
285  return lbValidar;
286  }
287 
291  private static void _RegistrerSageReport()
292  {
293  //T113157
294  String lcFile = Path.Combine(_cPathInicio, "config.ini");
295  String lcPathSageReports = FUNCTIONS.LeerConfigIni("[SAGEREPORTS]", _cPathInicio);
296 
297  Task.Factory.StartNew(() => Report._RegisterReportsDataSourceIni(lcPathSageReports));
298  }
299 
300 
306  public static bool _Validar_ConfigINI(string tcComunes="")
307  {
308  bool lbValidar = true;
309  string lcFile, lcFileBak;
310 
311  LoadingLog(21, tcTextCentral: "Validando config.ini ... ");
312 
313  lcFile = Path.Combine(_cPathInicio, "config.ini");
314  lcFileBak = Path.Combine(_cPathInicio, "config.bak");
315 
316  _cPathInicio = FUNCTIONS._AddBS(_cPathInicio);
317 
318  // Comprovar que exista el fichero
319  if (!File.Exists(lcFile))
320  {
321  _ErrorString = "No se ha encontrado el fichero de configuración en el directorio actual.";
322  lbValidar = false;
323  }
324 
325  // Comprovar si existeix la mínima configuració dins del config.INI
326  if (lbValidar)
327  lbValidar = _Validar_ConfigINI_Configuracion_Minima(tcComunes, lcFile);
328 
329  // Si el fichero config.ini no existe o no es correcto, intentamos utilizar el fichero de copia config.BAK
330  if (!lbValidar && File.Exists(lcFileBak) && !_lSemaforoConfigBak)
331  {
332  // Recuperar fichero config.BAK como config.INI
333  bool llOk = _Validar_ConfigINI_Gestion_BAK(lcFile, lcFileBak);
334 
335  // Realizar la validación del nuevo fichero config.INI
336  if (llOk)
337  {
338  _lSemaforoConfigBak = true;
339  llOk = _Validar_ConfigINI(tcComunes);
340  _lSemaforoConfigBak = false;
341  if (llOk) _ErrorString = "";
342  return llOk;
343  }
344  }
345 
346  LoadingLog(25, tcTextCentral: $"{(lbValidar ? "Ok" : "Fail")}{Environment.NewLine}");
347 
348  return lbValidar;
349  }
350 
357  private static bool _Validar_ConfigINI_Gestion_BAK(string lcFile, string lcFileBak)
358  {
359  bool llOk = false;
360 
361  // Fichero donde haremos una copia del actual fichero config.ini
362  string lcFileBak2 = Path.Combine(_cPathInicio, ("config_" + Path.GetRandomFileName() + ".bak"));
363 
364  try
365  {
366  // Si tenemos un fichero config.ini actualmente que no es bueno, por si a caso hacemos una copia
367  if (File.Exists(lcFile))
368  File.Copy(lcFile, lcFileBak2, true);
369 
370  // CCR 185039 - Se valida la fecha de modificación del fichero sea <= a 2 días
371  if ((DateTime.Now - File.GetLastWriteTime(lcFileBak)).TotalDays <= 2)
372  {
373  // Ahora copiamos el fichero config.bak que tenemos como config.ini
374  File.Copy(lcFileBak, lcFile, true);
375  llOk = true;
376  }
377  }
378  catch (Exception) { llOk = false; }
379 
380  return llOk;
381  }
382 
389  private static bool _Validar_ConfigINI_Configuracion_Minima(string tcComunes, string tcFileIni)
390  {
391 #if DEBUG
392  sage.ew.db.DB.Escribir_En_Log_Error(sage.ew.db.DB.Modo_Registro.Registro_Consulta, null, "Entrando en _Validar_ConfigINI_Configuracion_Minima. tcFileIni -> " + tcFileIni + " / _cPathInicio -> " + _cPathInicio);
393 #endif
394  bool lbValidar = true;
395 
396  //CCR 185039 - Mirar si el fichero está vacío.
397  string lcContent = FUNCTIONS._ReadFile(tcFileIni);
398  if (string.IsNullOrWhiteSpace(lcContent))
399  {
400  _ErrorString = "El fichero de configuración está vacío.";
401  lbValidar = false;
402  }
403  else
404  {
405  // [SERVIDOR]
406  _cRutaServ = FUNCTIONS._AddBS(FUNCTIONS.LeerConfigIni("[SERVIDOR]", _cPathInicio));
407  if (string.IsNullOrWhiteSpace(_cRutaServ))
408  {
409  _ErrorString = "El fichero de configuración no tiene la estructura esperada. No contiene el tag [SERVIDOR].";
410  lbValidar = false;
411  }
412  else
413  {
414  // Comprobar que sigui una ruta vàlida
415  if (!Directory.Exists(_cRutaServ))
416  {
417  _ErrorString = "La ruta del servidor encontrada en el fichero de configuración no es válida." + Environment.NewLine + _cRutaServ;
418  lbValidar = false;
419  }
420  }
421 
422  if (lbValidar)
423  {
424  // PE-97944. Insertamos ya la ruta a la global
425  EW_GLOBAL.ValorEnClave_VarGlob("wc_iniservidor", _cRutaServ);
426 
427  // [COMUNES]
428  // PE-104599 - Mirar si tenemos comunes por parámetro
429  if (string.IsNullOrEmpty(tcComunes.Trim()))
430  _cComunes = FUNCTIONS.LeerConfigIni("[COMUNES]", _cPathInicio);
431  else
432  _cComunes = tcComunes;
433 
434  if (string.IsNullOrWhiteSpace(_cComunes))
435  {
436  _ErrorString = "El fichero de configuración no tiene la estructura esperada. No contiene el tag [COMUNES].";
437  lbValidar = false;
438  }
439  }
440  }
441 
442  return lbValidar;
443  }
444 
449  public static bool _Validar_CfgCliSrv()
450  {
451  //JP: Chapuza por bug 193418 porque Sage50 no soporta parametros opcionales debido a la forma en la que precarga ciertos metodos
452  return _Validar_CfgCliSrv(string.Empty);
453  }
454 
460  public static bool _Validar_CfgCliSrv(string tcComunes)
461  {
462 
463  bool lbValidar = true;
464  bool lbAutWin = false;
465  string lcCfgCliSrvXml = "", lcNotificaComunes = "";
466 
467  LoadingLog(30, tcTextCentral: "Validando cfgclisrv.xml...");
468 
469  // Si pasa una segunda vez o más por aquí (por ejemplo en un cambio de grupo) y ya está creado el diccionario del cfgclisrv, ya no
470  // accederemos al fichero XML sino que trabajaremos sobre el diccionario _oCfgCliSrv en memoria que representa al fichero
471  // cfgclisrv.xml.
472  //
473  if (_oCfgCliSrv.Count == 0)
474  {
475  // Comprobar si existe cfgclisrv.xml
476  lcCfgCliSrvXml = Path.Combine(_cRutaServ, "cfgclisrv.xml");
477  if (!File.Exists(lcCfgCliSrvXml))
478  {
479  _ErrorString = "No se ha encontrado el fichero de configuración del servidor (cfgclisrv.xml).";
480  lbValidar = false;
481  }
482  else
483  cargarCfgCliSrv(lcCfgCliSrvXml);
484  }
485  else
486  {
487  _cComunes = FUNCTIONS.LeerConfigIni("[COMUNES]", _cPathInicio);
488  }
489 
490  if (lbValidar)
491  {
492  if (!Validar_Comunes(ref lbAutWin, ref lcNotificaComunes))
493  {
494  _ErrorString = "No se ha encontrado el COMUNES en el fichero de configuración del servidor.";
495  lbValidar = false;
496  }
497  }
498 
499  if (lbValidar)
500  {
501  // Comprobar si se ha encontrado el nodo
502  // TODO: Comprobar auth
503  if (string.IsNullOrWhiteSpace(_cUser) && lbAutWin == false)
504  {
505  _ErrorString = "No se ha encontrado el valor de COMUNES del fichero de configuración del terminal en el fichero de configuración del servidor.";
506  lbValidar = false;
507  }
508  }
509 
510  if (lbValidar)
511  {
512  bool llTopMost = false;
513 
514  // Desencriptar
515  _cPassword = FUNCTIONS._Encripta(_cPassword).Trim().ToLower();
516 
517  if (_frmSplash is Form)
518  {
519  llTopMost = !_lExternal_Entry && _frmSplash.TopMost; // Siempre está a true. pero pensando en el futuro lo gestionamos de esta forma
520 
521  if (llTopMost)
522  _frmSplash.TopMost = false;
523  }
524 
525  // Conectar
526  //193353: JP: Cuando se conecta a Sage50 a través de un programa externo (pj. DTS), se viene del método _main_Sage_50_External_Entry
527  //y no hay que conectar la DB al COMUNES que está en el ConfigIni sino al que viene como parámetro en la llamada. Ajustamos
528  string _comunesForConnect = string.IsNullOrWhiteSpace(tcComunes) ? _cComunes : tcComunes;
529  if (!DB.SQLConnect(_cIp, _cUser, _cPassword, _comunesForConnect, tcAliasConexion: "eurowin", tbAuthWin: lbAutWin))
530  {
531  _ErrorString = "No ha sido posible realizar la conexión con el servidor de datos.";
532  lbValidar = false;
533  }
534 
535 
536  //PE-105614 - No comprobar el módulo TPV, si se ha entrado externamente.
537  //PE-105536
538  if (lbValidar && !_lExternal_Entry && faltaModuloTPV())
539  {
540  ew.functions.AutoClosingMessageBox._Show("No se han encontrado AddOns necesarios para el correcto funcionamiento del programa." + Environment.NewLine
541  + Environment.NewLine + "Póngase en contacto con su soporte técnico habitual.", "Requisitos de AddOns instalados", 120000);
542  lbValidar = false;
543  }
544  //PE-105536
545  }
546 
547  if (lbValidar)
548  {
549  LoadingLog(35, tcTextCentral: $"Ok{Environment.NewLine}");
550  if (!string.IsNullOrWhiteSpace(lcNotificaComunes))
551  FUNCTIONS._Notificacion("Validación CONFIG.INI", "Etiqueta [COMUNES] con valor incorrecto", lcNotificaComunes, tcIcono: "warning");
552  }
553  else
554  {
555  LoadingLog(35, tcTextCentral: $"Fail{Environment.NewLine}");
556  }
557 
558  LoadingLog(35, tcTextCentral: "Driver:" + (!string.IsNullOrWhiteSpace(_cOdbc) ? _cOdbc : "SQL Native Client 2005") + Environment.NewLine);
559 
560  return lbValidar;
561  }
562 
569  private static bool Validar_Comunes(ref bool tbAutWin, ref string tcNotifica)
570  {
571  bool llOk = false;
572  string lcComunes = _cComunes;
573 
574  llOk = obtenerDatosConexion(_cComunes, ref _cUser, ref _cPassword, ref _cIp, ref tbAutWin, ref _cOdbc);
575  if (!llOk)
576  {
577  // Ir comprobando los comunes definidos en el fichero CFGCLISRV
578  foreach (KeyValuePair<string, RegCfgCliSrv> loComunes in _oCfgCliSrv)
579  {
580  if (loComunes.Key != lcComunes)
581  {
582  _cComunes = loComunes.Key;
583  llOk = obtenerDatosConexion(_cComunes, ref _cUser, ref _cPassword, ref _cIp, ref tbAutWin, ref _cOdbc);
584  if (llOk)
585  {
586  // Sustituir COMUNES en el config.ini con el nuevo bueno que hemos encontrado
587  FUNCTIONS._GuardarConfigIni("[COMUNES]", _cComunes, _cPathInicio, "config.ini");
588 
589  // Notificar que hay un COMUNES incorrecto en el config.ini y se ha sustituido por otro
590  tcNotifica = "Se ha encontrado el valor incorrecto '"+lcComunes+"' en la etiqueta [COMUNES] del fichero CONFIG.INI en "+
591  "la siguiente ruta: "+ _cPathInicio+ "." +Environment.NewLine+Environment.NewLine+
592  "Para poder iniciar la aplicación correctamente, se ha sustituido por el valor '" + _cComunes+"'.";
593 
594  break;
595  }
596  }
597  }
598  }
599 
600  return llOk;
601  }
602 
603 
608  private static void cargarCfgCliSrv(string tcFicheroXml)
609  {
610  XmlDocument xmlCfgCliSrv = new XmlDocument();
611  xmlCfgCliSrv.Load(tcFicheroXml);
612 
613  // Get principal node
614  XmlNode VFPDataNode = xmlCfgCliSrv["VFPData"];
615 
616  _oCfgCliSrv.Clear();
617 
618  foreach (XmlNode cfgclisrvNode in VFPDataNode.ChildNodes)
619  {
620  if (cfgclisrvNode.Name.ToLower().Trim() == "cfgclisrv")
621  {
622  // Voy cargando el la propiedad diccionario que de main_s50 que tiene todos los registros del CFGCLISRV.XML
623  //
624  if (!string.IsNullOrWhiteSpace(cfgclisrvNode["comunes"].InnerText.Trim()))
625  {
626  // Me aseguro de que este COMUNES no exista ya en el diccionario. Si el XML estuviese mal y tuviese el mismo comunes
627  // más de una vez petaria el diccionario al añadir de nuevo el mismo comunes por segunda vez.
628  //
629  RegCfgCliSrv loExisteReg = null;
630  if (!_oCfgCliSrv.TryGetValue(cfgclisrvNode["comunes"].InnerText.Trim().ToUpper(), out loExisteReg))
631  {
632  RegCfgCliSrv loRegCfgCliServ = new RegCfgCliSrv()
633  {
634  _User = cfgclisrvNode["user"].InnerText.Trim(),
635  _Password = cfgclisrvNode["password"].InnerText.Trim(),
636  _Ip = cfgclisrvNode["ip"].InnerText.Trim(),
637  _Comunes = cfgclisrvNode["comunes"].InnerText.Trim().ToUpper()
638  };
639 
640  if (cfgclisrvNode["server"] != null)
641  loRegCfgCliServ._Server = cfgclisrvNode["server"].InnerText.Trim();
642  else
643  loRegCfgCliServ._Server = "";
644 
645  if (cfgclisrvNode["port"] != null)
646  loRegCfgCliServ._Port = Convert.ToInt32(cfgclisrvNode["port"].InnerText.Trim());
647  else
648  loRegCfgCliServ._Port = 0;
649 
650  if (cfgclisrvNode["autwin"] != null)
651  loRegCfgCliServ._AutWin = Convert.ToBoolean(cfgclisrvNode["autwin"].InnerText.Trim());
652  else
653  loRegCfgCliServ._AutWin = false;
654 
655  if (cfgclisrvNode["odbc"] != null)
656  loRegCfgCliServ._Odbc = cfgclisrvNode["odbc"].InnerText.Trim();
657  else
658  loRegCfgCliServ._Odbc = "";
659 
660  _oCfgCliSrv.Add(cfgclisrvNode["comunes"].InnerText.Trim(), loRegCfgCliServ);
661  }
662  }
663  }
664  }
665 
666  return;
667  }
668 
669 
680  private static bool obtenerDatosConexion(string tcComunes, ref string tcUser, ref string tcPassword, ref string tcIp, ref bool tlAutWin, ref string tcOdbc)
681  {
682  bool llOk = true;
683 
684  RegCfgCliSrv loRegCfgCliSrv = null;
685 
686  // El comunes está guardado en mayúsculas, lo buscamos en mayúsculas.
687  //
688  if (!_oCfgCliSrv.TryGetValue(tcComunes.ToUpper(), out loRegCfgCliSrv))
689  {
690  llOk = false;
691  }
692  else
693  {
694  tcUser = loRegCfgCliSrv._User;
695  tcPassword = loRegCfgCliSrv._Password;
696  tcIp = loRegCfgCliSrv._Ip;
697  tlAutWin = loRegCfgCliSrv._AutWin;
698  tcOdbc = loRegCfgCliSrv._Odbc;
699  }
700 
701  return llOk;
702  }
703 
704 
709  private static bool faltaModuloTPV()
710  {
711  bool llFaltaModulo = (0 == Convert.ToInt32(DB._ValorSQL("MODULOS", new string[] { "NOMBRE='TPV'" }, new string[] { "COUNT(NOMBRE) AS CONTADOR" }, "COMUNES")));
712  bool llFaltaPrgs = (2 > Convert.ToInt32(DB._ValorSQL("PRGS", new string[] { "MODULO='TPV'" }, new string[] { "COUNT(MODULO) AS CONTADOR" }, "COMUNES")));
713  return (llFaltaModulo || llFaltaPrgs);
714  }
715 
720  public static bool _Validar_Eurowin()
721  {
722 
723  bool lbValidar = true;
724 
725  // Comprobar versión ficheros de Eurowin
726  string lcDbVistasServidor = Path.Combine(_cRutaServ, "db_vistas_serv");
727  string lcDbVistasTerminal = Path.Combine(_cPathInicio, "Db_Vistas");
728  string lcTriggersServidor = Path.Combine(_cRutaServ, "triggers");
729  string lcTriggersTerminal = Path.Combine(_cPathInicio, "Triggers");
730 
731  LoadingLog(30, tcTextCentral: "Validando ejecutable ... ");
732 
733  if (lbValidar)
734  {
735  // Comprobar directorio vistas
736  if (!Directory.Exists(lcDbVistasServidor))
737  {
738  _ErrorString = "No se ha encontrado el directorio Db_Vistas_Serv en el servidor de la aplicación.";
739  lbValidar = false;
740  }
741  }
742 
743  if (lbValidar)
744  {
745  // Comprobar directorio triggers
746  if (!Directory.Exists(lcTriggersServidor))
747  {
748  _ErrorString = "No se ha encontrado el directorio Triggers en el servidor de la aplicación.";
749  lbValidar = false;
750  }
751  }
752 
753  if (lbValidar)
754  {
755  // Comprobar directorio DB_Vistas
756  if (!Directory.Exists(lcDbVistasTerminal))
757  Directory.CreateDirectory(lcDbVistasTerminal);
758  if (!Directory.Exists(lcDbVistasTerminal))
759  {
760  _ErrorString = "No se ha podido crear el directorio Db_Vistas en el terminal de la aplicación.";
761  lbValidar = false;
762  }
763  }
764 
765  if (lbValidar)
766  {
767  // Comprobar directorio DB_Vistas
768  if (!Directory.Exists(lcTriggersTerminal))
769  Directory.CreateDirectory(lcTriggersTerminal);
770  if (!Directory.Exists(lcTriggersTerminal))
771  {
772  _ErrorString = "No se ha podido crear el directorio Triggers en el terminal de la aplicación.";
773  lbValidar = false;
774  }
775  }
776 
777  if (lbValidar)
778  {
779  // Try para comprobar en uso
780  try
781  {
782  // Copiar DB_Vistas
783  foreach (string file in Directory.GetFiles(lcDbVistasServidor))
784  {
785  string lcNomFile = new FileInfo(file).Name;
786  File.Copy(Path.Combine(lcDbVistasServidor, lcNomFile), Path.Combine(lcDbVistasTerminal, lcNomFile), true);
787  }
788  }
789  catch (Exception loEx)
790  {
791  DB.Registrar_Error(loEx); //Registramos excepción
792  }
793 
794  // Comprovar si existeixen tots els fitxer
795  if (!File.Exists(Path.Combine(lcDbVistasTerminal, "vistasbase.vcx"))
796  || !File.Exists(Path.Combine(lcDbVistasTerminal, "vistasbase.vct"))
797  || !File.Exists(Path.Combine(lcDbVistasTerminal, "vistas.vcx"))
798  || !File.Exists(Path.Combine(lcDbVistasTerminal, "vistas.vct")))
799  {
800  _ErrorString = "No se han podido copiar las vistas al terminal.";
801  lbValidar = false;
802  }
803  }
804 
805  if (lbValidar)
806  {
807  // Try para comprobar en uso
808  try
809  {
810  // Copiar DB_Vistas
811  foreach (string file in Directory.GetFiles(lcTriggersServidor))
812  {
813  string lcNomFile = new FileInfo(file).Name;
814  File.Copy(Path.Combine(lcTriggersServidor, lcNomFile), Path.Combine(lcTriggersTerminal, lcNomFile), true);
815  }
816  }
817  catch (Exception)
818  {
819  }
820 
821  // Comprovar si existeixen tots els fitxer
822  if (!File.Exists(Path.Combine(lcTriggersTerminal, "trigbase.vcx"))
823  || !File.Exists(Path.Combine(lcTriggersTerminal, "trigbase.vct"))
824  || !File.Exists(Path.Combine(lcTriggersTerminal, "triggers.vcx"))
825  || !File.Exists(Path.Combine(lcTriggersTerminal, "triggers.vct")))
826  {
827  _ErrorString = "No se han podido copiar las triggers al terminal.";
828  lbValidar = false;
829  }
830  }
831 
832  LoadingLog(35, tcTextCentral: $"{(lbValidar ? "Ok" : "Fail")}{Environment.NewLine}");
833 
834  return lbValidar;
835  }
836 
841  public static bool _Cargar_Licencia()
842  {
843  bool llOk = true;
844  string lcLicencia;
845 
846  LoadingLog(45, tcTextCentral: $"Comprobando licencia ... ");
847  // Obtener la licencia directamente de la BD y comprobarla
848  lcLicencia = LICENCIAS._ObtenerLicenciaActual();
849  if (string.IsNullOrWhiteSpace(lcLicencia))
850  {
851  _ErrorString = LICENCIAS._MensajeError;
852  llOk = false;
853  }
854 
855  LoadingLog(45, tcTextCentral: $"{(llOk ? "Ok" : "Fail")}{Environment.NewLine}");
856 
857  //if (LICENCIAS._EsLicenciaParaPruebas && !LICENCIAS._EsLicenciaParaEvaluacion)
858  // _frmSplash._MostrarMensajeLicenciaPruebas();
859 
860  return llOk;
861  }
862 
875  public static bool _Cargar_Globales(bool tlVerificarLicencia, string tcEmpresa = "", string tcCajaTpv = "")
876  {
877  return cargarGlobales(tcEmpresa, tcCajaTpv, tlVerificarLicencia);
878  }
879 
880 
886  public static bool _Cargar_Globales(string tcEmpresa = "", string tcCajaTpv="")
887  {
888  return cargarGlobales(tcEmpresa, tcCajaTpv, true);
889  }
890 
891 
899  private static bool cargarGlobales(string tcEmpresa, string tcCajaTpv, bool tlVerificarLicencia)
900  {
901  bool lbValidar = true;
902  string lcEmpresa = "";
903  string lcCajaTpv = "";
904 
905 
906  // Añadir estas variables al inicio de todo, ya que se necesitan antes.
907  EW_GLOBAL.ValorEnClave_VarGlob("wl_sage50", true); // PE-97745
908  EW_GLOBAL.ValorEnClave_VarGlob("wc_pathinicio", _cPathInicio);
909  EW_GLOBAL.ValorEnClave_VarGlob("wc_iniservidor", _cRutaServ);
910 
911  string lcLicencia = LICENCIAS._Licencia;
912 
913  // Task 142646 (Diciembre 2018), nueva variedad de producto Sage 50 Asesor Contable.
914  // Un Sage50 Asesor Contable será un Premium (wn_tipoprod=2) y además la licencia
915  // comience por SY. Si se dan las anteriores condiciones pondremos wn_AsesorContable a 1
916  //
917  //
918  EW_GLOBAL.ValorEnClave_VarGlob("wn_AsesorContable", 0);
919  if (!string.IsNullOrWhiteSpace(lcLicencia) && lcLicencia.Length >= 2 && lcLicencia.Substring(0, 2) == "SY")
920  {
921  // Para el caso de licencia SY asignamos un nivel por defecto de wn_asesorcontable de 10
922  //
923  // Si algún dia se decide crear algun nivel superior o inferior de asesorcontable en función de un nuevo
924  // prefijo de licencia, se declarará en wn_asesorcontable el valor que corresponda (superior o inferior a 10)
925  //
926  EW_GLOBAL._SetVariable("wn_AsesorContable", 10);
927  }
928 
929  // Bug 167355 - Comprobar existencia empresa
930  // Obtener valores mínimos para cargar diccionarios
931  lcEmpresa = ObtenerEmpresa(tcEmpresa);
932 
933  // PE-104301. Sólo tener en cuenta la Caja de TPV si el módulo de TPV está activo.
934  if (EW_GLOBAL._ModuloActivo("TPV"))
935  {
936  if (string.IsNullOrEmpty(tcCajaTpv))
937  lcCajaTpv = FUNCTIONS.LeerConfigIni("[CAJATPV]");
938  else
939  lcCajaTpv = tcCajaTpv;
940 
941  // PE-100470. Comprobar que la caja no contenga NO
942  if (lcCajaTpv.Trim().ToUpper() == "NO")
943  lcCajaTpv = string.Empty;
944  }
945 
946  LoadingLog(45, tcTextCentral: "Cargando diccionarios ... ");
947 
948  if (string.IsNullOrWhiteSpace(lcCajaTpv))
949  lbValidar = DiccionariosLoader.CargarDiccionarios(lcEmpresa);
950  else
951  lbValidar = DiccionariosLoader.CargarDiccionarios(lcEmpresa, lcCajaTpv);
952 
953 
954  if (lbValidar)
955  {
956  LoadingLog(55, tcTextCentral: $"Ok{Environment.NewLine}");
957  LoadingLog(55, tcTextCentral: "Obteniendo parámetros globales ... ");
958 
959  // Para saber si se ha actualizado sage 50
960  EW_GLOBAL._Sage50Actualizado = FUNCTIONS._Sage50Actualizado();
961 
962  // Task 142425
963  string lcUsuario = "";
964  if (!string.IsNullOrWhiteSpace(Program._cUserEurowin))
965  lcUsuario = Program._cUserEurowin;
966  else
967  lcUsuario = FUNCTIONS.LeerConfigIni("[USUARIO]");
968 
969  // Continuamos con la carga
970  string lcLetra = FUNCTIONS.LeerConfigIni("[LETRA]");
971  string lcAlmacen = FUNCTIONS.LeerConfigIni("[ALMACEN]"); //PE-102224
972 
973  // Obtener ejercicio predeterminado
974  string lcAny = DB.Ejercicio_EW.ToString().Trim();
975 
976  // Obtener operario predeterminado según caja
977  string lcOperarioTpv = string.Empty;
978  if (EW_GLOBAL._ModuloActivo("TPV"))
979  lcOperarioTpv = Convert.ToString(DB.SQLValor("CAJAS", "CODIGO", lcCajaTpv, "OPERARIO", "TPV"));
980 
981  // Otros valores
982  string lcusergraf = Path.Combine(_cRutaServ, @"usergraf\");
983 
984  // Asignamos el valor proviniente de la variable SQL_LOG del config.ini
985  string lcSqlLog = Convert.ToString(FUNCTIONS.LeerConfigIni("[SQL_LOG]")).ToUpper().Trim();
986 
987  // Asignamos si trabajamos con PRUEVAS SI
988  string lcPrueva = Convert.ToString(FUNCTIONS.LeerConfigIni("[PRUEVAS]")).ToUpper();
989  bool llPrueva = (lcPrueva == "SI" || lcPrueva == "PERMANENTE");
990 
991  // Carga de diccionarios
992  if (!string.IsNullOrWhiteSpace(lcAny))
993  {
994  // Bug-107350. Comprobar si el ejercicio existe en el grupo de empresas.
995  // En caso contrario, asignar el predeterminado
996  string lcDataBase = string.Empty;
997  lcAny = Convert.ToString(EW_GLOBAL._GetVariable("wc_any"));
998 
999  // Obtenemos la base de datos del ejercicio que vamos a predeterminar como GESTION
1000  if (!DB._oAliasDB.TryGetValue(lcAny, out lcDataBase))
1001  {
1002  lcAny = DB.Ejercicio_EW.ToString().Trim();
1003  }
1004 
1005  DB.SQLPredeterminarGestion(Convert.ToString(lcAny));
1006  }
1007 
1008  //Cargamos los esquemas => Se hace en este punto ya que antes no tenemos conexión y no se ha predeterminado ejercicio
1009  DB.PreloadSchemas();
1010 
1011  // Añadirlos a la global
1012  EW_GLOBAL.ValorEnClave_VarGlob("wc_usuario", lcUsuario);
1013  EW_GLOBAL.ValorEnClave_VarGlob("wc_empresa", lcEmpresa);
1014  EW_GLOBAL.ValorEnClave_VarGlob("wc_cajatpv", lcCajaTpv);
1015  EW_GLOBAL.ValorEnClave_VarGlob("wc_concomunes", _cComunes);
1016  EW_GLOBAL.ValorEnClave_VarGlob("wc_any", lcAny);
1017  EW_GLOBAL.ValorEnClave_VarGlob("wc_operariotpv", lcOperarioTpv);
1018  EW_GLOBAL.ValorEnClave_VarGlob("wc_usergraf", lcusergraf);
1019  EW_GLOBAL.ValorEnClave_VarGlob("wc_sql_log", lcSqlLog);
1020  EW_GLOBAL.ValorEnClave_VarGlob("wl_prueva", llPrueva);
1021  EW_GLOBAL.ValorEnClave_VarGlob("formvfp", ""); // Por compatibilidad
1022  EW_GLOBAL.ValorEnClave_VarGlob("wl_EsEjecutable", _lEsEjecutable); // PE-103025
1023 
1024  // PE-97592. Solo asignar el valor a wc_letra si hay valor en Config.ini. Si no, dejar la que se ha leido de Empresa
1025  if (!string.IsNullOrWhiteSpace(lcLetra))
1026  EW_GLOBAL.ValorEnClave_VarGlob("wc_letra", lcLetra);
1027 
1028  //PE-102224: Si nos llega desde config.ini, lo establecemos en wc_empresa independientemente del valor (con wc_almacen y wc_operario)
1029  if (!string.IsNullOrWhiteSpace(lcAlmacen))
1030  EW_GLOBAL.ValorEnClave_VarGlob("wc_almacen", lcAlmacen);
1031 
1032  LoadingLog(55, tcTextCentral: $"Ok{Environment.NewLine}");
1033  }
1034  else
1035  {
1036  LoadingLog(55, tcTextCentral: $"Fail{Environment.NewLine}");
1037  _ErrorString = "No se han podido cargar los diccionario de variables globales.";
1038  }
1039 
1040 
1041  if (tlVerificarLicencia)
1042  {
1043  // PE-99112. Descarga del fichero Sagelic
1044  LoadingLog(57, tcTextCentral: "Validando licencia ... ");
1045 
1046  if (LICENCIAS._Validar_Licencia_Suscripcion())
1047  {
1048  LoadingLog(57, tcTextCentral: $"Ok{Environment.NewLine}");
1049  }
1050  else
1051  {
1052  LoadingLog(57, tcTextCentral: $"Fail{Environment.NewLine}");
1053  _ErrorString = LICENCIAS._MensajeError; // PE-101933
1054  return false;
1055  }
1056 
1057 
1058  // PE-100885. Es posible que dejemos entrar en la aplicación, pero mostrando alguna advertencia.
1059  if (!string.IsNullOrWhiteSpace(LICENCIAS._MensajeError))
1060  {
1061  _ErrorString = LICENCIAS._MensajeError;
1062  LICENCIAS._MensajeError = "";
1063  }
1064  }
1065 
1066  FunctionsDependencies functionsDependencies = new FunctionsDependencies()
1067  {
1068  GenerarChecksumOpciones = Criptografia.GenerarChecksumOpciones,
1069  GetSage50PathLibrerias = FUNCTIONS.GetSage50PathLibrerias,
1070  CodigoLicencia = LICENCIAS._CodigoLicencia,
1071  PluginActivo = FUNCTIONS._PluginActivo,
1072  CrearNotificacionWarning = FUNCTIONS.CrearNotificacionWarning
1073  };
1074 
1075  // PE-96322,PE-97109. Cargamos los addons (modulos, pam)
1076  AddonsController.Instance.AddonsManager._CargarAddOns(functionsDependencies, !_lExternal_Entry);
1077  if (_lExternal_Entry)
1078  {
1079  // Esperar a finalizar la carga asincrona de los addons
1080  bool cargaraddonsuccess = AddonsController.Instance.AddonsManager._CargarAddons_WaitAll();
1081  }
1082 
1083  if ((!_garantizandoAddons || (!string.IsNullOrWhiteSpace(_cGrupo) && _cGrupo != _cGrupoEmpresaActual)) && !_lExternal_Entry)
1084  {
1085  //Solo se ejecutará una vez
1086  _garantizandoAddons = true;
1087 
1088  // La clase autoejecuta todo el codigo de validación
1089  // Pasar segundo parámetro "false" para que no se fuerce a bajar el fichero Sagelic
1090  // Adicionalmente le pasamos un true para que refresque los Addons destacados
1091  SetupAddons setup = new SetupAddons(true, false, false, true);
1092  }
1093 
1094  _cGrupo = _cGrupoEmpresaActual; // Asignamos el grupo para la carga de los Add-ons destacados al cambiar de grupo
1095 
1096  LoadServices();
1097 
1098  return lbValidar;
1099  }
1100 
1101  static bool _garantizandoAddons = false;
1102 
1103  private static string _cGrupo = string.Empty;
1104 
1108  private static string _cGrupoEmpresaActual
1109  {
1110  get
1111  {
1112  return DB.DbComunes.Substring(4, 4);
1113  }
1114  }
1115 
1120  private static bool LoadServices()
1121  {
1122  string lcError = string.Empty;
1123 
1124  FUNCTIONS._StateServiceForm(ref lcError); // De momento no es necesario gestionar el error para este tipo de petición
1125 
1126  return true;
1127  }
1128 
1133  public static bool _Cargar_LibreriasReports()
1134  {
1135  bool llOk = false;
1136  string lcPatron = "Sage.ES.S50c.Reports";
1137  string lcPathInicio = FUNCTIONS.GetSage50PathLibrerias();
1138 
1139  if (Directory.Exists(lcPathInicio))
1140  {
1141  DirectoryInfo loDir = new DirectoryInfo(lcPathInicio);
1142  //Mirem si el nom de la dll es del tipus que ens interessa carregar
1143  List<FileInfo> loList = (from loFile in loDir.GetFiles("*.dll")
1144  where loFile.Name.ToLower().StartsWith(lcPatron.ToLower())
1145  select loFile).ToList();
1146 
1147  //Recorrem totes les dlls
1148  foreach (FileInfo loFileInfo in loList)
1149  {
1150 
1151  string lcFicheroDll = loFileInfo.FullName;
1152  //La carreguem
1153  Assembly addonAssembly = null;
1154  try
1155  {
1156  var appDomain = AppDomain.CreateDomain(lcFicheroDll);
1157  addonAssembly = appDomain.Load(System.IO.File.ReadAllBytes(lcFicheroDll));
1158  }
1159  catch (Exception)
1160  {
1161  addonAssembly = null;
1162  }
1163  if (addonAssembly == null)
1164  {
1165  try
1166  {
1167  addonAssembly = Assembly.LoadFrom(lcFicheroDll);
1168  }
1169  catch (Exception)
1170  {
1171  addonAssembly = null;
1172  }
1173  }
1174  //Comprobem si s'ha carregat amb éxit
1175  if (addonAssembly != null)
1176  llOk = true;
1177  }
1178  }
1179 
1180  return llOk;
1181  }
1182 
1186  public static void _RegisterNotifications()
1187  {
1188  // Cogemos el comunes principal y el actual
1189  string lcComunesPripal = Convert.ToString(EW_GLOBAL._GetVariable("wc_ComunesPripal"));
1190  string lcComunesActual = Convert.ToString(EW_GLOBAL._GetVariable("wc_ComunesActual"));
1191 
1192  // Bug 172689 - Si el comunes actual está vacio, lo cogemos de la DB
1193  if (string.IsNullOrWhiteSpace(lcComunesActual))
1194  {
1195  if (DB._oAliasDB.TryGetValue("COMUNES", out lcComunesActual))
1196  lcComunesActual = lcComunesActual.Replace("].dbo.", "").Replace("[", "").Trim().ToUpper();
1197  }
1198 
1199  // PE-104253 - Si wc_ComunesPripal está vacio, indica que solamente hay un grupo
1200  // Solamente añadimos las notificaciones en el grupo principal
1201  // Mirar si el comunes principal y el actual no son el mismo
1202  if (!String.IsNullOrEmpty(lcComunesPripal.Trim()) && lcComunesActual != lcComunesPripal)
1203  return;
1204 
1205  // Coger la ruta del servidor principal
1206  string lcRutaServidor = Convert.ToString(EW_GLOBAL._GetVariable("wc_iniservidor")).Trim();
1207  //string lcRutaServidor2 = FUNCTIONS.LeerConfigIni("[SERVIDOR_2]").Trim();
1208 
1210  //if (!string.IsNullOrWhiteSpace(lcRutaServidor2))
1211  // lcRutaServidor = lcRutaServidor2;
1212 
1213  // Ruta fichero notificaciones
1214  string lcPath = FUNCTIONS._AddBS(lcRutaServidor) + @"\LOGS\NOTIFICA";
1215 
1216  // Mirar si existe el directorio
1217  if (!Directory.Exists(lcPath))
1218  return;
1219 
1220  // Recorrer los ficheros del directorio con la máscara "notifica*.xml"
1221  DirectoryInfo ldDir = new DirectoryInfo(lcPath);
1222  foreach (var lcFile in ldDir.GetFiles("notifica*.xml"))
1223  {
1224  string lcFileXml = Path.Combine(lcPath, lcFile.Name);
1225 
1226  // tratar el fichero XML y cambiar el nombre del fichero
1227  if (_RegisterNotificationXml(lcFileXml))
1228  {
1229  string lcFileCopy = Path.Combine(lcPath, "_" + lcFile.Name);
1230 
1231  try
1232  {
1233  // Eliminar fichero
1234  if (File.Exists(lcFileCopy))
1235  File.Delete(lcFileCopy);
1236 
1237  // renombrar fichero
1238  File.Move(lcFileXml, lcFileCopy);
1239  }
1240  catch (Exception loEx)
1241  {
1242  DB.Registrar_Error(new Exception("No se ha podido copiar fichero "+lcFileXml+" ("+loEx.Message+")."));
1243  }
1244  }
1245  }
1246  }
1247 
1253  private static bool _RegisterNotificationXml(string tcFile)
1254  {
1255  bool llOk = false, llReturn = false;
1256  DataTable ldtTabla = new DataTable();
1257 
1258  // Pasar el XML a Datatable
1259  if (System.IO.File.Exists(tcFile))
1260  llOk = FUNCTIONS._Xml2Datatable(tcFile, ref ldtTabla);
1261 
1262  // Mirar si existe la tabla
1263  if (!llOk || ldtTabla == null)
1264  return false;
1265 
1266  // Recorrer el datatable y añadir notificaciones
1267  foreach (DataRow ldrRow in ldtTabla.Rows)
1268  {
1269  string lcCat = "", lcNombre = "", lcDesc = "", lcLib = "", lcClase = "", lcPermanente = "";
1270  bool tlPermanente = false;
1271 
1272  if (ldtTabla.Columns.Contains("categoria"))
1273  lcCat = Convert.ToString(ldrRow["categoria"]);
1274 
1275  if (ldtTabla.Columns.Contains("nombre"))
1276  lcNombre = Convert.ToString(ldrRow["nombre"]);
1277 
1278  if (ldtTabla.Columns.Contains("descrip"))
1279  lcDesc = Convert.ToString(ldrRow["descrip"]);
1280 
1281  if (ldtTabla.Columns.Contains("libreria"))
1282  lcLib = Convert.ToString(ldrRow["libreria"]);
1283 
1284  if (ldtTabla.Columns.Contains("clase"))
1285  lcClase = Convert.ToString(ldrRow["clase"]);
1286 
1287  if (ldtTabla.Columns.Contains("permanente"))
1288  {
1289  lcPermanente = Convert.ToString(ldrRow["permanente"]);
1290  if (!String.IsNullOrEmpty(lcPermanente.Trim()) && lcPermanente.Trim()=="true")
1291  tlPermanente = true;
1292  }
1293 
1294  // Añadir la notificación
1295  if (!String.IsNullOrEmpty(lcCat.Trim()) && !String.IsNullOrEmpty(lcNombre.Trim()))
1296  {
1297  Notifica._This._Add(lcCat, lcNombre, lcDesc, tcLibreria: lcLib, tcClase: lcClase, toIcono: NotificaIconos.info, tlPermanente: tlPermanente);
1298  llReturn = true;
1299  }
1300  }
1301 
1302  return llReturn;
1303  }
1304 
1305 
1309  private static void RevisarLiveUpdate()
1310  {
1311  sage.ew.ewbase.LiveUpdate loLiveUpdate = new LiveUpdate(false);
1312  Task TaskLU = new Task(() => loLiveUpdate._RevisarLiveUpdate());
1313  TaskLU.Start();
1314  }
1315 
1316 
1326  public static bool Connect(string tcPathEuroTerm, string tcUser, string tcPassword, string tcEmpresa = "", bool tlMuestraErrores = true)
1327  {
1328  //Comprobació inicial per si ja tenim conexió a BD
1329  if (!string.IsNullOrWhiteSpace(sage.ew.db.DB.Conexion))
1330  {
1331  //Missatge d'error
1332  if(tlMuestraErrores)
1333  sage.ew.functions.FUNCTIONS._MessageBox("Ya está conectado a "+ lcNameProd+".",
1334  "Conexión a "+ lcNameProd, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
1335  return true;
1336  }
1337 
1338  bool llOk = false;
1339  //Validem que el directori del terminal al menys existeixi
1340  if (!string.IsNullOrWhiteSpace(tcPathEuroTerm) && Directory.Exists(tcPathEuroTerm))
1341  {
1342  //Validacions y carrega de l'entorn
1343  sage._50.main_s50._frmSplash = new sage._50.Forms.frmSplash();
1344  sage._50.main_s50._cPathInicio = tcPathEuroTerm;
1345  if (sage._50.main_s50._main_Sage_50())
1346  {
1347  DB._SetTimeCacheTo(0); //Deshabilitar caché de consultas ya que en este método connect no se estaba deshabilitando y hubiera dado problemas
1348 
1349  //Invoquem la pantalla de login
1351  //Definim la empresa
1352  if (!string.IsNullOrWhiteSpace(tcEmpresa))
1353  {
1354  loForm._Empresa = tcEmpresa;
1355  if (loForm._Empresa != tcEmpresa)
1356  _ErrorString += "No se ha podido asignar la empresa \"" + tcEmpresa + "\"." + Environment.NewLine + "¿Puede ser que la empresa no exista?";
1357  }
1358  //Comprobem errors
1359  if (string.IsNullOrWhiteSpace(_ErrorString))
1360  {
1361  //Resposta per defecte
1362  DialogResult leResposta = DialogResult.Cancel;
1363  //Comprobació user/pass
1364  if (string.IsNullOrWhiteSpace(tcUser) || string.IsNullOrWhiteSpace(tcPassword))
1365  leResposta = loForm.ShowDialog(); //Mostrem pantalla de login
1366  else
1367  leResposta = loForm._CheckLogin(tcUser, tcPassword); //Login automàtic
1368 
1369  llOk = (leResposta == DialogResult.OK);
1370  }
1371  }
1372  }
1373 
1374  if (!llOk)
1375  {
1376  //Borrem l'string de conexió a BD
1377  DB.Conexion = "";
1378  //Missatge d'error
1379  if (tlMuestraErrores)
1380  {
1381  string lcError = _ErrorString;
1382  if (string.IsNullOrWhiteSpace(lcError))
1383  lcError = "Usuario o contraseña incorrectos.";
1384  MessageBox.Show(lcError, "Conexión a "+ lcNameProd, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
1385  }
1386  }
1387  else
1388  {
1389  // TODO. Que fer amb els estils?
1390  EW_GLOBAL._CodiPerfilCarregat = ".predet";
1391  }
1392 
1393  return llOk;
1394  }
1395 
1406  public static bool Connect(string tcInstancia, string tcUser, string tcPassword, string tcBDComunes, string tcEmpresaGuid, bool tlMuestraErrores = true)
1407  {
1408  //Task 151163: Obtener el PathInicio y IniServidor para guardarlos en wc_pathinicio y wc_iniservidor de la global
1409  //sin que otras aplicaciones tengan que escribirlo (por ejemplo DTS)
1410  string codeBase = Assembly.GetExecutingAssembly().CodeBase;
1411  UriBuilder uri = new UriBuilder(codeBase);
1412  string pathInicio = Uri.UnescapeDataString(uri.Path);
1413  pathInicio = Path.GetDirectoryName(pathInicio);
1414  string iniServidor = string.Empty;
1415 
1416  if (!string.IsNullOrWhiteSpace(pathInicio))
1417  {
1418  pathInicio = System.IO.Directory.GetParent(pathInicio).FullName;
1419  if (!string.IsNullOrWhiteSpace(pathInicio))
1420  {
1421  pathInicio = FUNCTIONS._AddBS(pathInicio);
1422 
1423  //A partir del pathInicio buscar el config.ini y obtener el iniServidor
1424  iniServidor = FUNCTIONS._AddBS(FUNCTIONS.LeerConfigIni("[SERVIDOR]", pathInicio));
1425  }
1426  }
1427 
1428  if (!string.IsNullOrWhiteSpace(pathInicio) && !string.IsNullOrWhiteSpace(iniServidor))
1429  {
1430  //Si hemos podido cargar las dos variables las pasamos a las de la clase que se guardaran en EW_GLOBAL
1431  _cPathInicio = pathInicio;
1432  _cRutaServ = iniServidor;
1433  EW_GLOBAL.ValorEnClave_VarGlob("wc_pathinicio", _cPathInicio);
1434  }
1435  //FIN Task 151163
1436 
1437  EW_GLOBAL.ValorEnClave_VarGlob("wl_sage50", true); //Necesario, en la otra sobrecarga si que se asigna a true y debe ser true para sage50
1438 
1439  //Comprobació inicial per si ja tenim conexió a BD
1440  if (!string.IsNullOrWhiteSpace(sage.ew.db.DB.Conexion))
1441  {
1442  //Missatge d'error
1443  if (tlMuestraErrores)
1444  sage.ew.functions.FUNCTIONS._MessageBox("Ya está conectado a "+ lcNameProd+".",
1445  "Conexión a "+lcNameProd, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
1446  return true;
1447  }
1448 
1449  bool lbValidar = true;
1450  //Validem que tinguem dades
1451  if (!string.IsNullOrWhiteSpace(tcInstancia) && !string.IsNullOrWhiteSpace(tcUser)
1452  && !string.IsNullOrWhiteSpace(tcPassword) && !string.IsNullOrWhiteSpace(tcBDComunes))
1453  {
1454  //Definir variables
1455  _cComunes = tcBDComunes;
1456  _cUser = tcUser;
1457  _cPassword = tcPassword;
1458  _cIp = tcInstancia;
1459 
1460  // Conectar a Base de datos
1461  if (!DB.SQLConnect(_cIp, _cUser, _cPassword, _cComunes, tcAliasConexion: "eurowin", tbAuthWin: false))
1462  {
1463  _ErrorString = "No ha sido posible realizar la conexión con el servidor de datos.";
1464  lbValidar = false;
1465  }
1466 
1467  if (lbValidar)
1468  {
1469  RegisterTypesDependencyInjector();
1470  //CCR 148421 - Para crear el objeto Sagelic
1471  LICENCIAS._ObtenerLicenciaActual();
1472  LICENCIAS._Validar_Licencia_Suscripcion();
1473 
1474  //Recuperar ID de empresa
1475  string lcEmpresa = "";
1476  DataTable ldtTemp = new DataTable();
1477  string lcSql = "SELECT codigo FROM " + DB.SQLDatabase("EMPRESA") + " WHERE guid_id = " + DB.SQLString(tcEmpresaGuid);
1478  if (DB.SQLExec(lcSql, ref ldtTemp) && ldtTemp.Rows.Count > 0 && !string.IsNullOrWhiteSpace(ldtTemp.Rows[0]["codigo"].ToString()))
1479  {
1480  lcEmpresa = ldtTemp.Rows[0]["codigo"].ToString();
1481  //Cargar diccionarios
1482  lbValidar = DiccionariosLoader.CargarDiccionarios(lcEmpresa);
1483  if (!lbValidar)
1484  _ErrorString = "No se han podido cargar los diccionario de variables globales.";
1485  }
1486  else
1487  {
1488  //Para DTS: Recorrer todos los ejercicios y el que contenga el guid de empresa es el que predeterminamos y cargamos diccionarios
1489  lcSql = "SELECT [any] AS ano FROM " + DB.SQLDatabase("COMUNES", "ejercici") + " ORDER BY [any] DESC ";
1490  DataTable ldtEjercicis = new DataTable();
1491  if (DB.SQLExec(lcSql, ref ldtEjercicis) && ldtEjercicis.Rows.Count > 0)
1492  {
1493  foreach (DataRow ldr in ldtEjercicis.Rows)
1494  {
1495  EW_GLOBAL.ValorEnClave_VarGlob("wc_any", Convert.ToString(ldr["ano"]).Trim());
1496  DB.SQLPredeterminarGestion(Convert.ToString(ldr["ano"]).Trim()); //PE-101549
1498 
1499  lcSql = "SELECT codigo FROM " + DB.SQLDatabase("EMPRESA") + " WHERE guid_id = " + DB.SQLString(tcEmpresaGuid);
1500  if (DB.SQLExec(lcSql, ref ldtTemp) && ldtTemp.Rows.Count > 0 && !string.IsNullOrWhiteSpace(ldtTemp.Rows[0]["codigo"].ToString()))
1501  {
1502  lcEmpresa = ldtTemp.Rows[0]["codigo"].ToString();
1503  //Cargar diccionarios
1504  lbValidar = DiccionariosLoader.CargarDiccionarios(lcEmpresa);
1505  if (!lbValidar)
1506  _ErrorString = "No se han podido cargar los diccionario de variables globales.";
1507  if (lbValidar)
1508  break;
1509  }
1510  }
1511 
1512  if (!lbValidar)
1513  {
1514  _ErrorString = "No se ha encontrado ninguna empresa con el GUID \"" + tcEmpresaGuid + "\".";
1515  lbValidar = false;
1516  }
1517  }
1518  else
1519  {
1520  _ErrorString = "No se ha encontrado ninguna empresa con el GUID \"" + tcEmpresaGuid + "\".";
1521  lbValidar = false;
1522  }
1523  }
1524 
1525  if (lbValidar)
1526  {
1527  // Obtener ejercicio predeterminado
1528  string lcAny = DB.Ejercicio_EW.ToString().Trim();
1529 
1530  // Carga de diccionarios
1531  if (!string.IsNullOrWhiteSpace(lcAny))
1532  {
1533  // Bug-107350. Comprobar si el ejercicio existe en el grupo de empresas.
1534  // En caso contrario, asignar el predeterminado
1535  string lcDataBase = string.Empty;
1536  lcAny = Convert.ToString(EW_GLOBAL._GetVariable("wc_any"));
1537 
1538  // Obtenemos la base de datos del ejercicio que vamos a predeterminar como GESTION
1539  if (!DB._oAliasDB.TryGetValue(lcAny, out lcDataBase))
1540  {
1541  lcAny = DB.Ejercicio_EW.ToString().Trim();
1542  }
1543 
1544  DB.SQLPredeterminarGestion(Convert.ToString(lcAny));
1545  }
1546 
1547  // Añadirlos a la global
1548  EW_GLOBAL.ValorEnClave_VarGlob("wc_pathinicio", _cPathInicio);
1549  EW_GLOBAL.ValorEnClave_VarGlob("wc_iniservidor", _cRutaServ);
1550  EW_GLOBAL.ValorEnClave_VarGlob("wc_usuario", "SUPERVISOR"); //Necesario para tener permiso completo a ciertas pantallas (asientos, por ejemplo)
1551  EW_GLOBAL.ValorEnClave_VarGlob("wc_empresa", lcEmpresa);
1552  EW_GLOBAL.ValorEnClave_VarGlob("wc_cajatpv", "");
1553  EW_GLOBAL.ValorEnClave_VarGlob("wc_concomunes", _cComunes);
1554  EW_GLOBAL.ValorEnClave_VarGlob("wc_any", lcAny);
1555  EW_GLOBAL.ValorEnClave_VarGlob("wc_operariotpv", "");
1556  EW_GLOBAL.ValorEnClave_VarGlob("wc_ewlicencia", "");
1557  EW_GLOBAL.ValorEnClave_VarGlob("wc_usergraf", "");
1558  EW_GLOBAL.ValorEnClave_VarGlob("wc_sql_log", "");
1559  EW_GLOBAL.ValorEnClave_VarGlob("wl_prueva", false);
1560  EW_GLOBAL.ValorEnClave_VarGlob("formvfp", ""); // Por compatibilidad
1561  EW_GLOBAL.ValorEnClave_VarGlob("wl_EsEjecutable", _lEsEjecutable);
1562  EW_GLOBAL.ValorEnClave_VarGlob("wl_sage50", true); //Necesario, en la otra sobrecarga si que se asigna a true y debe ser true para sage50
1563 
1564  //RegisterTypesDependencyInjector();
1565  //DependencyInjector.Instance.RegisterTypes(RegisterType.All, true);
1566 
1567  // Rellenar el diccionario _Modulos con información sobre los módulos instalados(suscripción) .
1568  if (!LICENCIAS._CargarDiccionarioModulos())
1569  {
1570  _ErrorString = "No se ha podido cargar el diccionario de módulos.";
1571  }
1572 
1573  EW_GLOBAL._Empresa = new Empresa(Convert.ToString(EW_GLOBAL._GetVariable("wc_empresa"))); //Bug 114208: Faltaba inicializar el objeto empresa
1574  }
1575  }
1576  }
1577 
1578  if (!lbValidar)
1579  {
1580  //Borrem l'string de conexió a BD
1581  DB.Conexion = "";
1582  //Missatge d'error
1583  if (tlMuestraErrores)
1584  {
1585  string lcError = _ErrorString;
1586  if (string.IsNullOrWhiteSpace(lcError))
1587  lcError = "Error realizando conexión a base de datos.";
1588  MessageBox.Show(lcError, "Conexión a "+ lcNameProd, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
1589  }
1590  }
1591  else
1592  {
1593  // TODO. Que fer amb els estils?
1594  EW_GLOBAL._CodiPerfilCarregat = ".predet";
1595  }
1596 
1597  return lbValidar;
1598  }
1599 
1600  // Task 108063
1604  public static void _Show()
1605  {
1606  Forms.frmPrincipal loForm = new Forms.frmPrincipal(true);
1607  loForm.WindowState = FormWindowState.Maximized; // Presentaremos la pantalla maximizada
1608  loForm.Icon = sage.ew.images.Properties.Resources.Sage50code;
1609  loForm.ShowDialog();
1610  }
1611  // FTask 108063
1612 
1616  public static void RegisterTypesDependencyInjector()
1617  {
1618  //Registramos las dependencias
1619  RegisterTypesSage50 registerTypesSage50 = new RegisterTypesSage50();
1620  registerTypesSage50.RegisterTypes();
1621  }
1622 
1628  private static string ObtenerEmpresa(string tcEmpresa)
1629  {
1630  string lcEmpresa = "";
1631 
1632  if (string.IsNullOrEmpty(tcEmpresa))
1633  lcEmpresa = FUNCTIONS.LeerConfigIni("[EMPRESA]");
1634  else
1635  lcEmpresa = tcEmpresa;
1636 
1637  string lcEmpNew = FUNCTIONS._ExisteEmpresa(lcEmpresa);
1638  if (string.IsNullOrWhiteSpace(lcEmpresa) || lcEmpresa != lcEmpNew)
1639  FUNCTIONS._GuardarConfigIni("[EMPRESA]", lcEmpNew, _cPathInicio, "config.ini");
1640 
1641  return lcEmpNew;
1642  }
1643  }
1644 }
bool _AutWin
Conexión por autentificación de Windows si o no.
Definition: RegCfgCliSrv.cs:50
static string GenerarChecksumOpciones(string tcOpcion, string tcSalt)
PE-102978: Generar una función hash segura a partir de una opción y un salt
Classe empresa basada en sage.ew.ewmante
Definition: clsEmpresa.cs:48
string _Empresa
Empresa con la que trabajara el formulario
Definition: frmLogin.cs:57
static AddonsController Instance
Instancia al objeto singleton Addons
string _Ip
Servidor de la base de datos
Definition: RegCfgCliSrv.cs:30
Splash de Sage 50
Definition: frmSplash.cs:20
Argumentos para los eventos lanzados por el addons en caso de error
static bool ReCargarDiccionarios()
Método para volver a realizar la carga de diccionarios, por si hay que actualizar algun valor (PE-908...
virtual void RegisterTypes()
Registra los tipos
bool _CargarAddOns(FunctionsDependencies loFuntionsDependencies)
Carga addons
bool _Add(Notificacion toNotificacion)
Añade una notificacion al sistema
Definition: Notifica.cs:929
Clase que captura y filtra mensajes de Windows (Capturar eventos).
static System.Drawing.Icon Sage50code
Busca un recurso adaptado de tipo System.Drawing.Icon similar a (Icono).
Clase Singleton para la carga de los diccionarios
Clase de recurso fuertemente tipado, para buscar cadenas traducidas, etc.
Clase para la clase de negocio de la configuración del live update
Definition: LiveUpdate.cs:17
string _Server
Tipo de servidor de la base de datos
Definition: RegCfgCliSrv.cs:45
PE-85105: Clase donde se implementaran aquellas funciones de encriptación y desencriptación utilizand...
Definition: Criptografia.cs:15
NotificaIconos
Iconos predefinidos para notificaciones Mirar sage.ew.objects.widgets.Notificador._GetDataTableSeleccion()
Definition: Notifica.cs:27
static bool CargarDiccionarios(string tcempresa, string tcCajaTpv)
A partir de un código de empresa y un código de caja nos carga las variables de empresa, mascaras, anchuras de campos standar y de TPV
Clase para uso de funciones genéricas
Definition: functions.cs:146
Formulario de inicio de sesión del usuario
Definition: frmLogin.cs:28
IAddonsManager AddonsManager
Gestor de Addons
Clase para el traspaso de info en las barras de progreso
Definition: ProcessBar.cs:433
Clase para gestionar registros del CFGCLISRV.XML.
Definition: RegCfgCliSrv.cs:15
Clase para el inicio de Sage 50
Definition: main_s50.cs:33
string _Password
Password
Definition: RegCfgCliSrv.cs:25
Clase para gestión de notificaciones
Definition: Notifica.cs:645
static Notifica _This
Instancia estática del objeto usuario con los datos del usuario actual (wc_usuario) ...
Definition: Notifica.cs:675
int _Port
Puerto del servidor de la base de datos.
Definition: RegCfgCliSrv.cs:35
static void _RegisterReportsDataSourceIni(String lcPathSageReports)
Registra el Data Provider en el SageReport
Definition: Report.cs:1718
string _Odbc
Cadena ODBC
Definition: RegCfgCliSrv.cs:55
bool _CargarAddons_WaitAll()
Esperar a que se hayan cargado todos los addons
Registra los tipos de Sage50
Clase estática de acceso a Base de Datos
Definition: DB.cs:26