Program.cs
1 using Microsoft.Win32;
2 using System;
3 using System.Collections.Generic;
4 using System.Diagnostics;
5 using System.IO;
6 using System.Linq;
7 using System.Reflection;
8 using System.Text.RegularExpressions;
9 using System.Windows.Forms;
10 
11 namespace Sage.ES.S50.Launch
12 {
13 
14  static class Program
15  {
16  private const string _cNameProd = "Sage 50";
17  private const int nPrimeraVersionSOCompatible = 10240;
18 
22  [STAThread]
23  static void Main(String[] args)
24  {
25  try
26  {
27 
28  //System.Diagnostics.Debugger.Launch();
29  //Directory.SetCurrentDirectory(@"C:\sage50\7610\sage50cterm");
30  string lcProcessName, lcVersion, lcLibrary, lcClass, lcPath, lcArguments = "";
31 
32  lcVersion = DirectoryNameVersion(Directory.GetCurrentDirectory());
33  lcPath = Path.Combine(Directory.GetCurrentDirectory(), lcVersion);
34  lcLibrary = Path.Combine(lcPath, "Sage.50.exe");
35  lcClass = "Sage.ES.S50.S50Update.Classes.S50UpdateLibrary";
36  if (HasArgument(args, "NOVALIDATE") || ValidateSOFramework(lcVersion))
37  {
38  if (HasArgument(args, "WAIT5"))
39  {
40  //Esperamos 5 segundos
41  System.Threading.Thread.Sleep(5000);
42  //Quitamos el parametro
43  args = args.Where(x => x != "WAIT5").ToArray();
44  }
45 
46  if (File.Exists(lcLibrary))
47  {
48  //_UpdateSageUpdate(lcLibrary, lcClass);
49  Directory.SetCurrentDirectory(lcPath);
50 
51  Process loStart = new System.Diagnostics.Process();
52  ProcessStartInfo loStartInfo;
53 
54  lcProcessName = "SageUpdate.exe";
55  lcArguments = string.Format(" \"{0}\" \"{1}\" ", lcClass, lcLibrary); //Pasamos el tipo a instaciar
56  lcArguments += string.Join(" ", args);
57 
58  // String lcArguments = String.Format(" \"{0}\" \"{1}\" \"nodomain\" ", lcClass, lcLibrary); //Pasamos el tipo a instaciar
59 
60  loStartInfo = new System.Diagnostics.ProcessStartInfo(lcProcessName);
61  loStartInfo.Arguments = lcArguments;
62  loStartInfo.WorkingDirectory = lcPath;
63  loStart.StartInfo = loStartInfo;
64 
65  if (loStart.Start())
66  {
67  loStart.Close();
68  }
69  }
70  else
71  {
72  throw new Exception(String.Format("File not found {0}", lcLibrary));
73  }
74  }
75  }
76  catch (Exception ex)
77  {
78  _SetEventLog(ex.Message);
79  }
80 
81  Application.Exit();
82  }
83 
84  private static bool HasArgument(string[] toArgs, string tcKey)
85  {
86  return toArgs.Length > 0 && toArgs.Any(f => f.ToUpper() == tcKey);
87  }
88 
89  private static bool ValidateSOFramework(string tcVersion)
90  {
91  int lnVersion;
92  string lcError = "";
93  Version loVersion, loCuttingVersion;
94 
95  try
96  {
97  if (!string.IsNullOrEmpty(tcVersion) && tcVersion != "librerias")
98  {
99  loVersion = new Version(tcVersion);
100  loCuttingVersion = new Version(50, 7810, 0);
101 
102  if (loVersion >= loCuttingVersion)
103  {
104  if ((lnVersion = _GetValueRegistry(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentBuildNumber")) < nPrimeraVersionSOCompatible)
105  {
106  lcError = $"La versión de Windows de este ordenador ({lnVersion}) no es compatible con {_cNameProd}.";
107  lcError = $"{lcError}{Environment.NewLine}{Environment.NewLine}Solo es posible acceder a {_cNameProd} desde ordenadores con una versión de Windows igual o superior a Windows 10 o Windows Server 2016.";
108  }
109  else if (_GetValueRegistry("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\", "Release") < 528040)
110  {
111  lcError = $"El ordenador no tiene instalado Framework.NET 4.8.";
112  lcError = $"{lcError}{Environment.NewLine}{Environment.NewLine}Solo es posible acceder a {_cNameProd} si el ordenador tiene instalado el Framework.NET 4.8";
113  }
114 
115  if (!string.IsNullOrEmpty(lcError))
116  {
117  lcError = $"No es posible acceder a Sage 50.{Environment.NewLine}{Environment.NewLine}{lcError}";
118  MessageBox.Show(lcError, "Atención", MessageBoxButtons.OK, MessageBoxIcon.Error);
119  _SetEventLog(lcError);
120  return false;
121  }
122  }
123  }
124  }
125  catch
126  {
127 
128  }
129 
130  return true;
131  }
132 
133  private static void _UpdateSageUpdate(String tcLibrary, String tcClass)
134  {
135  try
136  {
137  Assembly assembly = Assembly.LoadFrom(tcLibrary);
138  Type elementType = assembly.GetType(tcClass);
139 
140  if (elementType is Type)
141  {
142  //Validamos que el tipo cumple la clase abstraca
143  if (elementType.GetMethod("UpdateSageUpdate") is MethodInfo)
144  {
145  dynamic updateLibrary = Activator.CreateInstance(elementType, new object[] { Directory.GetCurrentDirectory() });
146  updateLibrary.UpdateSageUpdate();
147  }
148  }
149  }
150  catch (Exception ex)
151  {
152  _SetEventLog(ex.Message);
153  }
154  }
155 
156 
157  private static String DirectoryNameVersion(String path)
158  {
159  List<DirectoryInfo> loListDirs;
160  String pathDirectoryVersion = "";
161  String[] listDirectories = Directory.GetDirectories(path, "50.*");
162 
163  if (listDirectories.Length > 0)
164  {
165  loListDirs = (from lcDirName in listDirectories
166  select new DirectoryInfo(lcDirName)).ToList();
167 
168  //Validamos que sea un path correcto y que al menos exista el ejecutable de Sage50
169  pathDirectoryVersion = (from loDir in loListDirs
170  where Regex.IsMatch(loDir.Name, @"^50\.[0-9]{4}\.[0-9]{1,3}$")
171  && File.Exists(Path.Combine(loDir.FullName, "sage.50.exe"))
172  orderby loDir.Name descending
173  select loDir.Name).FirstOrDefault();
174  }
175 
176  if (String.IsNullOrEmpty(pathDirectoryVersion)) pathDirectoryVersion = "librerias";
177 
178  return pathDirectoryVersion;
179  }
180 
181  private static void _SetEventLog(String tcMessage)
182  {
183  String source = "Sage 50c";
184  if (!EventLog.SourceExists(source)) EventLog.CreateEventSource(source, "Application");
185  EventLog.WriteEntry(source, tcMessage, System.Diagnostics.EventLogEntryType.Error);
186  }
187 
188  private static int _GetValueRegistry(string tcKey, string tcRegistry)
189  {
190  using (var key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(tcKey))
191  {
192  return int.TryParse(Convert.ToString(key?.GetValue(tcRegistry)), out int lnVersion) ? lnVersion : 0;
193  }
194  }
195 
196  }
197 }