FunctionsGestDoc.cs
1 # region Usings
2 using System;
3 using System.Collections.Generic;
4 using System.Linq;
5 using System.Text;
6 using System.Data;
7 using sage.ew.db;
8 using sage.ew.global;
9 using System.Drawing;
10 using Microsoft.Win32;
11 using System.Runtime.InteropServices;
12 using sage.ew.interficies;
13 using System.IO;
15 using System.Reflection;
16 using System.ComponentModel;
17 using sage.ew.docventatpv;
18 using sage.ew.docsven;
19 using sage.ew.stocks;
20 using sage.ew.ewbase;
21 using sage.ew.docscompra;
22 using sage.ew.functions;
23 using sage.ew.listados.Clases;
24 using sage.ew.enumerations;
25 #endregion Usings
26 
27 namespace sage.addons.gestdoc.Negocio.Clases
28 {
32  public static partial class FunctionsGestDoc
33  {
34  #region Importación de dll
35  [DllImport("Shell32", CharSet = CharSet.Auto)]
36  private static extern int ExtractIconEx(
37  string lpszFile,
38  int nIconIndex,
39  IntPtr[] phIconLarge,
40  IntPtr[] phIconSmall,
41  int nIcons);
42 
43  [DllImport("user32.dll", EntryPoint = "DestroyIcon", SetLastError = true)]
44  private static extern int DestroyIcon(IntPtr hIcon);
45  #endregion Importación de dll
46 
56  public static DataTable _Children(eTipoConsultaCarpetasDocumentos teTipoCarpetasDocumentos = eTipoConsultaCarpetasDocumentos.Nivel, int tnIdParentCarpeta = 1, string tcUsuario = "", bool tlFiltrarNivelAcceso = true, bool tlDelete = false)
57  {
58  DataTable ldtCarpetas = new DataTable();
59  DataTable ldtDocumentos = new DataTable();
60  DataTable ldtCarpetasDocs = new DataTable();
61 
62  string lcUsuario;
63  bool llOk, llOrphan;
64 
65  if (string.IsNullOrWhiteSpace(tcUsuario))
66  lcUsuario = Convert.ToString(EW_GLOBAL._GetVariable("wc_usuario"));
67  else
68  lcUsuario = tcUsuario;
69 
70  llOrphan = (teTipoCarpetasDocumentos == eTipoConsultaCarpetasDocumentos.Nivel && tnIdParentCarpeta == 1 && lcUsuario != "SUPERVISOR"); // Al consultar las carpetas del nivel si estamos en Documentos ha de presentar las carpetas huérfanas
71 
72  llOk = _Carpetas(ref ldtCarpetas, teTipoCarpetasDocumentos, tnIdParentCarpeta, lcUsuario, tlOrphan: llOrphan);
73  llOk = llOk && _Documentos(ref ldtDocumentos, teTipoCarpetasDocumentos, tnIdParentCarpeta, lcUsuario, tlDelete);
74 
75  if (llOk)
76  {
77  _AddColumnsIconDocumentos(ldtCarpetas);
78  _AddColumnDatatable(ldtCarpetas, "useract", "System.String");
79  _AddColumnDatatable(ldtCarpetas, "description", "System.Object");
80  _AddColumnDatatable(ldtCarpetas, "extension", "System.Object");
81 
82  ldtCarpetasDocs = ldtCarpetas.Clone(); // Clonamos la estructura del DataTable
83 
84  int lnNivel;
85  if (ldtCarpetas.Rows.Count > 0) // Ahora añadiremos las carpetas y los documentos si es necesario
86  lnNivel = Convert.ToInt32(ldtCarpetas.Rows[0]["nivel"]);
87  else
88  {
89  DataTable ldtCarpeta = new DataTable();
90  _Carpetas(ref ldtCarpeta, teTipoCarpetasDocumentos, tnIdParentCarpeta, lcUsuario, tlOrphan: llOrphan); // En un principio no seria necesario, siempre debería de tener acceso, si estamos desde la capa visual
91 
92  if (ldtCarpeta.Rows.Count > 0)
93  lnNivel = Convert.ToInt32(ldtCarpeta.Rows[0]["nivel"]);
94  else
95  lnNivel = 0;
96  }
97 
98  _ChildrenCarpetasDocumentos(teTipoCarpetasDocumentos, tnIdParentCarpeta, lnNivel, ref ldtCarpetasDocs, ref ldtCarpetas, ref ldtDocumentos, tlOrphan: llOrphan);
99 
100  if (!tlDelete && tlFiltrarNivelAcceso) // En el borrado de una carpeta ha de controlar si hay carpetas que no podamos eliminar
101  _NivelAccesoCarpetas(ref ldtCarpetasDocs, teTipoCarpetasDocumentos, tnIdParentCarpeta, lcUsuario);
102  }
103 
104  return ldtCarpetasDocs;
105  }
106 
112  public static void _AddColumnsIconDocumentos(DataTable tdtGestDoc, bool tlIconsEdition = true)
113  {
114  _AddColumnDatatable(tdtGestDoc, "iconSmall", "System.Object");
115  _AddColumnDatatable(tdtGestDoc, "iconLarge", "System.Object");
116 
117  if (tlIconsEdition)
118  {
119  _AddColumnDatatable(tdtGestDoc, "iconSmallEdition", "System.Object");
120  _AddColumnDatatable(tdtGestDoc, "iconLargeEdition", "System.Object");
121  _AddColumnDatatable(tdtGestDoc, "iconSmallEditionByOtherUSer", "System.Object");
122  _AddColumnDatatable(tdtGestDoc, "iconLargeEditionByOtherUSer", "System.Object");
123  }
124  }
125 
126 
135  public static bool _NivelAccesoCarpetas(ref DataTable tdtCarpetasDocs, eTipoConsultaCarpetasDocumentos teTipoCarpetasDocumentos, int tnIdParentCarpeta, string tcUsuario)
136  {
137  if (tdtCarpetasDocs.Rows.Count == 0)
138  return true;
139 
140  // Si somos el usuario supervisor ya podemos salir, tenemos acceso a todo el arbol
141  if (tcUsuario == "SUPERVISOR")
142  return true;
143 
144  var ldtCarpetas = tdtCarpetasDocs.AsEnumerable().Where(myRow => ((myRow.Field<int>("nivel") == -1))); // Necesario para poder realizar la asignación
145 
146  DataTable ldtCarpetasDocs = tdtCarpetasDocs.Clone();
147 
148  if (tnIdParentCarpeta == 1) // Si presentamos en el ID 1 ha de presentar únicamente las carpetas que cuelgan de "Documentos" y las carpetas huérfanas. En la carpeta 1 no podemos subir documentos
149  {
150  if (teTipoCarpetasDocumentos == eTipoConsultaCarpetasDocumentos.TodosNiveles) // Devuelve las carpetas/documentos existentes a partir de un Id parent en todos los niveles recursivo por debajo del parent.
151  ldtCarpetasDocs = tdtCarpetasDocs.AsEnumerable().Where(myRow => (myRow.Field<bool>("carpeta") == true && myRow.Field<int>("nivel") >= 1 && (myRow.Field<int>("id_parent") == tnIdParentCarpeta || myRow.Field<bool>("orphan")))).__CopyToDataTable();
152  else
153  ldtCarpetasDocs = tdtCarpetasDocs.AsEnumerable().Where(myRow => ((myRow.Field<int>("id_parent") == tnIdParentCarpeta && myRow.Field<int>("nivel") >= 1) || myRow.Field<bool>("orphan"))).__CopyToDataTable(); // Consultamos carpetas y documentos del Id Parent actual y las carpetas huérfanas
154  }
155  else
156  ldtCarpetasDocs = tdtCarpetasDocs.AsEnumerable().Where(myRow => (myRow.Field<int>("id_parent") == tnIdParentCarpeta && myRow.Field<int>("nivel") >= 1)).__CopyToDataTable(); // Consultamos carpetas y documentos del Id Parent actual
157 
158  tdtCarpetasDocs.Clear();
159  tdtCarpetasDocs.Dispose();
160 
161  tdtCarpetasDocs = ldtCarpetasDocs;
162 
163  return true;
164  }
165 
176  public static bool _Carpetas(ref DataTable tdtCarpetas, eTipoConsultaCarpetasDocumentos teTipoCarpetasDocumentos, int tnIdParentCarpeta, string tcUsuario, bool tlFilterId = false, bool tlOrphan = false)
177  {
178  string lcSql, lcNivelUsuarioCarpetas, lcLeftNivelCarpetas = "";
179  bool llOk;
180 
181  if (tcUsuario == "SUPERVISOR")
182  lcNivelUsuarioCarpetas = ", 2 AS nivel "; // 2. Acceso Total
183  else
184  {
185  lcNivelUsuarioCarpetas = "," + DB.SQLNvl("cu.nivel", "0") + " AS nivel "; // 1 Solo lectura, 2 Total , 0 Sin Registro Denegado
186  lcLeftNivelCarpetas = "LEFT JOIN " + DB.SQLDatabase("GESTDOC", "CARP_USER") + " cu ON c.id = cu.idcarpeta AND cu.usuario = " + DB.SQLString(tcUsuario);
187  }
188 
189  lcSql = "SELECT c.id, c.nombre, c.parent AS id_parent, c.modified, c.created, " + DB.SQLTrue() + " AS carpeta, " + DB.SQLFalse() + " AS orphan " + lcNivelUsuarioCarpetas +
190  " FROM " + DB.SQLDatabase("GESTDOC", "CARPETAS") + " c " + lcLeftNivelCarpetas;
191 
192  if (teTipoCarpetasDocumentos == eTipoConsultaCarpetasDocumentos.Nivel) // Consultamos únicamente la carpetas del parent que nos llega
193  {
194  if (tlFilterId)
195  lcSql += " WHERE c.id = " + DB.SQLString(tnIdParentCarpeta); // Consultaremos la carpeta actual
196  else
197  {
198  // Si filtramos por la carpeta documentos ---> ID == 1. ha de presentar las carpetas huerfanas
199  if (!tlOrphan)
200  lcSql += " WHERE c.parent = " + DB.SQLString(tnIdParentCarpeta); // Únicamente las carpetas del primer nivel, sin posibilidad de añadir nuevos documentos
201  }
202  }
203 
204  lcSql += " ORDER BY c.parent, c.nombre"; // Ordenamos las carpetas
205 
206  llOk = DB.SQLExec(lcSql, ref tdtCarpetas); // Consultamos las carpetas
207 
208  return llOk;
209  }
210 
220  public static bool _Documentos(ref DataTable tdtDocumentos, eTipoConsultaCarpetasDocumentos teTipoCarpetasDocumentos, int tnIdParent, string tcUsuario, bool tlDelete)
221  {
222  string lcSql, lcFields, lcLeft = "";
223  bool llOk = true;
224  DataTable ldtDocumentos = new DataTable();
225 
226  if (tcUsuario == "SUPERVISOR")
227  lcFields = ", 2 AS nivel "; // 2. Acceso Total
228  else
229  {
230  lcFields = "," + DB.SQLNvl("du.nivel", "0") + " AS nivel "; // 1 Solo lectura, 2 Total , 0 Sin Registro Denegado
231  lcLeft = "LEFT JOIN " + DB.SQLDatabase("GESTDOC", "DOC_USER") + " du ON c.id = du.iddoc AND du.usuario = " + DB.SQLString(tcUsuario);
232  }
233 
234  lcSql = "SELECT c.id, c.nom_doc AS nombre, c.extension, c.carpeta as id_parent, c.modified, c.created, " + DB.SQLFalse() + " AS carpeta," + DB.SQLFalse() + " AS orphan, " +
235  " de.ejercicio, d.useract " + lcFields +
236  " FROM " + DB.SQLDatabase("GESTDOC", "DOCUMENT_C") + " c" +
237  " LEFT JOIN " + DB.SQLDatabase("GESTDOC", "DOCUMENT_D") + " d ON c.id = d.iddoc AND c.version = d.version "+
238  " LEFT JOIN " + DB.SQLDatabase("GESTDOC", "DOC_ENLACE") + " de ON c.id = de.iddoc "+ // AND (de.ejercicio = " + DB.SQLString(lcAny) + " OR de.ejercicio = 0) " +
239  lcLeft;
240 
241  if (teTipoCarpetasDocumentos == eTipoConsultaCarpetasDocumentos.Nivel) // Únicamente me interesan los documento de la carpeta que tenemos en el Id de la carpeta parent
242  lcSql += " WHERE c.carpeta = " + DB.SQLString(tnIdParent);
243 
244  lcSql += " ORDER BY c.carpeta, c.nom_doc"; // Ordenamos los documentos
245 
246  llOk = DB.SQLExec(lcSql, ref ldtDocumentos); // Consultamos los documentos
247 
248  if (llOk)
249  {
250  if (ldtDocumentos.Rows.Count > 0)
251  {
252  List<Int16> lstEjercicios = new List<Int16>() { 0, Convert.ToInt16(Convert.ToString(EW_GLOBAL._GetVariable("wc_any"))) };
253  tdtDocumentos = ldtDocumentos.AsEnumerable().Where(row => (row["ejercicio"] == DBNull.Value) || lstEjercicios.Contains(Convert.ToInt16(row["ejercicio"]))).__CopyToDataTable(); // Excluimos los documentos de otros ejercicios
254 
255  if (tdtDocumentos.Rows.Count == 0) // Si no tenemos registros la función "__CopyToDataTable" no clona la estructura del datatable
256  tdtDocumentos = ldtDocumentos.Clone();
257  }
258  else
259  tdtDocumentos = ldtDocumentos.Copy();
260 
261  FUNCTIONS._DisposeDatatable(ldtDocumentos);
262  }
263 
264  return llOk;
265  }
266 
277  public static void _ChildrenCarpetasDocumentos(eTipoConsultaCarpetasDocumentos teTipoCarpetasDocumentos, int tnId_Parent, int tnNivel, ref DataTable tdtCarpetasDocs, ref DataTable tdtCarpetas, ref DataTable tdtDocumentos, bool tlOrphan = false)
278  {
279  if ((tlOrphan && tnId_Parent == 1) || (!tlOrphan))
280  {
281  _ChildrenDocumentos(tnId_Parent, tnNivel, ref tdtCarpetasDocs, ref tdtDocumentos); // Consultamos los documentos de la carpeta actual y los agregamos
282  }
283 
284  DataRow[] ldrCarpetas = tdtCarpetas.Select("id_parent = " + Convert.ToString(tnId_Parent).Trim(), "nombre"); // Consultamos todas las carpetas con el parent que le pasamos. Ordenamos las carpetas por nombre
285 
286  if (ldrCarpetas != null && ldrCarpetas.Count() > 0)
287  {
288  int lnNivel;
289  int lnParent = tnId_Parent;
290  bool llAcceso;
291 
292  foreach (DataRow ldrCarpeta in ldrCarpetas)
293  {
294  llAcceso = (Convert.ToInt32(ldrCarpeta["nivel"]) > 0);
295 
296  if (llAcceso && tnNivel == 0) // Si no tenemos acceso en la carpeta padre y tenemos acceso en la carpeta actual es un registro que lo tenemos de marcar como huérfana
297  ldrCarpeta["orphan"] = true;
298 
299  tdtCarpetasDocs.ImportRow(ldrCarpeta); // Añadimos el registro de la carpeta
300 
301  if (teTipoCarpetasDocumentos == eTipoConsultaCarpetasDocumentos.TodosNiveles || tlOrphan) // Si añadimos todo (documentos y carpetas) o estamos borrando un carpeta, ha de añadir los documentos y las carpetas hijas. Si ha de presentar los huérfanos
302  {
303  lnParent = Convert.ToInt32(ldrCarpeta["id"]);
304  lnNivel = Convert.ToInt32(ldrCarpeta["nivel"]);
305  _ChildrenCarpetasDocumentos(teTipoCarpetasDocumentos, lnParent, lnNivel, ref tdtCarpetasDocs, ref tdtCarpetas, ref tdtDocumentos, tlOrphan: tlOrphan); // Buscaremos si la carpeta actual tiene carpetas hijas con el ID actual
306  }
307  }
308  }
309  }
310 
318  public static void _ChildrenDocumentos(int tnParentCarpeta, int tnNivel, ref DataTable tdtCarpetasDocs, ref DataTable tdtDocumentos)
319  {
320  DataRow[] ldrDocumentos = tdtDocumentos.Select("id_parent = " + Convert.ToString(tnParentCarpeta).Trim(), "nombre"); // Consultamos todos las documentos con el parent de la carpeta. Ordenamos los documentos por nombre
321 
322  if (ldrDocumentos != null && ldrDocumentos.Count() > 0)
323  {
324  bool llAcceso;
325  string lcExtension;
326  int lnRegDocumento;
327 
328  foreach (DataRow ldrDocumento in ldrDocumentos)
329  {
330  llAcceso = (Convert.ToInt32(ldrDocumento["nivel"]) > 0);
331 
332  if (llAcceso && tnNivel == 0) // Si no tenemos acceso en la carpeta padre y tenemos acceso al documento actual es un registro que lo tenemos de marcar como huérfano
333  ldrDocumento["orphan"] = true;
334 
335  lcExtension = Convert.ToString(ldrDocumento["extension"]).Trim();
336 
337  tdtCarpetasDocs.ImportRow(ldrDocumento); // Añadimos el documento
338 
339  FileExensionDocumento loFileExensionDocumento = _FileExtensionDocumento(lcExtension);
340 
341  if (loFileExensionDocumento != null)
342  {
343  lnRegDocumento = tdtCarpetasDocs.Rows.Count - 1;
344 
345  tdtCarpetasDocs.Rows[lnRegDocumento]["description"] = ""; // TODO: loFileExensionDocumento._Description;
346  tdtCarpetasDocs.Rows[lnRegDocumento]["IconSmall"] = loFileExensionDocumento._IconSmall;
347  tdtCarpetasDocs.Rows[lnRegDocumento]["IconLarge"] = loFileExensionDocumento._IconLarge;
348  tdtCarpetasDocs.Rows[lnRegDocumento]["IconSmallEdition"] = loFileExensionDocumento._IconSmallEdition;
349  tdtCarpetasDocs.Rows[lnRegDocumento]["IconLargeEdition"] = loFileExensionDocumento._IconLargeEdition;
350  tdtCarpetasDocs.Rows[lnRegDocumento]["IconSmallEditionByOtherUser"] = loFileExensionDocumento._IconSmallEditionByOtherUser;
351  tdtCarpetasDocs.Rows[lnRegDocumento]["IconLargeEditionByOtherUser"] = loFileExensionDocumento._IconLargeEditionByOtherUser;
352  }
353  }
354  }
355  }
356 
362  public static FileExensionDocumento _FileExtensionDocumento(string tcExtension)
363  {
364  bool llExist = false;
365  object loObjet = sage.ew.global.EW_GLOBAL._GetVariable("wo_FileExensionDocumentoGestdoc");
366  string lcExtension = tcExtension.ToLower();
367 
368  FileExensionDocumento loFileExensionDocumento = null;
369  Dictionary<string, FileExensionDocumento> dictFileExtension = null;
370 
371  if (loObjet != null)
372  {
373  dictFileExtension = (Dictionary<string, FileExensionDocumento>)loObjet;
374  if (dictFileExtension.ContainsKey(lcExtension))
375  llExist = dictFileExtension.TryGetValue(lcExtension, out loFileExensionDocumento);
376 
377  }
378  else
379  {
380  EW_GLOBAL.ValorEnClave_VarGlob("wo_FileExensionDocumentoGestdoc", new Dictionary<string, FileExensionDocumento>());
381 
382  loObjet = sage.ew.global.EW_GLOBAL._GetVariable("wo_FileExensionDocumentoGestdoc");
383  llExist = false;
384  }
385 
386  if (!llExist)
387  {
388  loFileExensionDocumento = new FileExensionDocumento();
389  loFileExensionDocumento._Extension = lcExtension;
390  loFileExensionDocumento._Description = _DescriptionExtension(lcExtension);
391  try
392  {
393  loFileExensionDocumento._IconSmall = _IconForExtension(lcExtension, eIconSize.Small);
394  loFileExensionDocumento._IconLarge = _IconForExtension(lcExtension, eIconSize.Large);
395  loFileExensionDocumento._IconSmallEdition = _IconOverlay(loFileExensionDocumento._IconSmall, sage.ew.images.Properties.Resources.Edition16x16);
396  loFileExensionDocumento._IconLargeEdition = _IconOverlay(loFileExensionDocumento._IconLarge, sage.ew.images.Properties.Resources.Edition32x32);
397  loFileExensionDocumento._IconSmallEditionByOtherUser = _IconOverlay(loFileExensionDocumento._IconSmall, sage.ew.images.Properties.Resources.EditionByOtherUser16x16);
398  loFileExensionDocumento._IconLargeEditionByOtherUser = _IconOverlay(loFileExensionDocumento._IconLarge, sage.ew.images.Properties.Resources.EditionByOtherUser32x32);
399 
400  }
401  catch (Exception loEx)
402  {
403  DB.Registrar_Error(loEx);
404  }
405 
406 
407  if (dictFileExtension == null)
408  dictFileExtension = (Dictionary<string, FileExensionDocumento>)loObjet;
409 
410  dictFileExtension.Add(lcExtension, loFileExensionDocumento);
411  }
412 
413  return loFileExensionDocumento;
414  }
415 
421  public static RegistryKey _RegistryKeyDefaultIcon(RegistryKey keyForClass)
422  {
423  RegistryKey keyForCLSID = keyForClass.OpenSubKey("CLSID");
424  if (keyForCLSID == null) return null;
425 
426  string clsid = "CLSID\\" + Convert.ToString(keyForCLSID.GetValue(null)) + "\\DefaultIcon";
427  RegistryKey keyForIcon = Registry.ClassesRoot.OpenSubKey(clsid);
428  if (keyForIcon == null)
429  return null;
430 
431  return keyForIcon;
432  }
433 
439  public static RegistryKey _RegistryKeyDefaultOpenWithProdids(RegistryKey keyForExt)
440  {
441  RegistryKey keyOpenWithProgids = keyForExt.OpenSubKey("OpenWithProgids");
442 
443  if (keyOpenWithProgids != null)
444  {
445  RegistryKey keyForIcon = null;
446  string lcTipo;
447 
448  string[] valueNames = keyOpenWithProgids.GetValueNames();
449  foreach (string valueName in valueNames)
450  {
451  RegistryKey keyForExtName = Registry.ClassesRoot.OpenSubKey(valueName);
452 
453  if (keyForExtName != null)
454  {
455  keyForIcon = keyForExtName.OpenSubKey("DefaultIcon");
456  if (keyForIcon != null)
457  {
458  lcTipo = Convert.ToString(keyForExtName.GetValue(null)); // MP4 Video ...
459  if (lcTipo != null && !string.IsNullOrWhiteSpace(lcTipo))
460  return keyForIcon;
461  }
462  }
463  }
464  }
465 
466  return null;
467  }
468 
475  public static string Extension_GetExePath(string strExtension)
476  {
477  //We need a leading dot, so add it if it's missing.
478  if (!strExtension.StartsWith(".")) strExtension = "." + strExtension;
479 
480  //Get the class-name associated with the passed extension
481  Microsoft.Win32.RegistryKey rkClassName
482  = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(strExtension);
483  //Exit, if not found
484  if (rkClassName == null) return string.Empty;
485  string strClassName = rkClassName.GetValue("").ToString();
486 
487  //Get the shell-command for the retrieved executable
488  //This key is found at HKCR\[ClassName]\shell\open\command\(Default)
489  //One or more of the paths may be missing, so each of them is being tested
490  //separately.
491  Microsoft.Win32.RegistryKey rkShellCommandRoot
492  = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(strClassName);
493  if (rkShellCommandRoot == null) return string.Empty;
494 
495  Microsoft.Win32.RegistryKey rkShell
496  = rkShellCommandRoot.OpenSubKey("shell");
497  if (rkShell == null) return string.Empty;
498 
499  Microsoft.Win32.RegistryKey rkOpen
500  = rkShell.OpenSubKey("open");
501  if (rkOpen == null) return string.Empty;
502 
503  Microsoft.Win32.RegistryKey rkCommand
504  = rkOpen.OpenSubKey("command");
505  if (rkCommand == null) return string.Empty;
506 
507  string strShellCommand = rkCommand.GetValue("").ToString();
508 
509  //The shell-command may contain additional parameters and may be wrapped in double quotes,
510  //so parse out the exe-path.
511  string strExePath;
512  if (strShellCommand.StartsWith(@""""))
513  //Extract path (wrapped in double-quotes)
514  strExePath = strShellCommand.Split('"')[1];
515  else
516  //Extract first word (until first space char)
517  strExePath = strShellCommand.Split(' ')[0];
518 
519  return strExePath;
520  }
521 
528  public static Icon _IconForExtension(string tcExtension, eIconSize toeIconSize = eIconSize.Large)
529  {
530  tcExtension = tcExtension.ToLower().Trim();
531 
532  string lcKeyExtension = tcExtension.Trim();
533 
534  if (string.IsNullOrWhiteSpace(lcKeyExtension))
535  return _IconForExtension("txt", toeIconSize);
536 
537  lcKeyExtension = "." + lcKeyExtension.ToLower();
538 
539  RegistryKey keyForExt = Registry.ClassesRoot.OpenSubKey(lcKeyExtension);
540  if (keyForExt == null && tcExtension != "txt")
541  return _IconForExtension("txt", toeIconSize);
542 
543  string className = Convert.ToString(keyForExt.GetValue(null));
544  RegistryKey keyForClass = Registry.ClassesRoot.OpenSubKey(className);
545  if (keyForClass == null && tcExtension != "txt")
546  return _IconForExtension("txt", toeIconSize);
547 
548  RegistryKey keyForIcon = keyForClass.OpenSubKey("DefaultIcon");
549 
550  if (keyForIcon == null)
551  {
552  RegistryKey keyForClassDefaultIcon = _RegistryKeyDefaultIcon(keyForClass);
553 
554  if (keyForClassDefaultIcon == null)
555  {
556  RegistryKey keyOpenWithProgids = _RegistryKeyDefaultOpenWithProdids(keyForExt);
557  if (keyOpenWithProgids != null)
558  keyForIcon = keyOpenWithProgids;
559 
560  if (keyForIcon == null && tcExtension != "txt")
561  return _IconForExtension("txt", toeIconSize);
562  }
563  else
564  keyForIcon = keyForClassDefaultIcon;
565  }
566 
567  string[] defaultIcon = null;
568 
569  try
570  {
571  defaultIcon = Convert.ToString(keyForIcon.GetValue(null)).Split(',');
572  }
573  catch (Exception) // De momento no es necesario gestionar nada
574  {
575  }
576 
577  if (defaultIcon == null)
578  {
579  Icon loIcon = IconForExtensionResources(tcExtension, toeIconSize);
580 
581  if (loIcon == null && tcExtension != "txt")
582  loIcon = IconForExtensionResources("txt", toeIconSize);
583 
584  return loIcon;
585  }
586 
587  if (defaultIcon.Count() <= 1) // Si solo hay un icono, puede que no sea válido
588  {
589  RegistryKey keyForIconDef = _RegistryKeyDefaultIcon(keyForClass);
590 
591  if (keyForIconDef != null)
592  {
593  keyForIcon = keyForIconDef;
594  defaultIcon = Convert.ToString(keyForIcon.GetValue(null)).Split(',');
595  }
596  }
597 
598  return ExtractIcon(tcExtension, toeIconSize, defaultIcon);
599  }
600 
608  private static Icon ExtractIcon(string tcExtension, eIconSize toeIconSize, string[] toKeyDefaultIcon)
609  {
610  Icon loIcon = null;
611  int index = (toKeyDefaultIcon.Length > 1) ? Int32.Parse(toKeyDefaultIcon[1]) : 0;
612  int lnRead = 0;
613  IntPtr[] hDummy = new IntPtr[1] { IntPtr.Zero };
614  IntPtr[] hIconEx = new IntPtr[1] { IntPtr.Zero };
615 
616  try
617  {
618  if (toeIconSize == eIconSize.Large)
619  lnRead = ExtractIconEx(toKeyDefaultIcon[0], index, hIconEx, hDummy, 1);
620  else
621  lnRead = ExtractIconEx(toKeyDefaultIcon[0], index, hDummy, hIconEx, 1);
622 
623  if (lnRead > 0 && hIconEx[0] != IntPtr.Zero)
624  loIcon = (Icon)Icon.FromHandle(hIconEx[0]).Clone(); // Obtenemos el primer icono extraido
625  }
626  catch (Exception)
627  {
628  // De momento no es necesario gestionar nada
629  }
630  finally
631  {
632  foreach (IntPtr ptr in hIconEx)
633  if (ptr != IntPtr.Zero)
634  DestroyIcon(ptr);
635 
636  foreach (IntPtr ptr in hDummy)
637  if (ptr != IntPtr.Zero)
638  DestroyIcon(ptr);
639  }
640 
641  if (loIcon == null && tcExtension != "txt") // Si no encuentra el icono presentamos la imagen del txt
642  loIcon = _IconForExtension("txt", toeIconSize);
643 
644  if (loIcon == null) // Si por el motivo que sea no puede extraer el icono vamos a utilizar los que tenemos en el resources
645  IconForExtensionResources(tcExtension, toeIconSize);
646 
647  return loIcon;
648  }
649 
658  private static Icon IconForExtensionResources(string tcExtension, eIconSize toeIconSize = eIconSize.Large)
659  {
660  Icon loIcon = null;
661 
662  switch (tcExtension)
663  {
664  case "pdf":
665  if (toeIconSize == eIconSize.Large)
666  loIcon = Properties.Resources.icon_pdf_32;
667  else
668  loIcon = Properties.Resources.icon_pdf_16;
669  break;
670 
671  case "doc":
672  case "docx":
673  if (toeIconSize == eIconSize.Large)
674  loIcon = Properties.Resources.icon_docx_32;
675  else
676  loIcon = Properties.Resources.icon_docx_16;
677  break;
678 
679  case "xls":
680  case "xlsx":
681  if (toeIconSize == eIconSize.Large)
682  loIcon = Properties.Resources.icon_xls_32;
683  else
684  loIcon = Properties.Resources.icon_xls_16;
685  break;
686 
687  default:
688  if (toeIconSize == eIconSize.Large)
689  loIcon = Properties.Resources.icon_txt_32;
690  else
691  loIcon = Properties.Resources.icon_txt_16;
692 
693  break;
694  }
695 
696  return loIcon;
697  }
698 
704  public static string _ReadDefaultValueSubkey(string tcRegKey)
705  {
706  using (var lcKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(tcRegKey, false))
707  {
708  if (lcKey != null)
709  return lcKey.GetValue("") as string;
710  }
711  return null;
712  }
713 
720  public static Icon _IconOverlay(Icon toIconBackGround, Image toImageOverlay)
721  {
722  if (toIconBackGround != null)
723  {
724  if (toImageOverlay == null)
725  return toIconBackGround;
726 
727  Image imageOriginal = toIconBackGround.ToBitmap();
728  int lnHeight = toIconBackGround.Height;
729  int lnWidth = toIconBackGround.Size.Width;
730  int lnDif;
731 
732  if (lnHeight > 16)
733  lnDif = lnHeight / 12;
734  else
735  lnDif = lnHeight / 6;
736 
737  imageOriginal = (Image)(new Bitmap(imageOriginal, new Size(lnWidth - lnDif, lnHeight - lnDif)));
738 
739  Bitmap bitmap = new Bitmap(lnWidth, lnWidth);
740  Graphics canvas = Graphics.FromImage(bitmap);
741  canvas.DrawImage(imageOriginal, new Point(lnDif, lnDif));
742  canvas.DrawImage(toImageOverlay, new Point(0, 0));
743  canvas.Save();
744 
745  return Icon.FromHandle(bitmap.GetHicon());
746  }
747 
748  return null;
749  }
750 
756  public static string _DescriptionExtension(string tcExtension)
757  {
758  string lcExtension = tcExtension.ToLower().Trim();
759 
760  if (string.IsNullOrWhiteSpace(lcExtension))
761  return "";
762 
763  if (lcExtension.StartsWith(".") && lcExtension.Length > 1)
764  lcExtension = lcExtension.Substring(1);
765 
766  string lcDescription = _ReadDefaultValueSubkey(lcExtension + "file");
767  if (!String.IsNullOrEmpty(lcDescription))
768  return lcDescription;
769 
770  using (var lcKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("." + lcExtension, false))
771  {
772  if (lcKey == null)
773  return "";
774 
775  try
776  {
777  string lcProgId = lcKey.GetValue("").ToString();
778 
779  using (var lcSubkey = lcKey.OpenSubKey("OpenWithProgids"))
780  {
781  if (lcSubkey == null)
782  return "";
783 
784  var lcNames = lcSubkey.GetValueNames();
785  if (lcNames == null || lcNames.Length == 0)
786  return "";
787 
788  foreach (var lcName in lcNames)
789  {
790  lcDescription = _ReadDefaultValueSubkey(lcName);
791  if (!String.IsNullOrEmpty(lcDescription))
792  return lcDescription;
793  }
794  }
795 
796  }
797  catch (Exception)
798  {
799  }
800  }
801 
802  return "";
803  }
804 
811  public static int _EnlaceTabla(string tcDataBase, string tcTabla)
812  {
813  if (string.IsNullOrWhiteSpace(tcDataBase) || string.IsNullOrWhiteSpace(tcTabla))
814  return 0;
815 
816  int lnId = 0;
817  string lcSql;
818  bool llOk = true;
819  DataTable ldtEnlaces = new DataTable();
820 
821  lcSql = "SELECT ID, LIBRERIA, CLASE " +
822  " FROM " + DB.SQLDatabase("GESTDOC", "ENLACES") +
823  " WHERE DB = " + DB.SQLString(tcDataBase) +
824  " AND TABLA = " + DB.SQLString(tcTabla);
825  llOk = DB.SQLExec(lcSql, ref ldtEnlaces);
826 
827  if (llOk && ldtEnlaces != null && ldtEnlaces.Rows.Count > 0 && (Convert.ToInt32(ldtEnlaces.Rows[0]["id"]) > 0))
828  lnId = Convert.ToInt32(ldtEnlaces.Rows[0]["id"]);
829 
830  return lnId;
831  }
832 
842  public static int _Enlace(IGestionDocumental toEnlace, string tcLibreria, string tcClase, string tcCarpeta)
843  {
844  if (string.IsNullOrWhiteSpace(tcLibreria) || string.IsNullOrWhiteSpace(tcClase))
845  return 0;
846 
847  int lnId = 0;
848  string lcSql;
849  bool llOk = true;
850  DataTable ldtEnlaces = new DataTable();
851 
852  lcSql = "SELECT ID, LIBRERIA, CLASE " +
853  " FROM " + DB.SQLDatabase("GESTDOC", "ENLACES") +
854  " WHERE LIBRERIA = " + DB.SQLString(tcLibreria) +
855  " AND CLASE = " + DB.SQLString(tcClase);
856  llOk = DB.SQLExec(lcSql, ref ldtEnlaces);
857 
858  if (llOk && ldtEnlaces != null && ldtEnlaces.Rows.Count > 0 && (Convert.ToInt32(ldtEnlaces.Rows[0]["id"]) > 0))
859  lnId = Convert.ToInt32(ldtEnlaces.Rows[0]["id"]);
860  else
861  {
862  DataTable ldtMaxId = new DataTable();
863  lcSql = "SELECT MAX(id) AS maxim FROM " + DB.SQLDatabase("GESTDOC", "ENLACES");
864  DB.SQLExec(lcSql, ref ldtMaxId);
865 
866  if (ldtMaxId != null && ldtMaxId.Rows.Count > 0 && !string.IsNullOrWhiteSpace(Convert.ToString(ldtMaxId.Rows[0]["maxim"])))
867  lnId = (Convert.ToInt32(ldtMaxId.Rows[0]["maxim"]) + 1);
868  else
869  lnId = 1;
870 
871  lcSql = "INSERT INTO " + DB.SQLDatabase("GESTDOC", "ENLACES") +
872  " (ID, LIBRERIA, CLASE, CARPETA, DB, TABLA)" +
873  " Values(" + DB.SQLString(lnId) + ", " + DB.SQLString(tcLibreria) + ", " + DB.SQLString(tcClase) + ", " + DB.SQLString(tcCarpeta) + ", " + DB.SQLString(toEnlace._DataBase) + ", " + DB.SQLString(toEnlace._Tabla) + ")";
874  llOk = DB.SQLExec(lcSql);
875 
876  if (!llOk)
877  lnId = 0;
878  }
879 
880  return lnId;
881  }
882 
889  public static bool _Sage50Assembly(string tcLibreria)
890  {
891  List<string> ltsLibrerias = new List<string>() { "sage.ew.empresa", "sage.es.s50.comunicados", "sage.es.s50.fabricacion", "sage.es.S50.fintech", "sage.es.s50.modelos", "sage.es.s50.nuevoejercicio,", "sage.es.s50.s50Update", "sage.ew.articulo", "sage.ew.botones", "sage.ew.cliente", "sage.ew.contabilidad", "sage.ew.docscompra", "sage.ew.docsven", "sage.ew.docventatpv", "sage.ew.ewbase", "sage.ew.formul", "sage.ew.functions", "sage.ew.global", "sage.ew.graficas", "sage.ew.listados", "sage.ew.lote", "sage.ew.o365", "sage.ew.objetos", "sage.ew.perfiles", "sage.ew.sepa", "sage.ew.serie", "sage.ew.stocks", "sage.ew.tpv", "sage.ew.txtbox", "sage.ew.usuario" };
892 
893  return ltsLibrerias.Contains(tcLibreria.ToLower());
894  }
895 
902  public static void _AddColumnDatatable(DataTable tdtDatatable, string tcNameDataColumn, string tcTypeDataColumn)
903  {
904  DataColumn ldtNewCol = new DataColumn(tcNameDataColumn, Type.GetType(tcTypeDataColumn));
905  tdtDatatable.Columns.Add(ldtNewCol);
906  }
907 
915  public static DataTable _DocumentosEnlace(IGestionDocumental toIGestionDocumental, int tnIdEnlace, string tcValor)
916  {
917  if (tnIdEnlace == 0 || string.IsNullOrWhiteSpace(tcValor))
918  return null;
919 
920  DataTable ldtDocumentos = new DataTable();
921  string lcSql, lcExtension, lcUsuario, lcInnerAcceso = string.Empty, lcWhere = string.Empty, lcUseract;
922  bool llOk = true;
923 
924  lcUsuario = Convert.ToString(EW_GLOBAL._GetVariable("wc_usuario"));
925 
926  if (lcUsuario != "SUPERVISOR") // Si no somos el Supervisor certificamos que tenemos acceso al documento y a la carpeta
927  {
928  lcInnerAcceso = " INNER JOIN " + DB.SQLDatabase("GESTDOC", "DOC_USER") + " D_U ON D_U.IDDOC = D.IDDOC AND D_U.USUARIO = " + DB.SQLString(lcUsuario) + " AND D_U.NIVEL >=1 " +
929  " INNER JOIN " + DB.SQLDatabase("GESTDOC", "CARP_USER") + " C_U ON C_U.IDCARPETA = D_C.CARPETA AND C_U.USUARIO = " + DB.SQLString(lcUsuario) + " AND C_U.NIVEL >=1 ";
930  }
931 
932  lcSql = "SELECT D.ENLACE, D.IDDOC, D.VALOR, D.EJERCICIO, D_C.TITULO, D_C.NOM_DOC, D_C.EXTENSION, D_D.USERACT " +
933  " FROM " + DB.SQLDatabase("GESTDOC", "DOC_ENLACE") + " D " +
934  " INNER JOIN " + DB.SQLDatabase("GESTDOC", "DOCUMENT_C") + " D_C ON D_C.ID = D.IDDOC" +
935  " LEFT JOIN " + DB.SQLDatabase("GESTDOC", "DOCUMENT_D") + " D_D ON D_D.IDDOC = D.IDDOC AND D_C.VERSION = D_D.VERSION " +
936  lcInnerAcceso +
937  " WHERE D.ENLACE = " + DB.SQLString(tnIdEnlace) +
938  " AND D.VALOR = " + DB.SQLString(tcValor);
939 
940  if (toIGestionDocumental._GestEjercicio)
941  lcSql += " AND D.EJERCICIO = " + Convert.ToString(EW_GLOBAL._GetVariable("wc_any"));
942 
943  lcSql += " ORDER BY D_C.TITULO";
944 
945  llOk = DB.SQLExec(lcSql, ref ldtDocumentos);
946 
947  if (llOk && ldtDocumentos != null && ldtDocumentos.Rows.Count > 0)
948  {
949  _AddColumnsIconDocumentos(ldtDocumentos, false);
950 
951  foreach (DataRow ldrDocumento in ldtDocumentos.Rows)
952  {
953  lcExtension = Convert.ToString(ldrDocumento["extension"]);
954  lcUseract = Convert.ToString(ldrDocumento["useract"]).Trim();
955  FileExensionDocumento loFileExensionDocumento = _FileExtensionDocumento(lcExtension);
956  if (loFileExensionDocumento != null) // Actualmente utilizamos el IconSmall
957  {
958  if (string.IsNullOrWhiteSpace(lcUseract))
959  {
960  ldrDocumento["IconSmall"] = loFileExensionDocumento._IconSmall;
961  ldrDocumento["IconLarge"] = loFileExensionDocumento._IconLarge;
962  }
963  else
964  {
965  if (lcUseract == lcUsuario)
966  {
967  ldrDocumento["IconSmall"] = loFileExensionDocumento._IconSmallEdition;
968  ldrDocumento["IconLarge"] = loFileExensionDocumento._IconLargeEdition;
969  }
970  else
971  {
972  ldrDocumento["IconSmall"] = loFileExensionDocumento._IconSmallEditionByOtherUser;
973  ldrDocumento["IconLarge"] = loFileExensionDocumento._IconLargeEditionByOtherUser;
974  }
975  }
976  }
977  }
978  }
979 
980  return ldtDocumentos;
981  }
982 
988  public static string _ValueKeys(IGestionDocumental toEnlace)
989  {
990  string lcValor = string.Empty;
991 
992  if (toEnlace._Keys != null)
993  {
994  foreach (string lcPropertyName in toEnlace._Keys.Values)
995  {
996  object loPropertyValue = _GetReflectionPropertyValue(toEnlace, lcPropertyName);
997 
998  if (loPropertyValue != null)
999  {
1000  string lcPropertyValue;
1001 
1002  if (loPropertyValue.GetType() == typeof(DateTime))
1003  lcPropertyValue = ((DateTime)loPropertyValue).ToString(EW_GLOBAL._CustomFormatDate); // De momento guardaremos la fecha en formato corto
1004  else
1005  lcPropertyValue = loPropertyValue.ToString();
1006 
1007  if (!string.IsNullOrWhiteSpace(lcValor))
1008  lcValor += "|";
1009 
1010  lcValor += lcPropertyValue;
1011  }
1012  }
1013  }
1014 
1015  return lcValor;
1016  }
1017 
1024  public static object _GetReflectionPropertyValue(object toObjeto, string tcPropertyName)
1025  {
1026  if (toObjeto == null)
1027  return null;
1028 
1029  PropertyInfo loPropertyInfo = null;
1030  object loObjeto = toObjeto;
1031  string lcPropertyName;
1032 
1033  if (tcPropertyName.Contains("."))
1034  {
1035  string[] lstPropertyNames = tcPropertyName.Split('.'); // Si tenemos "_Cabecera._Proveedor"
1036 
1037  if (lstPropertyNames.Count() == 2) // De momento este es el nivel máximo permitido
1038  {
1039  string lclcPropertyNameParent = lstPropertyNames[0];
1040  object loPropertyValueParent = _GetReflectionPropertyValue(toObjeto, lclcPropertyNameParent); // Instancia de "_Cabecera"
1041 
1042  if (loPropertyValueParent == null)
1043  return null;
1044  else
1045  {
1046  loObjeto = loPropertyValueParent;
1047  lcPropertyName = lstPropertyNames[1];
1048  }
1049  }
1050  else
1051  return null;
1052  }
1053  else
1054  lcPropertyName = tcPropertyName;
1055 
1056  try
1057  {
1058  loPropertyInfo = loObjeto.GetType().GetProperty(lcPropertyName);
1059  }
1060  catch (Exception)
1061  {
1062  }
1063 
1064  if (loPropertyInfo == null)
1065  return null;
1066 
1067  return loPropertyInfo.GetValue(loObjeto, null);
1068  }
1069 
1076  public static bool _SetReflectionPropertyValues(object toObjeto, string tcValues)
1077  {
1078  bool llOk = (toObjeto is IGestionDocumental);
1079  if (llOk)
1080  {
1081  string[] lstValores = tcValues.Split('|');
1082  IGestionDocumental loIGestionDocumental = (IGestionDocumental)toObjeto;
1083  int lnIndice = 0;
1084  string lcPropertyName;
1085  object loValue;
1086 
1087  if (loIGestionDocumental._Keys.Count == lstValores.Count()) // Certificamos que coincide
1088  {
1089  foreach (KeyValuePair<string, string> kvpGestion in loIGestionDocumental._Keys)
1090  {
1091  lcPropertyName = kvpGestion.Value;
1092  loValue = lstValores[lnIndice];
1093  lnIndice++;
1094 
1095  ReflectionPropertyValue(loIGestionDocumental, ref lcPropertyName, ref loValue); // Tratamiento especial para asientos ...
1096 
1097  llOk = FunctionsGestDoc._SetReflectionPropertyValue(loIGestionDocumental, lcPropertyName, loValue);
1098 
1099  if (!llOk)
1100  break;
1101  }
1102  }
1103  }
1104 
1105  return llOk;
1106  }
1107 
1114  private static void ReflectionPropertyValue(IGestionDocumental toIGestionDocumental, ref string tcPropertyName, ref object toValue)
1115  {
1116  bool llAsientos = (toIGestionDocumental is IAsientos);
1117 
1118  if (llAsientos && tcPropertyName == "_Guid") // Tratamiento especial para asientos, tenemos guardado el GUID
1119  {
1120  int lnAsiento = Convert.ToInt32(DB.SQLValor("ASIENTOS", "EMPRESA='" + ((dynamic)toIGestionDocumental)._Empresa + "' AND GUID", Convert.ToString(toValue), "NUMERO"));
1121 
1122  if (lnAsiento > 0)
1123  {
1124  toValue = Convert.ToString(lnAsiento); // Lo convertimos a string para poder asignarlo por reflection en la función correspondiente
1125  tcPropertyName = "_Numero";
1126  }
1127  }
1128  }
1129 
1137  public static bool _SetReflectionPropertyValue(object toObjeto, string tcPropertyName, object toValue)
1138  {
1139  bool llOk = false;
1140  string lcPropertyName = tcPropertyName;
1141  dynamic loObjeto = (dynamic)toObjeto; // DMD dynamic
1142  PropertyInfo propertyInfo = null;
1143 
1144  try
1145  {
1146  if (tcPropertyName.Contains("."))
1147  {
1148  string[] lstPropertyNames = tcPropertyName.Split('.'); // Si tenemos "_Cabecera._Proveedor"
1149 
1150  if (lstPropertyNames.Count() == 2) // De momento este es el nivel máximo permitido
1151  {
1152  string lclcPropertyNameParent = lstPropertyNames[0]; // _Cabecera
1153  object loPropertyValueParent = loObjeto.GetType().GetProperty(lclcPropertyNameParent).GetValue(loObjeto); // Instancia de "_Cabecera"
1154 
1155  if (loPropertyValueParent == null)
1156  return false;
1157  else
1158  {
1159  loObjeto = (dynamic)loPropertyValueParent;
1160  lcPropertyName = lstPropertyNames[1]; // _ Proveedor
1161  }
1162  }
1163  else
1164  return false;
1165  }
1166 
1167  propertyInfo = loObjeto.GetType().GetProperty(lcPropertyName);
1168 
1169  if (propertyInfo != null)
1170  {
1171  Type type = propertyInfo.PropertyType;
1172  object loValue = null;
1173 
1174  TypeConverter converter = TypeDescriptor.GetConverter(type);
1175  if (converter.CanConvertFrom(typeof(string)))
1176  loValue = converter.ConvertFrom(toValue);
1177 
1178  if (loValue != null)
1179  propertyInfo.SetValue(loObjeto, loValue, null);
1180 
1181  llOk = true;
1182  }
1183  }
1184  catch (Exception)
1185  {
1186  }
1187 
1188  return llOk;
1189  }
1190 
1198  public static bool _DeleteDocumentos(dynamic toDocumento, string tcValueKeys = "")
1199  {
1200  bool llOk = true, llDelete = false;
1201 
1202  if (toDocumento is IGestionDocumental)
1203  {
1204  IGestionDocumental loIGestionDocumental = (IGestionDocumental)toDocumento;
1205  int lnIdEnlace = FunctionsGestDoc._EnlaceTabla(loIGestionDocumental._DataBase, loIGestionDocumental._Tabla);
1206  if (lnIdEnlace > 0)
1207  {
1208  string lcSql, lcValueKeys, lcWhereEjercicio = string.Empty;
1209  if (string.IsNullOrWhiteSpace(tcValueKeys))
1210  lcValueKeys = FunctionsGestDoc._ValueKeys(loIGestionDocumental);
1211  else
1212  lcValueKeys = tcValueKeys;
1213 
1214  if (!string.IsNullOrWhiteSpace(lcValueKeys)) // Buscaremos los diferentes documentos
1215  {
1216  DataTable ldtDocumentos = new DataTable();
1217 
1218  if (loIGestionDocumental._GestEjercicio)
1219  lcWhereEjercicio = " AND ejercicio = " + DB.SQLString(Convert.ToString(EW_GLOBAL._GetVariable("wc_any")));
1220 
1221  lcSql = "SELECT iddoc FROM " + DB.SQLDatabase("GESTDOC", "DOC_ENLACE") +
1222  " WHERE enlace = " + DB.SQLString(lnIdEnlace) + " AND valor = " + DB.SQLString(lcValueKeys) +
1223  lcWhereEjercicio;
1224  llOk = DB.SQLExec(lcSql, ref ldtDocumentos);
1225 
1226  if (llOk && ldtDocumentos != null && ldtDocumentos.Rows.Count > 0 && (Convert.ToInt32(ldtDocumentos.Rows[0]["iddoc"]) > 0))
1227  {
1228  int lnIdDoc;
1229  foreach (DataRow ldrDocumento in ldtDocumentos.Rows) // Borraremos los diferentes documentos de la gestión documental
1230  {
1231  lnIdDoc = Convert.ToInt32(ldrDocumento["iddoc"]);
1232  IDocumento loDocumento = new Documento(lnIdDoc);
1233  if (loDocumento._Id > 0)
1234  {
1235  llDelete = loDocumento._Delete();
1236  llOk = llOk && llDelete; // TODO: Si falla el borrado de algun documento, al menos se ha de avisar
1237  }
1238  }
1239  }
1240  }
1241  }
1242  }
1243 
1244  return llOk;
1245  }
1246 
1252  public static eTipoDocumentoGestDoc _TipoDocumento(dynamic toDocumento)
1253  {
1254  eTipoDocumentoGestDoc loeTipoDocumentoGestDoc = eTipoDocumentoGestDoc.Otro;
1255 
1256  if (toDocumento is StockAlbRegulari || toDocumento is StockAlbTraspaso || toDocumento is StockINI || toDocumento is StockInventario)
1257  loeTipoDocumentoGestDoc = eTipoDocumentoGestDoc.Stock;
1258  else if (toDocumento is ewMante)
1259  loeTipoDocumentoGestDoc = eTipoDocumentoGestDoc.Mante;
1260  else if (toDocumento is IAsientos)
1261  loeTipoDocumentoGestDoc = eTipoDocumentoGestDoc.Asiento;
1262  else if (toDocumento is ewDocVentaTPV || toDocumento is ewDocVentaPED || toDocumento is ewDocVentaPRESUP || toDocumento is ewDocVentaDEPOSITO || toDocumento is ewDocVentaFRA)
1263  loeTipoDocumentoGestDoc = eTipoDocumentoGestDoc.Venta;
1264  else if (toDocumento is ewDocCompraALBARAN || toDocumento is ewDocCompraPEDIDO || toDocumento is ewDocCompraPROPUESTA || toDocumento is ewDocCompraDEPOSITO)
1265  loeTipoDocumentoGestDoc = eTipoDocumentoGestDoc.Compra;
1266  else if (toDocumento is ewDocCompraFACTURA)
1267  loeTipoDocumentoGestDoc = eTipoDocumentoGestDoc.FacturaCompra;
1268 
1269  return loeTipoDocumentoGestDoc;
1270  }
1271 
1276  public static int _NumArchivosYCarpetas(string tcPath)
1277  {
1278  if (!Directory.Exists(tcPath))
1279  return 0;
1280 
1281  int lnFicheros = Directory.GetFiles(tcPath, "*.*", SearchOption.AllDirectories).Count();
1282  // TODO, esto de aqui abajo parece que no va bien, cuenta carpetas donde no las hay
1283  int lnCarpetas = Directory.GetDirectories(tcPath, "*", SearchOption.AllDirectories).Count();
1284  int lnNumeroTotal = (lnFicheros + lnCarpetas);
1285 
1286  lnNumeroTotal = lnNumeroTotal < 0 ? 0 : lnNumeroTotal;
1287 
1288  return lnNumeroTotal;
1289  }
1290 
1296  public static string _TamanyoDocumentoFormateado(decimal tnBytes)
1297  {
1298  double lnBytesPorKB = 1024;
1299  double lnBytesDocumento = Convert.ToDouble(tnBytes);
1300  string lcCadenaTamanyo = "";
1301 
1302  if (tnBytes < 1024)
1303  lcCadenaTamanyo = String.Format("{0:n0}", lnBytesDocumento) + " bytes";
1304  else
1305  {
1306  if (tnBytes >= 1024 && tnBytes < 1048576)
1307  {
1308  lcCadenaTamanyo = String.Format("{0:n0}", Math.Ceiling(lnBytesDocumento / lnBytesPorKB)) + " KB";
1309  }
1310  else
1311  {
1312  if (tnBytes >= 1048576 && tnBytes < 1073741824)
1313  {
1314  lcCadenaTamanyo = String.Format("{0:n1}", lnBytesDocumento / Math.Pow(lnBytesPorKB, 2)) + " MB";
1315  }
1316  else
1317  {
1318  if (tnBytes >= 1073741824 && tnBytes < 1099511627776)
1319  {
1320  lcCadenaTamanyo = String.Format("{0:n1}", lnBytesDocumento / Math.Pow(lnBytesPorKB, 3)) + " GB";
1321  }
1322  else
1323  {
1324  if (tnBytes >= 1099511627776)
1325  {
1326  lcCadenaTamanyo = String.Format("{0:n2}", lnBytesDocumento / Math.Pow(lnBytesPorKB, 4)) + " TB";
1327  }
1328  }
1329 
1330  }
1331  }
1332  }
1333 
1334  return lcCadenaTamanyo;
1335  }
1336 
1342  public static string _DirectorioGestDoc(string tcCarpeta = "")
1343  {
1344  string lcPath = Convert.ToString(EW_GLOBAL._GetVariable("wc_iniservidor")).ToString().Trim();
1345 
1346  if (string.IsNullOrWhiteSpace(lcPath))
1347  return "";
1348 
1349  lcPath = Path.Combine(lcPath, "Modulos");
1350  lcPath = Path.Combine(lcPath, "GestDoc");
1351 
1352  if (!string.IsNullOrWhiteSpace(tcCarpeta))
1353  lcPath = Path.Combine(lcPath, tcCarpeta);
1354 
1355  return lcPath;
1356  }
1357 
1363  public static string _DirectorySeparatorChar(string tcPath)
1364  {
1365  string lcDirectoryName = tcPath;
1366 
1367  if (lcDirectoryName.EndsWith("\\") == false)
1368  lcDirectoryName += Path.DirectorySeparatorChar;
1369 
1370  return lcDirectoryName;
1371  }
1372 
1377  public static string _DirectorioSincro()
1378  {
1379  return Path.Combine(FunctionsGestDoc._DirectorioGestDoc("Sincro"), "Docs" + FUNCTIONS._Grupo_Actual());
1380  }
1381 
1385  public static void _SincronizarGestDocUnload()
1386  {
1387  object loObjet = sage.ew.global.EW_GLOBAL._GetVariable("wo_Sincroniza_GestDoc");
1388 
1389  if (loObjet != null)
1390  {
1391  Sincroniza_GestDoc loSincroniza_GestDoc = (Sincroniza_GestDoc)loObjet;
1392  loSincroniza_GestDoc._Unload();
1393  }
1394  }
1395 
1401  public static Sincroniza_GestDoc _SincronizarGestDoc(TipoConexion toTipoConexionServicio)
1402  {
1403  bool llNew = false;
1404  // Únicamente me interesa tener una instancia de la clase de gestión documental
1405  object loObjet = sage.ew.global.EW_GLOBAL._GetVariable("wo_Sincroniza_GestDoc");
1406 
1407  Sincroniza_GestDoc loSincroniza_GestDoc = null;
1408 
1409  if (loObjet == null)
1410  llNew = true;
1411  else
1412  {
1413  loSincroniza_GestDoc = (Sincroniza_GestDoc)loObjet;
1414 
1415  if (loSincroniza_GestDoc._TipoConexionServicio != toTipoConexionServicio || (loSincroniza_GestDoc._Grupo != FUNCTIONS._Grupo_Actual())) // Si cambiamos de grupo o de tipo de conexión, descargamos
1416  {
1417  llNew = true;
1418  loSincroniza_GestDoc._Unload();
1419  }
1420  }
1421 
1422  if (llNew)
1423  {
1424  loSincroniza_GestDoc = new Sincroniza_GestDoc(toTipoConexionServicio);
1425  EW_GLOBAL.ValorEnClave_VarGlob("wo_Sincroniza_GestDoc", loSincroniza_GestDoc);
1426  }
1427 
1428  return loSincroniza_GestDoc;
1429  }
1430 
1443  public static void _SincronizarDocumento(eSincronizacionGestDoc teSincronizacionGestDoc, string tcRutaDocsOneDrive, TipoConexion toTipoConexionServicio, int tnId, string tcGuid, string tcFileName, string tcOldName, string tcFilePathUpload, string tcPathSincronizacion)
1444  {
1445  Sincroniza_GestDoc loSincroniza_GestDoc = _SincronizarGestDoc(toTipoConexionServicio);
1446 
1447  if (loSincroniza_GestDoc != null)
1448  loSincroniza_GestDoc._SincronizarDocumento(teSincronizacionGestDoc, tcRutaDocsOneDrive, tnId, tcGuid, tcFileName, tcOldName, tcFilePathUpload, tcPathSincronizacion);
1449  }
1450 
1462  public static void _SincronizarCarpeta(eSincronizacionGestDoc teSincronizacionGestDoc, string tcRutaDocsOneDrive, TipoConexion toTipoConexionServicio, int tnId, string tcGuid, string tcPath, string tcPathSincro, string tcPathSincronizacion = "")
1463  {
1464  Sincroniza_GestDoc loSincroniza_GestDoc = _SincronizarGestDoc(toTipoConexionServicio);
1465 
1466  if (loSincroniza_GestDoc != null)
1467  loSincroniza_GestDoc._SincronizarCarpeta(teSincronizacionGestDoc, tcRutaDocsOneDrive, tnId, tcGuid, tcPath, tcPathSincro, tcPathSincronizacion);
1468  }
1469  }
1470 }
Clase de negocio base para mantenimientos
Definition: clsEwBase.cs:1643
static System.Drawing.Bitmap EditionByOtherUser32x32
Busca un recurso adaptado de tipo System.Drawing.Bitmap.
Clase para la gestión de los stocks iniciales (Cabecera)
Definition: clsStockINI.cs:23
string _Tabla
Tabla relacionada del enlace del documento
bool _Delete(int tnVersion)
Borrará una versión del documento
Clase documento de DEPOSITO DE COMPRA
Interficie Asientos
Definition: IAsientos.cs:17
Clase documento de venta TPV
Definition: DocVentaTpv.cs:47
Interfaz IGestionDocumental para gestionar el enlace de la gestión documental con los diferentes docu...
Interfaz para el el Objeto Documento
Definition: IDocumento.cs:14
Clase para la gestión de los albaranes de regularización (C_ALBARE)
eTipoConsultaCarpetasDocumentos
Enumeración para gestionar la consulta de la estructura de carpetas y documentos
Definition: EnumGestDoc.cs:29
Clase documento de PRESUPUESTOS
Definition: DocsPresup.cs:39
Es como el tipo de entrada asientos pero por negocio, sin formulario, pq quiero que me haga las propu...
Clase para la gestión de los inventarios de stocks -REGULARI- (Cabecera)
Classe documento Factura de venta
Definition: DocsVentaFra.cs:61
Clase de recurso fuertemente tipado, para buscar cadenas traducidas, etc.
Clase documento de PROPUESTAS DE COMPRA
string _DataBase
Base de datos relacionada del enlace del documento
Classe documento Factura de compra
Clase documento de PEDIDOS
Definition: DocsPed.cs:39
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 para la gestión de los albaranes de traspaso (C_ALBATR)
static System.Drawing.Bitmap EditionByOtherUser16x16
Busca un recurso adaptado de tipo System.Drawing.Bitmap.
static System.Drawing.Bitmap Edition32x32
Busca un recurso adaptado de tipo System.Drawing.Bitmap.
static System.Drawing.Bitmap Edition16x16
Busca un recurso adaptado de tipo System.Drawing.Bitmap.
Clase documento de ALBARANES DE COMPRA
Clase documento de PEDIDOS DE COMPRA
eIconSize
Tamaño de los iconos
Definition: EnumGestDoc.cs:63
eTipoDocumentoGestDoc
Enumeración para gestionar el tipo de documento
Definition: EnumGestDoc.cs:95
bool _GestEjercicio
Indica si el enlace se debe de realizar teniendo en cuenta el ejercicio
TipoConexion
Tipo de conexión
Dictionary< string, string > _Keys
Relación entre los campos y las propiedades de la clase de negocio
Clase de documentos DEPOSITO
Definition: DocsDeposito.cs:33