2 using System.Collections.Generic;
3 using Sage.DriveManagement.Interfaces;
5 using Sage.O365Management.Classes;
6 using System.Web.Script.Serialization;
8 using Sage.O365Management.Classes.OData;
12 namespace sage.ew.o365
19 #region User calendar Data 25 internal static string _Sage50User
27 get {
return _cSage50User; }
31 if (!String.IsNullOrWhiteSpace(_cSage50User) && _cSage50User != value && _O365ManagementUser != null)
33 _O365ManagementUser.Logout();
34 _O365ManagementUser.RefreshToken =
"";
39 private static string _cSage50User =
"";
44 public static string _ClientId
59 public static string _ServiceResourceIds
74 public static string _RefreshToken
86 #endregion User calendar Data 88 #region Shared calendar Data 93 protected static internal bool _lRegisterMode =
false;
98 private static SharedCalendarData _oSharedCalendarData =
new SharedCalendarData();
100 internal static SharedCalendarData OSharedCalendarData
103 {
if(_oSharedCalendarData == null)
104 _oSharedCalendarData =
new SharedCalendarData();
105 return _oSharedCalendarData;
107 set { _oSharedCalendarData = value; }
113 internal static string _SharedServiceResourceIds
115 get {
return OSharedCalendarData._RRIdsO365; }
116 set { OSharedCalendarData._RRIdsO365 = value; }
122 internal static string _SharedRefreshToken
124 get {
return OSharedCalendarData._TokenO365; }
125 set { OSharedCalendarData._TokenO365 = value; }
131 internal static string _SharedEmail
133 get {
return OSharedCalendarData._EmailO365; }
137 if (_lRegisterMode) OSharedCalendarData._EmailO365 = value;
144 internal static string _SharedCalendarId
146 get {
return OSharedCalendarData._IdCalO365; }
150 if (_lRegisterMode) OSharedCalendarData._IdCalO365 = value;
157 internal static bool _SharedCalendarActive
159 get {
return OSharedCalendarData._ShareCalendar; }
160 set { OSharedCalendarData._ShareCalendar = value; }
166 public bool _IsSharingCalendar
171 return (OSharedCalendarData._ShareCalendar && !String.IsNullOrWhiteSpace(OSharedCalendarData._EmailO365));
175 #endregion Shared calendar Data 180 protected static string _UserCalendars
195 protected static string _CurrentUserCode
207 public string _ErrorMessage
209 get {
return _cErrorMessage; }
210 set { _cErrorMessage = value; }
212 private string _cErrorMessage =
"";
219 public delegate
void _Authentication_Failed(
object sender, EventArgs e);
229 private void _Throw_Authentication_Failed_Event()
232 var handler = _OnAuthenticationFailed;
240 #region O365Management 246 private static bool RenewToken()
248 _IsLogged = _O365ManagementUser.Login();
252 AccountInfo loAccount = (AccountInfo)_O365ManagementUser.GetAccountInfo();
253 if (loAccount != null) _OperatingAs = loAccount.Id;
256 _ClientId = _O365ManagementUser.ClientId;
257 _RefreshToken = _O365ManagementUser.RefreshToken;
258 _ServiceResourceIds =
new JavaScriptSerializer().Serialize(O365Management.ServiceResourceIds);
271 private void Clear_User_Data()
275 _ServiceResourceIds =
"";
280 private static string _OperatingAs {
get;
set; }
285 private static bool _IsLogged =
false;
294 if (_lUseSharedCalendar) tcCalendarId = _SharedCalendarId;
301 private static bool RenewTokenSage50()
303 _IsLogged = _O365ManagementSage50.Login();
307 AccountInfo loAccount = (AccountInfo)_O365ManagementSage50.GetAccountInfo();
308 if (loAccount != null) _OperatingAs = loAccount.Id;
310 if (String.IsNullOrWhiteSpace(_SharedEmail) || loAccount.Id.Trim() == _SharedEmail.Trim())
312 _SharedRefreshToken = _O365ManagementSage50.RefreshToken;
313 _SharedServiceResourceIds =
new JavaScriptSerializer().Serialize(O365ManagementSage50.ServiceResourceIds);
317 string lcErrorMessage =
"Para esta operación se requiere la cuenta: " + Environment.NewLine + _SharedEmail.Trim();
319 functions.FUNCTIONS._MessageBox(lcErrorMessage,
"Error operación o365",
320 System.Windows.Forms.MessageBoxButtons.OK,
321 System.Windows.Forms.MessageBoxIcon.Error,
322 System.Windows.Forms.MessageBoxDefaultButton.Button1);
325 _O365ManagementSage50.Logout();
335 public virtual bool _UseSharedCalendar
337 get {
return _lUseSharedCalendar; }
338 set { _lUseSharedCalendar = value; }
340 private static bool _lUseSharedCalendar =
false;
345 public static IManagement O365Management
349 if (_lUseSharedCalendar || _lRegisterMode)
360 protected static IManagement O365ManagementUser
367 if (_O365ManagementUser == null || String.IsNullOrEmpty(_O365ManagementUser.RefreshToken) || String.IsNullOrEmpty(_O365ManagementUser.ClientId))
369 _O365ManagementUser =
new O365Management();
371 if (!String.IsNullOrWhiteSpace(_RefreshToken) && !String.IsNullOrWhiteSpace(_ServiceResourceIds))
373 _O365ManagementUser.RefreshToken = _RefreshToken;
375 _O365ManagementUser.ServiceResourceIds =
new JavaScriptSerializer().Deserialize<O365Service[]>(_ServiceResourceIds);
377 _O365ManagementUser.ClientId = _ClientId;
384 return _O365ManagementUser;
387 private static IManagement _O365ManagementUser;
395 _Reset_User_Credentials(toUsuario);
406 if (!String.IsNullOrWhiteSpace(_Sage50User) && _O365ManagementUser != null && _Sage50User == toUser.
_Codigo)
412 _ServiceResourceIds =
"";
414 _O365ManagementUser = null;
420 IManagement oManager =
new O365Management();
425 _IsLogged = oManager.Login();
430 toUser.
_ServiceResourceIds =
new JavaScriptSerializer().Serialize(oManager.ServiceResourceIds);
449 protected static IManagement O365ManagementSage50
453 if (_O365ManagementSage50 == null || String.IsNullOrEmpty(_O365ManagementSage50.RefreshToken) || String.IsNullOrEmpty(_O365ManagementSage50.ClientId))
455 _O365ManagementSage50 =
new O365Management();
457 if (!String.IsNullOrWhiteSpace(_SharedRefreshToken) && !String.IsNullOrWhiteSpace(_SharedServiceResourceIds))
459 _O365ManagementSage50.RefreshToken = _SharedRefreshToken;
460 _O365ManagementSage50.ServiceResourceIds =
new JavaScriptSerializer().Deserialize<O365Service[]>(_SharedServiceResourceIds);
467 return _O365ManagementSage50;
470 private static IManagement _O365ManagementSage50;
486 #endregion Constructors 488 #region Public methods 497 string lcUsuariosSeleccionados =
"";
501 lbtBrowser._Seleccion_Multiple =
true;
502 lbtBrowser._Tabla =
"USUARIOS";
503 lbtBrowser._DataBase =
"COMUNES";
504 lbtBrowser._Codigo =
"NOMBRE";
505 lbtBrowser._Clave =
"NOMBRE";
506 lbtBrowser._Campo_Predet =
"NOMBRE";
507 lbtBrowser._Titulos_Campos =
"Nombre, Email";
508 lbtBrowser._Campos =
"NOMBRE, MAIL";
509 lbtBrowser._Condicion =
"MAIL<>'' ";
510 lbtBrowser.PerformClick();
513 if (lbtBrowser._Codigo_List != null && lbtBrowser._Codigo_List.Count > 0)
516 foreach (KeyValuePair<string,object> lkvpISelectedItem
in lbtBrowser._Codigo_List)
519 DataRow loRow = lkvpISelectedItem.Value as DataRow;
524 string lcUsuario = Convert.ToString(loRow[
"mail"]).Trim();
525 if (!String.IsNullOrWhiteSpace(lcUsuario) && !lcUsuario.EndsWith(
";")) lcUsuario +=
";";
526 lcUsuariosSeleccionados += lcUsuario;
528 catch (Exception loEx)
530 _RaiseException(loEx);
535 return lcUsuariosSeleccionados;
546 string lcErrorMessage =
"";
549 if (O365Management.MessageError != null && O365Management.MessageError.Contains(
"The user or administrator has not consented to use the application"))
551 lcErrorMessage =
"Se ha poducido una incidencia en la validación de la cuenta de correo al acceder al calendario en Microsoft 365. " +
552 "Deberá revisar los siguientes apartados de configuración:" + Environment.NewLine +
553 "- No se trata de una cuenta de Microsoft 365" + Environment.NewLine +
554 "- No existen los permisos necesarios en la aplicación" + Environment.NewLine +
555 "- Se han denegado los permisos en la aplicación";
561 lcErrorMessage =
"Se ha producido un error cuando se ha intentado realizar la comunicación con Microsoft 365" +
562 Environment.NewLine +
"El mensaje por parte de Microsoft 365 es: " + Environment.NewLine + toException.Message +
563 Environment.NewLine + Environment.NewLine +
564 "Revisa la configuración de la cuenta en Microsoft 365";
569 if(toException.Message.Contains(
"refresh token has expired due to inactivity"))
575 functions.FUNCTIONS._MessageBox(lcErrorMessage,
"Error operación o365",
576 System.Windows.Forms.MessageBoxButtons.OK,
577 System.Windows.Forms.MessageBoxIcon.Error,
578 System.Windows.Forms.MessageBoxDefaultButton.Button1);
579 _ErrorMessage = toException.Message;
580 db.DB.Registrar_Error(toException);
584 string lcErrorMessage =
"No ha sido posible obtener el código de autenticación.";
585 functions.FUNCTIONS._MessageBox(lcErrorMessage,
"Error operación o365",
586 System.Windows.Forms.MessageBoxButtons.OK,
587 System.Windows.Forms.MessageBoxIcon.Error,
588 System.Windows.Forms.MessageBoxDefaultButton.Button1);
589 _ErrorMessage = toException.Message;
590 db.DB.Registrar_Error(toException);
593 _Throw_Authentication_Failed_Event();
597 #endregion Public methods 602 internal void _ResetOManagers()
604 if(_O365ManagementSage50 != null) _O365ManagementSage50.Logout();
605 _O365ManagementSage50 = null;
606 _O365ManagementSage50 =
new O365Management();
607 if (_O365ManagementUser != null) _O365ManagementUser.Logout();
608 _O365ManagementUser = null;
609 _O365ManagementUser =
new O365Management();
610 OSharedCalendarData = null;
617 internal void _ResetUserStoredCalendars()
620 string lcSql =
"UPDATE " + DB.SQLDatabase(
"COMUNES",
"USUARIOS") +
" SET USERCALENDARS = ''";
621 llOk = DB.SQLExec(lcSql);
631 internal class SharedCalendarData
643 private string _cClaveCifrado =
"#Nice to see you";
645 #endregion Encryption 647 #region Public properties 652 public bool _ShareCalendar
654 get {
return _lShareCalendar; }
657 _lShareCalendar = value;
658 _SetDataField(
"CMPCALO365", value.ToString());
661 private bool _lShareCalendar;
666 public string _EmailO365
668 get {
return _cEmailO365; }
669 set { _cEmailO365 = value; }
671 private string _cEmailO365;
676 public string _IdCalO365
678 get {
return _cIdCalO365; }
679 set { _cIdCalO365 = value; }
681 private string _cIdCalO365;
686 public string _TokenO365
688 get {
return _cTokenO365; }
689 set { _cTokenO365 = value; }
691 private string _cTokenO365;
696 public string _RRIdsO365
698 get {
return _cRRIdsO365; }
699 set { _cRRIdsO365 = value; }
701 private string _cRRIdsO365;
703 #endregion Public properties 710 public SharedCalendarData()
715 #endregion Constructors 717 #region Public methods 725 string lcSql =
"SELECT CMPCALO365, EMAILO365, IDCALO365, TOKENO365, RRIDSO365 FROM" + DB.SQLDatabase(
"COMUNES",
"CODCOM");
727 DataTable ldtResultado =
new DataTable();
729 llOk = DB.SQLExec(lcSql, ref ldtResultado);
730 if (llOk && ldtResultado.Rows.Count > 0)
732 _lShareCalendar = Convert.ToBoolean(ldtResultado.Rows[0][
"CMPCALO365"]);
733 _cEmailO365 = _oCifrado.
DesencriptaSimetricaAES(Convert.ToString(ldtResultado.Rows[0][
"EMAILO365"]).TrimEnd(), _cClaveCifrado);
734 _cIdCalO365 = _oCifrado.
DesencriptaSimetricaAES(Convert.ToString(ldtResultado.Rows[0][
"IDCALO365"]).TrimEnd(), _cClaveCifrado);
735 _cTokenO365 = _oCifrado.
DesencriptaSimetricaAES(Convert.ToString(ldtResultado.Rows[0][
"TOKENO365"]).TrimEnd(), _cClaveCifrado);
736 _cRRIdsO365 = _oCifrado.
DesencriptaSimetricaAES(Convert.ToString(ldtResultado.Rows[0][
"RRIDSO365"]).TrimEnd(), _cClaveCifrado);
747 string lcSql =
"UPDATE " + DB.SQLDatabase(
"COMUNES",
"CODCOM") +
" SET " +
748 " CMPCALO365 = " + DB.SQLString(_lShareCalendar) +
", " +
749 " EMAILO365 = " + DB.SQLString(_oCifrado.
EncriptaSimetricaAES(_cEmailO365, _cClaveCifrado)) +
", " +
750 " IDCALO365 = " + DB.SQLString(_oCifrado.
EncriptaSimetricaAES(_cIdCalO365, _cClaveCifrado)) +
", " +
751 " TOKENO365 = " + DB.SQLString(_oCifrado.
EncriptaSimetricaAES(_cTokenO365, _cClaveCifrado)) +
", " +
754 return DB.SQLExec(lcSql);
763 public void _Update(AccountInfo toAccount,
string tcRefreshToken,
string tcResoucesServiceIds)
766 if (toAccount.Id != _cEmailO365)
return;
768 _cTokenO365 = tcRefreshToken;
769 _cRRIdsO365 = tcResoucesServiceIds;
772 #endregion Public methods 774 #region Private methods 782 private bool _GetDataField(
string tcDataFieldName, out
string tcDataValue)
784 string lcSql =
"SELECT [" + tcDataFieldName.TrimEnd() +
"] FROM" + DB.SQLDatabase(
"COMUNES",
"CODCOM");
786 string lcDataValue =
"";
787 DataTable ldtResultado =
new DataTable();
789 llOk = DB.SQLExec(lcSql, ref ldtResultado);
790 if (llOk && ldtResultado.Rows.Count > 0)
793 lcDataValue = _oCifrado.
DesencriptaSimetricaAES(Convert.ToString(ldtResultado.Rows[0][tcDataFieldName]).TrimEnd(), _cClaveCifrado);
796 tcDataValue = lcDataValue;
806 private bool _SetDataField(
string tcDataFieldName,
string tcDataValue)
808 if (tcDataFieldName ==
"CMPCALO365")
810 string lcSql =
"UPDATE " + DB.SQLDatabase(
"COMUNES",
"CODCOM") +
" SET [" + tcDataFieldName +
"] = " +
811 DB.SQLString(tcDataValue);
813 return DB.SQLExec(lcSql);
817 string lcSql =
"UPDATE " + DB.SQLDatabase(
"COMUNES",
"CODCOM") +
" SET [" + tcDataFieldName +
"] = " +
820 return DB.SQLExec(lcSql);
824 #endregion Private methods _Authentication_Failed _OnAuthenticationFailed
Authentication failed event
void _ValidateCalendarId(ref string tcCalendarId)
During shared calendar operations may get invalid calendar id. This function enforces the correct one...
static IManagement O365ManagementUser
Property O365Management: Returns the O365Management for user calendar operations creates the instance...
string _ServiceResourceIds
Get or set the ServiceResourceIds Uses encryption. BBDD Name RESOURCEIDS not SERVICERESOURCEIDS for b...
static sage.ew.usuario.Usuario _This
Instancia estática del objeto usuario con los datos del usuario actual (wc_usuario) ...
string _ClientId
Get or set the ClientId Uses encryption.
string _UserCalendars
Get or set the UserCalendars Uses encryption. Serialitzed dictionary Calendar Name (key) - Calendar I...
static void _Resetear_Credenciales(Usuario toUsuario)
Método estatico para resetear las credenciales de un usuario
Browser, basat en sage.ew.objetos.ewbutton
PE-85105: Clase donde se implementaran aquellas funciones de encriptación y desencriptación utilizand...
o365consumer()
Default Constructor
virtual string _ShowUsers()
Method show the program users with email informed
new string _Codigo
Valor de campo clave
static void _Reset_User_Credentials(Usuario toUser)
Método para restablecer las credenciales de un usuario
Class to consume the O365 API
static IManagement O365ManagementSage50
Property O365Management: Returns the O365Management for shared calendar operations creates the instan...
void _RaiseException(Exception toException)
Method to inform the user and log an exception
string EncriptaSimetricaAES(string tcMensaje)
Encriptación simétrica AES. Para encriptar un mensaje que después se puede desencriptar con la funció...
string DesencriptaSimetricaAES(string tcMensajeEncriptado)
Encriptación simétrica AES. Para encriptar un mensaje que después se puede desencriptar con la funció...
override bool _Save()
Override del método SAVE
string _RefreshToken
Get or set the RefreshToken Uses encryption.
Definición de la clase Usuario