2 using System.Collections.Generic;
6 using Sage.DriveManagement.Interfaces;
8 using Sage.DriveManagement;
10 using System.Text.RegularExpressions;
12 using Sage.O365Management.Classes.OData;
13 using System.Globalization;
27 private string[] _oAllowedDrives = null;
28 private IFileDialogLauncher _oDialog = null;
29 private Dictionary<string, string> _oConversion =
new Dictionary<string, string>();
34 public string _Path {
get;
set; }
39 public string _ErrorMessage {
get;
set; } =
string.Empty;
54 private string[] _AllowedDrives
59 DriveInfo[] loDrives = DriveInfo.GetDrives();
61 _oAllowedDrives = loDrives.Select(x => x.Name.Contains(
":") ? x.Name.Substring(0, x.Name.IndexOf(
":")) : x.Name).ToArray();
69 _oAllowedDrives = _oAllowedDrives.Union(
new string[] {
"OD",
"SH" }).ToArray();
73 _oAllowedDrives = _oAllowedDrives.Union(
new string[] {
"OD" }).ToArray();
77 _oAllowedDrives = _oAllowedDrives.Union(
new string[] {
"SH" }).ToArray();
82 _oAllowedDrives = _oAllowedDrives.Union(
new string[] {
"OD"}).ToArray();
86 _oAllowedDrives = _oAllowedDrives.Union(
new string[] {
"SH" }).ToArray();
89 return _oAllowedDrives;
96 public IFileDialogLauncher _Dialog
100 if (_oDialog == null)
102 _oDialog =
new FileDialogLauncher();
114 private void _InitializeStyles()
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;
122 loForm.Controls[
"FoldersDrive"].Font = loForm.Font;
123 loForm.Controls[
"FileViewDrive"].Font = loForm.Font;
124 loForm.Controls[
"TxtAddressBar"].BackColor = loForm.BackColor;
126 loForm.MinimumSize =
new Size(700, loForm.Height);
129 #region Constructores 144 _TipoOneDrive = toTipoOneDrive;
155 _Tipo = toTipoConexion;
156 _TipoOneDrive = toTipoOneDrive;
160 #endregion Constructores 168 _oO365Management.
_Load();
171 _oOneDriveManagement.
_Load();
173 _oConversion.Add(
"sh:",
@"\O365");
174 _oConversion.Add(
"od:",
@"\OneDrive");
186 foreach (KeyValuePair<string, string> oValue
in _oConversion)
188 if (tcPath.StartsWith(oValue.Value))
return true;
200 public bool _UploadFile(
string tcPathOriginal,
string tcPathDestination)
206 tcPathDestination = _TransformPathOneDriveToDrive(tcPathDestination);
209 if (tcPathDestination.StartsWith(
"sh:") && _ValidateConnection(
TipoConexion.O365))
215 if (tcPathDestination.StartsWith(
"od:") && _ValidateConnection(
TipoConexion.OneDrive))
219 tcPathDestination = _CleanStringToUpdate(tcPathDestination);
224 FolderFileClientManager _Folder =
new FolderFileClientManager
226 AllowedDrives = _AllowedDrives,
227 Credentials = _GetCredentials()
233 llOk = _Folder.FileUpload(tcPathDestination, tcPathOriginal);
242 if (e.Message.IndexOf(
"filePath") != -1)
243 _ErrorMessage =
"No se puede guardar el fichero en la carpeta raíz de Microsoft 365";
262 oneDriveFilePath = _TransformPathOneDriveToDrive(oneDriveFilePath);
266 localFilePath = _CleanStringToUpdate(localFilePath);
269 if (oneDriveFilePath.StartsWith(
"sh:") && _ValidateConnection(
TipoConexion.O365))
275 if (oneDriveFilePath.StartsWith(
"od:") && _ValidateConnection(
TipoConexion.OneDrive))
282 if(_FileExist(oneDriveFilePath))
284 FolderFileClientManager _Folder =
new FolderFileClientManager
286 AllowedDrives = _AllowedDrives,
287 Credentials = _GetCredentials()
290 var oneDriveFileName = Path.GetFileName(oneDriveFilePath);
291 var localFileExtension = Path.GetExtension(localFilePath);
292 if (
string.IsNullOrWhiteSpace(localFileExtension))
293 localFilePath = Path.Combine(localFilePath, oneDriveFileName);
295 var ok = _Folder.FileDownload(oneDriveFilePath, localFilePath);
303 _ErrorMessage =
"Se ha producido un error al descargar el fichero.";
304 DB.Registrar_Error(e);
320 tcFileName = _TransformPathOneDriveToDrive(tcFileName);
323 if (tcFileName.StartsWith(
"sh:") && _ValidateConnection(
TipoConexion.O365))
329 if (tcFileName.StartsWith(
"od:") && _ValidateConnection(
TipoConexion.OneDrive))
333 tcFileName = _CleanStringToUpdate(tcFileName);
338 FolderFileClientManager _Folder =
new FolderFileClientManager
340 AllowedDrives = _AllowedDrives,
341 Credentials = _GetCredentials()
344 llOk = _Folder.DeleteFile(tcFileName);
351 _ErrorMessage = e.Message;
365 Boolean llOk =
false;
369 tcFileName = _TransformPathOneDriveToDrive(tcFileName);
372 if (tcFileName.StartsWith(
"sh:") && _ValidateConnection(
TipoConexion.O365))
378 if (tcFileName.StartsWith(
"od:") && _ValidateConnection(
TipoConexion.OneDrive))
382 tcFileName = _CleanStringToUpdate(tcFileName);
387 FolderFileClientManager _Folder =
new FolderFileClientManager
389 AllowedDrives = _AllowedDrives,
390 Credentials = _GetCredentials()
393 llOk = _Folder.FileExists(tcFileName);
400 _ErrorMessage = e.Message;
419 tcDirectoryPath = _TransformPathOneDriveToDrive(tcDirectoryPath);
422 if (tcDirectoryPath.StartsWith(
"sh:") && _ValidateConnection(
TipoConexion.O365))
428 if (tcDirectoryPath.StartsWith(
"od:") && _ValidateConnection(
TipoConexion.OneDrive))
431 tcDirectoryPath = _CleanStringToUpdate(tcDirectoryPath);
436 FolderFileClientManager _Folder =
new FolderFileClientManager
438 AllowedDrives = _AllowedDrives,
439 Credentials = _GetCredentials()
442 llOk = _Folder.CreatePath(tcDirectoryPath);
449 _ErrorMessage = e.Message;
460 Boolean llOk =
false;
464 tcDirectoryPath = _TransformPathOneDriveToDrive(tcDirectoryPath);
467 if (tcDirectoryPath.StartsWith(
"sh:") && _ValidateConnection(
TipoConexion.O365))
473 if (tcDirectoryPath.StartsWith(
"od:") && _ValidateConnection(
TipoConexion.OneDrive))
476 tcDirectoryPath = _CleanStringToUpdate(tcDirectoryPath);
481 FolderFileClientManager _Folder =
new FolderFileClientManager
483 AllowedDrives = _AllowedDrives,
484 Credentials = _GetCredentials()
489 Regex path_regex =
new Regex(InvalidFormatPath_Regex);
490 if (!path_regex.IsMatch(tcDirectoryPath))
492 throw new Exception(InvalidFormatPath_Literal);
494 IPathInformation _PathInformation =
new PathInformation(tcDirectoryPath,
false);
495 IDrive oDrive = StaticObjects.GetIDriveByPath(tcDirectoryPath);
496 var result = oDrive.DriveFolder.FolderDelete(tcDirectoryPath);
500 catch (Exception _Exception)
510 _ErrorMessage = e.Message;
514 internal string InvalidFormatPath_Regex
519 return @"^(?:(\w{1,2})\:|\\)((\\[^\*\?\/\""\:<>\|]+)+)[^\.]$";
530 Boolean llOk =
false;
534 tcDirectoryPath = _TransformPathOneDriveToDrive(tcDirectoryPath);
537 if (tcDirectoryPath.StartsWith(
"sh:") && _ValidateConnection(
TipoConexion.O365))
543 if (tcDirectoryPath.StartsWith(
"od:") && _ValidateConnection(
TipoConexion.OneDrive))
546 tcDirectoryPath = _CleanStringToUpdate(tcDirectoryPath);
551 FolderFileClientManager _Folder =
new FolderFileClientManager
553 AllowedDrives = _AllowedDrives,
554 Credentials = _GetCredentials()
559 Regex path_regex =
new Regex(InvalidFormatPath_Regex);
560 if (!path_regex.IsMatch(tcDirectoryPath))
562 throw new Exception(InvalidFormatPath_Literal);
565 IPathInformation _PathInformation =
new PathInformation(tcDirectoryPath,
false);
566 IDrive oDrive = StaticObjects.GetIDriveByPath(tcDirectoryPath);
567 var result = oDrive.DriveFolder.FolderRename(tcDirectoryPath, tcNewForderName);
571 catch (Exception _Exception)
581 _ErrorMessage = e.Message;
588 internal string InvalidFormatPath_Literal
592 string Culture =
string.Empty;
594 if (CultureInfo.CurrentCulture.DisplayName.Contains(
"English"))
600 if (CultureInfo.CurrentCulture.DisplayName.Contains(
"Spanish"))
609 return @"A name can't contain any of the following characters: \ / : * ? < > |";
611 return @"Escribe un nombre que no termine con un punto y que no contenga ninguno de los siguientes caracteres: * ? \ / "" : < > |";
623 private string _CleanStringToUpdate(String tcPathDestination)
625 tcPathDestination = functions.FUNCTIONS._Quitar_Acentos(tcPathDestination);
628 Regex loChar_n =
new Regex(
"[ñ]", RegexOptions.Compiled);
629 Regex loChar_N =
new Regex(
"[Ñ]", RegexOptions.Compiled);
631 tcPathDestination = loChar_n.Replace(tcPathDestination,
"n");
632 tcPathDestination = loChar_N.Replace(tcPathDestination,
"N");
634 string lcPath = Path.GetDirectoryName(tcPathDestination);
635 string lcFile = Path.GetFileName(tcPathDestination);
638 Regex loEspace =
new Regex(
"[ ]", RegexOptions.Compiled);
639 lcFile = loEspace.Replace(lcFile,
"_");
641 return Path.Combine(lcPath, lcFile);
651 Boolean llOk =
false;
653 tcDirectoryPath = _TransformPathOneDriveToDrive(tcDirectoryPath);
656 if (tcDirectoryPath.StartsWith(
"sh:") && _ValidateConnection(
TipoConexion.O365))
662 if (tcDirectoryPath.StartsWith(
"od:") && _ValidateConnection(
TipoConexion.OneDrive))
669 FolderFileClientManager _Folder =
new FolderFileClientManager
671 AllowedDrives = _AllowedDrives,
672 Credentials = _GetCredentials()
678 llOk = _Folder.FolderExists(tcDirectoryPath);
680 catch (Exception loEx)
683 _RaiseException(loEx);
698 public DialogResult
_GetPathFile(String tcTitle, String tcType =
"Todos los archivos (*.*)|*.*", String tcPath =
"")
700 return _Launch(tcTitle, DialogTypes.SaveDialog, tcType, tcPath);
712 return _Launch(tcTitle, DialogTypes.FolderDialog);
714 catch (Exception loException)
716 _RaiseException(loException);
717 return DialogResult.None;
734 tcDirectoryPath = _TransformPathOneDriveToDrive(tcDirectoryPath);
737 if (tcDirectoryPath.StartsWith(
"sh:") && _ValidateConnection(
TipoConexion.O365))
743 if (tcDirectoryPath.StartsWith(
"od:") && _ValidateConnection(
TipoConexion.OneDrive))
750 if (_DirectoryExists(tcDirectoryPath))
752 FolderFileClientManager _Folder =
new FolderFileClientManager
754 AllowedDrives = _AllowedDrives,
755 Credentials = _GetCredentials()
759 var resultado = _Folder.DirectoryFiles(tcDirectoryPath,
"*.*");
761 if (resultado != null)
762 return resultado.ToList();
764 return new List<string>();
770 _ErrorMessage =
"Se ha producido un error al descargar el fichero.";
771 db.DB.Registrar_Error(e);
773 return new List<string>();
784 private DialogResult _Launch(String tcTitle, DialogTypes toType, String tcType =
"Todos los archivos (*.*)|*.*", String tcPath =
"")
787 DialogResult loResult = DialogResult.Cancel;
789 if (_ValidateConnection(_Tipo) ||
790 _SinConfigurar(_Tipo))
793 _SetDefaultPath(tcPath);
794 loResult = (DialogResult)_Dialog.LaunchFileDialog(_AllowedDrives, tcType, toType,
false,
false, _GetCredentials(),
false, tcTitle,
false,
false);
796 if (loResult == DialogResult.OK)
798 _Path = _TranformPathDriveToOneDrive(_Dialog.Path);
801 if (_Dialog.Files.Count() > 0)
803 _Path = Path.Combine(_Path, _Dialog.Files[0]);
807 if (_oDialog.Form != null && !((FileDialogForm)_Dialog.Form).IsDisposed)
809 ((FileDialogForm)_Dialog.Form).Dispose();
818 private void _SetDefaultPath(
string tcPath)
825 lcFile = lcPath =
"";
827 if (
String.IsNullOrWhiteSpace(tcPath.Trim()))
829 lcPath = _TransformPathOneDriveToDrive(_GetDefaultPath(_Tipo)).Trim();
832 else if (_IsPath(tcPath))
834 lcPath = _TransformPathOneDriveToDrive(tcPath);
836 if (tcPath.Contains(
"\\"))
838 lcPath = tcPath.Substring(0, tcPath.LastIndexOf(
"\\") );
839 if (!tcPath.EndsWith(
"\\")) lcFile = tcPath.Substring(tcPath.LastIndexOf(
"\\") + 1);
840 loFiles =
new string[] { lcFile };
846 FileInfo loFile =
new FileInfo(tcPath);
848 lcPath = loFile.DirectoryName;
849 lcFile = loFile.Name;
850 loFiles =
new string[] { lcFile };
854 _Dialog.Path = lcPath;
855 _Dialog.Files = loFiles;
867 private bool _ValidateConnection(
TipoConexion toTipoConexion)
891 private bool _SinConfigurar(
TipoConexion toTipoConexion)
893 var tenemosConfiguracion =
false;
910 return !tenemosConfiguracion;
931 return (lcPath == null ?
"" : lcPath);
942 Boolean llOk =
false;
943 DialogResult loResult;
945 loResult = tnTipo == 0 ? _GetPathFolder(
"Seleccione la carpeta"): _GetPathFile(
"Seleccione el fichero");
947 if (DialogResult.OK == loResult)
949 if (!String.IsNullOrEmpty(_Path))
952 System.IO.File.WriteAllText(tcPathDestino,
string.Format(
"{0}|{1}", _Path, Convert.ToInt16(_IsPath(_Path))));
964 private string _TransformPathOneDriveToDrive(
string tcDirectoryPath)
967 if((!_IsPath(tcDirectoryPath) && !tcDirectoryPath.StartsWith(
"sh:") && !tcDirectoryPath.StartsWith(
"od:")) ||
string.IsNullOrWhiteSpace(tcDirectoryPath))
969 tcDirectoryPath = _GetDefaultPath(_Tipo).TrimEnd() + tcDirectoryPath;
973 foreach (KeyValuePair<string, string> oValue
in _oConversion)
975 tcDirectoryPath = tcDirectoryPath.Replace(oValue.Value, oValue.Key);
979 if (!tcDirectoryPath.StartsWith(
"sh:") && !tcDirectoryPath.StartsWith(
"od:"))
983 tcDirectoryPath =
@"sh:\" + tcDirectoryPath;
988 tcDirectoryPath =
@"od:\" + tcDirectoryPath;
992 return tcDirectoryPath;
1000 private string _TranformPathDriveToOneDrive(String tcDirectoryPath)
1002 foreach (KeyValuePair<String,String> oValue
in _oConversion)
1004 tcDirectoryPath = Regex.Replace(tcDirectoryPath, oValue.Key, oValue.Value);
1006 return tcDirectoryPath;
1013 private ICredentials[] _GetCredentials()
1017 List<ICredentials> _CredentialsList =
new List<ICredentials>();
1018 ICredentials _Credential = null;
1025 _Credential =
new Credentials
1030 _CredentialsList.Add(_Credential);
1036 _Credential =
new Credentials
1039 ClientId = ((IService[])_oO365Management.ServiceResourceIds).Where(x => x.capability ==
"MyFiles").FirstOrDefault().serviceResourceId,
1042 _CredentialsList.Add(_Credential);
1050 _Credential =
new Credentials
1055 _CredentialsList.Add(_Credential);
1063 _Credential =
new Credentials
1066 ClientId = ((IService[])_oO365Management.ServiceResourceIds).Where(x => x.capability ==
"MyFiles").FirstOrDefault().serviceResourceId,
1069 _CredentialsList.Add(_Credential);
1074 return _CredentialsList.ToArray();
1076 catch (Exception _Exception)
1088 string lcErrorMessage =
"";
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;
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);
1100 private bool disposed =
false;
1107 Dispose(disposing:
true);
1108 GC.SuppressFinalize(
this);
1125 _oO365Management = null;
1126 _oOneDriveManagement = null;
1127 _oAllowedDrives = null;
1128 if (_oDialog != null)
1131 _oConversion = null;
1153 Dispose(disposing:
false);
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
string _RefreshToken
RefreshToken
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 ...
string _RefreshToken
RefreshToken
bool _DeleteFile(string tcFileName)
Elimina un fichero en O365
void _Load()
Carga la configuración
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
FileDialog365()
Constructor
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