FileDialog365.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using Sage.FileDialog;
5 using System.Data;
6 using Sage.DriveManagement.Interfaces;
7 using System.Windows.Forms;
8 using Sage.DriveManagement;
9 using System.IO;
10 using System.Text.RegularExpressions;
11 using System.Drawing;
12 using Sage.O365Management.Classes.OData;
13 using System.Globalization;
14 using sage.ew.enumerations;
15 using sage.ew.interficies;
16 using sage.ew.db;
17 
18 namespace sage.ew.o365.Clases
19 {
24  {
25  private O365FileConsumer _oO365Management;
26  private OneDriveFileConsumer _oOneDriveManagement;
27  private string[] _oAllowedDrives = null;
28  private IFileDialogLauncher _oDialog = null;
29  private Dictionary<string, string> _oConversion = new Dictionary<string, string>();
30 
34  public string _Path { get; set; }
35 
39  public string _ErrorMessage { get; set; } = string.Empty;
40 
44  public TipoConexion _Tipo { get; set; } = TipoConexion.Todas;
45 
49  public TipoOneDrive _TipoOneDrive { get; set; } = TipoOneDrive.Exportacion;
50 
54  private string[] _AllowedDrives
55  {
56  get
57  {
58 
59  DriveInfo[] loDrives = DriveInfo.GetDrives();
60 
61  _oAllowedDrives = loDrives.Select(x => x.Name.Contains(":") ? x.Name.Substring(0, x.Name.IndexOf(":")) : x.Name).ToArray();
62 
63  loDrives = null;
64 
65  if (_Tipo == TipoConexion.Todas)
66  {
67  if (_oOneDriveManagement._IsConfigured && _oO365Management._IsConfigured)
68  {
69  _oAllowedDrives = _oAllowedDrives.Union(new string[] { "OD", "SH" }).ToArray();
70  }
71  else if (_oOneDriveManagement._IsConfigured)
72  {
73  _oAllowedDrives = _oAllowedDrives.Union(new string[] { "OD" }).ToArray();
74  }
75  else if (_oO365Management._IsConfigured)
76  {
77  _oAllowedDrives = _oAllowedDrives.Union(new string[] { "SH" }).ToArray();
78  }
79  }
80  else if (_Tipo == TipoConexion.OneDrive && _oOneDriveManagement._IsConfigured)
81  {
82  _oAllowedDrives = _oAllowedDrives.Union(new string[] { "OD"}).ToArray();
83  }
84  else if (_Tipo == TipoConexion.O365 && _oO365Management._IsConfigured)
85  {
86  _oAllowedDrives = _oAllowedDrives.Union(new string[] { "SH" }).ToArray();
87  }
88 
89  return _oAllowedDrives;
90  }
91  }
92 
96  public IFileDialogLauncher _Dialog
97  {
98  get
99  {
100  if (_oDialog == null)
101  {
102  _oDialog = new FileDialogLauncher();
103 
104  _InitializeStyles();
105  if (!string.IsNullOrEmpty(_oO365Management._DefaultPath)) _oDialog.Path = _oO365Management._DefaultPath;
106  }
107  return _oDialog;
108  }
109  }
110 
114  private void _InitializeStyles()
115  {
116  FileDialogForm loForm = (FileDialogForm)_Dialog.Form;
117  loForm.BackColor = Color.FromArgb(250, 250, 250);
118  loForm.WindowState = FormWindowState.Maximized;
119  loForm.Font = new Font("Segoe UI", 9);
120  loForm.WindowState = FormWindowState.Normal;
121 
122  loForm.Controls["FoldersDrive"].Font = loForm.Font;
123  loForm.Controls["FileViewDrive"].Font = loForm.Font;
124  loForm.Controls["TxtAddressBar"].BackColor = loForm.BackColor;
125 
126  loForm.MinimumSize = new Size(700, loForm.Height);
127  }
128 
129  #region Constructores
130 
134  public FileDialog365()
135  {
136  _Load();
137  }
138 
142  public FileDialog365(TipoOneDrive toTipoOneDrive)
143  {
144  _TipoOneDrive = toTipoOneDrive;
145  _Load();
146  }
147 
153  public FileDialog365(TipoConexion toTipoConexion, TipoOneDrive toTipoOneDrive)
154  {
155  _Tipo = toTipoConexion;
156  _TipoOneDrive = toTipoOneDrive;
157  _Load();
158  }
159 
160  #endregion Constructores
161 
165  private void _Load()
166  {
167  _oO365Management = new O365FileConsumer(_TipoOneDrive);
168  _oO365Management._Load();
169 
170  _oOneDriveManagement = new OneDriveFileConsumer(_TipoOneDrive);
171  _oOneDriveManagement._Load();
172 
173  _oConversion.Add("sh:", @"\O365");
174  _oConversion.Add( "od:", @"\OneDrive");
175  }
176 
182  public bool _IsPath(string tcPath)
183  {
184  bool llOk = false;
185 
186  foreach (KeyValuePair<string, string> oValue in _oConversion)
187  {
188  if (tcPath.StartsWith(oValue.Value)) return true;
189  }
190 
191  return llOk;
192  }
193 
200  public bool _UploadFile(string tcPathOriginal, string tcPathDestination)
201  {
202  bool llOk = false;
203 
204  try
205  {
206  tcPathDestination = _TransformPathOneDriveToDrive(tcPathDestination);
207 
208  //Validamos la conexión de O365 si el destino es O365
209  if (tcPathDestination.StartsWith("sh:") && _ValidateConnection(TipoConexion.O365))
210  {
211  llOk = true;
212  }
213 
214  //Validamos la conexión de OneDrive si el destino es OneDrive
215  if (tcPathDestination.StartsWith("od:") && _ValidateConnection(TipoConexion.OneDrive))
216  {
217  llOk = true;
218  //PE-98984 Quitamos los acentos y las ñ ya que sino falla al subir el fichero
219  tcPathDestination = _CleanStringToUpdate(tcPathDestination);
220  }
221 
222  if (llOk)
223  {
224  FolderFileClientManager _Folder = new FolderFileClientManager
225  {
226  AllowedDrives = _AllowedDrives,
227  Credentials = _GetCredentials()
228  };
229 
230  //Pe:
231  //tcPathDestination => od:\gestdoc\aaa.JPEG
232  //tcPathOriginal => C:\EUROWINSPRB\STD\EW800SERV\Modulos\GestDoc\Sincro\Docs0008\48.JPEG
233  llOk = _Folder.FileUpload(tcPathDestination, tcPathOriginal);
234  }
235 
236  return llOk;
237  }
238  catch (Exception e)
239  {
240  //PE-103320: Buscamos en la excepción generada el error de no se encuentra el filePath. Si lo encontramos, guardamos en _ErrorMessage un mensaje explícito
241  //de que no se puede guardar fichero en la carpeta raíz de Microsoft 365
242  if (e.Message.IndexOf("filePath") != -1)
243  _ErrorMessage = "No se puede guardar el fichero en la carpeta raíz de Microsoft 365";
244  }
245  return false;
246  }
247 
254  public bool _DownLoadFile(string oneDriveFilePath, string localFilePath)
255  {
256  bool llOk = false;
257 
258  //Tratamiento previo
259  try
260  {
261  //Formateo origen
262  oneDriveFilePath = _TransformPathOneDriveToDrive(oneDriveFilePath);
263 
264  //Formateo destino
265  //Quitamos los acentos y las ñ ya que sino falla al subir el fichero
266  localFilePath = _CleanStringToUpdate(localFilePath);
267 
268  //Validamos la conexión de O365 si el destino es O365
269  if (oneDriveFilePath.StartsWith("sh:") && _ValidateConnection(TipoConexion.O365))
270  {
271  llOk = true;
272  }
273 
274  //Validamos la conexión de OneDrive si el destino es OneDrive
275  if (oneDriveFilePath.StartsWith("od:") && _ValidateConnection(TipoConexion.OneDrive))
276  {
277  llOk = true;
278  }
279 
280  if(llOk) //El formato es bueno y tengo conexión
281  {
282  if(_FileExist(oneDriveFilePath)) //Verifico que el fichero exista
283  {
284  FolderFileClientManager _Folder = new FolderFileClientManager
285  {
286  AllowedDrives = _AllowedDrives,
287  Credentials = _GetCredentials()
288  };
289 
290  var oneDriveFileName = Path.GetFileName(oneDriveFilePath);
291  var localFileExtension = Path.GetExtension(localFilePath);
292  if (string.IsNullOrWhiteSpace(localFileExtension))
293  localFilePath = Path.Combine(localFilePath, oneDriveFileName); //Le pongo el mismo nombre que en origen
294 
295  var ok = _Folder.FileDownload(oneDriveFilePath, localFilePath);
296 
297  return ok;
298  }
299  }
300  }
301  catch (Exception e)
302  {
303  _ErrorMessage = "Se ha producido un error al descargar el fichero.";
304  DB.Registrar_Error(e);
305  }
306  return false;
307  }
308 
314  public bool _DeleteFile(string tcFileName)
315  {
316  bool llOk = false;
317 
318  try
319  {
320  tcFileName = _TransformPathOneDriveToDrive(tcFileName);
321 
322  //Validamos la conexión de O365 si el destino es O365
323  if (tcFileName.StartsWith("sh:") && _ValidateConnection(TipoConexion.O365))
324  {
325  llOk = true;
326  }
327 
328  //Validamos la conexión de OneDrive si el destino es OneDrive
329  if (tcFileName.StartsWith("od:") && _ValidateConnection(TipoConexion.OneDrive))
330  {
331  llOk = true;
332  //PE-98984 Quitamos los acentos y las ñ ya que sino falla al subir el fichero
333  tcFileName = _CleanStringToUpdate(tcFileName);
334  }
335 
336  if (llOk)
337  {
338  FolderFileClientManager _Folder = new FolderFileClientManager
339  {
340  AllowedDrives = _AllowedDrives,
341  Credentials = _GetCredentials()
342  };
343 
344  llOk = _Folder.DeleteFile(tcFileName);
345  }
346 
347  return llOk;
348  }
349  catch (Exception e)
350  {
351  _ErrorMessage = e.Message;
352  // revisar el error para poner un mensaje explicito
353  //if (e.Message.IndexOf("filePath") != -1)
354  // _ErrorMessage = "No se puede guardar el fichero en la carpeta raíz de Microsoft 365";
355  }
356  return false;
357  }
363  public bool _FileExist(String tcFileName)
364  {
365  Boolean llOk = false;
366 
367  try
368  {
369  tcFileName = _TransformPathOneDriveToDrive(tcFileName);
370 
371  //Validamos la conexión de O365 si el destino es O365
372  if (tcFileName.StartsWith("sh:") && _ValidateConnection(TipoConexion.O365))
373  {
374  llOk = true;
375  }
376 
377  //Validamos la conexión de OneDrive si el destino es OneDrive
378  if (tcFileName.StartsWith("od:") && _ValidateConnection(TipoConexion.OneDrive))
379  {
380  llOk = true;
381  //PE-98984 Quitamos los acentos y las ñ ya que sino falla al subir el fichero
382  tcFileName = _CleanStringToUpdate(tcFileName);
383  }
384 
385  if (llOk)
386  {
387  FolderFileClientManager _Folder = new FolderFileClientManager
388  {
389  AllowedDrives = _AllowedDrives,
390  Credentials = _GetCredentials()
391  };
392 
393  llOk = _Folder.FileExists(tcFileName);
394  }
395 
396  return llOk;
397  }
398  catch (Exception e)
399  {
400  _ErrorMessage = e.Message;
401  // revisar el error para poner un mensaje explicito
402  //if (e.Message.IndexOf("filePath") != -1)
403  // _ErrorMessage = "No se puede guardar el fichero en la carpeta raíz de Microsoft 365";
404  }
405  return false;
406  }
407 
413  public bool _CreateFolder(string tcDirectoryPath)
414  {
415  bool llOk = false;
416 
417  try
418  {
419  tcDirectoryPath = _TransformPathOneDriveToDrive(tcDirectoryPath);
420 
421  //Validamos la conexión de O365 si el destino es O365
422  if (tcDirectoryPath.StartsWith("sh:") && _ValidateConnection(TipoConexion.O365))
423  {
424  llOk = true;
425  }
426 
427  //Validamos la conexión de OneDrive si el destino es OneDrive
428  if (tcDirectoryPath.StartsWith("od:") && _ValidateConnection(TipoConexion.OneDrive))
429  {
430  llOk = true;
431  tcDirectoryPath = _CleanStringToUpdate(tcDirectoryPath);
432  }
433 
434  if (llOk)
435  {
436  FolderFileClientManager _Folder = new FolderFileClientManager
437  {
438  AllowedDrives = _AllowedDrives,
439  Credentials = _GetCredentials()
440  };
441 
442  llOk = _Folder.CreatePath(tcDirectoryPath);
443  }
444 
445  return llOk;
446  }
447  catch (Exception e)
448  {
449  _ErrorMessage = e.Message;
450  }
451  return false;
452  }
458  public bool _DeleteFolder(String tcDirectoryPath)
459  {
460  Boolean llOk = false;
461 
462  try
463  {
464  tcDirectoryPath = _TransformPathOneDriveToDrive(tcDirectoryPath);
465 
466  //Validamos la conexión de O365 si el destino es O365
467  if (tcDirectoryPath.StartsWith("sh:") && _ValidateConnection(TipoConexion.O365))
468  {
469  llOk = true;
470  }
471 
472  //Validamos la conexión de OneDrive si el destino es OneDrive
473  if (tcDirectoryPath.StartsWith("od:") && _ValidateConnection(TipoConexion.OneDrive))
474  {
475  llOk = true;
476  tcDirectoryPath = _CleanStringToUpdate(tcDirectoryPath);
477  }
478 
479  if (llOk)
480  {
481  FolderFileClientManager _Folder = new FolderFileClientManager
482  {
483  AllowedDrives = _AllowedDrives,
484  Credentials = _GetCredentials()
485  };
486 
487  try
488  {
489  Regex path_regex = new Regex(InvalidFormatPath_Regex);
490  if (!path_regex.IsMatch(tcDirectoryPath))
491  {
492  throw new Exception(InvalidFormatPath_Literal);
493  }
494  IPathInformation _PathInformation = new PathInformation(tcDirectoryPath, false);
495  IDrive oDrive = StaticObjects.GetIDriveByPath(tcDirectoryPath);
496  var result = oDrive.DriveFolder.FolderDelete(tcDirectoryPath);
497  oDrive = null;
498  return result;
499  }
500  catch (Exception _Exception)
501  {
502  throw _Exception;
503  }
504  }
505 
506  return llOk;
507  }
508  catch (Exception e)
509  {
510  _ErrorMessage = e.Message;
511  }
512  return false;
513  }
514  internal string InvalidFormatPath_Regex
515  {
516  get
517  {
518  //Que no termine con un punto y que no contenga ninguno de los siguientes caracteres: * ? \ / "" : < > |
519  return @"^(?:(\w{1,2})\:|\\)((\\[^\*\?\/\""\:<>\|]+)+)[^\.]$";
520  }
521  }
528  public bool _RenameFolder(String tcDirectoryPath, string tcNewForderName)
529  {
530  Boolean llOk = false;
531 
532  try
533  {
534  tcDirectoryPath = _TransformPathOneDriveToDrive(tcDirectoryPath);
535 
536  //Validamos la conexión de O365 si el destino es O365
537  if (tcDirectoryPath.StartsWith("sh:") && _ValidateConnection(TipoConexion.O365))
538  {
539  llOk = true;
540  }
541 
542  //Validamos la conexión de OneDrive si el destino es OneDrive
543  if (tcDirectoryPath.StartsWith("od:") && _ValidateConnection(TipoConexion.OneDrive))
544  {
545  llOk = true;
546  tcDirectoryPath = _CleanStringToUpdate(tcDirectoryPath);
547  }
548 
549  if (llOk)
550  {
551  FolderFileClientManager _Folder = new FolderFileClientManager
552  {
553  AllowedDrives = _AllowedDrives,
554  Credentials = _GetCredentials()
555  };
556 
557  try
558  {
559  Regex path_regex = new Regex(InvalidFormatPath_Regex);
560  if (!path_regex.IsMatch(tcDirectoryPath))
561  {
562  throw new Exception(InvalidFormatPath_Literal);
563  }
564 
565  IPathInformation _PathInformation = new PathInformation(tcDirectoryPath, false);
566  IDrive oDrive = StaticObjects.GetIDriveByPath(tcDirectoryPath);
567  var result = oDrive.DriveFolder.FolderRename(tcDirectoryPath, tcNewForderName);
568  oDrive = null;
569  return result;
570  }
571  catch (Exception _Exception)
572  {
573  throw _Exception;
574  }
575  }
576 
577  return llOk;
578  }
579  catch (Exception e)
580  {
581  _ErrorMessage = e.Message;
582  //if (e.Message.IndexOf("filePath") != -1)
583  // _ErrorMessage = "No se puede guardar el fichero en la carpeta raíz de Microsoft 365";
584  }
585  return false;
586  }
587 
588  internal string InvalidFormatPath_Literal
589  {
590  get
591  {
592  string Culture = string.Empty;
593 
594  if (CultureInfo.CurrentCulture.DisplayName.Contains("English"))
595  {
596  Culture = "en";
597  }
598  else
599  {
600  if (CultureInfo.CurrentCulture.DisplayName.Contains("Spanish"))
601  Culture = "es";
602  else
603  Culture = "es";
604  }
605 
606  switch (Culture)
607  {
608  case "en":
609  return @"A name can't contain any of the following characters: \ / : * ? < > |";
610  case "es":
611  return @"Escribe un nombre que no termine con un punto y que no contenga ninguno de los siguientes caracteres: * ? \ / "" : < > |";
612  default:
613  return string.Empty;
614  }
615  }
616  }
623  private string _CleanStringToUpdate(String tcPathDestination)
624  {
625  tcPathDestination = functions.FUNCTIONS._Quitar_Acentos(tcPathDestination);
626 
627  // Eliminamos las Ñ de la ruta y del fichero
628  Regex loChar_n = new Regex("[ñ]", RegexOptions.Compiled);
629  Regex loChar_N = new Regex("[Ñ]", RegexOptions.Compiled);
630 
631  tcPathDestination = loChar_n.Replace(tcPathDestination, "n");
632  tcPathDestination = loChar_N.Replace(tcPathDestination, "N");
633 
634  string lcPath = Path.GetDirectoryName(tcPathDestination);
635  string lcFile = Path.GetFileName(tcPathDestination);
636 
637  // Los espacios de los ficheros los sube con "%20", en las carpetas lo permite correctamente
638  Regex loEspace = new Regex("[ ]", RegexOptions.Compiled);
639  lcFile = loEspace.Replace(lcFile, "_");
640 
641  return Path.Combine(lcPath, lcFile);
642  }
643 
649  public bool _DirectoryExists(String tcDirectoryPath)
650  {
651  Boolean llOk = false;
652 
653  tcDirectoryPath = _TransformPathOneDriveToDrive(tcDirectoryPath);
654 
655  //Validamos la conexión de O365 si el destino es O365
656  if (tcDirectoryPath.StartsWith("sh:") && _ValidateConnection(TipoConexion.O365))
657  {
658  llOk = true;
659  }
660 
661  //Validamos la conexión de OneDrive si el destino es OneDrive
662  if (tcDirectoryPath.StartsWith("od:") && _ValidateConnection(TipoConexion.OneDrive))
663  {
664  llOk = true;
665  }
666 
667  if (llOk)
668  {
669  FolderFileClientManager _Folder = new FolderFileClientManager
670  {
671  AllowedDrives = _AllowedDrives,
672  Credentials = _GetCredentials()
673  };
674 
675  //PE-105340 Si al validar da excepción (presuntamente de login, lo doy por malo pero no lanzo excepción)
676  try
677  {
678  llOk = _Folder.FolderExists(tcDirectoryPath);
679  }
680  catch (Exception loEx)
681  {
682  //No se lanza excepción durante la comprobación. Se da por mala.
683  _RaiseException(loEx);
684  llOk = false;
685  }
686  }
687 
688  return llOk;
689  }
690 
698  public DialogResult _GetPathFile(String tcTitle, String tcType = "Todos los archivos (*.*)|*.*", String tcPath = "")
699  {
700  return _Launch(tcTitle, DialogTypes.SaveDialog, tcType, tcPath);
701  }
702 
708  public DialogResult _GetPathFolder(String tcTitle)
709  {
710  try
711  {
712  return _Launch(tcTitle, DialogTypes.FolderDialog);
713  }
714  catch (Exception loException)
715  {
716  _RaiseException(loException);
717  return DialogResult.None;
718  }
719  }
720 
726  public List<string> _GetFolderFilenamesList(string tcDirectoryPath)
727  {
728  bool llOk = false;
729 
730  //Tratamiento previo
731  try
732  {
733  //Formateo origen
734  tcDirectoryPath = _TransformPathOneDriveToDrive(tcDirectoryPath);
735 
736  //Validamos la conexión de O365 si el destino es O365
737  if (tcDirectoryPath.StartsWith("sh:") && _ValidateConnection(TipoConexion.O365))
738  {
739  llOk = true;
740  }
741 
742  //Validamos la conexión de OneDrive si el destino es OneDrive
743  if (tcDirectoryPath.StartsWith("od:") && _ValidateConnection(TipoConexion.OneDrive))
744  {
745  llOk = true;
746  }
747 
748  if (llOk) //El formato es bueno y tengo conexión
749  {
750  if (_DirectoryExists(tcDirectoryPath)) //Verifico que el fichero exista
751  {
752  FolderFileClientManager _Folder = new FolderFileClientManager
753  {
754  AllowedDrives = _AllowedDrives,
755  Credentials = _GetCredentials()
756  };
757 
758 
759  var resultado = _Folder.DirectoryFiles(tcDirectoryPath, "*.*");
760 
761  if (resultado != null)
762  return resultado.ToList();
763  else
764  return new List<string>();
765  }
766  }
767  }
768  catch (Exception e)
769  {
770  _ErrorMessage = "Se ha producido un error al descargar el fichero.";
771  db.DB.Registrar_Error(e);
772  }
773  return new List<string>();
774  }
775 
784  private DialogResult _Launch(String tcTitle, DialogTypes toType, String tcType = "Todos los archivos (*.*)|*.*", String tcPath = "")
785  {
786 
787  DialogResult loResult = DialogResult.Cancel;
788 
789  if (_ValidateConnection(_Tipo) || //Conexion bien configurada y conectada
790  _SinConfigurar(_Tipo)) //No utiliza conexion => Ha de abrir igual pero lo hará sin los iconos de unidades cloud
791  {
792  //PE-104439 Tratamos el path para pasarselo a FileDialog
793  _SetDefaultPath(tcPath);
794  loResult = (DialogResult)_Dialog.LaunchFileDialog(_AllowedDrives, tcType, toType, false, false, _GetCredentials(), false, tcTitle, false, false);
795 
796  if (loResult == DialogResult.OK)
797  {
798  _Path = _TranformPathDriveToOneDrive(_Dialog.Path);
799 
800  //Si tiene algún fichero seleccionado, lo añadimos a la ruta
801  if (_Dialog.Files.Count() > 0)
802  {
803  _Path = Path.Combine(_Path, _Dialog.Files[0]);
804  }
805  }
806 
807  if (_oDialog.Form != null && !((FileDialogForm)_Dialog.Form).IsDisposed)
808  {
809  ((FileDialogForm)_Dialog.Form).Dispose();
810  }
811 
812  _oDialog.Dispose();
813  }
814 
815  return loResult;
816  }
817 
818  private void _SetDefaultPath(string tcPath)
819  {
820  String lcFile, lcPath;
821  String[] loFiles = new String[] { };
822 
823  try
824  {
825  lcFile = lcPath = "";
826  //Si esta vacio ponemos el por defecto
827  if (String.IsNullOrWhiteSpace(tcPath.Trim()))
828  {
829  lcPath = _TransformPathOneDriveToDrive(_GetDefaultPath(_Tipo)).Trim();
830  }
831  //Miramos que no sea de OneDrive o O365
832  else if (_IsPath(tcPath))
833  {
834  lcPath = _TransformPathOneDriveToDrive(tcPath);
835 
836  if (tcPath.Contains("\\"))
837  {
838  lcPath = tcPath.Substring(0, tcPath.LastIndexOf("\\") );
839  if (!tcPath.EndsWith("\\")) lcFile = tcPath.Substring(tcPath.LastIndexOf("\\") + 1);
840  loFiles = new string[] { lcFile };
841  }
842  }
843  //Es un path fisico
844  else
845  {
846  FileInfo loFile = new FileInfo(tcPath);
847 
848  lcPath = loFile.DirectoryName;
849  lcFile = loFile.Name;
850  loFiles = new string[] { lcFile };
851  }
852 
853 
854  _Dialog.Path = lcPath;
855  _Dialog.Files = loFiles;
856  }
857  catch
858  {
859  }
860  }
861 
867  private bool _ValidateConnection(TipoConexion toTipoConexion)
868  {
869  if (toTipoConexion == TipoConexion.Todas)
870  {
871  return _oOneDriveManagement._ValidateConnection() || _oO365Management._ValidateConnection();
872  }
873  else
874  {
875  if (toTipoConexion == TipoConexion.OneDrive)
876  {
877  return _oOneDriveManagement._ValidateConnection();
878  }
879  else
880  {
881  return _oO365Management._ValidateConnection();
882  }
883  }
884  }
885 
891  private bool _SinConfigurar(TipoConexion toTipoConexion)
892  {
893  var tenemosConfiguracion = false;
894  if (toTipoConexion == TipoConexion.Todas)
895  {
896  tenemosConfiguracion = _oOneDriveManagement._IsConfigured || _oO365Management._IsConfigured;
897  }
898  else
899  {
900  if (toTipoConexion == TipoConexion.OneDrive)
901  {
902  tenemosConfiguracion = _oOneDriveManagement._IsConfigured;
903  }
904  else
905  {
906  tenemosConfiguracion = _oO365Management._IsConfigured;
907  }
908  }
909 
910  return !tenemosConfiguracion;
911  }
912 
918  private String _GetDefaultPath(TipoConexion toTipoConexion)
919  {
920  String lcPath = "";
921 
922  if (toTipoConexion == TipoConexion.OneDrive)
923  {
924  lcPath = _oOneDriveManagement._DefaultPath;
925  }
926  else if(toTipoConexion == TipoConexion.O365)
927  {
928  lcPath = _oO365Management._DefaultPath;
929  }
930 
931  return (lcPath == null ? "" : lcPath);
932  }
933 
940  public Boolean _OpenAndSavePath(String tcPathDestino, Int16 tnTipo)
941  {
942  Boolean llOk = false;
943  DialogResult loResult;
944 
945  loResult = tnTipo == 0 ? _GetPathFolder("Seleccione la carpeta"): _GetPathFile("Seleccione el fichero");
946 
947  if (DialogResult.OK == loResult)
948  {
949  if (!String.IsNullOrEmpty(_Path))
950  {
951  //PE-98984 Cambiamos el encoding del fichero
952  System.IO.File.WriteAllText(tcPathDestino, string.Format("{0}|{1}", _Path, Convert.ToInt16(_IsPath(_Path))));
953  }
954  }
955 
956  return llOk;
957  }
958 
964  private string _TransformPathOneDriveToDrive(string tcDirectoryPath)
965  {
966  //Sino es un path (tipo OneDrive\xxx) ni es una unidad (tipo od:) o está vacio le asigno el path por defecto
967  if((!_IsPath(tcDirectoryPath) && !tcDirectoryPath.StartsWith("sh:") && !tcDirectoryPath.StartsWith("od:")) || string.IsNullOrWhiteSpace(tcDirectoryPath))
968  {
969  tcDirectoryPath = _GetDefaultPath(_Tipo).TrimEnd() + tcDirectoryPath;
970  }
971 
972 
973  foreach (KeyValuePair<string, string> oValue in _oConversion)
974  {
975  tcDirectoryPath = tcDirectoryPath.Replace(oValue.Value, oValue.Key);
976  }
977 
978  //En este punto mi path ha de tener unidad... o mal vamos... Las llamadas por código es posible que no la tengan
979  if (!tcDirectoryPath.StartsWith("sh:") && !tcDirectoryPath.StartsWith("od:"))
980  {
981  if (_Tipo == TipoConexion.O365)
982  {
983  tcDirectoryPath = @"sh:\" + tcDirectoryPath;
984  }
985  else
986  {
987  //Para tipo conexión Todas lo trato como OneDrive... sino haber especificado la unidad.
988  tcDirectoryPath = @"od:\" + tcDirectoryPath;
989  };
990  }
991 
992  return tcDirectoryPath;
993  }
994 
1000  private string _TranformPathDriveToOneDrive(String tcDirectoryPath)
1001  {
1002  foreach (KeyValuePair<String,String> oValue in _oConversion)
1003  {
1004  tcDirectoryPath = Regex.Replace(tcDirectoryPath, oValue.Key, oValue.Value);
1005  }
1006  return tcDirectoryPath;
1007  }
1008 
1013  private ICredentials[] _GetCredentials()
1014  {
1015  try
1016  {
1017  List<ICredentials> _CredentialsList = new List<ICredentials>();
1018  ICredentials _Credential = null;
1019 
1020  if (_Tipo == TipoConexion.Todas)
1021  {
1023  if (_oOneDriveManagement._IsConfigured)
1024  {
1025  _Credential = new Credentials
1026  {
1027  Name = "OneDrive",
1028  Credential = _oOneDriveManagement._RefreshToken
1029  };
1030  _CredentialsList.Add(_Credential);
1031  }
1032 
1034  if (_oO365Management._IsConfigured)
1035  {
1036  _Credential = new Credentials
1037  {
1038  Name = "Office365",
1039  ClientId = ((IService[])_oO365Management.ServiceResourceIds).Where(x => x.capability == "MyFiles").FirstOrDefault().serviceResourceId,
1040  Credential = _oO365Management._RefreshToken
1041  };
1042  _CredentialsList.Add(_Credential);
1043  }
1044  }
1045  else if (_Tipo == TipoConexion.OneDrive)
1046  {
1048  if (_oOneDriveManagement._IsConfigured)
1049  {
1050  _Credential = new Credentials
1051  {
1052  Name = "OneDrive",
1053  Credential = _oOneDriveManagement._RefreshToken
1054  };
1055  _CredentialsList.Add(_Credential);
1056  }
1057  }
1058  else
1059  {
1061  if (_oO365Management._IsConfigured)
1062  {
1063  _Credential = new Credentials
1064  {
1065  Name = "Office365",
1066  ClientId = ((IService[])_oO365Management.ServiceResourceIds).Where(x => x.capability == "MyFiles").FirstOrDefault().serviceResourceId,
1067  Credential = _oO365Management._RefreshToken
1068  };
1069  _CredentialsList.Add(_Credential);
1070  }
1071  }
1072 
1073 
1074  return _CredentialsList.ToArray();
1075  }
1076  catch (Exception _Exception)
1077  {
1078  throw _Exception;
1079  }
1080  }
1081 
1086  public void _RaiseException(Exception toException)
1087  {
1088  string lcErrorMessage = "";
1089 
1090  lcErrorMessage = "Se ha producido un error cuando se ha intentado realizar operaciones con FileDialog365" +
1091  Environment.NewLine + "El mensaje por parte de FileDialog365 es: " + Environment.NewLine + toException.Message;
1092 
1093  functions.FUNCTIONS._MessageBox(lcErrorMessage, "Error FileDialog365",
1094  System.Windows.Forms.MessageBoxButtons.OK,
1095  System.Windows.Forms.MessageBoxIcon.Error,
1096  System.Windows.Forms.MessageBoxDefaultButton.Button1);
1097  db.DB.Registrar_Error(toException);
1098  }
1099 
1100  private bool disposed = false;
1101 
1105  public void Dispose()
1106  {
1107  Dispose(disposing: true);
1108  GC.SuppressFinalize(this);
1109  }
1110 
1115  protected virtual void Dispose(bool disposing)
1116  {
1117  // Check to see if Dispose has already been called.
1118  if (!this.disposed)
1119  {
1120  // If disposing equals true, dispose all managed
1121  // and unmanaged resources.
1122  if (disposing)
1123  {
1124  // Dispose managed resources.
1125  _oO365Management = null;
1126  _oOneDriveManagement = null;
1127  _oAllowedDrives = null;
1128  if (_oDialog != null)
1129  _oDialog.Dispose();
1130  _oDialog = null;
1131  _oConversion = null;
1132  }
1133  // Note disposing has been done.
1134  disposed = true;
1135  }
1136  }
1137 
1138  // Use C# finalizer syntax for finalization code.
1139  // This finalizer will run only if the Dispose method
1140  // does not get called.
1141  // It gives your base class the opportunity to finalize.
1142  // Do not provide finalizer in types derived from this class.
1146  ~FileDialog365()
1147  {
1148  //if (!hasFinalized)
1149  //{
1150  // Do not re-create Dispose clean-up code here.
1151  // Calling Dispose(disposing: false) is optimal in terms of
1152  // readability and maintainability.
1153  Dispose(disposing: false);
1154 
1155  // //h ttps://docs.microsoft.com/es-es/dotnet/api/system.gc.reregisterforfinalize?view=net-6.0
1156  // hasFinalized = true;
1157  // GC.ReRegisterForFinalize(this);
1158  //}
1159  }
1160 
1161  //private bool hasFinalized = false;
1162  }
1163 }
string _DefaultPath
Path por defecto del usuario
bool _UploadFile(string tcPathOriginal, string tcPathDestination)
Sube un fichero a O365
void Dispose()
Implementación de IDisposable
FileDialog365(TipoOneDrive toTipoOneDrive)
Constructor
Interficie del gestor de ficheros o365
void _RaiseException(Exception toException)
Método para trata excepciones
bool _FileExist(String tcFileName)
Comprueba si existe un fichero en O365
Boolean _OpenAndSavePath(String tcPathDestino, Int16 tnTipo)
Abre un FolderDialog y guarda la selección del usuario en el path pasado por parémetros ...
bool _DeleteFile(string tcFileName)
Elimina un fichero en O365
Clase per centralizar las operaciones de FileDialog (OneDrive)
bool _IsConfigured
Retorna si esta configurado
FileDialog365(TipoConexion toTipoConexion, TipoOneDrive toTipoOneDrive)
Constructor
string _DefaultPath
Path por defecto del usuario
bool _IsPath(string tcPath)
Valida si el path pasado por parámetros tiene algunos de los paths configuracios para O365 ...
DialogResult _GetPathFolder(String tcTitle)
Abre un FileDialog, para la selección de carpetas
bool _DownLoadFile(string oneDriveFilePath, string localFilePath)
Descarga un fichero de OneDrive / o365
bool _CreateFolder(string tcDirectoryPath)
Crea un directorio en O365
virtual void Dispose(bool disposing)
Implementación de la liberación del recurso
bool _RenameFolder(String tcDirectoryPath, string tcNewForderName)
Renombra un directorio en O365
PE-97035 Clase para la conexión con O365
bool _ValidateConnection()
Valida si tiene conexión
DialogResult _GetPathFile(String tcTitle, String tcType="Todos los archivos (*.*)|*.*", String tcPath="")
Abre un FileDialog, con selección de ficheros
bool _IsConfigured
Retorn si esta configurado
bool _ValidateConnection()
Valida la conexión
TipoOneDrive
Tipos de OneDrive dentro de Sage50
List< string > _GetFolderFilenamesList(string tcDirectoryPath)
Obtiene una lista de nombres de ficheros de un directorio
bool _DeleteFolder(String tcDirectoryPath)
Elimina un directorio en O365
PE-97035 Clase para la conexión con O365
void _Load()
Carga la configuración
TipoConexion
Tipo de conexión
bool _DirectoryExists(String tcDirectoryPath)
Verifica si existe un directorio en O365