public void Run(object parameter = null) { Status = CheckStatus((ISchemaInfo)parameter); if (Status != EComponentStatus.READY) { return; } Status = EComponentStatus.WORKING; try { //Before calling. Maybe could be an error UpdateLastExecution((ISchemaInfo)parameter); Status = DoRun(parameter); Status = EComponentStatus.OK; //After calling. Real last update UpdateLastExecution((ISchemaInfo)parameter); MyLogger.LogText("COMPLETE", string.Format("{0}::Run", ID)); } catch (Exception ex) { MyLogger.LogText("FINALIZED WITH ERROR", string.Format("{0}::Run", ID)); MyLogger.LogException(ex, string.Format("{0}::Run", ID)); Status = EComponentStatus.ERROR; } return; }
protected virtual void Login() { try { if (AppContext.Principal != null) { AppContext.Principal.Logout(); } PrincipalBase.Login(); MyLogger.LogText(string.Format("CONNECTED TO {0}:{1} AS USER {2}", SettingsMng.Instance.GetActiveServer(), SettingsMng.Instance.GetDBName(), SettingsMng.Instance.GetDBUser()), "Service::Login"); } catch (Exception ex) { MyLogger.LogException(ex, "ServiceBase::Login"); if (AppContext.Principal != null) { AppContext.Principal.Close(); } } }
protected void StartTimer() { try { TimerGuid = TimerMng.Instance.InitTimer(ETimerType.System, ServiceTimerController, PollInterval); MyLogger.LogText(string.Format("Service Timer Started. TICK EVERY {0}s", PollInterval), "Service::StartTimer"); } catch (Exception ex) { MyLogger.LogException(ex, "ServiceBase::StartTimer"); } }
protected override void OnStop() { try { Close(); } catch (Exception ex) { MyLogger.LogException(ex, "ServiceBase::OnStop"); } finally { MyLogger.LogText("Service Stopped", "ServiceBase::OnStop"); } }
//System.Timers.Timer EventHandler private void Timer_Elapsed(object sender, ElapsedEventArgs e) { try { TTimer timer = TickTimers.Values.Single(item => (((TTimer)item).Type == ETimerType.System) && ((System.Timers.Timer)((TTimer)item).Timer).Equals((System.Timers.Timer)sender)); timer.Controller(timer); } catch (Exception ex) { if (IsLogEnabled) { MyLogger.LogText(ex.Message); } } }
protected virtual void Execute() { try { //To avoid overlapped executions if (Running) { MyLogger.LogText("LAST EXECUTION IS STILL BUSY. NOT EXECUTED TO AVOID OVERLAPPING", "ServiceBase::Execute"); return; } Running = true; foreach (ISchemaInfo item in Schemas) { MyLogger.LogText(String.Format("PROCESSING SCHEMA '{0}'...", item.Name), "ServiceBase::Execute"); if (!LoadSchema(item)) { MyLogger.LogText(String.Format("ERROR LOADING SCHEMA {0}", item.Name), "ServiceBase::Execute"); Running = false; return; } foreach (KeyValuePair <string, ICronJob> cronjob in CronJobs) { Thread cronThread = ExecuteTask(cronjob.Value, item); while (cronThread != null && cronThread.IsAlive) { } ; } } Running = false; } catch (Exception ex) { Running = false; MyLogger.LogException(ex, "ServiceBase::Execute"); Login(); } }
protected virtual void LoadCronJobs() { try { foreach (KeyValuePair <string, ICronJob> item in CronJobs) { if (item.Value.Status == EComponentStatus.DISABLED) { MyLogger.LogText(string.Format("{0} is DISABLED", item.Key), "ServiceBase::LoadCronjobs"); } else { MyLogger.LogText(string.Format("{0} is ENABLED EVERY {1}s", item.Key, item.Value.Interval), "ServiceBase::LoadCronjobs"); } } } catch (Exception ex) { MyLogger.LogException(ex, "ServiceBase::LoadCronJobs"); } }
private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData) { HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest; request.AllowAutoRedirect = false; //request.Headers.Add("Accept-Language:" + System.Threading.Thread.CurrentThread.CurrentCulture.Name); request.Headers.Add("Accept-Language:" + "en"); if (request == null) { throw new NullReferenceException("request is not a http request"); } request.Method = "POST"; request.ContentType = contentType; request.UserAgent = userAgent; request.CookieContainer = new CookieContainer(); request.ContentLength = formData.Length; request.Timeout = 300000; request.KeepAlive = true; request.ReadWriteTimeout = 1000000; request.Credentials = System.Net.CredentialCache.DefaultCredentials; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(formData, 0, formData.Length); requestStream.Close(); } if (Properties.Settings.Default.IsDebug) { MyLogger.LogText("HttpWebResponse::PostForm POST URL: " + postUrl); MyLogger.LogText("HttpWebResponse::PostForm FORM DATA: " + request.GetRequestStream().ToString()); } return(request.GetResponse() as HttpWebResponse); }
/*public static nHManager InitnHManager(string mapFilesPath) { return InitnHManager(mapFilesPath, string.Empty); } * public static nHManager InitnHManager(string mapFilesPath, string server) { return InitnHManager(mapFilesPath, string.Empty, string.Empty, server); }*/ public static nHManager InitnHManager(string appAlias, string mapFilesPath, string user, string pwd, string server) { if (String.IsNullOrEmpty(mapFilesPath)) { mapFilesPath = Path.Combine(AppContext.StartUpPath, SettingsMng.Instance.GetNHConfigFileRelativePath(appAlias)); } MyLogger.LogText("Application Type is " + SettingsMng.Instance.GetApplicationType().ToString(), "PrincipalBase::InitnHManager"); MyLogger.LogText("Application config file is " + mapFilesPath ?? string.Empty, "PrincipalBase::InitnHManager"); if (String.IsNullOrEmpty(user)) { user = SettingsMng.GetSuperUser(); } if (String.IsNullOrEmpty(pwd)) { pwd = SettingsMng.Instance.GetDBPassword(); } Type[] mappings = new Type[0]; foreach (KeyValuePair <Type, IModuleDef> module in AppControllerBase.AppControler.Modules) { mappings = MergeMapping(mappings, module.Value.Mappings); } nHManager.Instance.Configure(mapFilesPath, mappings, pwd, User.MapToDBUsername(user), string.Empty, server); SettingsMng.Instance.SetActiveServer(nHManager.Instance.Host); SettingsMng.Instance.SetDBName(nHManager.Instance.Database); SettingsMng.Instance.SetDBUser(user); SettingsMng.Instance.SetDBPassword(pwd); return(nHManager.Instance); }
public void GETToSite(Control control, WebBrowser webBrowser, string url, Delegate packer) { TProxyResult result = new TProxyResult { Status = EComponentStatus.WORKING, Message = string.Empty, }; try { // Generate post objects Dictionary <string, object> postParameters = new Dictionary <string, object>(); Dictionary <string, object> postParametersLog = new Dictionary <string, object>(); if (packer != null) { control.Invoke(packer, postParameters); } // Parameters are written to log file in JSON string postParameteresJson = JsonConvert.SerializeObject(postParametersLog); //string postUrl = HttpUtility.UrlEncode(url + GetPHPFormatParams(postParameters)); string getUrl = url + GetPHPFormatParams(postParameters); if (!Properties.Settings.Default.IsDebug) { MyLogger.LogText("NEW GET TO: " + getUrl, "Proxy:: GETToSite"); } else { MyLogger.LogText("NEW DEBUG GET TO : " + getUrl, "Proxy:: GETToSite"); } try { if (Settings.Default.IsDebug) { MyLogger.LogText(getUrl); } MyLogger.LogText("BEGIN DATA GET", "Proxy:: GETToSite"); webBrowser.Navigate(getUrl, null, null, "User-Agent: " + GetUserAgent(EBrowser.Chrome)); MyLogger.LogText("END DATA GET", "Proxy:: GETToSite"); } catch (Exception ex) { result.Status = EComponentStatus.ERROR; result.Message = String.Format(Resources.Messages.SERVER_CONNECTION_ERROR, ex.Message); MyLogger.LogText("ERROR IN GET: " + result.Message, "Proxy:: GETToSite"); return; } result.Status = EComponentStatus.OK; } catch (Exception ex) { MyLogger.LogText("IN GETToSite" + ex.Message, "Proxy:: GETToSite"); result.Status = EComponentStatus.ERROR; result.Message = ex.Message; } finally { InsertResult(GetResultKey(url), result); } }
public void POSTToSite(string url, DlgPackPOSTData packer) { TProxyResult result = new TProxyResult { Status = EComponentStatus.WORKING, Message = string.Empty, ExceptionStatus = WebExceptionStatus.Success, }; try { // Generate post objects Dictionary <string, object> postParameters = new Dictionary <string, object>(); Dictionary <string, object> postParametersLog = new Dictionary <string, object>(); packer(postParameters, postParametersLog); // Parameters are written to log file in JSON string postParameteresJson = JsonConvert.SerializeObject(postParametersLog); string userAgent = Properties.Settings.Default.UserAgent; string postURL = url; try { if (Settings.Default.IsDebug) { MyLogger.LogText(postURL); MyLogger.LogText("POST Parameters"); foreach (KeyValuePair <string, object> item in postParameters) { MyLogger.LogText(item.Key + ": " + item.Value); } } MyLogger.LogText("BEGIN DATA POST TO " + postURL, "Proxy::POSTToSite"); result.Response = MultipartFormDataPost(postURL, userAgent, postParameters); MyLogger.LogText("END DATA POST", "Proxy::POSTToSite"); } catch (System.Net.WebException ex) { result.Status = EComponentStatus.ERROR; result.Message = Resources.Messages.SERVER_CONNECTION_ERROR; result.Response = ex.Response as HttpWebResponse; result.ExceptionStatus = ex.Status; MyLogger.LogText("ERROR IN POST: " + iQExceptionHandler.GetAllMessages(ex) + System.Environment.NewLine + "POST URL: " + postURL + System.Environment.NewLine + "POST RESPONSE: " + result.Response.ToString(), "Proxy::POSTToSite"); InsertResult(url, result); return; } if (result.Response.StatusCode == HttpStatusCode.OK) { // Process response StreamReader responseReader = new StreamReader(result.Response.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); result.Response.Close(); try { Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer(); Newtonsoft.Json.JsonReader r = new Newtonsoft.Json.JsonTextReader(new StringReader(fullResponse)); Newtonsoft.Json.Linq.JObject res = ser.Deserialize(r) as Newtonsoft.Json.Linq.JObject; StringBuilder sb = new StringBuilder(); foreach (KeyValuePair <string, JToken> kvp in res) { switch (kvp.Key) { case "message": { result.Status = (kvp.Value.ToString() == "OK") ? EComponentStatus.OK : EComponentStatus.ERROR; sb.AppendLine((kvp.Value != null ? (kvp.Value.HasValues ? kvp.Value.First.ToString() : kvp.Value.ToString()) : "")); } break; default: sb.AppendLine(kvp.Value != null ? (kvp.Value.HasValues ? kvp.Value.First.ToString() : kvp.Value.ToString()) : ""); break; } } result.Message = sb.ToString(); } catch { MyLogger.LogText("JSON DESERIALIZE ERROR", "Proxy::POSTToSite"); MyLogger.LogText("FULL RESPONSE: " + fullResponse, "Proxy::POSTToSite"); result.Message = fullResponse; } } else { MyLogger.LogText("HTTP REQUEST STATUS ERROR.", "Proxy::POSTToSite"); MyLogger.LogText("HTTP URL: " + url, "Proxy::POSTToSite"); } } catch (Exception ex) { MyLogger.LogText("IN POSTToSite: " + ex.Message, "Proxy::POSTToSite"); result.Status = EComponentStatus.ERROR; result.Message = ex.Message; } finally { InsertResult(url, result); } }
public void POSTToSite(Control control, string url, Delegate packer) { TProxyResult result = new TProxyResult { Status = EComponentStatus.WORKING, Message = string.Empty, Response = null, ExceptionStatus = WebExceptionStatus.Success, }; try { // Generate post objects Dictionary <string, object> postParameters = new Dictionary <string, object>(); Dictionary <string, object> postParametersLog = new Dictionary <string, object>(); control.Invoke(packer, new object[2] { postParameters, postParametersLog }); string postURL = url; string userAgent = Properties.Settings.Default.UserAgent; // Parameters are written to log file in JSON string postParameteresJson = JsonConvert.SerializeObject(postParametersLog); if (!Properties.Settings.Default.IsDebug) { MyLogger.LogText("NEW POST. " + postParameteresJson, "Proxy::POSTToSite"); } else { MyLogger.LogText("NEW DEBUG POST. " + postParameteresJson, "Proxy::POSTToSite"); } try { if (Settings.Default.IsDebug) { MyLogger.LogText(postURL); foreach (KeyValuePair <string, object> item in postParameters) { MyLogger.LogText(item.Key + ": " + item.Value); } } MyLogger.LogText("BEGIN DATA POST TO " + postURL, "Proxy::POSTToSite"); result.Response = MultipartFormDataPost(postURL, userAgent, postParameters); MyLogger.LogText("END DATA POST", "Proxy::POSTToSite"); } catch (System.Net.WebException ex) { result.Status = EComponentStatus.ERROR; result.Message = String.Format(Resources.Messages.SERVER_CONNECTION_ERROR, ex.Message); result.Response = ex.Response as HttpWebResponse; result.ExceptionStatus = ex.Status; MyLogger.LogText("ERROR IN POST: " + ex.Message + System.Environment.NewLine + "POST URL: " + postURL , "Proxy::POSTToSite"); InsertResult(url, result); return; } if (result.Response.StatusCode == HttpStatusCode.OK) { MyLogger.LogText("HTTP STATUS OK: " + result.Message, "Proxy::POSTToSite"); result.Status = EComponentStatus.ERROR; // Process response StreamReader responseReader = new StreamReader(result.Response.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); result.Response.Close(); MyLogger.LogText("FULL RESPONSE: " + fullResponse, "Proxy::POSTToSite"); try { MyLogger.LogText("JSON DESERIALIZE BEGIN", "Proxy::POSTToSite"); Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer(); Newtonsoft.Json.JsonReader r = new Newtonsoft.Json.JsonTextReader(new StringReader(fullResponse)); Newtonsoft.Json.Linq.JObject res = ser.Deserialize(r) as Newtonsoft.Json.Linq.JObject; StringBuilder sb = new StringBuilder(); sb.AppendLine("Server response"); foreach (KeyValuePair <string, JToken> kvp in res) { sb.AppendLine(string.Format("{0} - {1}", kvp.Key, kvp.Value != null ? (kvp.Value.HasValues ? kvp.Value.First.ToString() : kvp.Value.ToString()) : "")); } result.Message = sb.ToString(); MyLogger.LogText("JSON DESERIALIZE END. RESULT: " + result.Message, "Proxy::POSTToSite"); InsertResult(url, result); return; } catch { MyLogger.LogText("JSON DESERIALIZE ERROR", "Proxy::POSTToSite"); result.Message = fullResponse; InsertResult(url, result); return; } } else { result.Status = EComponentStatus.OK; MyLogger.LogText("NO RESPONSE ERROR. USER REGISTERED. REDIRECTION.", "Proxy::POSTToSite"); InsertResult(url, result); return; } } catch (Exception ex) { MyLogger.LogText("IN POSTToSite: " + ex.Message, "Proxy::POSTToSite"); result.Status = EComponentStatus.ERROR; result.Message = ex.Message; InsertResult(url, result); } }
protected static void DoCreateBackup(string dbHost, string dbName, string dbUser, List <ISchemaInfo> schemas, string outputFile) { System.Diagnostics.Process process = null; try { //Obtención de la ruta de pg_dump string path_pg_dump = Reg32GetPGBinPath() + Paths.PG_DUMP; if (path_pg_dump == string.Empty) { return; } if (!File.Exists(path_pg_dump)) { throw new iQException(Errors.BACKUP_APP_NOT_FOUND); } string msg = "Creating db credentials file " + outputFile; MyLogger.LogText(msg, "AppControllerBase::DoCreateBackup"); Console.WriteLine(msg); string db_pass = SettingsMng.Instance.GetDBPassword(); //Creamos el fichero pgpass.conf para que no salte el prompt pidiendo password string pgpassPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); pgpassPath += Paths.PG_PASS; if (!Directory.Exists(Path.GetPathRoot(pgpassPath))) { Directory.CreateDirectory(Path.GetPathRoot(pgpassPath)); } StreamWriter sw = File.CreateText(pgpassPath); sw.WriteLine(dbHost + ":*:*:" + dbUser + ":" + db_pass); sw.Close(); if (!Directory.Exists(Path.GetDirectoryName(outputFile))) { Directory.CreateDirectory(Path.GetDirectoryName(outputFile)); } //Crea un nuevo proceso process = new System.Diagnostics.Process(); if (schemas == null) { //Ejecución del pg_dump process.StartInfo.FileName = path_pg_dump; process.StartInfo.Arguments = string.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8}" , new string[] { "--format=c" , "--ignore-version" , "--oids" , "--blobs" , "--verbose" , "--host=" + dbHost , "-U " + dbUser , @"--file=""" + string.Format(outputFile, "FULL") + @"""" , @"""" + dbName + @"""" } ); process.Start(); process.WaitForExit(); } else { //COMMON SCHEMA try { //Ejecución del pg_dump process.StartInfo.FileName = path_pg_dump; process.StartInfo.Arguments = string.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}" , new string[] { "--format=c" , "--ignore-version" , "--oids" , "--blobs" , "--verbose" , "--host=" + dbHost , "-U " + dbUser , @"--file=""" + string.Format(outputFile, AppContext.CommonSchema) + @"""" , "--schema=" + AppContext.CommonSchema , @"""" + dbName + @"""" } ); process.Start(); process.WaitForExit(); } catch (Exception ex) { MyLogger.LogException(ex, "AppControllerBase::DoCreateBackup"); } //DETAILED SCHEMAS foreach (ISchemaInfo schema in schemas) { try { //Ejecución del pg_dump process.StartInfo.FileName = path_pg_dump; process.StartInfo.Arguments = string.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}" , new string[] { "--format=c" , "--ignore-version" , "--oids" , "--blobs" , "--verbose" , "--host=" + dbHost , "-U " + dbUser , @"--file=""" + string.Format(outputFile, schema.SchemaCode) + @"""" , "--schema=" + schema.SchemaCode , @"""" + dbName + @"""" } ); process.Start(); process.WaitForExit(); } catch (Exception ex) { MyLogger.LogException(ex, "AppControllerBase::DoCreateBackup"); } } } //Borramos el fichero pgpass.conf File.Delete(pgpassPath); SettingsMng.Instance.SetBackupsLastDate(DateTime.Now); SettingsMng.Instance.SaveSettings(); } catch (Exception ex) { MyLogger.LogException(ex, "AppControllerBase::DoCreateBackup"); if (process != null) { MyLogger.LogText("process.StartInfo.Arguments = " + process.StartInfo.Arguments); } } }
public static void TreatException(Exception ex, object[] parameters) { MyLogger.LogText(ex.Message + ex.StackTrace, GetCaller(ex)); if (ex is Npgsql.NpgsqlException) { if (ex.InnerException != null) { TreatException(ex.InnerException); } else { MyLogger.LogText(ex.Message, GetCaller(ex)); ThrowExceptionByCode(ex as Npgsql.NpgsqlException, parameters); } } else if (ex is NHibernate.ADOException) { //DB Exception if ((ex.InnerException != null) && (ex.InnerException is NHibernate.ADOException)) { TreatException(ex.InnerException); } else { MyLogger.LogText(ex.Message, GetCaller(ex)); ThrowExceptionByCode(ex as NHibernate.ADOException, parameters); } } else if ((ex is Csla.DataPortalException) || (ex is Csla.Server.CallMethodException)) { if (ex.InnerException != null) { TreatException(ex.InnerException); } else { MyLogger.LogText(ex.Message, GetCaller(ex)); throw new iQException(GetAllMessages(ex)); } } else if (ex is System.Net.Sockets.SocketException) { MyLogger.LogText(ex.Message, GetCaller(ex)); //Conexion Exception throw new iQException(Resources.Errors.SERVER_NOT_FOUND, ex.Message, iQExceptionCode.SERVER_NOT_FOUND); } else if (ex is iQAuthorizationException) { //User Authorization throw ex; } else if (ex is Csla.Validation.ValidationException) { //Object Validation throw new iQValidationException(Resources.Errors.GENERIC_VALIDATION_FAIL, (ex as Csla.Validation.ValidationException).Message); } else if (ex is iQLockException) { //Code Validation throw ex; } else if (ex is iQDuplicateCodeException) { //Code Validation throw ex; } else if (ex is iQValidationException) { //Child Validation if (((iQValidationException)ex).Field == string.Empty) { throw new iQValidationException(string.Empty, (ex as iQValidationException).Message, ((iQValidationException)ex).SysMessage); } else { throw ex; } } else if (ex is System.NullReferenceException) { MyLogger.LogText(ex.Message, GetCaller(ex)); //Rules checking throw new iQException(Resources.Errors.RULES_CHECK + Environment.NewLine + iQExceptionHandler.GetAllMessages(ex)); } else if (ex is System.Web.HttpException) { //Code Validation string msg = string.IsNullOrEmpty(((System.Web.HttpException)ex).GetHtmlErrorMessage()) ? string.Empty : ((System.Web.HttpException)ex).GetHtmlErrorMessage(); throw new iQException(msg, iQExceptionHandler.GetAllMessages(ex, true), iQExceptionCode.HTTP_ERROR, new object[] { ex }); } else { MyLogger.LogText(ex.Message, GetCaller(ex)); throw new iQException(GetAllMessages(ex as Exception)); } }
protected virtual void Initialize() { MyLogger.LogText(String.Format("{0} SCHEMAS FOUND", (Schemas == null) ? 0 : Schemas.Count), "ServiceBase::OnStart"); StartTimer(); }
protected Thread ExecuteTask(ICronJob cronjob, object parameter) { if (cronjob == null) { return(null); } try { switch (cronjob.CheckStatus((ISchemaInfo)parameter)) { case EComponentStatus.DISABLED: { if (LogLevel == ELogLevel.ALL) { MyLogger.LogText(string.Format("{0} DISABLED", cronjob.ID), "ServiceBase::ExecuteTask"); } return(null); } case EComponentStatus.WORKING: { if (LogLevel == ELogLevel.ALL || LogLevel == ELogLevel.WARN) { MyLogger.LogText(string.Format("{0} STILL BUSY", cronjob.ID), "ServiceBase::ExecuteTask"); } return(null); } case EComponentStatus.UNAVAILABLE: { if (LogLevel == ELogLevel.ALL) { MyLogger.LogText(string.Format("{0} OUT OF DATE ", cronjob.ID), "ServiceBase::ExecuteTask"); } return(null); } case EComponentStatus.READY: { if (LogLevel == ELogLevel.ALL || LogLevel == ELogLevel.WARN) { MyLogger.LogText(string.Format("{0} STARTED ", cronjob.ID), "ServiceBase::ExecuteTask"); } #if DEBUG cronjob.Run(parameter); return(null); #else Thread taskthread = new Thread(new ParameterizedThreadStart(cronjob.Run)); taskthread.Start(parameter); return(taskthread); #endif } } return(null); } catch (Exception ex) { MyLogger.LogException(ex, "ServiceBase::ExecuteTask"); return(null); } }