2 using System.Collections.Generic;
3 using System.ComponentModel;
15 using System.Windows.Threading;
19 using System.Web.Script.Serialization;
26 namespace sage.ew.objetos
36 #region Implementación de las propiedades de las interficies 42 DisplayName(
"Editando"),
44 DescriptionAttribute(
"Indica si el control está en modo de edición"),
47 public new bool _Editando
49 get {
return _lEditando; }
54 if (_lEditando && !Visible)
62 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
66 get {
return _oControladorDesktop; }
67 set { _oControladorDesktop = value; }
71 #endregion Implementación de las propiedades de las interficies 73 #region Propiedades privadas 74 private bool _lEditando =
false;
79 private bool _lVisible =
false;
81 private string _cRuta_Prgs_err =
string.Empty;
82 private string _cRuta_Temp_Prgs_err =
string.Empty;
83 private bool _llRenameOk =
true;
84 private bool _llCloseApplication =
false;
89 private bool _lActualizando =
false;
90 private bool _lUpdateVariables =
false;
92 private StateActualizacion _oStateActualizacion = StateActualizacion.SinEstado;
94 private string _cMensaje_Error =
string.Empty;
95 private const string _cFileUpdateSage50 =
"ActualizarSage50.exe";
96 private string _cPathIniTerminal =
string.Empty;
97 private string _cPathIniServidor =
string.Empty;
98 private string _cText =
"Nueva actualización de " + Convert.ToString(EW_GLOBAL._GetVariable(
"wc_nameproducto"));
104 private string _cVersionSage50Webservice =
string.Empty;
109 private string _cFechaPublicaSage50Webservice =
string.Empty;
111 private string _cKeyCopy =
string.Empty;
118 private BackgroundWorker _oBackgroundWorker;
123 private bool _lBackgroudWorkerIsRunning =
false;
133 private string _cToolTip =
string.Empty;
138 private string _cVersionTerminalDllSage50
142 if (
string.IsNullOrWhiteSpace(_cVersionTerminalDll))
145 return _cVersionTerminalDll;
148 private string _cVersionTerminalDll =
string.Empty;
153 private string _cVersionServidorDllSage50
157 if (
string.IsNullOrWhiteSpace(_cVersionDllServidor))
160 return _cVersionDllServidor;
163 private string _cVersionDllServidor =
string.Empty;
165 private string _cNameProducto = Convert.ToString(EW_GLOBAL._GetVariable(
"wc_nameproducto"));
170 private Dictionary<string, object> _dictVersionActualizacion =
new Dictionary<string, object>();
171 #endregion Propiedades privadas 173 #region Propiedades públicas 178 public InfoNuevaActualizacion _InfoNuevaActualizacion
182 if (_oInfoNuevaActualizacion == null)
185 return _oInfoNuevaActualizacion;
190 #endregion Propiedades públicas 192 #region Delegados y eventos 193 public delegate
void _Refresh_Actualizacion_Handler(
bool tlVisible);
202 #endregion Delegados y eventos 204 #region Enumeración StateActualizacion 205 private enum StateActualizacion
215 #endregion Enumeración StateActualizacion 217 #region Enumeración ServidorTerminal 218 public enum eServidorTerminalLib
236 #endregion Enumeración StateActualizacion 239 public NuevaActualizacion()
244 InitializeComponent();
248 _oBusinessNuevaActualizacion =
new BusinessNuevaActualizacion();
250 _cPathIniTerminal = Convert.ToString(EW_GLOBAL._GetVariable(
"wc_pathinicio")).Trim();
251 _cPathIniServidor = Convert.ToString(EW_GLOBAL._GetVariable(
"wc_iniservidor")).Trim();
252 _cKeyCopy = Convert.ToString(EW_GLOBAL._GetVariable(
"wc_keycopy"));
254 SubscripcionEventos();
257 #endregion Constructor 259 #region Implementación de los métodos de las interficies 260 public bool _Deleting()
285 _cVersionDllServidor =
string.Empty;
308 Dictionary<string, string> ldReturn =
new Dictionary<string, string>();
318 public bool _Loading(Dictionary<string, string> tdictPersonalizado)
322 #endregion Implementación de los métodos de las interficies 324 #region Métodos públicos 343 bool llUpdate = UpdateAvailable();
348 _InfoNuevaActualizacion._VersionServidor = _cVersionServidorDllSage50;
350 _InfoNuevaActualizacion._VersionTerminal = _cVersionTerminalDllSage50;
352 _InfoNuevaActualizacion._VersionActua = _cVersionSage50Webservice;
353 _InfoNuevaActualizacion._FechaActua = _cFechaPublicaSage50Webservice;
358 #endregion Métodos públicos 360 #region Métodos protected 361 protected internal void _Actualiza()
368 MessageBox.Show($
"No es necesario realizar ninguna actualización.{Environment.NewLine}En estos momentos dispone de la última versión de {_cNameProducto}.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
372 NuevaActualizacion_Click(ewImagenInformacion,
new EventArgs());
374 #endregion Métodos protected 376 #region Métodos privados 377 private string PathS50(
bool tlServidor)
385 return Convert.ToString(EW_GLOBAL._GetVariable(
"wc_iniservidor"));
387 return _cPathIniTerminal;
394 private void SubscripcionEventos(
bool tlUnSubscribe =
false)
398 ewImagenInformacion.Click -= NuevaActualizacion_Click;
400 ewImagenInformacion.MouseEnter -= Imagen_MouseHover;
401 ewImagenInformacion.MouseHover -= Imagen_MouseHover;
402 ewImagenInformacion.MouseLeave -= Imagen_MouseLeave;
407 ewImagenInformacion.Click += NuevaActualizacion_Click;
409 ewImagenInformacion.MouseEnter += Imagen_MouseHover;
410 ewImagenInformacion.MouseHover += Imagen_MouseHover;
411 ewImagenInformacion.MouseLeave += Imagen_MouseLeave;
420 private void Imagen_MouseHover(
object sender, EventArgs e)
422 if (Cursor != Cursors.Hand)
423 Cursor = Cursors.Hand;
431 private void Imagen_MouseLeave(
object sender, EventArgs e)
433 if (Cursor != Cursors.Default)
434 Cursor = Cursors.Default;
443 private bool InternetConnection_Deprecated(
bool tlMessage =
false)
445 if (!
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
448 MessageBox.Show($
"Para poder ejecutar el proceso de actualización de {_cNameProducto} es necesario tener una conexión a internet.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Stop);
461 private void NuevaActualizacion_Click(
object sender, EventArgs e)
463 bool llActualizar =
false;
465 if (!ValidateFilePath(_cPathIniTerminal, _cFileUpdateSage50))
468 if (_lBackgroudWorkerIsRunning && _oStateActualizacion == StateActualizacion.Actualizar)
470 DescripcionTooltTip();
471 MessageBox.Show($
"En estos momentos ya se está ejecutando la actualización de {_cNameProducto}.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Information);
475 if ((_oStateActualizacion != StateActualizacion.SinEstado && _lBackgroudWorkerIsRunning) || _oStateActualizacion == StateActualizacion.PendienteCerrar)
478 if (!PrevalidatePrgs_Err())
481 _cVersionDllServidor =
string.Empty;
482 _dictVersionActualizacion = LoadVersionVariable();
484 DescripcionTooltTip();
486 if (NowUpdating(tlMessage:
true))
489 if (!PrevalidateListasPrevias())
492 string lcPregunta = TextoActualizacion(ref llActualizar,
true);
494 if (llActualizar && !PuedoActualizar())
496 MessageBox.Show($
"Para poder actualizar {_cNameProducto} debe tener activado el acceso especial 'Permitir actualizar desde dentro de la aplicación'.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Information);
500 if (
MessageBox.Show(lcPregunta, _cText, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
509 _oStateActualizacion = StateActualizacion.Actualizar;
512 ewImagenInformacion.Click -= NuevaActualizacion_Click;
516 ewImagenInformacion.Click += NuevaActualizacion_Click;
525 private bool PuedoActualizar()
527 return ((Convert.ToString(EW_GLOBAL._GetVariable(
"wc_usuario")).Trim() ==
"SUPERVISOR") ||
Usuario.
_This.
_Opcesp(
"5005"));
534 private bool PrevalidatePrgs_Err()
538 _cRuta_Prgs_err = FUNCTIONS._AddBS(Path.Combine(_cPathIniServidor,
"PRGS_ERR"));
539 _cRuta_Temp_Prgs_err = FUNCTIONS._AddBS(Path.Combine(_cRuta_Prgs_err,
"TEMP_ACTUALIZACIONSAGE50"));
541 if (Directory.Exists(_cRuta_Prgs_err))
543 if (!CreateDirectoryTemp())
545 MessageBox.Show(
"Para poder ejecutar el proceso de actualización es necesario tener permisos en la carpeta de PRGS_ERR del servidor.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Stop);
549 string[] lcFiles = Directory.GetFiles(_cRuta_Prgs_err);
551 lcFiles.AsEnumerable().ToList().ForEach(f =>
RenameFile(f));
553 RemoveDirectoryTemp();
558 string lcError = $
"Existen ficheros en uso en la carpeta {_cRuta_Prgs_err} del servidor que impiden ejecutar el proceso de actualización de {_cNameProducto}." + Environment.NewLine + Environment.NewLine +
559 $
"Ejecute el proceso '{_cFileUpdateSage50}' para realizar la actualización.";
561 if (Convert.ToBoolean(EW_GLOBAL._GetVariable(
"wl_prueva")) && !
string.IsNullOrWhiteSpace(_cMensaje_Error))
562 lcError += Environment.NewLine + Environment.NewLine + _cMensaje_Error;
564 MessageBox.Show(lcError, _cText, MessageBoxButtons.OK, MessageBoxIcon.Stop);
574 private bool CreateDirectoryTemp()
580 llOk = Directory.Exists(_cRuta_Temp_Prgs_err);
584 Directory.CreateDirectory(_cRuta_Temp_Prgs_err);
585 llOk = Directory.Exists(_cRuta_Temp_Prgs_err);
588 catch (Exception loEx)
590 _cMensaje_Error =
"No se ha podido crear el directorio temporal para la copia de ficheros." + Environment.NewLine + loEx.Message;
600 private bool RemoveDirectoryTemp()
606 if (Directory.Exists(_cRuta_Temp_Prgs_err))
608 Directory.Delete(_cRuta_Temp_Prgs_err);
609 llOk = !Directory.Exists(_cRuta_Temp_Prgs_err);
612 catch (Exception loEx)
614 _cMensaje_Error =
"No se ha podido eliminar el directorio temporal para la copia de ficheros." + Environment.NewLine + loEx.Message;
629 string lcFileName, lcNewFileName;
631 lcFileName = Path.Combine(_cRuta_Prgs_err, tcFile);
632 lcNewFileName = Path.Combine(_cRuta_Temp_Prgs_err, tcFile);
636 File.Move(lcFileName, lcNewFileName);
638 catch (Exception loEx)
641 _cMensaje_Error =
"No se ha podido renombrar el fichero " + Path.GetFileName(tcFile) +
"." + Environment.NewLine + Environment.NewLine + loEx.Message;
649 File.Move(lcNewFileName, lcFileName);
651 catch (Exception loEx)
653 _cMensaje_Error =
"No se ha podido restaurar el fichero " + Path.GetFileName(tcFile) +
"." + Environment.NewLine + Environment.NewLine + loEx.Message;
666 private bool PreValidate()
670 MessageBox.Show(
"Para actualizar la aplicación es necesario guardar primero el diseño actual.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
674 if (_lActualizando && ExistProcessActualizarSage50())
676 MessageBox.Show(
"Se está ejecutando el proceso de actualización.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
680 if (!PrevalidateListasPrevias())
690 private bool PrevalidateListasPrevias()
695 int openformsATenerEnCuenta = EW_GLOBAL._OpenForms.Count;
696 for (
int nInd = 0; nInd < EW_GLOBAL._OpenForms.Count ; nInd++)
698 if (EW_GLOBAL._OpenForms.ElementAt(nInd).GetType().Name ==
"frmAcercaDe" || EW_GLOBAL._OpenForms.ElementAt(nInd).GetType().Name ==
"frmPrincipal")
700 openformsATenerEnCuenta --;
704 if (openformsATenerEnCuenta > 1)
706 var loFormsListas = EW_GLOBAL._OpenForms.Where(f => f.Name.ToLower().Trim() ==
"frmlistasprevias" || f.Name.ToLower().Trim() ==
"formtabs");
708 llOk = (loFormsListas != null && loFormsListas.Count() > 0);
711 FUNCTIONS._MessageBox(
"El proceso de actualización no ha podido finalizar porque se ha detectado alguna de las listas previas que están en uso necesita ser actualizada." + Environment.NewLine+ Environment.NewLine +
712 "Cierra todas las listas previas que tengas abiertas en cualquiera de los ordenadores donde se esté utilizando " + _cNameProducto +
" y vuelve a lanzar el proceso de actualización.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Stop);
717 ControladorDesktop loControlador = (ControladorDesktop)EW_GLOBAL._GetVariable(
"wo_ControladorDesktop");
718 if (loControlador != null)
720 List<Control> lstMenus = loControlador._GetWidgets().AsEnumerable().Where(c => c.GetType() == typeof(WidgetFormTabs)).ToList();
722 if (lstMenus.Count > 0 && (lstMenus[0] as WidgetFormTabs)._Listas > 0)
725 FUNCTIONS._MessageBox(
"El proceso de actualización no ha podido finalizar porque se ha detectado el widget de listas previas incrustado en un escritorio en uso."+ Environment.NewLine + Environment.NewLine +
726 "Cierra todas las listas previas que tengas abiertas en el diseño del escritorio en cualquiera de los ordenadores donde se esté utilizando " + _cNameProducto +
" o cambia a un escritorio donde no exista el widget de listas previas incrustado y vuelve a lanzar el proceso de actualización.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Stop);
739 private bool ValidatePath(
string tcPath)
741 if (
string.IsNullOrWhiteSpace(tcPath) || !Directory.Exists(tcPath))
743 MessageBox.Show(
"No se ha definido la ruta del terminal.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
756 private bool ValidateFilePath(
string tcPath,
string tcFile)
758 if (!ValidatePath(tcPath))
761 string lcFilePath = Path.Combine(tcPath, tcFile);
763 if (!File.Exists(lcFilePath))
765 MessageBox.Show($
"No se ha encontrado el ejecutable ActualizarSage50.exe en el terminal necesario para la actualización de {_cNameProducto}.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
776 private bool UpdateAvailable()
780 if (!FUNCTIONS.InternetOk())
784 _dictVersionActualizacion = LoadVersionVariable();
788 _cVersionSage50Webservice = _dictVersionActualizacion.ContainsKey(
"_Version") ? Convert.ToString(_dictVersionActualizacion[
"_Version"]) :
"";
789 _cFechaPublicaSage50Webservice = _dictVersionActualizacion.ContainsKey(
"_Publicacion") ? Convert.ToString(_dictVersionActualizacion[
"_Publicacion"]) :
"";
791 llCont = IsSuperiorVersionWebServiceServidor() || IsSuperiorVersionWebServiceTerminal();
796 _VersionActualizarSage50WebService();
798 llCont = !
string.IsNullOrWhiteSpace(_cVersionSage50Webservice);
802 llCont = UpdateVariables(
false);
804 if (!IsSuperiorVersionWebServiceServidor())
817 private bool IsSuperiorVersionWebServiceServidor()
819 bool llOk = (!
string.IsNullOrWhiteSpace(_cVersionSage50Webservice) && _cVersionSage50Webservice != _cVersionServidorDllSage50);
823 llOk = (ConvertToDecimal(_cVersionSage50Webservice) > ConvertToDecimal(_cVersionServidorDllSage50));
825 catch (Exception loEx)
827 _cMensaje_Error =
"No se ha podido comparar la versión del servidor" + Environment.NewLine + loEx.Message;
830 _InfoNuevaActualizacion._ServidorTerminal = llOk ? eServidorTerminalLib.Servidor : _InfoNuevaActualizacion._ServidorTerminal;
839 private bool IsSuperiorVersionServidorTerminal()
843 if (_cVersionTerminalDllSage50 != _cVersionServidorDllSage50)
847 llOk = (ConvertToDecimal(_cVersionServidorDllSage50) > ConvertToDecimal(_cVersionTerminalDllSage50));
862 private bool IsSuperiorVersionWebServiceTerminal()
864 if (IsSuperiorVersionWebServiceServidor())
872 llOk = (!
string.IsNullOrWhiteSpace(_cVersionSage50Webservice) && _cVersionSage50Webservice != _cVersionServidorDllSage50);
875 llOk = llOk && (ConvertToDecimal(_cVersionSage50Webservice) >= ConvertToDecimal(_cVersionServidorDllSage50));
879 llOk = llOk && (ConvertToDecimal(_cVersionServidorDllSage50) > ConvertToDecimal(_cVersionTerminalDllSage50));
881 catch (Exception loEx)
883 _cMensaje_Error =
"No se ha podido comparar la versión del servidor" + Environment.NewLine + loEx.Message;
889 llOk = llOk || (ConvertToDecimal(_cVersionSage50Webservice) > ConvertToDecimal(_cVersionTerminalDllSage50));
891 catch (Exception loEx)
893 _cMensaje_Error =
"No se ha podido comparar la versión del terminal" + Environment.NewLine + loEx.Message;
896 _InfoNuevaActualizacion._ServidorTerminal = llOk ? eServidorTerminalLib.Terminal : _InfoNuevaActualizacion._ServidorTerminal;
906 private decimal ConvertToDecimal(
string tcVersion)
908 decimal lnVersion = 0;
912 lnVersion = Convert.ToDecimal(tcVersion.Replace(
".",
"").Replace(
",",
""));
914 catch (Exception loEx)
916 _cMensaje_Error =
"Se ha producido un error al convertir la versión" + Environment.NewLine + loEx.Message;
926 private string VersionVariables()
928 string lcVersion =
"0";
930 if (_dictVersionActualizacion.ContainsKey(
"_Version"))
931 lcVersion = Convert.ToString(_dictVersionActualizacion[
"_Version"]);
941 private bool VersionDLLs()
943 if (_oStateActualizacion == StateActualizacion.PendienteCerrar)
946 return IsSuperiorVersionServidorTerminal();
953 private bool ValidDate()
957 if (_dictVersionActualizacion.Count > 0 && _dictVersionActualizacion.ContainsKey(
"_Fecha"))
963 llOk = ((Convert.ToDateTime(_dictVersionActualizacion[
"_Fecha"])) > DateTime.UtcNow);
965 catch (Exception loEx)
967 _cMensaje_Error =
"Fecha no válida." + Environment.NewLine + loEx.Message;
981 private bool NowUpdating(
bool tlUpdate =
false,
bool tlMessage =
false,
bool tlAferUpdate =
false)
983 if (!FUNCTIONS.InternetOk())
986 bool llUpdating =
false;
988 if (_dictVersionActualizacion.Count > 0 && _dictVersionActualizacion.ContainsKey(
"_Actualizando"))
990 llUpdating = Convert.ToBoolean(_dictVersionActualizacion[
"_Actualizando"]);
992 if (llUpdating && _dictVersionActualizacion.ContainsKey(
"_Fecha"))
994 DateTime ldFecha = Convert.ToDateTime(_dictVersionActualizacion[
"_Fecha"]).Date;
995 llUpdating = (ldFecha > DateTime.Now.Date && !tlAferUpdate);
999 if ((tlUpdate && !llUpdating) || tlAferUpdate)
1000 UpdateVariables(
false);
1004 if (llUpdating && tlMessage)
1006 DescripcionTooltTip();
1007 MessageBox.Show($
"En estos momentos se está actualizando la versión de {_cNameProducto}.", _cText, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
1016 private void DescripcionTooltTip()
1018 if (_oToolTip == null)
1019 _oToolTip =
new ewToolTip();
1021 bool llActualizar =
false;
1022 string lcTexto = TextoActualizacion(tlActualizar: ref llActualizar);
1023 _oToolTip.SetToolTip(ewImagenInformacion, lcTexto);
1032 private string TextoActualizacion(ref
bool tlActualizar,
bool tlQuestion =
false)
1034 string lcTexto =
"";
1037 lcTexto = $
"En estos momentos se está ejecutando la actualización de {_cNameProducto}.";
1042 lcTexto = $
"Existe la nueva versión {_cVersionServidorDllSage50} disponible en el servidor para actualizar {_cNameProducto}";
1045 lcTexto +=
"." + Environment.NewLine + Environment.NewLine +
"¿Desea cerrar la aplicación para actualizar a la nueva versión?";
1049 tlActualizar =
true;
1050 lcTexto = $
"Existe una nueva versión disponible para descargar y actualizar {_cNameProducto}";
1053 lcTexto +=
"." + Environment.NewLine + Environment.NewLine +
"¿Desea actualizar a la nueva versión?";
1064 private string _VersionActualizarSage50WebService()
1066 if (!FUNCTIONS.InternetOk())
1069 _cVersionSage50Webservice =
string.Empty;
1070 _cFechaPublicaSage50Webservice =
string.Empty;
1072 Dictionary<string, object> loDic =
new Dictionary<string, object>();
1073 loDic = FUNCTIONS._VersionActualizarSage50WebServiceInfo();
1077 if (loDic.ContainsKey(
"Version"))
1078 _cVersionSage50Webservice = Convert.ToString(loDic[
"Version"]);
1079 if (loDic.ContainsKey(
"Publicacion"))
1080 _cFechaPublicaSage50Webservice = Convert.ToString(loDic[
"Publicacion"]);
1083 _cFechaPublicaSage50Webservice = FormatFecha(_cFechaPublicaSage50Webservice);
1086 return _cVersionSage50Webservice;
1095 private Dictionary<string, object> LoadVersionVariable()
1098 DataTable ldtVariable =
new DataTable();
1099 Dictionary<string, object> loDictVersion =
new Dictionary<string, object>();
1103 _lUpdateVariables = (ldtVariable != null && ldtVariable.Rows.Count > 0);
1106 loDictVersion = DeserializaInformationDataTable(ldtVariable);
1108 FUNCTIONS._DisposeDatatable(ldtVariable);
1110 return loDictVersion;
1118 private Dictionary<string, object> DeserializaInformationDataTable(DataTable tdtVariable)
1120 Dictionary<string, object> loDictInformacion =
new Dictionary<string, object>();
1122 if (tdtVariable != null && tdtVariable.Rows.Count > 0)
1124 string lcValor = Convert.ToString(tdtVariable.Rows[0][
"valor"]).Trim();
1126 if (!
string.IsNullOrWhiteSpace(lcValor))
1130 loDictInformacion =
new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(lcValor);
1132 catch (Exception loEx)
1134 _cMensaje_Error =
"No se ha podido deserializar la información de la versión de la tabla variables." + Environment.NewLine + loEx.Message;
1139 return loDictInformacion;
1146 private void RefreshDictValues(
bool tlActualizando)
1148 _dictVersionActualizacion[
"_Fecha"] = GetNewDate();
1149 _dictVersionActualizacion[
"_Version"] = _cVersionSage50Webservice;
1150 _dictVersionActualizacion[
"_Publicacion"] = _cFechaPublicaSage50Webservice;
1151 _dictVersionActualizacion[
"_Actualizando"] = tlActualizando;
1152 _dictVersionActualizacion[
"_Keycopy"] = (tlActualizando ? _cKeyCopy :
"");
1160 private DateTime GetNewDate()
1163 DateTime ldNewDate = DateTime.Now;
1166 ldNewDate = ldNewDate.AddDays(GetRandom(1, 7));
1169 ldNewDate = ldNewDate.AddMinutes(GetRandom(1, 47));
1172 DateTime ldDateLimit =
new DateTime(ldNewDate.Year, ldNewDate.Month, ldNewDate.Day, 20, 0, 0);
1173 if (DateTime.Compare(ldNewDate, ldDateLimit) > 0)
1174 ldNewDate =
new DateTime(ldNewDate.Year, ldNewDate.Month, ldNewDate.Day, 8, 0, 0);
1186 private string FormatFecha(
string tcFecha)
1188 string lcReturn = tcFecha;
1189 if (tcFecha.Length >= 10 && tcFecha.Substring(4,1) ==
"-" && tcFecha.Substring(7, 1) ==
"-")
1193 DateTime ldTime = Convert.ToDateTime(tcFecha);
1194 lcReturn = ldTime.ToShortDateString();
1210 private int GetRandom(
int tnMin,
int tnMax)
1212 Random loRandom =
new Random();
1213 return loRandom.Next(tnMin, tnMax);
1221 private string Serialize(
bool tlActualizando)
1223 string lcStringSerialize =
string.Empty;
1225 RefreshDictValues(tlActualizando);
1229 lcStringSerialize =
new JavaScriptSerializer().Serialize(_dictVersionActualizacion);
1231 catch (Exception loEx)
1233 _cMensaje_Error =
"No se ha podido serializar la información de la versión de la tabla variables." + Environment.NewLine + loEx.Message;
1236 return lcStringSerialize;
1249 private bool UpdateVersion()
1252 Dictionary<string, object> dictVersionActualizacion =
new Dictionary<string, object>();
1257 _dictVersionActualizacion = LoadVersionVariable();
1259 llOk = UpdateVariables(
true);
1272 private bool UpdateVariables(
bool tlActualizando)
1276 string lcValores = Serialize(tlActualizando);
1278 if (_lUpdateVariables)
1283 _lUpdateVariables = llOk;
1293 private bool ExistProcessActualizarSage50()
1295 Process[] loProcessName = Process.GetProcessesByName(
"ActualizarSage50");
1297 bool llExist = loProcessName.Length > 0;
1299 if (_lActualizando && !llExist)
1300 _lActualizando =
false;
1308 private void AfterUpdate()
1311 _dictVersionActualizacion = LoadVersionVariable();
1313 if (!NowUpdating(tlAferUpdate:
true))
1315 _cVersionDllServidor =
string.Empty;
1318 if (IsSuperiorVersionServidorTerminal())
1320 if (
MessageBox.Show($
"El proceso de actualización de {_cNameProducto} ha finalizado." + Environment.NewLine + Environment.NewLine +
1321 $
"¿Desea cerrar {_cNameProducto} para actualizar los cambios de la nueva versión?", _cText, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
1323 _llCloseApplication =
true;
1327 _cVersionDllServidor =
string.Empty;
1328 _oStateActualizacion = StateActualizacion.PendienteCerrar;
1337 private void CloseAplication()
1339 if (Application.OpenForms.Count > 0)
1341 Form loForm = Application.OpenForms[
"frmPrincipal"];
1344 _50.Forms.frmPrincipal loPripal = (_50.Forms.frmPrincipal)loForm;
1345 loPripal._Terminar_Ejecucion();
1353 private void ChangeVisibility()
1356 ewImagenInformacion.Visible = _lVisible;
1358 if (_Refresh_Actualizacion != null)
1359 _Refresh_Actualizacion(_lVisible);
1370 private bool ExecuteUpdate()
1372 if (!FUNCTIONS.InternetOk())
1376 string lcError =
string.Empty;
1378 if (!ValidateFilePath(_cPathIniTerminal, _cFileUpdateSage50))
1383 _lActualizando =
true;
1385 llOk = Execute(_cPathIniTerminal, _cFileUpdateSage50, ParamsExecuteUpdate(), ref lcError);
1393 while (ExistProcessActualizarSage50());
1399 catch (Exception loEx)
1401 lcError = loEx.Message;
1405 MessageBox.Show($
"No se ha podido realizar la actualización de {_cNameProducto}." + Environment.NewLine + lcError, _cText, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
1407 _lActualizando =
false;
1416 private string ParamsExecuteUpdate()
1418 string lcParams =
string.Empty;
1420 Dictionary<string, object> dictParams =
new Dictionary<string, object>();
1421 dictParams.Add(
"Usuario",
"SUPERVISOR");
1422 dictParams.Add(
"ModoAvanzado",
false);
1426 lcParams =
new JavaScriptSerializer().Serialize(dictParams);
1427 lcParams = lcParams.Replace(
"\"",
"\\\"");
1429 catch (Exception loEx)
1431 _cMensaje_Error = $
"No se ha podido serializar la información de la actualizacion de {_cNameProducto}." + Environment.NewLine + loEx.Message;
1446 private bool Execute(
string tcPath,
string tcFile,
string tcParams, ref
string tcError)
1449 tcError =
string.Empty;
1451 Process loProcess =
new Process();
1452 loProcess.EnableRaisingEvents =
false;
1453 ProcessStartInfo loExe =
new ProcessStartInfo(Path.Combine(tcPath, tcFile));
1454 loExe.WorkingDirectory = tcPath;
1455 loExe.Arguments = tcParams;
1456 loProcess.StartInfo = loExe;
1457 loProcess.StartInfo.CreateNoWindow =
true;
1458 loProcess.EnableRaisingEvents =
true;
1462 llOk = loProcess.Start();
1463 loProcess.WaitForExit();
1465 catch (Exception loEx)
1467 tcError = loEx.Message;
1477 private void LoadImage()
1479 if (_lVisible && ewImagenInformacion.Image == null)
1480 ewImagenInformacion.Image = images.Properties.Resources.icon_actualizacion32x24;
1482 #endregion Métodos privados 1484 #region Métodos BackGroundWorker 1485 private void _GetData_Async()
1495 private void DoWork()
1497 if (!_lBackgroudWorkerIsRunning && _oStateActualizacion != StateActualizacion.PendienteCerrar)
1499 _lBackgroudWorkerIsRunning =
true;
1502 _oBackgroundWorker =
new BackgroundWorker();
1505 _oBackgroundWorker.WorkerSupportsCancellation =
true;
1506 _oBackgroundWorker.WorkerReportsProgress =
false;
1509 _oBackgroundWorker.DoWork +=
new DoWorkEventHandler(ExecuteRunWorker);
1510 _oBackgroundWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(RunWorkerCompleted);
1513 _oBackgroundWorker.RunWorkerAsync();
1522 private void ExecuteRunWorker(
object sender, DoWorkEventArgs e)
1527 loResult.
_Resultado =
new Dictionary<string, object>() { };
1529 if (_oStateActualizacion == StateActualizacion.Actualizar)
1533 bool llUpdate = UpdateAvailable();
1535 loResult.
_Resultado.Add(
"ExisteActualizacion", llUpdate);
1538 e.Result = loResult;
1540 catch (Exception loEx)
1542 DB.Escribir_En_Log_Error(DB.Modo_Registro.Registro_Error, loEx);
1551 private void RunWorkerCompleted(
object sender, RunWorkerCompletedEventArgs e)
1553 if (_llCloseApplication)
1561 if (_oStateActualizacion == StateActualizacion.Actualizar)
1568 if (loWidgetResultadoBackgroundWorker.
_Resultado.ContainsKey(
"ExisteActualizacion"))
1570 _lVisible = Convert.ToBoolean(loWidgetResultadoBackgroundWorker.
_Resultado[
"ExisteActualizacion"]);
1579 DescripcionTooltTip();
1583 _oStateActualizacion = StateActualizacion.SinEstado;
1585 _lBackgroudWorkerIsRunning =
false;
1588 #endregion Métodos BackGroundWorker 1592 bool disposed =
false;
1600 GC.SuppressFinalize(
this);
1607 protected new virtual void Dispose(
bool disposing)
1615 SubscripcionEventos(
true);
1617 if (_oToolTip != null)
1618 _oToolTip.Dispose();
1620 _oBusinessNuevaActualizacion = null;
1622 _oBackgroundWorker?.Dispose();
1623 _oBackgroundWorker = null;
1625 _dictVersionActualizacion?.Clear();
1626 _dictVersionActualizacion = null;
1628 if (components != null)
1629 components.Dispose();
1643 #endregion IDisposable 1646 #region clase BusinessNuevaActualizacion 1647 public class BusinessNuevaActualizacion
1652 #region Propiedades privadas 1653 private string _cVariable =
"ACTUA_S50";
1658 private string _cComunesPripal =
"";
1659 #endregion Propiedades privadas 1662 public BusinessNuevaActualizacion()
1667 _cComunesPripal = Convert.ToString(EW_GLOBAL._GetVariable(
"wc_ComunesPripal"));
1668 _cComunesPripal =
string.IsNullOrWhiteSpace(_cComunesPripal) ? DB.DbComunes : _cComunesPripal;
1670 #endregion Constrcutor 1672 #region Métodos públicos 1681 bool llOk = (DB.SQLExec(
"SELECT VALOR FROM " + DB.SQLDatabaseReal(_cComunesPripal,
"VARIABLE") + Environment.NewLine +
1682 " WHERE VARIABLE = " + DB.SQLString(_cVariable), ref tdtVariable));
1697 lcSql =
"INSERT INTO " + DB.SQLDatabaseReal(_cComunesPripal,
"VARIABLE") + Environment.NewLine +
1698 " (VARIABLE, VALOR, TIPO) " + Environment.NewLine +
1699 " VALUES (" + DB.SQLString(_cVariable) +
" , " + DB.SQLString(tcValores) +
", 'C')";
1701 llOk = DB.SQLExec(lcSql);
1716 lcSql =
"UPDATE " + DB.SQLDatabaseReal(_cComunesPripal,
"VARIABLE") + Environment.NewLine +
1717 " SET VALOR = " + DB.SQLString(tcValores) + Environment.NewLine +
1718 " WHERE VARIABLE = " + DB.SQLString(_cVariable);
1720 llOk = DB.SQLExec(lcSql);
1726 #endregion Métodos públicos 1729 #endregion clase BusinessNuevaActualizacion 1731 #region clase InfoNuevaActualizacion 1732 public class InfoNuevaActualizacion
1737 #region Propiedades públicas 1738 public NuevaActualizacion.eServidorTerminalLib _ServidorTerminal {
get;
set; } = NuevaActualizacion.eServidorTerminalLib.Indefinido;
1746 public string _VersionServidor {
get;
set; } =
"";
1750 public string _FechaServidor {
get;
set; } =
"";
1755 public string _VersionTerminal {
get;
set; } =
"";
1760 public string _FechaTerminal {
get;
set; } =
"";
1765 public string _VersionActua {
get;
set; } =
"";
1769 public string _FechaActua {
get;
set; } =
"";
1771 #endregion Propiedades públicas 1780 #endregion Constrcutor 1783 #endregion clase InfoNuevaActualizacion
static sage.ew.usuario.Usuario _This
Instancia estática del objeto usuario con los datos del usuario actual (wc_usuario) ...
Dictionary< string, string > _Saving()
Evento que se produce al guardar el escritorio No realiza ninguna acción
bool _OnRefresh()
Evento que se produce en el refresco del widget
virtual new void Dispose(bool disposing)
Protected implementation of Dispose pattern.
bool _InsertVariable(string tcValores)
Realiza el Insert de la información en la tabla COMUNES!VARIABLE
bool _OnShow()
Evento que se produce al mostrar el widget
bool _Filtrar(bool tlBefore=false)
Realizar los cambios necesarios en las propiedades filtradas
static String _Sage50Version
Versión de Sage50
_Refresh_Actualizacion_Handler _Refresh_Actualizacion
Desencadena el evento
new void Dispose()
Public implementation of Dispose pattern callable by consumers.
Interfaz que deben cumplir los objetos que se pueden poner en el escritorio de Sage 50 ...
Clase de negocio con la información
Widget para las notificaciones de nuevas actualizaciones de Sage50
bool _Loading(Dictionary< string, string > tdictPersonalizado)
Carga personalizada del widget De momento no realizamos el refresco debido a que luego ya realizará e...
bool _DatatableVersionVariable(ref DataTable tdtVariable)
Consulta la información de la tabla COMUNES!VARIABLE para la variable ACTUA_S50
Clase de negocio para la actualización de la información
Clase controlador que se utilizará en el escritorio de Sage 50
static String _ObtenerFechaVersion(string tcPath)
Obtener fecha de la versión del fichero según ruta definida en el parámetro
eServidorTerminalLib
Enumeración para indicar que librerias se tienen de actualizar (servidor o terminal) ...
Clase para determinar el número de versión
void _ActualizaSage50()
Lanza el asistente de actualización si hay versión para actualizar
bool _Opcesp(string tcCodigo)
Método que nos devuelve "true" en caso que el usuario actual tenga acceso a la opción especial con có...
bool _UpdateVariable(string tcValores)
Realiza el Update de la información en la tabla COMUNES!VARIABLE
static String _Sage50VersionServidor()
Versión del servidor de Sage50
bool _ExisteActualización()
Método para saber si existe una actualización de Sage50
Interfaz que nos permite configurar el contorno del Widget
Definición de la clase Usuario