ConsultasBrowsers.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using sage.ew.ewbase;
6 using System.Text.RegularExpressions;
7 using sage.ew.db;
8 using System.Data;
9 using sage.ew.global;
10 
11 namespace sage.ew.formul
12 {
16  public class ConsultasBrowsers : ewMante
17  {
18  #region CONSTRUCTORS
19 
24  {
25  this._DataBase = "COMUNES";
26  this._Tabla = "BROWSERS";
27  this._Clave = "CODIGO";
28  this._TituloMantenimiento = "Mantenimiento de consultas personalizadas";
29  this._FormManteBaseType = typeof(Forms.frmConsultasBrowsers);
30  this._Pantalla = "BROWSERS";
31  this._TituloCabecera = "Consultas de Browsers";
32  this._TituloMenu = "Consultas de Browsers"; // PE-95692. Error de sintaxis
33  }
34 
38  public ConsultasBrowsers(string tcCodigo) :
39  this()
40  {
41  // Cargamos el registro correspondiente al tcCodigo
42  this._Codigo = tcCodigo;
43  }
44 
45  #endregion CONSTRUCTORS
46 
47 
48 
49  #region PROPIETATS
50 
51  private BrowserColumnsConfig _oBrowserColumnsConfig = null;
52 
56  public BrowserColumnsConfig _ColumnsConfig
57  {
58  get
59  {
60  string mascaras = (_lisCampos.ContainsKey("MASCARAS") ? _lisCampos["MASCARAS"]._NewVal.ToString() : "");
61  if (_oBrowserColumnsConfig == null) _oBrowserColumnsConfig = new BrowserColumnsConfig(mascaras);
62  return _oBrowserColumnsConfig;
63  }
64  set
65  {
66  _oBrowserColumnsConfig = value;
67  _RefreshBrowserColumnsConfig();
68  }
69  }
70 
75  {
76  _lisCampos["MASCARAS"]._NewVal = _lisCampos.ContainsKey("MASCARAS") && _oBrowserColumnsConfig is BrowserColumnsConfig ? _oBrowserColumnsConfig.ToString() : "";
77  }
78 
82  public string _Consulta
83  {
84  get
85  {
86  if (_lisCampos.ContainsKey("CONSULTA"))
87  {
88  return _lisCampos["CONSULTA"]._NewVal.ToString();
89  }
90  else
91  {
92  return String.Empty;
93  }
94  }
95  set
96  {
97  if (_lisCampos.ContainsKey("CONSULTA"))
98  {
99  _lisCampos["CONSULTA"]._NewVal = value;
100  }
101  }
102  }
103 
107  public string _FieldTabla
108  {
109  get
110  {
111  if (_lisCampos.ContainsKey("TABLA"))
112  {
113  return _lisCampos["TABLA"]._NewVal.ToString().ToUpper();
114  }
115  else
116  {
117  return String.Empty;
118  }
119  }
120  set
121  {
122  if (_lisCampos.ContainsKey("TABLA"))
123  {
124  _lisCampos["TABLA"]._NewVal = value;
125  }
126  }
127  }
128 
132  public string _Claves
133  {
134  get
135  {
136  if (_lisCampos.ContainsKey("CLAVES"))
137  {
138  return _lisCampos["CLAVES"]._NewVal.ToString().ToUpper();
139  }
140  else
141  {
142  return String.Empty;
143  }
144  }
145  set
146  {
147  if (_lisCampos.ContainsKey("CLAVES"))
148  {
149  _lisCampos["CLAVES"]._NewVal = value;
150  }
151  }
152  }
153 
154  private string _cBrowserClave = "";
158  public string _BrowserClave
159  {
160  get { return _cBrowserClave; }
161  set { _cBrowserClave = value; }
162  }
163 
164 
165  private string _cTablaConsulta = "";
169  public string _TablaConsulta
170  {
171  get { return _cTablaConsulta; }
172  set
173  {
174  if (value != null)
175  {
176  _cTablaConsulta = value.ToUpper();
177  }
178  }
179  }
180 
181  private string _cDataBaseConsulta = "";
185  public string _DataBaseConsulta
186  {
187  get { return _cDataBaseConsulta; }
188  set
189  {
190  if (value == null)
191  value = String.Empty;
192  _cDataBaseConsulta = value.ToUpper();
193  }
194  }
195 
196  private string _cTituloBrowser = "";
200  public string _TituloBrowser
201  {
202  get { return _cTituloBrowser; }
203  set { _cTituloBrowser = value; }
204  }
205 
209  public string _RequiredFieldsForBrowserExtensions { get; set; }
210 
214  public List<string> _CamposResultado = new List<string>();
215 
216  #endregion PROPIETATS
217 
218 
219 
220  #region OVERRIDES
221 
226  public override void _New(string tcCodigo = "")
227  {
228  base._New(tcCodigo);
229 
230  // Assigno el valor a tabla
231  _FieldTabla = _TablaConsulta.ToUpper();
232  }
233 
237  public override void _Load()
238  {
239  base._Load();
240 
241  _oBrowserColumnsConfig = null;
242  }
243 
248  public override bool _Save()
249  {
250  // Comprovacions per guardar
251  if ((_Estado == _EstadosMantenimiento.EntrandoNuevo || _Estado == _EstadosMantenimiento.EditandoRegistro))
252  {
253  if (string.IsNullOrWhiteSpace(this._Consulta))
254  {
255  this._Error_Message = "Es obligatorio introducir una consulta.";
256  return false;
257  }
258 
259  // Comprobar si hi ha error a la consulta
260  string lcMensajeError = "";
261  string lcSql = this._Consulta.ToUpper();
262  DataTable loResultat = new DataTable();
263 
264  if (!_ComprobarConsulta(ref lcSql, out lcMensajeError, ref loResultat))
265  {
266  this._Error_Message = "La consulta no es correcta. No se puede guardar.";
267  return false;
268  }
269 
270  // Comprovar si la clau està inclosa a la consulta
271  int lnPosSelect = this._Consulta.IndexOf("Select", StringComparison.OrdinalIgnoreCase);
272  int lnPosFrom = this._Consulta.IndexOf("From", StringComparison.OrdinalIgnoreCase);
273  string lcSelect = this._Consulta.Substring(lnPosSelect + 6, lnPosFrom - (lnPosSelect + 6));
274  int lnPosAll = lcSelect.IndexOf("*", StringComparison.OrdinalIgnoreCase);
275  if (lnPosAll == -1)
276  {
277  int lnPosClave = -1;
278  String lcClave, lcConsulta;
279  //PE-105884
280  if (_Hera && _TablaConsulta.ToUpper() == "CLIENTES")
281  {
282  lcConsulta = this._Consulta.ToLower();
283  MatchCollection loMatches = Regex.Matches(lcConsulta.Substring(0, lnPosFrom), @"\s+(as)\s+(?<alias>\w+)");
284  lcClave = "CLIENTEERP";
285 
286  foreach (Match loMatch in loMatches)
287  {
288  if (loMatch.Groups["alias"].Value == lcClave.ToLower()) lnPosClave = 0;
289  }
290  }
291  else
292  {
293  lnPosClave = lcSelect.IndexOf(_Clave, StringComparison.OrdinalIgnoreCase);
294  lcClave =_Clave;
295  }
296 
297  //if (lnPosClave == -1)
300  // if (!loResultat.Columns.Contains(_Clave.ToUpper()))
301  // {
302  // this._Error_Message = "El resultado de la consulta no contiene el campo clave (" + lcClave + "). No se puede guardar.";
303  // return false;
304  // }
305  }
306  }
307 
308  //Refrescamos el campo Mascaras
309  _RefreshBrowserColumnsConfig();
310 
311  bool saved = base._Save();
312 
313  if (saved)
314  {
315  // Borrar la configuración guardada por si se han cambiado campos...
316  string usuario = EW_GLOBAL._GetVariable("wc_usuario").ToString();
317  _Vista browserExtPos = new _Vista("COMUNES", "BROWSEREXTPOS", new Dictionary<string, object>() { { "Tabla", _TablaConsulta + "_" + _Codigo }, { "Usuario", usuario } });
318  if (browserExtPos._Reccount > 0)
319  {
320  browserExtPos._Delete();
321  browserExtPos._TableUpdate();
322  }
323  }
324 
325  return saved;
326  }
327 
332  public override bool _Delete()
333  {
334  bool lbDelete = false;
335 
336  lbDelete = base._Delete();
337 
338  if (lbDelete)
339  {
340  // PE-95727. Si és la consulta predeterminada,
341  string lcCodiConsulta = DB.SQLValor("USRBROWSER", new string[] { "USUARIO", "Upper(TABLA)" }, new string[] { global.EW_GLOBAL._GetVariable("wc_usuario").ToString(), _FieldTabla.ToUpper() }, "CODIGO", "COMUNES").ToString();
342  if (this._Codigo.Trim() == lcCodiConsulta.Trim())
343  {
344  // l'esborrem
345  _Borrar_Predeterminada();
346  }
347  }
348 
349  return lbDelete;
350  }
351 
355  public override void _Show(string tcCodigoConsulta = "")
356  {
357  _Codigo = tcCodigoConsulta;
358 
359  base._Show();
360  }
361 
362  #endregion OVERRIDES
363 
364 
365 
366  #region MÈTODES PUBLICS
367 
375  public bool _ComprobarConsulta(ref string tcConsulta, out string tcMensajeError, bool tbSoloComprobar = true)
376  {
377  bool lbCorrecte = false;
378  tcMensajeError = "";
379 
380  DataTable loResultat = new DataTable();
381 
382  // No cal que retorni cap registre
383  if (tbSoloComprobar)
384  {
385  // PE-104661. Añadir top 0 para que no devuelva ningún resultado
386  // CCR-Cambiar String.Replace por Regex.Replace para que no sea CS
387  tcConsulta = Regex.Replace(tcConsulta, "Select", "Select Top 0", RegexOptions.IgnoreCase);
388  }
389 
390  lbCorrecte = _ComprobarConsulta(ref tcConsulta, out tcMensajeError, ref loResultat);
391 
392  if (tbSoloComprobar)
393  {
394  // Quitar el top
395  // Cambiar String.Replace por Regex.Replace para que no sea CS
396  tcConsulta = Regex.Replace(tcConsulta, "Top 0 ", "", RegexOptions.IgnoreCase);
397  }
398  return lbCorrecte;
399  }
400 
408  public bool _ComprobarConsulta(ref string tcConsula, out string tcMensajeError, ref DataTable toResultat)
409  {
410  bool lbCorrecte = false;
411  string consultalocal = "";
412  tcMensajeError = "";
413 
414  toResultat = new DataTable();
415 
416  // Trec els espais duplicats a la consulta
417  tcConsula = Regex.Replace(tcConsula, @"\s+", " ");
418 
419  try
420  {
421  // Només busquem els alias de base de dades i els canviem pel seu nom
422  foreach (KeyValuePair<string, string> loDB in DB._oAliasDB)
423  {
424  tcConsula = QuitarAsBD(tcConsula, loDB.Key.Trim());
425  tcConsula = Regex.Replace(tcConsula, loDB.Key.Trim() + "!", loDB.Value.Trim(), RegexOptions.IgnoreCase);
426  }
427 
428  consultalocal = tcConsula;
429  if (!EW_GLOBAL._ReplaceVariables(ref consultalocal))
430  {
431  tcMensajeError = "Falta el corchete de cierre en alguna variable global.";
432  return false;
433  }
434 
435  // Executem la consulta
436  if (DB.SQLExec(consultalocal, ref toResultat) && toResultat != null)
437  {
438  // No comprovem resultats, només que no falli
439  lbCorrecte = true;
440  }
441  }
442  catch (Exception ex)
443  {
444  tcMensajeError = ex.Message;
445  }
446 
447  _CamposResultado.Clear();
448 
449  if (lbCorrecte)
450  {
451  // Extraer los campos para que puedan seleccionar la clave principal
452  if (toResultat.Columns.Count > 0)
453  {
454  _CamposResultado.Add("");
455  }
456 
457  // Aunque he intentado controlarlo, sqlserver cambia el nombre del alias repetido. le añade un ordinal
458  foreach (DataColumn camp in toResultat.Columns)
459  {
460  if (_CamposResultado.Contains(camp.ColumnName.Trim().ToUpper()))
461  {
462  tcMensajeError = "Ha incluido el mismo campo o el mismo alias más de una vez en el resultado de la consulta.";
463  lbCorrecte = false;
464  _CamposResultado.Clear();
465  break;
466  }
467 
468  _CamposResultado.Add(camp.ColumnName.Trim().ToUpper());
469  }
470  }
471 
472  // Reemplazar las variables globales
473 
474  return lbCorrecte;
475  }
476 
480  public void _Predeterminar()
481  {
482  string lcUsuario = global.EW_GLOBAL._GetVariable("wc_usuario").ToString();
483 
484  // Primer esborro el que hi pugui haver
485  _Borrar_Predeterminada();
486 
487  // i inserto l'actual
488  DB.SQLExec("Insert Into " + DB.SQLDatabase("COMUNES", "USRBROWSER") +
489  "(USUARIO, TABLA, CODIGO) " +
490  "Values (" + DB.SQLString(lcUsuario) + "," + DB.SQLString(_FieldTabla.ToUpper()) + "," + DB.SQLString(_Codigo) + ")");
491  }
492 
497  {
498  string lcUsuario = global.EW_GLOBAL._GetVariable("wc_usuario").ToString();
499 
500  DB.SQLExec("Delete From " + DB.SQLDatabase("COMUNES", "USRBROWSER") +
501  " Where USUARIO = " + DB.SQLString(lcUsuario) +
502  " And Upper(TABLA) = " + DB.SQLString(_FieldTabla.ToUpper()));
503  }
504 
509  public DataTable _GetDataTablePredeterminado()
510  {
511  DataTable ldDTP = new DataTable();
512  string lcMissatge="";
513  bool lbCorrecte = false;
514 
515  string lcCodiConsulta = DB.SQLValor("USRBROWSER", new string[] { "USUARIO", "Upper(TABLA)" }, new string[] { global.EW_GLOBAL._GetVariable("wc_usuario").ToString(), _FieldTabla.ToUpper() }, "CODIGO", "COMUNES").ToString();
516 
517  if (!string.IsNullOrWhiteSpace(lcCodiConsulta))
518  {
519  string lcSql = DB.SQLValor("BROWSERS", "CODIGO", lcCodiConsulta, "CONSULTA", "COMUNES").ToString();
520 
521  if (!string.IsNullOrWhiteSpace(lcSql))
522  {
523  // Comprova i recupera les dades
524  lbCorrecte = _ComprobarConsulta(ref lcSql, out lcMissatge, ref ldDTP);
525  }
526 
527  return ldDTP;
528  }
529  else
530  return null;
531  }
532 
537  public List<string> _GetConsultasByTabla()
538  {
539  List<string> lstConsultas = new List<string>(){""};
540  DataTable ldtConsultas = _GetDataTableConsultasByTabla();
541 
542  if (ldtConsultas != null && ldtConsultas.Rows.Count > 0)
543  {
544  lstConsultas = ldtConsultas.Rows.OfType<DataRow>().Select(dr => dr.Field<string>(1)).ToList();
545  }
546 
547  // PE-95742. Añadir un primer elemento en blanco para poder cargar la consulta original
548  lstConsultas.Add("");
549  lstConsultas.Sort();
550 
551  return lstConsultas;
552  }
553 
558  public DataTable _GetDataTableConsultasByTabla()
559  {
560  DataTable ldtConsultas = new DataTable();
561  string usuario = global.EW_GLOBAL._GetVariable("wc_usuario").ToString();
562 
563  string lcSql = "Select browsers.codigo, browsers.nombre, CAST( case when usrbrowser.codigo is null then 0 else 1 end as bit) as predet " +
564  "From " + DB.SQLDatabase("COMUNES", "BROWSERS") + " browsers " +
565  "Left Join " + DB.SQLDatabase("COMUNES", "USRBROWSER") + " usrbrowser On usrbrowser.codigo = browsers.codigo " +
566  " and usrbrowser.usuario = " + DB.SQLString(usuario) +
567  " and Upper(usrbrowser.tabla) = " + DB.SQLString(_TablaConsulta.ToUpper()) + " " +
568  "Where Upper(browsers.tabla) = " + DB.SQLString(_TablaConsulta.ToUpper()) +
569  "Order by browsers.codigo";
570 
571  DB.SQLExec(lcSql, ref ldtConsultas);
572 
573  return ldtConsultas;
574  }
575 
581  {
582  //string lcMissatge = "";
583  //bool lbCorrecte = false;
584 
585  string lcCodiConsulta = DB.SQLValor("USRBROWSER", new string[] { "USUARIO", "Upper(TABLA)" }, new string[] { global.EW_GLOBAL._GetVariable("wc_usuario").ToString(), _TablaConsulta.ToUpper() }, "CODIGO", "COMUNES").ToString();
586 
587  return lcCodiConsulta;
588  }
589 
595  {
596  //string lcMissatge = "";
597  //bool lbCorrecte = false;
598 
599  string lcCodiConsulta = DB.SQLValor("USRBROWSER", new string[] { "USUARIO", "Upper(TABLA)" }, new string[] { global.EW_GLOBAL._GetVariable("wc_usuario").ToString(), _TablaConsulta.ToUpper() }, "CODIGO", "COMUNES").ToString();
600 
601  if (!string.IsNullOrWhiteSpace(lcCodiConsulta))
602  {
603  string lcNombre = DB.SQLValor("BROWSERS", "CODIGO", lcCodiConsulta, "NOMBRE", "COMUNES").ToString();
604 
605  //if (!string.IsNullOrWhiteSpace(lcNombre))
606  //{
607  // // Comprova i recupera les dades
608  // lbCorrecte = _ComprobarConsulta(ref lcNombre, out lcMissatge, false);
609  //}
610 
611  return lcNombre;
612  }
613  else
614  return "";
615  }
616 
621  public string _GetConsultaByCodigo(string tcCodigoConsulta, bool soloComprobar = false)
622  {
623  // PE-104661. Añadir parametro soloComprobar para que la consulta no devuelva registros
624  string lcMissatge = "";
625  string lcSql = "";
626  bool lbCorrecte = false;
627 
628  string codi = tcCodigoConsulta; //DB.SQLValor("BROWSERS", "NOMBRE", tcCodigoConsulta, "CODIGO", "COMUNES").ToString();
629 
630  if (!string.IsNullOrWhiteSpace(codi))
631  {
632  // Carreguem el registre
633  this._Codigo = codi;
634  lcSql = this._Consulta;
635 
636  if (!string.IsNullOrWhiteSpace(lcSql))
637  {
638  // Comprovar retornos de carro...
639  lcSql = lcSql.Trim().Replace("\r", " ").Replace("\n", " ");
640 
641  // Comprova i recupera les dades
642  lbCorrecte = _ComprobarConsulta(ref lcSql, out lcMissatge, soloComprobar);
643  }
644  }
645 
646  if (lbCorrecte)
647  return lcSql;
648  else
649  return "";
650  }
651 
656  public string _GetConsultaByName(string tcNombreConsulta, bool soloComprobar = false)
657  {
658  // PE-104661. Añadir parametro soloComprobar para que la consulta no devuelva registros
659  string lcMissatge = "";
660  string lcSql = "";
661  bool lbCorrecte = false;
662 
663  string codi = DB.SQLValor("BROWSERS", "NOMBRE", tcNombreConsulta, "CODIGO", "COMUNES").ToString();
664 
665  if (!string.IsNullOrWhiteSpace(codi))
666  {
667  // Carreguem el registre
668  this._Codigo = codi;
669  lcSql = this._Consulta;
670 
671  if (!string.IsNullOrWhiteSpace(lcSql))
672  {
673  // Comprovar retornos de carro...
674  lcSql = lcSql.Trim().Replace("\r", " ").Replace("\n", " ");
675 
676  // Comprova i recupera les dades
677  lbCorrecte = _ComprobarConsulta(ref lcSql, out lcMissatge, soloComprobar);
678  }
679  }
680 
681  if (lbCorrecte)
682  return lcSql;
683  else
684  return "";
685  }
686 
687  #endregion MÈTODES PUBLICS
688 
689  private string QuitarAsBD(string tcConsula, string basedatos)
690  {
691  basedatos = basedatos.ToUpper();
692 
693  // Busco totes les base de dades per comprovar si tenen la paraula ' as '
694  int posbd = 0;
695  do
696  {
697  posbd = tcConsula.ToUpper().IndexOf(basedatos + "!", posbd + 1);
698  if (posbd > -1)
699  {
700  // Busco el primer espai
701  int pos1 = tcConsula.ToUpper().IndexOf(" ", posbd);
702  if (pos1 > -1)
703  {
704  // Busco el seguent espai
705  int pos2 = tcConsula.ToUpper().IndexOf(" ", pos1 + 1);
706  if (pos2 > -1)
707  {
708  // Comprobo si la paraula del mig és ' as '
709  if (tcConsula.Substring(pos1 + 1, pos2 - pos1 - 1).ToLower() == "as")
710  {
711  // La trec
712  tcConsula = tcConsula.Substring(0, pos1) + tcConsula.Substring(pos2);
713  }
714  }
715  }
716  }
717  else
718  break;
719 
720  } while (true);
721 
722  return tcConsula;
723  }
724 
725  }
726 }
DataTable _GetDataTableConsultasByTabla()
Devuelve una lista con las consultas definidas para la tabla
Clase de negocio base para mantenimientos
Definition: clsEwBase.cs:1643
bool _ComprobarConsulta(ref string tcConsula, out string tcMensajeError, ref DataTable toResultat)
Comprueba que la consulta sea correcta
Objeto para la consulta, edición y actualización de datos de tablas (simula vistas de Fox) ...
Definition: Vista.cs:13
Mantenimiento de consultas para el browser
override string ToString()
Devuelve la configuración en formato JSON
void _Predeterminar()
Inserta en la tabla UsrBrowser el registro actual para que se utilice como predeterminado ...
Clase para gestíonar la configuración de las columnas del brownser
string _GetConsultaByCodigo(string tcCodigoConsulta, bool soloComprobar=false)
Devuelve la consulta SQL por nombre
override bool _Save()
Guarda el registro actual
string _GetConsultaPredeterminadaCodigo()
Devuelve el codigo la consulta SQL predterminada
string _GetConsultaPredeterminada()
Devuelve el nombre la consulta SQL predterminada
List< string > _GetConsultasByTabla()
Devuelve una lista con las consultas definidas para la tabla
ConsultasBrowsers(string tcCodigo)
Inicializa el mantenimiento de consultas y carga el registro correspondinete
override void _Show(string tcCodigoConsulta="")
Muestra el formulario asociado
bool _Delete()
Elimina la fila actual
Definition: Vista.cs:1035
int _Reccount
Cantidad de registros recuperados
Definition: Vista.cs:48
override void _Load()
Sobreescribir el metodo _Load para vaciar _oBrownserColumnsConfig
bool _ComprobarConsulta(ref string tcConsulta, out string tcMensajeError, bool tbSoloComprobar=true)
Comprueba que la consulta sea correcta
ConsultasBrowsers()
Inicializa el mantenimiento de consultas
void _RefreshBrowserColumnsConfig()
Refrescar el valor del campo
void _Borrar_Predeterminada()
Borra la consulta predeterminada del usuario
override bool _Delete()
Eliminar el registro y las predeterminadas de los usuarios
_EstadosMantenimiento
Declaro un enum para los estados del mantenimiento.
Definition: clsEwBase.cs:1671
DataTable _GetDataTablePredeterminado()
Devuelve un datatable con el resultado de la consulta
bool _TableUpdate()
Guarda los registros a la tabla
Definition: Vista.cs:1266
override void _New(string tcCodigo="")
Nuevo registro.
string _GetConsultaByName(string tcNombreConsulta, bool soloComprobar=false)
Devuelve la consulta SQL por nombre