/// <summary> /// Creates a HTML file that contains central documentation of the Error Codes that are used throughout OpenPetra code /// </summary> public static bool Execute(string ACSharpPath, string ATemplateFilePath, string AOutFilePath) { Dictionary <string, ErrCodeInfo> ErrorCodes = new Dictionary <string, ErrCodeInfo>(); CSParser parsedFile = new CSParser(ACSharpPath + "/ICT/Common/ErrorCodes.cs"); string ErrCodeCategoryNice = String.Empty; TLogging.Log("Creating HTML documentation of OpenPetra Error Codes..."); ProcessFile(parsedFile, ref ErrorCodes); parsedFile = new CSParser(ACSharpPath + "/ICT/Petra/Shared/ErrorCodes.cs"); ProcessFile(parsedFile, ref ErrorCodes); parsedFile = new CSParser(ACSharpPath + "/ICT/Common/Verification/StringChecks.cs"); ProcessFile(parsedFile, ref ErrorCodes); ProcessTemplate t = new ProcessTemplate(ATemplateFilePath); Dictionary <string, ProcessTemplate> snippets = new Dictionary <string, ProcessTemplate>(); snippets.Add("GENC", t.GetSnippet("TABLE")); snippets["GENC"].SetCodelet("TABLEDESCRIPTION", "GENERAL (<i>Ict.Common* Libraries only</i>)"); snippets.Add("GEN", t.GetSnippet("TABLE")); snippets["GEN"].SetCodelet("TABLEDESCRIPTION", "GENERAL (across the OpenPetra application)"); snippets.Add("PARTN", t.GetSnippet("TABLE")); snippets["PARTN"].SetCodelet("TABLEDESCRIPTION", "PARTNER Module"); snippets.Add("PERS", t.GetSnippet("TABLE")); snippets["PERS"].SetCodelet("TABLEDESCRIPTION", "PERSONNEL Module"); snippets.Add("FIN", t.GetSnippet("TABLE")); snippets["FIN"].SetCodelet("TABLEDESCRIPTION", "FINANCE Module"); snippets.Add("CONF", t.GetSnippet("TABLE")); snippets["CONF"].SetCodelet("TABLEDESCRIPTION", "CONFERENCE Module"); snippets.Add("FINDEV", t.GetSnippet("TABLE")); snippets["FINDEV"].SetCodelet("TABLEDESCRIPTION", "FINANCIAL DEVELOPMENT Module"); snippets.Add("SYSMAN", t.GetSnippet("TABLE")); snippets["SYSMAN"].SetCodelet("TABLEDESCRIPTION", "SYSTEM MANAGER Module"); foreach (string snippetkey in snippets.Keys) { snippets[snippetkey].SetCodelet("ABBREVIATION", snippetkey); snippets[snippetkey].SetCodelet("ROWS", string.Empty); } foreach (string code in ErrorCodes.Keys) { foreach (string snippetkey in snippets.Keys) { if (code.StartsWith(snippetkey + ".")) { ProcessTemplate row = t.GetSnippet("ROW"); row.SetCodelet("CODE", code); ErrCodeInfo ErrCode = ErrorCodes[code]; switch (ErrCode.Category) { case ErrCodeCategory.NonCriticalError: ErrCodeCategoryNice = "Non-critical Error"; break; default: ErrCodeCategoryNice = ErrCode.Category.ToString("G"); break; } row.AddToCodelet("SHORTDESCRIPTION", (ErrCode.ShortDescription)); row.AddToCodelet("FULLDESCRIPTION", (ErrCode.FullDescription)); row.AddToCodelet("ERRORCODECATEGORY", (ErrCodeCategoryNice)); row.AddToCodelet("DECLARINGCLASS", (ErrCode.ErrorCodeConstantClass)); snippets[snippetkey].InsertSnippet("ROWS", row); } } } foreach (string snippetkey in snippets.Keys) { t.InsertSnippet("TABLES", snippets[snippetkey]); } return(t.FinishWriting(AOutFilePath, ".html", true)); }
/// <summary> /// get all partners and their commitment details /// </summary> public static DataTable GetLengthOfCommitment(TParameterList AParameters, TResultList AResults) { SortedList <string, string> Defines = new SortedList <string, string>(); List <OdbcParameter> SqlParameterList = new List <OdbcParameter>(); try { SqlParameterList.Add(new OdbcParameter("staffdate", OdbcType.Date) { Value = AParameters.Get("param_dtpCurrentStaff").ToDate() }); SqlParameterList.Add(new OdbcParameter("staffdate2", OdbcType.Date) { Value = AParameters.Get("param_dtpCurrentStaff").ToDate() }); } catch (Exception e) { TLogging.Log("problem while preparing sql statement for length of commitment report: " + e.ToString()); return(null); } string SqlStmt = TDataBase.ReadSqlFile("Personnel.Reports.AllCommitments.sql", Defines); Boolean NewTransaction; TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted, out NewTransaction); try { // now run the database query TLogging.Log("Getting the data from the database...", TLoggingType.ToStatusBar); LengthOfCommitmentReportTDSPmStaffDataTable CommitmentTable = new LengthOfCommitmentReportTDSPmStaffDataTable(); DBAccess.GDBAccessObj.SelectDT(CommitmentTable, SqlStmt, Transaction, SqlParameterList.ToArray(), 0, 0); // if this is taking a long time, every now and again update the TLogging statusbar, and check for the cancel button if (AParameters.Get("CancelReportCalculation").ToBool() == true) { return(null); } List <Int32> SpecialAnniversaries = new List <int>(); if (AParameters.Get("param_chkAnniversaries").ToBool() == true) { string[] Anniversaries = AParameters.Get("param_txtAnniversaries").ToString().Split(new char[] { ',', ';' }); foreach (string s in Anniversaries) { SpecialAnniversaries.Add(Convert.ToInt32(s.Trim())); } } return(CalculateLengthOfCommitment( CommitmentTable, AParameters.Get("param_dtpFromDate").ToDate(), AParameters.Get("param_dtpToDate").ToDate(), SpecialAnniversaries)); } catch (Exception e) { TLogging.Log(e.ToString()); return(null); } finally { if (NewTransaction) { DBAccess.GDBAccessObj.RollbackTransaction(); } } }
/// <summary> /// Returns an XML node that defines a number of the properties of each Shepherd. Including size and title. /// </summary> /// <param name="AYamlFile">Full path to the Shepherd's YAML Definition file.</param> /// <returns></returns> protected XmlNode ParseYAMLFileElements(string AYamlFile) { TLogging.Log("ParseYAMLFileElements method starting."); TYml2Xml parser = new TYml2Xml(AYamlFile); XmlDocument XmlPages = parser.ParseYML2XML(); TLogging.Log("ParseYAMLFileElements currently has this many attributes: " + XmlPages.LastChild.LastChild.Attributes.Count); XmlNode FileElementData = XmlPages.DocumentElement; FileElementData = XmlPages.LastChild.LastChild; string ShepherdHeight = ""; string ShepherdWidth = ""; string ShepherdTitle = ""; string TestElement = ""; string FinishPageNote = ""; #region YAML Attributes Input if (FileElementData.Attributes["FinishPageNote"] != null) { FinishPageNote = FileElementData.Attributes["FinishPageNote"].Value; } else { TLogging.Log("DID NOT FIND FINISH PAGE"); } if (FileElementData.Attributes["Testelement"] != null) { TLogging.Log("FOUND TEST ELEMENT"); TLogging.Log("Printing the value of test: " + FileElementData.Attributes["Testelement"].Value); TestElement = FileElementData.Attributes["Testelement"].Value; } else { TLogging.Log("Did not find a test element for this shepherd."); } if (FileElementData.Attributes["Width"] != null) { TLogging.Log("Printing the width of shepherd: " + FileElementData.Attributes["Width"].Value); ShepherdWidth = FileElementData.Attributes["Width"].Value; } else { TLogging.Log("Did not find a width for this shepherd."); } if (FileElementData.Attributes["Height"] != null) { TLogging.Log("Printing the height of shepherd: " + FileElementData.Attributes["Height"].Value); ShepherdHeight = FileElementData.Attributes["Height"].Value; } else { TLogging.Log("Did not find a height for this shepherd."); } if (FileElementData.Attributes["Title"] != null) { TLogging.Log("Printing the title of shepherd: " + FileElementData.Attributes["Title"].Value); ShepherdTitle = FileElementData.Attributes["Title"].Value; } else { TLogging.Log("Did not find a title for this shepherd."); } #endregion try { FForm.UpdateShepherdFormProperties(ShepherdTitle, Convert.ToInt32(ShepherdWidth), Convert.ToInt32(ShepherdHeight)); } catch (FormatException) { TLogging.Log("An element (height or width) cannot be converted to integer. Check the datatype and try again."); } return(FileElementData); }
/// <summary> /// This function checks if the current user has enough access rights to execute that query. /// </summary> /// <returns>True if the user has access, false if access is denied. /// </returns> public new bool HasAccess(string ASQLStatement) { bool ReturnValue; System.Data.DataTable tab; String SQLStatement; System.Int32 Counter; System.Int32 EndOfNamePos; String TableName; char[] WhiteChar; DataRow[] FoundRows; String RequiredAccessPermission; String RequiredAccessPermission4GLName; String SQLTablePrecedingKeyword; String ErrorMessage; ReturnValue = false; try { // inherited if (HasAccess(ASQLStatement) == true) { if (FRetrievingTablePermissions == true) { return(true); } SQLStatement = ASQLStatement.Trim().ToUpper(); TLogging.LogAtLevel(10, "TDataBasePetra.HasAccess: SQLStatement: " + SQLStatement); // get all the access rights to the tables of the user // TODO 2 oChristianK cThread safety : This is currently not threadsave and probably not the most efficient way to use cached data. Change this. FRetrievingTablePermissions = true; tab = FCache.GetDataTable( this, "SELECT s_can_create_l, s_can_modify_l, s_can_delete_l, s_can_inquire_l, s_table_name_c FROM PUB_s_user_table_access_permission WHERE s_user_id_c = '" + UserID + "'"); FRetrievingTablePermissions = false; RequiredAccessPermission = ""; if (SQLStatement.IndexOf("SELECT") == 0) { RequiredAccessPermission = "s_can_inquire_l"; RequiredAccessPermission4GLName = "INQUIRE"; SQLTablePrecedingKeyword = "FROM"; TLogging.LogAtLevel(10, "TDataBasePetra.HasAccess: Access permission: " + RequiredAccessPermission4GLName); } else if (SQLStatement.IndexOf("UPDATE") == 0) { RequiredAccessPermission = "s_can_modify_l"; RequiredAccessPermission4GLName = "MODIFY"; SQLTablePrecedingKeyword = " "; TLogging.LogAtLevel(10, "TDataBasePetra.HasAccess: Access permission: " + RequiredAccessPermission4GLName); } else if (SQLStatement.IndexOf("INSERT") == 0) { RequiredAccessPermission = "s_can_create_l"; RequiredAccessPermission4GLName = "CREATE"; SQLTablePrecedingKeyword = "INTO"; TLogging.LogAtLevel(10, "TDataBasePetra.HasAccess: Access permission: " + RequiredAccessPermission4GLName); } else if (SQLStatement.IndexOf("DELETE") == 0) { RequiredAccessPermission = "s_can_delete_l"; RequiredAccessPermission4GLName = "DELETE"; SQLTablePrecedingKeyword = "FROM"; TLogging.LogAtLevel(10, "TDataBasePetra.HasAccess: Access permission: " + RequiredAccessPermission4GLName); } else { TLogging.Log("DBAccessSecurity: SQL query could not be recognised. Starting with: " + SQLStatement.Substring(0, 10)); throw new Exception("DBAccessSecurity: SQL query could not be recognised."); } if (RequiredAccessPermission.Length != 0) { TLogging.LogAtLevel(10, "TDataBasePetra.HasAccess: RequiredAccessPermission.Length <> 0"); WhiteChar = new char[] { ',', ')', '.', ' ' }; Counter = SQLStatement.IndexOf(SQLTablePrecedingKeyword); if (Counter == -1) { TLogging.Log( "DBAccessSecurity: SQL query could not be recognised. Keyword that should precede the DB table name (" + SQLTablePrecedingKeyword + ") was not found!"); throw new Exception("DBAccessSecurity: SQL query could not be recognised."); } ReturnValue = true; while (Counter != -1) { Counter = SQLStatement.IndexOf("PUB_", Counter); if (Counter != -1) { EndOfNamePos = SQLStatement.IndexOfAny(WhiteChar, Counter); if (EndOfNamePos == -1) { EndOfNamePos = SQLStatement.Length; } TableName = SQLStatement.Substring(Counter + 4, EndOfNamePos - Counter - 4).Trim(); TLogging.LogAtLevel(10, "TDataBasePetra.HasAccess: Table name: " + TableName); Counter = Counter + TableName.Length; if (TableName == "S_USER_DEFAULTS") { // always allow access to the s_user_defaults // strangely enough, that is not in the table s_user_table_access_permission } else if ((RequiredAccessPermission == "s_can_inquire_l") && (TableName == "S_USER_MODULE_ACCESS_PERMISSION")) { // always allow INQUIRE access to the // s_user_module_access_permission table } else { // test for DB table FoundRows = tab.Select("s_table_name_c = '" + TableName + "'"); if (FoundRows.Length == 0) { ErrorMessage = String.Format(Catalog.GetString( "You do not have permission to access {0}."), TableName.ToLower()); TLogging.Log(StrAccessDeniedLogPrefix + ErrorMessage); LogInPetraErrorLog(ErrorMessage); TLogging.LogAtLevel(10, "TDataBasePetra.HasAccess: logged access error in DB Log Table."); throw new ESecurityDBTableAccessDeniedException(String.Format(ErrorMessage, RequiredAccessPermission4GLName.ToLower(), TableName.ToLower()), RequiredAccessPermission4GLName.ToLower(), TableName.ToLower()); } // test for access permission if (Convert.ToBoolean(FoundRows[0][RequiredAccessPermission]) == false) { ErrorMessage = String.Format(Catalog.GetString("You do not have permission to {0} {1} records."), RequiredAccessPermission4GLName.ToLower(), TableName.ToLower()); TLogging.Log(StrAccessDeniedLogPrefix + ErrorMessage); LogInPetraErrorLog(ErrorMessage); TLogging.LogAtLevel(10, "TDataBasePetra.HasAccess: logged access error in DB Log Table."); throw new ESecurityDBTableAccessDeniedException(ErrorMessage, RequiredAccessPermission4GLName.ToLower(), TableName.ToLower()); } } } } } } } catch { throw; } return(ReturnValue); }
static private ProcessTemplate CreateModuleAccessPermissionCheck(ProcessTemplate ATemplate, string AConnectorClassWithNamespace, MethodDeclaration m) { if (m.Attributes != null) { foreach (AttributeSection attrSection in m.Attributes) { foreach (ICSharpCode.NRefactory.Ast.Attribute attr in attrSection.Attributes) { if (attr.Name == "RequireModulePermission") { ProcessTemplate snippet = ATemplate.GetSnippet("CHECKUSERMODULEPERMISSIONS"); snippet.SetCodelet("METHODNAME", m.Name); snippet.SetCodelet("CONNECTORWITHNAMESPACE", AConnectorClassWithNamespace); snippet.SetCodelet("LEDGERNUMBER", ""); string ParameterTypes = ";"; foreach (ParameterDeclarationExpression p in m.Parameters) { if (p.ParameterName == "ALedgerNumber") { snippet.SetCodelet("LEDGERNUMBER", ", ALedgerNumber"); } string ParameterType = p.TypeReference.Type.Replace("&", "").Replace("System.", String.Empty); if (ParameterType == "List") { ParameterType = ParameterType.Replace("List", "List[" + p.TypeReference.GenericTypes[0].ToString() + "]"); ParameterType = ParameterType.Replace("System.", String.Empty); } if (ParameterType == "Dictionary") { // this does not seem to work with Mono 5.12 api browser // ParameterType = ParameterType.Replace("Dictionary", "Dictionary[" + // p.TypeReference.GenericTypes[0].ToString() + "," + // p.TypeReference.GenericTypes[1].ToString() + "]"); // ParameterType = ParameterType.Replace("System.", String.Empty); ParameterType = "String"; } if (ParameterType.Contains(".")) { ParameterType = ParameterType.Substring(ParameterType.LastIndexOf(".") + 1); } if (p.TypeReference.Type == "System.Nullable") { ParameterType = ParameterType.Replace("Nullable", "Nullable[" + p.TypeReference.GenericTypes[0].ToString() + "]"); } if (p.TypeReference.IsArrayType) { ParameterType += ".ARRAY"; } // if (ParameterType == "SortedList") // { //Console.WriteLine(p.ParameterName + "'s ParameterType = SortedList"); // ParameterType = ParameterType.Replace("List", "List[" + // p.TypeReference.GenericTypes[0].ToString() + "," + // p.TypeReference.GenericTypes[1].ToString() + "]"); // ParameterType = ParameterType.Replace("System.", String.Empty); // } ParameterType = ParameterType.Replace("Boolean", "bool"); ParameterType = ParameterType.Replace("Int32", "int"); ParameterType = ParameterType.Replace("Int64", "long"); ParameterTypes += ParameterType + ";"; } ParameterTypes = ParameterTypes.ToUpper(); snippet.SetCodelet("PARAMETERTYPES", ParameterTypes); return(snippet); } else if (attr.Name == "CheckServerAdminToken") { ProcessTemplate snippet = ATemplate.GetSnippet("CHECKSERVERADMINPERMISSION"); string paramdefinition = "string AServerAdminSecurityToken"; if (ATemplate.FCodelets["PARAMETERDEFINITION"].Length != 0) { paramdefinition += ", "; } ATemplate.AddToCodeletPrepend("PARAMETERDEFINITION", paramdefinition); return(snippet); } } } } TLogging.Log("Warning !!! Missing module access permissions for " + AConnectorClassWithNamespace + "::" + m.Name); return(new ProcessTemplate()); }
/// <summary> /// initialise the server once for everyone /// </summary> public static bool Init() { if (ConfigFileName == string.Empty) { // make sure the correct config file is used if (Environment.CommandLine.Contains("/appconfigfile=")) { // this happens when we use fastcgi-mono-server4 ConfigFileName = Environment.CommandLine.Substring( Environment.CommandLine.IndexOf("/appconfigfile=") + "/appconfigfile=".Length); if (ConfigFileName.IndexOf(" ") != -1) { ConfigFileName = ConfigFileName.Substring(0, ConfigFileName.IndexOf(" ")); } } else { // this is the normal behaviour when running with local http server ConfigFileName = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "web.config"; } } new TAppSettingsManager(ConfigFileName); new TSrvSetting(); new TLogging(TSrvSetting.ServerLogFile); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0); if (HttpContext.Current != null) { HttpContext.Current.Server.ScriptTimeout = Convert.ToInt32( TimeSpan.FromMinutes(TAppSettingsManager.GetInt32("WebRequestTimeOutInMinutes", 15)). TotalSeconds); } // if the Login Method is called: reset cookie, ignore any old session if ((HttpContext.Current != null) && (HttpContext.Current.Request.PathInfo == "/Login")) { TSession.Clear(); } if (TServerManager.TheServerManager == null) { Catalog.Init(); TServerManager.TheServerManager = new TServerManager(); try { TServerManager.TheCastedServerManager.EstablishDBConnection(); TSystemDefaultsCache.GSystemDefaultsCache = new TSystemDefaultsCache(); DomainManager.GetSiteKeyFromSystemDefaultsCacheDelegate = @TSystemDefaultsCache.GSystemDefaultsCache.GetSiteKeyDefault; TLanguageCulture.Init(); // initialise the cached tables TSetupDelegates.Init(); TUserDefaults.InitializeUnit(); } catch (Exception e) { TLogging.Log(e.Message); TLogging.Log(e.StackTrace); throw; } TLogging.Log("Server has been initialised"); return(true); } if (DomainManager.CurrentClient != null) { if (DomainManager.CurrentClient.FAppDomainStatus == TSessionStatus.adsStopped) { TLogging.Log("There is an attempt to reconnect to stopped session: " + DomainManager.CurrentClient.ClientName); HttpContext.Current.Response.Status = "404 " + THTTPUtils.SESSION_ALREADY_CLOSED; HttpContext.Current.Response.End(); } // TLogging.Log("Init(): WebService Method name that got called: " + HttpContext.Current.Request.PathInfo); if (HttpContext.Current.Request.PathInfo != "/PollClientTasks") { DomainManager.CurrentClient.UpdateLastAccessTime(); } } return(false); }
/// <summary> /// Converts an Array of DbParameter (eg. OdbcParameter) to an Array /// of NpgsqlParameter. If the Parameters don't have a name yet, they /// are given one because PostgreSQL needs named Parameters. /// <para>Furthermore, the parameter placeholders '?' in the the passed in /// <paramref name="ASqlStatement" /> are replaced with PostgreSQL /// ':paramX' placeholders (where 'paramX' is the name of the Parameter).</para> /// </summary> /// <param name="AParameterArray">Array of DbParameter that is to be converted.</param> /// <param name="ASqlStatement">SQL Statement. It will be converted!</param> /// <returns>Array of NpgsqlParameter (converted from <paramref name="AParameterArray" />.</returns> public DbParameter[] ConvertOdbcParameters(DbParameter[] AParameterArray, ref string ASqlStatement) { NpgsqlParameter[] ReturnValue = new NpgsqlParameter[AParameterArray.Length]; OdbcParameter[] AParameterArrayOdbc; string ParamName = ""; if (!(AParameterArray is NpgsqlParameter[])) { AParameterArrayOdbc = (OdbcParameter[])AParameterArray; // Parameter Type change and Parameter Name assignment for (int Counter = 0; Counter < AParameterArray.Length; Counter++) { ParamName = AParameterArrayOdbc[Counter].ParameterName; if (ParamName == "") { ParamName = "param" + Counter.ToString(); #if DEBUGMODE_TODO if (FDebugLevel >= DBAccess.DB_DEBUGLEVEL_TRACE) { TLogging.Log("Assigned Parameter Name '" + ParamName + "' for Parameter with Value '" + AParameterArrayOdbc[Counter].Value.ToString() + "'."); } #endif } switch (AParameterArrayOdbc[Counter].OdbcType) { case OdbcType.Decimal: ReturnValue[Counter] = new NpgsqlParameter( ParamName, NpgsqlDbType.Numeric, AParameterArrayOdbc[Counter].Size); break; case OdbcType.VarChar: ReturnValue[Counter] = new NpgsqlParameter( ParamName, NpgsqlDbType.Varchar, AParameterArrayOdbc[Counter].Size); break; case OdbcType.Bit: ReturnValue[Counter] = new NpgsqlParameter( ParamName, NpgsqlDbType.Boolean); break; case OdbcType.Date: if (AParameterArrayOdbc[Counter].Value != DBNull.Value) { DateTime TmpDate = (DateTime)AParameterArrayOdbc[Counter].Value; if ((TmpDate.Hour == 0) && (TmpDate.Minute == 0) && (TmpDate.Second == 0) && (TmpDate.Millisecond == 0)) { ReturnValue[Counter] = new NpgsqlParameter( ParamName, NpgsqlDbType.Date); } else { ReturnValue[Counter] = new NpgsqlParameter( ParamName, NpgsqlDbType.Timestamp); } } else { ReturnValue[Counter] = new NpgsqlParameter( ParamName, NpgsqlDbType.Date); } break; case OdbcType.DateTime: ReturnValue[Counter] = new NpgsqlParameter( ParamName, NpgsqlDbType.Timestamp); break; case OdbcType.Int: ReturnValue[Counter] = new NpgsqlParameter( ParamName, NpgsqlDbType.Integer); break; case OdbcType.BigInt: ReturnValue[Counter] = new NpgsqlParameter( ParamName, NpgsqlDbType.Bigint); break; case OdbcType.Text: ReturnValue[Counter] = new NpgsqlParameter( ParamName, NpgsqlDbType.Text); break; default: ReturnValue[Counter] = new NpgsqlParameter( ParamName, NpgsqlDbType.Integer); break; } ReturnValue[Counter].Value = AParameterArrayOdbc[Counter].Value; } } else { ReturnValue = (NpgsqlParameter[])AParameterArray; } if (ASqlStatement.Contains("?")) { StringBuilder SqlStatementBuilder = new StringBuilder(); int QMarkPos = 0; int LastQMarkPos = -1; int ParamCounter = 0; /* SQL Syntax change from ODBC style to PostgreSQL style: Replace '?' with * ':xxx' (where xxx is the name of the Parameter). */ while ((QMarkPos = ASqlStatement.IndexOf("?", QMarkPos + 1)) > 0) { SqlStatementBuilder.Append(ASqlStatement.Substring( LastQMarkPos + 1, QMarkPos - LastQMarkPos - 1)); SqlStatementBuilder.Append(":").Append(ReturnValue[ParamCounter].ParameterName); ParamCounter++; LastQMarkPos = QMarkPos; } SqlStatementBuilder.Append(ASqlStatement.Substring( LastQMarkPos + 1, ASqlStatement.Length - LastQMarkPos - 1)); // TLogging.Log("old statement: " + ASqlStatement); ASqlStatement = SqlStatementBuilder.ToString(); // TLogging.Log("new statement: " + ASqlStatement); } return(ReturnValue); }
/// <summary> /// this is where all the calculations take place /// </summary> /// <returns> /// true if the report was successfully generated /// </returns> public Boolean GenerateResultRemoteClient(TLogging.TStatusCallbackProcedure AStatusBarProcedure = null) { Boolean ReturnValue; Thread ProgressCheckThread; ReturnValue = false; if (AStatusBarProcedure != null) { FStatusBarProcedure = AStatusBarProcedure; } FReportingGenerator = TRemote.MReporting.UIConnectors.ReportGenerator(); FKeepUpProgressCheck = true; try { this.Results = new TResultList(); FReportingGenerator.Start(this.Parameters.ToDataTable()); ProgressCheckThread = new Thread(new ThreadStart(AsyncProgressCheckThread)); ProgressCheckThread.Start(); } catch (Exception e) { TLogging.Log(e.Message); // Release the server object FReportingGenerator = null; return(false); } // todo: allow canceling of the calculation of a report while (FKeepUpProgressCheck) { Thread.Sleep(500); } ReturnValue = FReportingGenerator.GetSuccess(); // Do not release the server object, we still might want to send an email... // FReportingGenerator = null; if (ReturnValue) { if (FCalculatesExtract) { TLogging.Log("Extract calculation finished. Look for extract '" + Parameters.Get("param_extract_name").ToString() + "' in Extract Master List.", TLoggingType.ToStatusBar, FStatusBarProcedure); TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcExtractCreated); BroadcastMessage.SetMessageDataName(Parameters.Get("param_extract_name").ToString()); TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage); } else { TLogging.Log("Report calculation finished.", TLoggingType.ToStatusBar, FStatusBarProcedure); } } return(ReturnValue); }
private void AsyncProgressCheckThread() { String OldLoggingText; DateTime startTime; String ErrorMessage = null; Exception ServersideException; OldLoggingText = ""; startTime = DateTime.Now; while (FKeepUpProgressCheck) { TProgressState state = FReportingGenerator.Progress; if (state.JobFinished) { this.Duration = DateTime.Now - startTime; if (FReportingGenerator.GetSuccess() == true) { this.Parameters.LoadFromDataTable(FReportingGenerator.GetParameter()); this.Results.LoadFromDataTable(FReportingGenerator.GetResult()); this.Results.SetMaxDisplayColumns(this.Parameters.Get("MaxDisplayColumns").ToInt()); } else { ErrorMessage = FReportingGenerator.GetErrorMessage(out ServersideException); if (ErrorMessage != null) { if (ErrorMessage != String.Empty) { if (!ErrorMessage.StartsWith( SharedConstants.NO_PARALLEL_EXECUTION_OF_XML_REPORTS_PREFIX, StringComparison.InvariantCulture)) { TLogging.Log(ErrorMessage, FStatusBarProcedure); } else { FStatusBarProcedure(ErrorMessage.Substring( SharedConstants.NO_PARALLEL_EXECUTION_OF_XML_REPORTS_PREFIX.Length)); } } else { // We get here e.g. when Report Generation was cancelled: this clears anything that the // Status Bar has previously shown. FStatusBarProcedure(String.Empty); } // Let any Exception that happened server-side escalate to the 'Unhandled Exception Handler' // to give it visibility if (ServersideException != null) { if (TDBExceptionHelper.IsTransactionSerialisationException(ServersideException)) { FStatusBarProcedure(string.Empty); TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog(); } else { throw ServersideException; } } } } FKeepUpProgressCheck = false; } else { if ((state.StatusMessage != null) && (!OldLoggingText.Equals(state.StatusMessage))) { TLogging.Log(state.StatusMessage, TLoggingType.ToStatusBar, FStatusBarProcedure); OldLoggingText = state.StatusMessage; } } if (FKeepUpProgressCheck) { // Sleep for some time. Then check again for latest progress information Thread.Sleep(500); } } }
public void Test_PEMM_05_Revaluation() { FLedgerNumber = CommonNUnitFunctions.CreateNewLedger(); // load foreign currency account 6001 CommonNUnitFunctions.LoadTestDataBase("csharp\\ICT\\Testing\\lib\\MFinance\\server\\GL\\" + "test-sql\\gl-test-account-data.sql", FLedgerNumber); // post a batch for foreign currency account 6001 TCommonAccountingTool commonAccountingTool = new TCommonAccountingTool(FLedgerNumber, "NUNIT"); commonAccountingTool.AddForeignCurrencyJournal("GBP", 1.1m); commonAccountingTool.JournalDescription = "Test foreign currency account"; string strAccountGift = "0200"; string strAccountBank = "6001"; // Accounting of some gifts ... commonAccountingTool.AddBaseCurrencyTransaction( strAccountBank, (FLedgerNumber * 100).ToString(), "Gift Example", "Debit", MFinanceConstants.IS_DEBIT, 100); commonAccountingTool.AddBaseCurrencyTransaction( strAccountGift, (FLedgerNumber * 100).ToString(), "Gift Example", "Credit", MFinanceConstants.IS_CREDIT, 100); Boolean PostedOk = commonAccountingTool.CloseSaveAndPost(); // returns true if posting seemed to work Assert.IsTrue(PostedOk, "Post foreign gift batch"); TVerificationResultCollection verificationResult; /* * This error is no longer critical - it's OK to run month end even if a reval is required. (Mantis# 03905) * * bool blnHasErrors = !TPeriodIntervalConnector.TPeriodMonthEnd( * FLedgerNumber, true, out verificationResult); * * for (int i = 0; i < verificationResult.Count; ++i) * { * if (verificationResult[i].ResultCode.Equals( * TPeriodEndErrorAndStatusCodes.PEEC_05.ToString())) * { * blnStatusArrived = true; * Assert.IsTrue(verificationResult[i].ResultSeverity == TResultSeverity.Resv_Critical, * "A critical error is required: need to run revaluation first ..."); * } * } */ // run revaluation Int32 forexBatchNumber; List <Int32> glBatchNumbers; Boolean stewardshipBatch; Boolean revalueOk = TRevaluationWebConnector.Revaluate(FLedgerNumber, new string[] { strAccountGift }, new string[] { "GBP" }, new decimal[] { 1.2m }, TLedgerInfo.GetStandardCostCentre(FLedgerNumber), out forexBatchNumber, out verificationResult); if (!revalueOk) { TLogging.Log("\n\n\nTRevaluationWebConnector.Revaluate had problems. VerificationResult follows:"); TLogging.Log(verificationResult.BuildVerificationResultString()); } Assert.IsTrue(revalueOk, "Problem running the revaluation"); Boolean Err = !TPeriodIntervalConnector.PeriodMonthEnd( FLedgerNumber, true, out glBatchNumbers, out stewardshipBatch, out verificationResult); if (Err) { TLogging.Log("\n\n\nTPeriodMonthEnd returned true, VerificationResult follows:"); TLogging.Log(verificationResult.BuildVerificationResultString()); } Assert.IsFalse(Err, "Should be able to close the month after revaluation has been run."); }
/// <summary> /// this supports the batch export files from Petra 2.x. /// Each line starts with a type specifier, B for batch, J for journal, T for transaction /// </summary> private void BtnOK_Click(object sender, EventArgs e) { FExportFileName = txtFilename.Text; String fileContents = string.Empty; Int32 budgetCount = 0; if (txtFilename.Text == String.Empty) { MessageBox.Show(Catalog.GetString("Please choose a location for the Export File."), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!Directory.Exists(Path.GetDirectoryName(FExportFileName))) { MessageBox.Show(Catalog.GetString("Please select an existing directory for this file!"), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); FExportFileName = string.Empty; return; } if (File.Exists(FExportFileName)) { if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"), Catalog.GetString("Export Budget"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) { return; } try { File.Delete(FExportFileName); } catch (Exception ex) { MessageBox.Show(String.Format( Catalog.GetString( "Failed to delete the file. Maybe it is already open in another application? The system message was:{0}{1}"), Environment.NewLine, ex.Message), Catalog.GetString("Export Budget"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } //Hashtable requestParams = new Hashtable(); //requestParams.Add("ALedgerNumber", FLedgerNumber); //requestParams.Add("Delimiter", ConvertDelimiter(cmbDelimiter.GetSelectedString(), false)); //requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString()); //requestParams.Add("NumberFormat", ConvertNumberFormat(cmbNumberFormat)); TVerificationResultCollection AMessages; string[] delims = new string[1]; delims[0] = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false); try { this.Cursor = Cursors.WaitCursor; budgetCount = TRemote.MFinance.Budget.WebConnectors.ExportBudgets(FLedgerNumber, FExportFileName, delims, ref fileContents, ref FBudgetDS, out AMessages); this.Cursor = Cursors.Default; if ((AMessages != null) && (AMessages.Count > 0)) { if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages)) { MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); FExportFileName = string.Empty; return; } else { MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"), MessageBoxButtons.OK, MessageBoxIcon.Information); } } SaveUserDefaults(); if (budgetCount == 0) { MessageBox.Show(Catalog.GetString("There are no Budgets matching your criteria"), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); FExportFileName = string.Empty; return; } StreamWriter sw1 = new StreamWriter(FExportFileName); sw1.Write(fileContents); sw1.Close(); } catch (Exception ex) { TLogging.Log("ExportBudget.ManualCode: " + ex.ToString()); MessageBox.Show(ex.Message, Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } finally { this.Cursor = Cursors.Default; } // Offer the client the chance to open the file in Excel or whatever if (MessageBox.Show(String.Format(Catalog.GetString( "{0} Budget rows were exported successfully! Would you like to open the file in your default application?"), budgetCount.ToString()), Catalog.GetString("Budget Export"), MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes) { ProcessStartInfo si = new ProcessStartInfo(txtFilename.Text); si.UseShellExecute = true; si.Verb = "open"; Process p = new Process(); p.StartInfo = si; p.Start(); } Close(); }
/// <summary> /// connect the client /// </summary> /// <param name="AUserName"></param> /// <param name="APassword"></param> /// <param name="AClientManager"></param> /// <param name="AProcessID"></param> /// <param name="AWelcomeMessage"></param> /// <param name="ASystemEnabled"></param> /// <param name="AError"></param> /// <param name="AUserInfo"></param> /// <returns></returns> virtual protected bool ConnectClient(String AUserName, String APassword, IClientManagerInterface AClientManager, out Int32 AProcessID, out String AWelcomeMessage, out Boolean ASystemEnabled, out String AError, out IPrincipal AUserInfo) { AError = ""; ASystemEnabled = false; AWelcomeMessage = ""; AProcessID = -1; AUserInfo = null; try { AClientManager.ConnectClient(AUserName, APassword, TClientInfo.ClientComputerName, TClientInfo.ClientIPAddress, new Version(TClientInfo.ClientAssemblyVersion), DetermineClientServerConnectionType(), out FClientName, out FClientID, out FCrossDomainURI, out FRemotingURLs, out FServerOS, out AProcessID, out AWelcomeMessage, out ASystemEnabled, out AUserInfo); if (FRemotingURLs.ContainsKey(RemotingConstants.REMOTINGURL_IDENTIFIER_POLLCLIENTTASKS)) { FRemotingURL_PollClientTasks = (String)FRemotingURLs[RemotingConstants.REMOTINGURL_IDENTIFIER_POLLCLIENTTASKS]; } FConnector.Init(FCrossDomainURI, FClientID.ToString()); return(true); } catch (EUserNotExistantException exp) { AError = exp.Message; return(false); } catch (ESystemDisabledException exp) { AError = exp.Message; return(false); } catch (EClientVersionMismatchException) { throw; } catch (ELoginFailedServerTooBusyException) { throw; } catch (Exception exp) { TLogging.Log(exp.ToString() + Environment.NewLine + exp.StackTrace, TLoggingType.ToLogfile); throw; } }
/// <summary> /// todoComment /// </summary> public bool ConnectToServer(String AUserName, String APassword, out Int32 AProcessID, out String AWelcomeMessage, out Boolean ASystemEnabled, out String AError, out IPrincipal AUserInfo) { AError = ""; String ConnectionError; if (FConnector == null) { FConnector = (TConnector)Activator.CreateInstance(ConnectorType); } try { if (TAppSettingsManager.ConfigFileName.Length > 0) { // connect to the PetraServer's ClientManager FConnector.GetRemoteServerConnection(TAppSettingsManager.ConfigFileName, out FClientManager); } else { // connect to the PetraServer's ClientManager FConnector.GetRemoteServerConnection(Environment.GetCommandLineArgs()[0] + ".config", out FClientManager); } // register Client session at the PetraServer bool ReturnValue = ConnectClient(AUserName, APassword, FClientManager, out AProcessID, out AWelcomeMessage, out ASystemEnabled, out ConnectionError, out AUserInfo); TRemoteBase.ClientManager = FClientManager; if (!ReturnValue) { AError = ConnectionError; return(ReturnValue); } } catch (System.Net.Sockets.SocketException) { throw new EServerConnectionServerNotReachableException(); } catch (EDBConnectionNotEstablishedException exp) { if (exp.Message.IndexOf("Access denied") != -1) { // Prevent passing out stack trace in case the PetraServer cannot connect // a Client (to make this happen, somebody would have tampered with the // DB Password decryption routines...) throw new EServerConnectionGeneralException("PetraServer misconfiguration!"); } else { throw; } } catch (EClientVersionMismatchException) { throw; } catch (ELoginFailedServerTooBusyException) { throw; } catch (Exception exp) { TLogging.Log(exp.ToString() + Environment.NewLine + exp.StackTrace, TLoggingType.ToLogfile); throw new EServerConnectionGeneralException(exp.ToString()); } // // acquire .NET Remoting Proxy objects for remoted Server objects // FRemotePollClientTasks = (IPollClientTasksInterface)FConnector.GetRemoteObject(FRemotingURL_PollClientTasks, typeof(IPollClientTasksInterface)); // // start the KeepAlive Thread (which needs to run as long as the Client is running) // FKeepAlive = new TEnsureKeepAlive(); // // start the PollClientTasks Thread (which needs to run as long as the Client is running) // FPollClientTasks = new TPollClientTasks(FClientID, FRemotePollClientTasks); // // initialise object that holds references to all our remote object .NET Remoting Proxies // FRemote = new TRemoteBase(FClientManager); return(true); }
/// <summary> /// serialize any object. if it is a complex type, use JSON /// </summary> static public string SerializeObjectJSON(object o, bool binary) { if (!binary) { if (o.GetType() == typeof(bool)) { return(o.ToString().ToLower()); } if (o.GetType() == typeof(string)) { return('"' + o.ToString().Replace('"', '\'') + '"'); } return(o.ToString()); } if (o == null) { return("null"); } if (o is Type) { return(o.ToString()); } if (o is IList && o.GetType().IsGenericType) { JavaScriptSerializer serializer = new JavaScriptSerializer(); return(serializer.Serialize(o)); } if (o is DataSet) { return(DataSetToJson((DataSet)o)); } if (o is DataTable) { return(DataTableToJson((DataTable)o)); } if (o is TVerificationResultCollection) { return(VerificationResultCollectionToJson((TVerificationResultCollection)o)); } MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); try { binaryFormatter.Serialize(memoryStream, o); } catch (Exception e) { TLogging.Log("cannot serialize object of type " + o.GetType().ToString()); TLogging.Log(e.ToString()); } string encoded = Convert.ToBase64String(memoryStream.ToArray()) + ":binary"; if (encoded.Length > 1024 * 1024 * 4) { TLogging.Log("Warning: THttpBinarySerializer.SerializeObject: Binary parameter is too long: " + encoded.Length.ToString()); } return(encoded); }
/// <summary> /// Populate ledger with gifts and invoices, post batches, close periods and years, according to FNumberOfClosedPeriods /// </summary> public static void PopulateData(string datadirectory, bool smallNumber = false) { int periodOverall = 0; int yearCounter = 0; int period = 1; int YearAD = DateTime.Today.Year - (FNumberOfClosedPeriods / 12); SampleDataGiftBatches.FLedgerNumber = FLedgerNumber; SampleDataAccountsPayable.FLedgerNumber = FLedgerNumber; SampleDataGiftBatches.LoadBatches(Path.Combine(datadirectory, "donations.csv"), smallNumber); SampleDataAccountsPayable.GenerateInvoices(Path.Combine(datadirectory, "invoices.csv"), YearAD, smallNumber); while (periodOverall <= FNumberOfClosedPeriods) { TLogging.LogAtLevel(1, "working on year " + yearCounter.ToString() + " / period " + period.ToString()); SampleDataGiftBatches.CreateGiftBatches(period); if (!SampleDataGiftBatches.PostBatches(yearCounter, period, (periodOverall == FNumberOfClosedPeriods) ? 1 : 0)) { throw new Exception("could not post gift batches"); } if (!SampleDataAccountsPayable.PostAndPayInvoices(yearCounter, period, (periodOverall == FNumberOfClosedPeriods) ? 1 : 0)) { throw new Exception("could not post invoices"); } TLedgerInfo LedgerInfo = new TLedgerInfo(FLedgerNumber); if (periodOverall < FNumberOfClosedPeriods) { TAccountPeriodInfo AccountingPeriodInfo = new TAccountPeriodInfo(FLedgerNumber, period); TLogging.Log("closing period at " + AccountingPeriodInfo.PeriodEndDate.ToShortDateString()); // run month end TMonthEnd MonthEndOperator = new TMonthEnd(LedgerInfo); MonthEndOperator.SetNextPeriod(); if (period == 12) { TYearEnd YearEndOperator = new TYearEnd(LedgerInfo); // run year end TVerificationResultCollection verificationResult = new TVerificationResultCollection(); TReallocation reallocation = new TReallocation(LedgerInfo); reallocation.VerificationResultCollection = verificationResult; reallocation.IsInInfoMode = false; reallocation.RunOperation(); TGlmNewYearInit glmNewYearInit = new TGlmNewYearInit(LedgerInfo, yearCounter, YearEndOperator); glmNewYearInit.VerificationResultCollection = verificationResult; glmNewYearInit.IsInInfoMode = false; glmNewYearInit.RunOperation(); SampleDataLedger.InitExchangeRate(); YearAD++; yearCounter++; SampleDataAccountsPayable.GenerateInvoices(Path.Combine(datadirectory, "invoices.csv"), YearAD, smallNumber); period = 0; } } period++; periodOverall++; } }
/// <summary> /// verify that all windows open either without error or with proper exception handling /// </summary> private void TestOpenAllWindows() { TLogging.Log(String.Format("Running test 'TestOpenAllWindows' with Culture '{0}'...", Thread.CurrentThread.CurrentCulture.ToString()) + Environment.NewLine); // get all nodes that have an attribute ActionOpenScreen XPathExpression expr = FNavigator.Compile("//*[@ActionOpenScreen]"); XPathNodeIterator iterator = FNavigator.Select(expr); //create counter variables to keep track of number of failures (might do with lists soon...for modules(?)) int NoSysManPermissionCount = 0; int NoOtherPermissionCount = 0; int BadFailures = 0; int TotalWindowsOpened = 0; List <String> notOpened = new List <String>(); List <String> sysManPermissions = new List <String>(); List <String> otherPermissions = new List <String>(); List <String> workingWindows = new List <String>(); while (iterator.MoveNext()) { if (iterator.Current is IHasXmlNode) { XmlNode ActionNode = ((IHasXmlNode)iterator.Current).GetNode(); string className = ActionNode.Attributes["ActionOpenScreen"].Value; if (className == "TFrmBankStatementImport") { // skip this one because it pops up an additional dialog that requires user input continue; } // look at the permissions module the window came from string Module = TXMLParser.GetAttributeRecursive(ActionNode, "PermissionsRequired", true); TLstTasks.CurrentLedger = TFrmMainWindowNew.CurrentLedger; // Try to open each screen and log the screens that cannot open try { Assert.AreEqual(String.Empty, TLstTasks.ExecuteAction(ActionNode, null)); if (TLstTasks.LastOpenedScreen != null) { TLstTasks.LastOpenedScreen.Close(); } TotalWindowsOpened++; string WindowAndModule = ActionNode.Name + Environment.NewLine + " Permission Required: " + Module; workingWindows.Add(WindowAndModule); //make sure the user had the permissions to open the windows that it opened if (!UserInfo.GUserInfo.IsInModule(Module) && !Module.Contains("")) { BadFailures++; workingWindows.Add("User did not have permission to access " + Module); } } catch (AssertionException e) { TLogging.Log("Window can't be opened: " + ActionNode.Name + " " + ActionNode.Attributes["ActionOpenScreen"].Value + Environment.NewLine + e.ToString()); // if the failure is a permission failure, just log it but don't fail the test if (Catalog.GetString("Sorry, you don't have enough permissions to do this") == TLstTasks.ExecuteAction(ActionNode, null)) { // make sure user didn't have the necessary permissions to open that window // true means user should have been able to open without error if (UserInfo.GUserInfo.IsInModule(Module)) { BadFailures++; string whyFailed = "User should have been able to open " + ActionNode.Name + " with his " + Module + " permission..."; notOpened.Add(whyFailed); } else { string permissions = TXMLParser.GetAttributeRecursive(ActionNode, "PermissionsRequired", true); string WindowAndModule = ActionNode.Name + Environment.NewLine + " Permission Required: " + permissions; if (permissions.Contains("SYSMAN")) { NoSysManPermissionCount++; sysManPermissions.Add(WindowAndModule); } else { NoOtherPermissionCount++; otherPermissions.Add(WindowAndModule); } } } else { BadFailures++; string WindowAndModule = ActionNode.Name + Environment.NewLine + " Permission Required: " + TXMLParser.GetAttributeRecursive(ActionNode, "PermissionsRequired", true); notOpened.Add(WindowAndModule); } } // if the exception has to due with a ledger that the user doesn't have permission to access, // make it a permission exception. Else, fail the test. catch (Exception e) { TLogging.Log("Window can't be opened: " + ActionNode.Name + " " + ActionNode.Attributes["ActionOpenScreen"].Value + Environment.NewLine + e.ToString()); string ledgerNumber = TXMLParser.GetAttributeRecursive(ActionNode, "LedgerNumber", true); string ledger = "LEDGER00" + ledgerNumber; if ((ledgerNumber != String.Empty) && !UserInfo.GUserInfo.IsInModule(ledger)) { NoOtherPermissionCount++; string WindowAndModule = ActionNode.Name + Environment.NewLine + " Permission Required: " + TXMLParser.GetAttributeRecursive(ActionNode, "PermissionsRequired", true) + Environment.NewLine + " " + ledger; otherPermissions.Add(WindowAndModule); } else { BadFailures++; string WindowAndModule = ActionNode.Name + Environment.NewLine + " Permission Required: " + TXMLParser.GetAttributeRecursive(ActionNode, "PermissionsRequired", true); if (ledgerNumber != String.Empty) { WindowAndModule += (Environment.NewLine + " " + ledger); } notOpened.Add(WindowAndModule); } } } } //Give stats about where failures were //feel free to change any formatting, I'm not in love with it right now string notOpenedString = string.Join(Environment.NewLine + " ", notOpened.ToArray()); string sysManPermissionsString = string.Join(Environment.NewLine + " ", sysManPermissions.ToArray()); string otherPermissionsString = string.Join(Environment.NewLine + " ", otherPermissions.ToArray()); string workingWindowsString = string.Join(Environment.NewLine + " ", workingWindows.ToArray()); //print the permissions the user should have TLogging.Log(Environment.NewLine + Environment.NewLine + "User Permissions: " + Environment.NewLine + UserInfo.GUserInfo.GetPermissions()); TLogging.Log(Environment.NewLine + Environment.NewLine + "Statistics: " + Environment.NewLine + "Number of windows opened: " + TotalWindowsOpened + Environment.NewLine + " " + workingWindowsString + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + "SYSMAN Permission Exceptions: " + sysManPermissions.Count + Environment.NewLine + " " + sysManPermissionsString + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + "Other Permission Exceptions: " + otherPermissions.Count + Environment.NewLine + " " + otherPermissionsString + Environment.NewLine + Environment.NewLine + Environment.NewLine + "Windows that should be opened but couldn't: " + notOpened.Count + Environment.NewLine + " " + notOpenedString + Environment.NewLine); //Now the loop is finished so fail if there were exceptions Assert.GreaterOrEqual(TotalWindowsOpened, 200, "Expected to open at least 200 windows"); Assert.GreaterOrEqual(sysManPermissions.Count, 3, "Expected to fail to open at least 3 windows requiring SYSMAN permissions"); Assert.AreEqual(notOpened.Count, 0, "Failed to open at least one window for unexplained reasons"); Assert.AreEqual(otherPermissions.Count, 0, "Unexpected failure to open some windows due to a permissions error, when we should have had sufficient permission"); if (BadFailures > 0) { Assert.Fail(String.Format("General failure to successfully open {0} window(s). Maybe there was an exception??", BadFailures)); } }
/// <summary> /// post and pay all invoices in the given period, but leave some (or none) unposted /// </summary> public static bool PostAndPayInvoices(int AYear, int APeriod, int ALeaveInvoicesUnposted = 0) { TLogging.LogAtLevel(1, "PostAndPayInvoices for year " + AYear.ToString() + " / period " + APeriod.ToString()); AccountsPayableTDS MainDS = new AccountsPayableTDS(); string sqlLoadDocuments = "SELECT * FROM PUB_a_ap_document WHERE a_ledger_number_i = ? AND a_date_issued_d >= ? AND a_date_issued_d <= ? AND a_document_status_c='APPROVED'"; DateTime PeriodStartDate, PeriodEndDate; TFinancialYear.GetStartAndEndDateOfPeriod(FLedgerNumber, APeriod, out PeriodStartDate, out PeriodEndDate, null); List <OdbcParameter> parameters = new List <OdbcParameter>(); OdbcParameter parameter; parameter = new OdbcParameter("ledgernumber", OdbcType.Int); parameter.Value = FLedgerNumber; parameters.Add(parameter); parameter = new OdbcParameter("startDate", OdbcType.DateTime); parameter.Value = PeriodStartDate; parameters.Add(parameter); parameter = new OdbcParameter("endDate", OdbcType.DateTime); parameter.Value = PeriodEndDate; parameters.Add(parameter); DBAccess.GDBAccessObj.SelectDT(MainDS.AApDocument, sqlLoadDocuments, null, parameters.ToArray(), -1, -1); int countUnPosted = MainDS.AApDocument.Count; List <int> DocumentIdsToPost = new List <int>(); foreach (AApDocumentRow invoice in MainDS.AApDocument.Rows) { if (countUnPosted <= ALeaveInvoicesUnposted) { break; } DocumentIdsToPost.Add(invoice.ApDocumentId); countUnPosted--; } TVerificationResultCollection VerificationResult; Int32 glBatchNumber; if (DocumentIdsToPost.Count > 0) { if (!TAPTransactionWebConnector.PostAPDocuments(FLedgerNumber, DocumentIdsToPost, PeriodEndDate, false, out glBatchNumber, out VerificationResult)) { TLogging.Log(VerificationResult.BuildVerificationResultString()); return(false); } } // TODO pay the invoices as well return(true); }
/// <summary> /// Starts all processing Timers. /// </summary> /// <description>This Method performs immediate processing /// if the time where processing is supposed to start is already in /// the past.</description> public static void StartProcessing() { DateTime TodaysStartTime; DateTime TomorrowsStartTime; TimeSpan InitialSleepTime; TimeSpan TwentyfourHrs; // Check if any Processing is enabled at all if (FProcessDelegates.Count == 0) { // No Processing is enabled, therefore we don't do anything here! return; } /* * Calculate the Timer's time periods */ // Calculate the DateTime of the processing time of today TodaysStartTime = DateTime.Now.Date.Add( new TimeSpan(FDailyStartTime24Hrs.Hour, FDailyStartTime24Hrs.Minute, 0)); // Calculate the DateTime of the processing time of the following day TomorrowsStartTime = TodaysStartTime.AddDays(1); // Calculate the time that the Timer should sleep until it wakes up on processing time of the following day InitialSleepTime = TomorrowsStartTime.Subtract(DateTime.Now); // Create a TimeSpan that is 1 day (=24 hrs). This is the interval in which following Timer wakeups will occur TwentyfourHrs = new TimeSpan(1, 0, 0, 0); // = 1 day if (TLogging.DebugLevel >= 9) { TLogging.Log("TTimedProcessing.StartProcessing: TodaysStartTime: " + TodaysStartTime.ToString()); TLogging.Log("TTimedProcessing.StartProcessing: TomorrowsStartTime: " + TomorrowsStartTime.ToString()); TLogging.Log("TTimedProcessing.StartProcessing: InitialSleepTime: " + InitialSleepTime.ToString()); TLogging.Log("TTimedProcessing.StartProcessing: TomorrowsStartTime + TwentyfourHrs: " + TomorrowsStartTime.AddTicks(TwentyfourHrs.Ticks).ToString()); } /* * If the daily start time is earlier that the current time: process individual Processing processes * immediately to ensure that they were run today. */ if (TodaysStartTime < DateTime.Now) { foreach (string delegatename in FProcessDelegates.Keys) { // run the job GenericProcessor(delegatename); } } /* * Start the Timer(s) for the individual processing Processes */ foreach (string delegatename in FProcessDelegates.Keys) { InitialSleepTime = InitialSleepTime.Add(new TimeSpan(0, MINUTES_DELAY_BETWEEN_INDIV_PROCESSES, 0)); TwentyfourHrs = TwentyfourHrs.Add(new TimeSpan(0, MINUTES_DELAY_BETWEEN_INDIV_PROCESSES, 0)); // Schedule the regular processing calls. FTimers.Add(new System.Threading.Timer( new TimerCallback(new TGenericProcessor(GenericProcessor)), delegatename, InitialSleepTime, TwentyfourHrs)); } }
private Action GetActionDelegateForDBConnectionAndDisconnection(int AThreadNumber) { TDataBase TDataBaseInstance = null; // Attempt to establish a new, separate DB Connection return(() => { if (AThreadNumber == 1) { FTestingThread1 = Thread.CurrentThread; // threads from the ThreadPool can be reused, and we are not allowed to set the name again in Mono if (FTestingThread1.Name == String.Empty) { // using a Guid to avoid confusion //FTestingThread1.Name = String.Format(TestThreadName, AThreadNumber); FTestingThread1.Name = String.Format(TestThreadName, Guid.NewGuid()); } } else { FTestingThread2 = Thread.CurrentThread; // threads from the ThreadPool can be reused, and we are not allowed to set the name again in Mono if (FTestingThread2.Name == String.Empty) { // using a Guid to avoid confusion //FTestingThread2.Name = String.Format(TestThreadName, AThreadNumber); FTestingThread2.Name = String.Format(TestThreadName, Guid.NewGuid()); } } try { TDataBaseInstance = DBAccess.Connect(String.Format(TestConnectionName, AThreadNumber)); TLogging.Log(String.Format("GetActionDelegateForDBConnectionAndDisconnection: Established DB Connection (Thread {0})", AThreadNumber)); if (AThreadNumber == 1) { FTestDBInstance1 = TDataBaseInstance; // Signal main Test Thread that we have successfully established a DB Connection! FEstablishedDBConnectionSignalDBConn1.Set(); // Now wait until main test Thread signals us to close the DB Connection we have established earlier... TLogging.Log(String.Format( "GetActionDelegateForDBConnectionAndDisconnection: Waiting for signal for closing of DB Connection (Thread {0})", AThreadNumber)); FCloseDBConnectionSignalDBConn1.WaitOne(); TLogging.Log(String.Format( "GetActionDelegateForDBConnectionAndDisconnection: RECEIVED signal for closing of DB Connection (Thread {0})", AThreadNumber)); FCloseDBConnectionSignalDBConn1.Dispose(); // Close the DB Connection we have established earlier FTestDBInstance1.CloseDBConnection(); // Signal main Test Thread that we have successfully closed the DB Connection! FDBConnectionClosedSignalDBConn1.Set(); } else { FTestDBInstance2 = TDataBaseInstance; // Signal main Test Thread that we have successfully established a DB Connection! FEstablishedDBConnectionSignalDBConn2.Set(); // Now wait until main test Thread signals us to close the DB Connection we have established earlier... TLogging.Log(String.Format( "GetActionDelegateForDBConnectionAndDisconnection: Waiting for signal for closing of DB Connection (Thread {0})", AThreadNumber)); FCloseDBConnectionSignalDBConn2.WaitOne(); TLogging.Log(String.Format( "GetActionDelegateForDBConnectionAndDisconnection: RECEIVED signal for closing of DB Connection (Thread {0})", AThreadNumber)); FCloseDBConnectionSignalDBConn2.Dispose(); // Close the DB Connection we have established earlier FTestDBInstance2.CloseDBConnection(); // Signal main Test Thread that we have successfully closed the DB Connection! FDBConnectionClosedSignalDBConn2.Set(); } } catch (Exception Exc) { if (AThreadNumber == 1) { FTestingThread1Exception = Exc; // Signal main Test Thread that we have finished our work here! (The Test Thread will need // to check FTestingThread1Exception to find out the Exception that happened here.) FEstablishedDBConnectionSignalDBConn1.Set(); } else { FTestingThread2Exception = Exc; // Signal main Test Thread that we have finished our work here! (The Test Thread will need // to check FTestingThread2Exception to find out the Exception that happened here.) FEstablishedDBConnectionSignalDBConn2.Set(); } } }); }
public static bool SavePartner(PartnerEditTDS AMainDS, List <string> ASubscriptions, List <string> APartnerTypes, bool ASendMail, string ADefaultEmailAddress, string ADefaultPhoneMobile, string ADefaultPhoneLandline, out TVerificationResultCollection AVerificationResult) { List <string> Dummy1, Dummy2; string Dummy3, Dummy4, Dummy5; PartnerEditTDS SaveDS; AVerificationResult = new TVerificationResultCollection(); if (AMainDS.PPartner[0].ModificationId == DateTime.MinValue) { // this is a new partner SaveDS = AMainDS; if (SaveDS.PPartner[0].PartnerKey == -1) { SaveDS.PPartner[0].PartnerKey = NewPartnerKey(); } if (SaveDS.PFamily.Count > 0) { SaveDS.PFamily[0].PartnerKey = SaveDS.PPartner[0].PartnerKey; } else if (SaveDS.PPerson.Count > 0) { SaveDS.PPerson[0].PartnerKey = SaveDS.PPartner[0].PartnerKey; } else if (SaveDS.PChurch.Count > 0) { SaveDS.PChurch[0].PartnerKey = SaveDS.PPartner[0].PartnerKey; } else if (SaveDS.POrganisation.Count > 0) { SaveDS.POrganisation[0].PartnerKey = SaveDS.PPartner[0].PartnerKey; } PPartnerLocationRow partnerlocation = SaveDS.PPartnerLocation.NewRowTyped(); partnerlocation.PartnerKey = SaveDS.PPartner[0].PartnerKey; partnerlocation.LocationKey = SaveDS.PLocation[0].LocationKey; partnerlocation.SiteKey = SaveDS.PLocation[0].SiteKey; partnerlocation.SendMail = ASendMail; SaveDS.PPartnerLocation.Rows.Add(partnerlocation); } else { SaveDS = GetPartnerDetails(AMainDS.PPartner[0].PartnerKey, out Dummy1, out Dummy2, out Dummy3, out Dummy4, out Dummy5); DataUtilities.CopyDataSet(AMainDS, SaveDS); } List <string> ExistingPartnerTypes = new List <string>(); foreach (PPartnerTypeRow partnertype in SaveDS.PPartnerType.Rows) { if (!APartnerTypes.Contains(partnertype.TypeCode)) { partnertype.Delete(); } else { ExistingPartnerTypes.Add(partnertype.TypeCode); } } // add new partner types foreach (string partnertype in APartnerTypes) { if (!ExistingPartnerTypes.Contains(partnertype)) { PPartnerTypeRow partnertypeRow = SaveDS.PPartnerType.NewRowTyped(); partnertypeRow.PartnerKey = AMainDS.PPartner[0].PartnerKey; partnertypeRow.TypeCode = partnertype; SaveDS.PPartnerType.Rows.Add(partnertypeRow); } } List <string> ExistingSubscriptions = new List <string>(); foreach (PSubscriptionRow subscription in SaveDS.PSubscription.Rows) { if (!ASubscriptions.Contains(subscription.PublicationCode)) { subscription.Delete(); } else { ExistingSubscriptions.Add(subscription.PublicationCode); } } // add new subscriptions foreach (string subscription in ASubscriptions) { if (!ExistingSubscriptions.Contains(subscription)) { PSubscriptionRow subscriptionRow = SaveDS.PSubscription.NewRowTyped(); subscriptionRow.PartnerKey = AMainDS.PPartner[0].PartnerKey; subscriptionRow.PublicationCode = subscription; subscriptionRow.ReasonSubsGivenCode = "FREE"; SaveDS.PSubscription.Rows.Add(subscriptionRow); } } bool foundDefaultEmailAddress = false; bool foundDefaultPhoneLandLine = false; bool foundDefaultMobileLandLine = false; foreach (PPartnerAttributeRow partnerattr in SaveDS.PPartnerAttribute.Rows) { if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_EMAIL) { partnerattr.Value = ADefaultEmailAddress; foundDefaultEmailAddress = true; } else if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_PHONE) { partnerattr.Value = ADefaultPhoneLandline; foundDefaultPhoneLandLine = true; } else if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_MOBILE_PHONE) { partnerattr.Value = ADefaultPhoneMobile; foundDefaultMobileLandLine = true; } } if (!foundDefaultEmailAddress) { PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped(); partnerattr.PartnerKey = SaveDS.PPartner[0].PartnerKey; partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_EMAIL; partnerattr.Value = ADefaultEmailAddress; SaveDS.PPartnerAttribute.Rows.Add(partnerattr); } if (!foundDefaultPhoneLandLine) { PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped(); partnerattr.PartnerKey = SaveDS.PPartner[0].PartnerKey; partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_PHONE; partnerattr.Value = ADefaultPhoneLandline; SaveDS.PPartnerAttribute.Rows.Add(partnerattr); } if (!foundDefaultMobileLandLine) { PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped(); partnerattr.PartnerKey = SaveDS.PPartner[0].PartnerKey; partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_MOBILE_PHONE; partnerattr.Value = ADefaultPhoneMobile; SaveDS.PPartnerAttribute.Rows.Add(partnerattr); } // TODO: either reuse Partner Edit UIConnector // or check for changed partner key, or changed Partner Class, etc. // set Partner Short Name if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_PERSON) { SaveDS.PPartner[0].PartnerShortName = Calculations.DeterminePartnerShortName( SaveDS.PPerson[0].FamilyName, SaveDS.PPerson[0].Title, SaveDS.PPerson[0].FirstName, SaveDS.PPerson[0].MiddleName1); } else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_FAMILY) { SaveDS.PPartner[0].PartnerShortName = Calculations.DeterminePartnerShortName( SaveDS.PFamily[0].FamilyName, SaveDS.PFamily[0].Title, SaveDS.PFamily[0].FirstName); } else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_UNIT) { SaveDS.PPartner[0].PartnerShortName = SaveDS.PUnit[0].UnitName; } else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_ORGANISATION) { SaveDS.PPartner[0].PartnerShortName = SaveDS.POrganisation[0].OrganisationName; } else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_BANK) { SaveDS.PPartner[0].PartnerShortName = SaveDS.PBank[0].BranchName; } // change legacy addresses. create a new separate location for each partner if (SaveDS.PLocation[0].LocationKey == 0) { PLocationRow location = SaveDS.PLocation.NewRowTyped(); DataUtilities.CopyAllColumnValues(SaveDS.PLocation[0], location); location.SiteKey = DomainManager.GSiteKey; location.LocationKey = -1; SaveDS.PLocation.Rows.Clear(); SaveDS.PLocation.Rows.Add(location); PPartnerLocationRow plocation = SaveDS.PPartnerLocation.NewRowTyped(); DataUtilities.CopyAllColumnValues(SaveDS.PPartnerLocation[0], plocation); plocation.LocationKey = -1; plocation.SiteKey = DomainManager.GSiteKey; SaveDS.PPartnerLocation[0].Delete(); SaveDS.PPartnerLocation.Rows.Add(plocation); } // check if we have a valid country code if (SaveDS.PLocation[0].CountryCode.Trim().Length == 0) { AVerificationResult.Add(new TVerificationResult("error", "The country code is missing", TResultSeverity.Resv_Critical)); return(false); } TDBTransaction Transaction = new TDBTransaction(); bool WrongCountryCode = false; DBAccess.ReadTransaction(ref Transaction, delegate { WrongCountryCode = !PCountryAccess.Exists(SaveDS.PLocation[0].CountryCode, Transaction); }); if (WrongCountryCode) { AVerificationResult.Add(new TVerificationResult("error", "The country code does not match a country", TResultSeverity.Resv_Critical)); return(false); } DataSet ResponseDS = new PartnerEditTDS(); TPartnerEditUIConnector uiconnector = new TPartnerEditUIConnector(SaveDS.PPartner[0].PartnerKey); try { TSubmitChangesResult result = uiconnector.SubmitChanges( ref SaveDS, ref ResponseDS, out AVerificationResult); return(result == TSubmitChangesResult.scrOK); } catch (Exception e) { TLogging.Log(e.ToString()); AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical)); return(false); } }
/// <summary> /// Creates a PostgreSQL connection using the 'Npgsql' .NET Data Provider. /// This works on Windows and on Linux. /// </summary> /// <param name="AServer">Database Server.</param> /// <param name="APort">Port that the DB server is running on.</param> /// <param name="ADatabaseName">Name of the database that we want to connect to.</param> /// <param name="AUsername">Username for opening the PostgreSQL connection.</param> /// <param name="APassword">Password for opening the PostgreSQL connection.</param> /// <param name="AConnectionString">Connection string; if it is not empty, it will /// overrule the previous parameters.</param> /// <param name="AStateChangeEventHandler">Event Handler for connection state changes /// (NOTE: This doesn't work yet with the Npgsql driver - see code comments in this Methods' /// source code)!</param> /// <returns> /// Instantiated NpgsqlConnection, but not opened yet (null if connection could not be established). /// </returns> public DbConnection GetConnection(String AServer, String APort, String ADatabaseName, String AUsername, ref String APassword, ref String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { ArrayList ExceptionList; NpgsqlConnection TheConnection = null; #if EXTREME_DEBUGGING NpgsqlEventLog.Level = LogLevel.Debug; NpgsqlEventLog.LogName = "NpgsqlTests.LogFile"; NpgsqlEventLog.EchoMessages = false; #endif if (String.IsNullOrEmpty(AConnectionString)) { if (String.IsNullOrEmpty(AUsername)) { throw new ArgumentException("AUsername", "AUsername must not be null or an empty string!"); } if (String.IsNullOrEmpty(APassword)) { throw new ArgumentException("APassword", "APassword must not be null or an empty string!"); } // TODO: Make 'ConnectionLifeTime' and 'CommandTimeout' configurable somehow. That would allow // us to cater better for server environments where the server is quite busy and the RDBMS could // therefore be slow to respond! See https://tracker.openpetra.org/view.php?id=2330. AConnectionString = "Server=" + AServer + ";Port=" + APort + ";User Id=" + AUsername + ";Database=" + ADatabaseName + ";ConnectionLifeTime=60;CommandTimeout=3600;Password="******";"; } catch (Exception exp) { ExceptionList = new ArrayList(); ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine)); ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine)); TLogging.Log(ExceptionList, true); } if (TheConnection != null) { // Somehow the StateChange Event is never fired for an NpgsqlConnection, although it is documented. // As a result of that we cannot rely on the FConnectionReady variable to contain valid values for // NpgsqlConnection. Therefore I (ChristianK) wrote a wrapper routine, ConnectionReady, which // handles this difference. FConnectionReady must therefore never be inquired directly, but only // through calling ConnectionReady()! // (As of Npgsql 2.0.11.92 the Event still isn't raised) // TODO: need to test this again ((NpgsqlConnection)TheConnection).StateChange += AStateChangeEventHandler; } return(TheConnection); }
/// <summary> /// export all GL Transactions in the given year, towards the specified cost centres /// </summary> public static void ExportGLTransactions(string AOutputPath, char ACSVSeparator, string ANewLine, Int32 ALedgerNumber, Int32 AFinancialYear, string ACostCentres, string AIgnoreAccounts, string AIgnoreReferences, SortedList <string, string> ATaxAnalysisAttributes, ref List <string> ACostCentresInvolved, ref List <string> AAccountsInvolved) { string filename = Path.GetFullPath(Path.Combine(AOutputPath, "transaction.csv")); Console.WriteLine("Writing file: " + filename); StringBuilder sb = new StringBuilder(); TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted); string sql = String.Format("SELECT T.*, B.{4} AS a_transaction_date_d " + "FROM PUB_{8} AS B, PUB_{7} AS T " + "WHERE B.{9} = {10} AND B.{15} = {16} AND B.{11}='{12}' " + "AND T.{9} = B.{9} AND T.{0} = B.{0} " + "AND T.{13} IN ({14}) " + "AND NOT T.{17} IN ({19}) " + "AND NOT T.{20} IN ({21}) " + "ORDER BY {0}, {1}, {2}", ATransactionTable.GetBatchNumberDBName(), ATransactionTable.GetJournalNumberDBName(), ATransactionTable.GetTransactionNumberDBName(), ATransactionTable.GetTransactionAmountDBName(), ABatchTable.GetDateEffectiveDBName(), ATransactionTable.GetNarrativeDBName(), ATransactionTable.GetReferenceDBName(), ATransactionTable.GetTableDBName(), ABatchTable.GetTableDBName(), ATransactionTable.GetLedgerNumberDBName(), ALedgerNumber, ABatchTable.GetBatchStatusDBName(), MFinanceConstants.BATCH_POSTED, ATransactionTable.GetCostCentreCodeDBName(), "'" + ACostCentres.Replace(",", "','") + "'", ABatchTable.GetBatchYearDBName(), AFinancialYear, ATransactionTable.GetAccountCodeDBName(), ATransactionTable.GetDebitCreditIndicatorDBName(), "'" + AIgnoreAccounts.Replace(",", "','") + "'", ATransactionTable.GetReferenceDBName(), "'" + AIgnoreReferences.Replace(",", "','") + "'"); ATransactionTable transactions = new ATransactionTable(); transactions = (ATransactionTable)DBAccess.GDBAccessObj.SelectDT(transactions, sql, Transaction, null, 0, 0); // get the analysis attributes sql = String.Format("SELECT A.* from PUB_{1} AS B, PUB_{13} AS T, PUB_{0} AS A " + "WHERE B.{2} = {3} AND B.{4} = {5} AND B.{6}='{7}' " + "AND T.{2} = B.{2} AND T.{8} = B.{8} " + "AND T.{9} IN ({10}) " + "AND A.{2} = T.{2} AND A.{8} = T.{8} AND A.{11} = T.{11} AND A.{12} = T.{12}", ATransAnalAttribTable.GetTableDBName(), ABatchTable.GetTableDBName(), ABatchTable.GetLedgerNumberDBName(), ALedgerNumber, ABatchTable.GetBatchYearDBName(), AFinancialYear, ABatchTable.GetBatchStatusDBName(), MFinanceConstants.BATCH_POSTED, ATransactionTable.GetBatchNumberDBName(), ATransactionTable.GetCostCentreCodeDBName(), "'" + ACostCentres.Replace(",", "','") + "'", ATransactionTable.GetJournalNumberDBName(), ATransactionTable.GetTransactionNumberDBName(), ATransactionTable.GetTableDBName(), ABatchTable.GetBatchYearDBName()); ATransAnalAttribTable TransAnalAttrib = new ATransAnalAttribTable(); DBAccess.GDBAccessObj.SelectDT(TransAnalAttrib, sql, Transaction, null, 0, 0); TransAnalAttrib.DefaultView.Sort = ATransAnalAttribTable.GetBatchNumberDBName() + "," + ATransAnalAttribTable.GetJournalNumberDBName() + "," + ATransAnalAttribTable.GetTransactionNumberDBName(); // get a list of all batches involved List <Int64> batches = new List <Int64>(); StringBuilder batchnumbers = new StringBuilder(); foreach (ATransactionRow r in transactions.Rows) { if (!batches.Contains(r.BatchNumber)) { batches.Add(r.BatchNumber); batchnumbers.Append(r.BatchNumber.ToString() + ","); } } // get the other transactions in the same journal for finding the opposite cc/acc involved // for performance reasons, get all transactions of the whole batch sql = String.Format("SELECT DISTINCT TJ.* " + "FROM PUB_{0} AS TJ " + "WHERE TJ.{1} = {2} AND TJ.{3} IN ({4})", ATransactionTable.GetTableDBName(), ATransactionTable.GetLedgerNumberDBName(), ALedgerNumber, ATransactionTable.GetBatchNumberDBName(), batchnumbers.ToString() + "-1"); ATransactionTable allTransactionsInJournal = new ATransactionTable(); allTransactionsInJournal = (ATransactionTable)DBAccess.GDBAccessObj.SelectDT(allTransactionsInJournal, sql, Transaction, null, 0, 0); allTransactionsInJournal.DefaultView.Sort = ATransactionTable.GetBatchNumberDBName() + "," + ATransactionTable.GetJournalNumberDBName(); // get all names of gift batches sql = String.Format("SELECT * FROM PUB_{0} " + "WHERE {1} = {2} " + "AND {3} = {4}", AGiftBatchTable.GetTableDBName(), AGiftBatchTable.GetLedgerNumberDBName(), ALedgerNumber, AGiftBatchTable.GetBatchYearDBName(), AFinancialYear); AGiftBatchTable giftbatches = new AGiftBatchTable(); DBAccess.GDBAccessObj.SelectDT(giftbatches, sql, Transaction, null, 0, 0); giftbatches.DefaultView.Sort = AGiftBatchTable.GetBatchNumberDBName(); sql = String.Format("SELECT * FROM PUB_{0} " + "WHERE {1} = {2}", AAccountTable.GetTableDBName(), AAccountTable.GetLedgerNumberDBName(), ALedgerNumber); AAccountTable accounts = new AAccountTable(); DBAccess.GDBAccessObj.SelectDT(accounts, sql, Transaction, null, 0, 0); accounts.DefaultView.Sort = AAccountTable.GetAccountCodeDBName(); DBAccess.GDBAccessObj.RollbackTransaction(); int rowCounter = 0; StringCollection costcentreCollection = StringHelper.StrSplit(ACostCentres, ","); foreach (ATransactionRow row in transactions.Rows) { if (row.DebitCreditIndicator) { row.TransactionAmount *= -1.0m; } StringBuilder attributes = new StringBuilder(); DataRowView[] attribs = TransAnalAttrib.DefaultView.FindRows(new object[] { row.BatchNumber, row.JournalNumber, row.TransactionNumber }); decimal TaxOnIncome = 0.0m; decimal TaxOnExpense = 0.0m; // only mention tax codes, if this transaction was against a costcentre that has to pay taxes if (costcentreCollection.Contains(row.CostCentreCode)) { foreach (DataRowView rv in attribs) { ATransAnalAttribRow attribRow = (ATransAnalAttribRow)rv.Row; // also export attribRow.AnalysisTypeCode? attributes.Append(attribRow.AnalysisAttributeValue); if (attribRow.AnalysisAttributeValue == "v19") { TaxOnExpense = row.TransactionAmount * 0.19m; } else if (attribRow.AnalysisAttributeValue == "v7") { TaxOnExpense = row.TransactionAmount * 0.07m; } else if (attribRow.AnalysisAttributeValue == "70v7") { TaxOnExpense = row.TransactionAmount * 0.7m * 0.07m; } else if (attribRow.AnalysisAttributeValue == "70v19") { TaxOnExpense = row.TransactionAmount * 0.7m * 0.19m; } else if (attribRow.AnalysisAttributeValue == "m19") { TaxOnIncome = row.TransactionAmount * 0.19m; } else if (attribRow.AnalysisAttributeValue == "m7") { TaxOnIncome = row.TransactionAmount * 0.07m; } } } DataRowView[] RelatedTransactions = allTransactionsInJournal.DefaultView.FindRows(new object[] { row.BatchNumber, row.JournalNumber }); ATransactionRow[] OtherTransactions = GetOtherTransactions(row, RelatedTransactions); string OtherCostCentres = string.Empty; string OtherAccountCodes = string.Empty; if (OtherTransactions.Length < 30) { foreach (ATransactionRow r in OtherTransactions) { OtherCostCentres = StringHelper.AddCSV(OtherCostCentres, r.CostCentreCode); OtherAccountCodes = StringHelper.AddCSV(OtherAccountCodes, r.AccountCode); } } if (!ACostCentresInvolved.Contains(row.CostCentreCode)) { ACostCentresInvolved.Add(row.CostCentreCode); } if (!AAccountsInvolved.Contains(row.AccountCode)) { AAccountsInvolved.Add(row.AccountCode); } // we are using gift batch for receiving payments string Narrative = row.Narrative; if (Narrative.StartsWith("GB - Gift Batch ") && row.Reference.StartsWith("GB")) { // find the account and set the account description into the narrative try { DataRowView[] acc = accounts.DefaultView.FindRows(row.AccountCode); Narrative = ((AAccountRow)acc[0].Row).AccountCodeLongDesc; } catch (Exception) { } try { DataRowView[] gb = giftbatches.DefaultView.FindRows(Convert.ToInt32(row.Reference.Substring(2))); Narrative += " " + ((AGiftBatchRow)gb[0].Row).BatchDescription; } catch (Exception) { } } sb.Append(StringHelper.StrMerge( new string[] { "B" + row.BatchNumber.ToString() + "_J" + row.JournalNumber.ToString() + "_T" + row.TransactionNumber.ToString(), row.CostCentreCode, row.AccountCode, row.TransactionDate.ToString("yyyyMMdd"), OtherCostCentres, OtherAccountCodes, Narrative, row.Reference, String.Format("{0:N}", row.TransactionAmount), attributes.ToString(), TaxOnIncome.ToString(), TaxOnExpense.ToString() }, ACSVSeparator)); sb.Append(ANewLine); rowCounter++; if (rowCounter % 500 == 0) { TLogging.Log("Processing transactions " + rowCounter.ToString()); } } TLogging.Log("Processing transactions " + rowCounter.ToString()); StreamWriter sw = new StreamWriter(filename, false, Encoding.GetEncoding(1252)); sw.Write(sb.ToString()); sw.Close(); }
/// <summary> /// load statements from an sql file that we use for PostgreSQL /// </summary> /// <param name="ADataDefinition"></param> /// <param name="ADBFilename"></param> /// <param name="APath"></param> /// <param name="ASqlfile"></param> /// <param name="ADBPwd"></param> /// <returns></returns> static public bool ExecuteLoadScript(TDataDefinitionStore ADataDefinition, string ADBFilename, string APath, string ASqlfile, string ADBPwd) { // see tutorial for fast bulk loads: http://Sqlite.phxsoftware.com/forums/t/134.aspx // sqlite on Windows does not support encryption with a password // System.EntryPointNotFoundException: sqlite3_key ADBPwd = string.Empty; TLogging.Log("Connecting to sqlite database " + ADBFilename); TLogging.Log("Loading file " + ASqlfile); if (!File.Exists(ADBFilename)) { TLogging.Log("File does not exist: " + ADBFilename); return(false); } SqliteConnection conn; try { conn = new SqliteConnection("Data Source=" + ADBFilename + (ADBPwd.Length > 0 ? ";Password="******"")); conn.Open(); } catch (Exception e) { TLogging.Log("cannot open file " + ADBFilename); TLogging.Log(e.ToString()); return(false); } StreamReader reader = new StreamReader(ASqlfile); string line = null; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); if (line.ToUpper().StartsWith("DELETE FROM ")) { RunCommand(conn, line); } else if (line.ToUpper().StartsWith("INSERT INTO ") || line.ToUpper().StartsWith("UPDATE ")) { line = line.Replace("true", "1"); line = line.Replace("false", "0"); RunCommand(conn, line); } else if (line.ToUpper().StartsWith("COPY ") && line.ToUpper().Contains("FROM STDIN")) { string tablename = StringHelper.GetCSVValue(line.Replace(" ", ","), 1); string columnnames = line.Substring(line.IndexOf("(") + 1); columnnames = columnnames.Substring(0, columnnames.IndexOf(")")); LoadDataFromReader(ADataDefinition, conn, reader, tablename, StringHelper.GetCSVList(columnnames, ",", true)); } else if (line.ToUpper().StartsWith("COPY ")) { string tablename = StringHelper.GetCSVValue(line.Replace(" ", ","), 1); LoadData(ADataDefinition, conn, APath, tablename); } else if (line.ToUpper().StartsWith("SELECT NEXTVAL(")) { string SequenceName = line.Substring(line.IndexOf("'") + 1); SequenceName = SequenceName.Substring(0, SequenceName.IndexOf("'")); RunCommand(conn, "INSERT INTO " + SequenceName + " VALUES(NULL, -1);"); } else if (!line.StartsWith("--") && (line.Trim().Length > 0)) { throw new Exception("unknown command " + line); } } conn.Close(); return(true); }
/// <summary> /// Sets up .NET Remoting Lifetime Services and TCP Channel for this AppDomain. /// /// @comment WARNING: If you need to change the parameters of the Constructor, /// you also need to change the parameters in the .NET Reflection call in /// TClientAppDomainConnection! /// /// </summary> /// <param name="AClientID">ClientID as assigned by the ClientManager</param> /// <param name="AClientServerConnectionType">Tells in which way the Client connected /// to the PetraServer</param> /// <param name="AClientManagerRef">A reference to the ClientManager object /// (Note: .NET Remoting will be working behind the scenes since calls to /// this Object will cross AppDomains!)</param> /// <param name="AUserID"></param> /// <returns>void</returns> public TClientDomainManagerBase(String AClientID, TClientServerConnectionType AClientServerConnectionType, TClientManagerCallForwarder AClientManagerRef, string AUserID) { new TAppSettingsManager(false); FUserID = AUserID; // Console.WriteLine('TClientDomainManager.Create in AppDomain: ' + Thread.GetDomain().FriendlyName); DomainManagerBase.GClientID = Convert.ToInt16(AClientID); DomainManagerBase.UClientManagerCallForwarderRef = AClientManagerRef; FClientServerConnectionType = AClientServerConnectionType; FClientTasksManager = new TClientTasksManager(); FTearDownAppDomainMonitor = new System.Object(); Random random = new Random(); FRandomAppDomainTearDownToken = random.Next(Int32.MinValue, Int32.MaxValue).ToString(); // // Set up .NET Remoting Lifetime Services and TCP Channel for this AppDomain. // Note: .NET Remoting needs to be set up separately for each AppDomain, and settings in // the .NET (Remoting) Configuration File are valid only for the Default AppDomain. // try { // The following settings equal to a config file's // <lifetime leaseTime="10MS" renewOnCallTime="10MS" leaseManagerPollTime = "5MS" /> // setting. // Please note that this breaks remoting on mono, but these settings help on MS .NET // to find any remoted objects whose lifetime was inadvertedly not configured, and // therefore live only very short and calls to them break... // LifetimeServices.LeaseTime := TimeSpan.FromMilliseconds(10); // LifetimeServices.RenewOnCallTime := TimeSpan.FromMilliseconds(10); // LifetimeServices.LeaseManagerPollTime := TimeSpan.FromMilliseconds(5); // More sensible settings for Lifetime Services // TODO 1 ochristiank cRemoting : .NET Remoting LifetimeSettings should be flexible instead hardcoded in the future! try { LifetimeServices.LeaseTime = TimeSpan.FromSeconds(60); LifetimeServices.RenewOnCallTime = TimeSpan.FromSeconds(60); LifetimeServices.LeaseManagerPollTime = TimeSpan.FromSeconds(5); } catch (RemotingException) { // ignore System.Runtime.Remoting.RemotingException : 'LeaseTime' can only be set once within an AppDomain. // this happens in the Server NUnit test, when running several tests, therefore reconnecting with the same AppDomain. } } catch (Exception e) { TLogging.Log(e.ToString()); throw; } if (TLogging.DL >= 4) { Console.WriteLine("Application domain: " + Thread.GetDomain().FriendlyName); Console.WriteLine(" for User: " + FUserID); } }
/** * Thread that checks in regular intervals whether the Date and Time when the * last Client call to 'PollClientTasks' was made exceeds a certain timeout * limit (different for Clients connected via LAN or Remote). * * @comment The Thread is started at Class instantiation and can be stopped by * calling the StopClientStillAliveCheckThread method. * * @comment The check interval can be configured with the ServerSetting * 'Server.ClientKeepAliveCheckIntervalInSeconds'. * */ public void ClientStillAliveCheckThread() { TimeSpan Duration; DateTime LastPollingTime; // Check whether this Thread should still execute while (UKeepServerAliveCheck) { TLogging.LogAtLevel(2, "TClientStillAliveCheck (for ClientName '" + ClientName + "'): ClientStillAliveCheckThread: checking..."); // Get the time of the last call to TPollClientTasks.PollClientTasks LastPollingTime = FClientObject.FPollClientTasks.GetLastPollingTime(); // Calculate time between the last call to TPollClientTasks.PollClientTasks and now Duration = DateTime.Now.Subtract(LastPollingTime); // Determine whether the timeout has been exceeded if (Duration.TotalSeconds < UClientStillAliveTimeout) { // No it hasn't TLogging.LogAtLevel( 2, "TClientStillAliveCheck (for ClientName '" + ClientName + "'): ClientStillAliveCheckThread: timeout hasn't been exceeded (Clients' last PollClientTasks was called " + Duration.TotalSeconds.ToString() + " ago)."); try { // Sleep for some time. After that, this procedure is called again automatically. TLogging.LogAtLevel(2, "TClientStillAliveCheck (for ClientName '" + ClientName + "'): ClientStillAliveCheckThread: going to sleep..."); Thread.Sleep(UClientStillAliveCheckInterval * 1000); TLogging.LogAtLevel(12, "TClientStillAliveCheck (for ClientName '" + ClientName + "'): ClientStillAliveCheckThread: re-awakening..."); } catch (ThreadAbortException) { TLogging.LogAtLevel( 2, "TClientStillAliveCheck (for ClientName '" + ClientName + "'): ClientStillAliveCheckThread: ThreadAbortException occured!!!"); UKeepServerAliveCheck = false; } } else { TLogging.LogAtLevel( 1, "TClientStillAliveCheck (for ClientName '" + ClientName + "'): ClientStillAliveCheckThread: timeout HAS been exceeded (last PollClientTasks call: " + LastPollingTime.ToString() + ") -> forcefully disconnecting the Client!"); /* * Timeout has been exceeded, this means the Client didn't make a call * to TPollClientTasks.PollClientTasks within the time that is specified * in UClientStillAliveTimeout */ /* * KeepServerAliveCheck Thread should no longer run (has an effect only * when this procedure is called from the ClientStillAliveCheckThread * Thread itself) */ UKeepServerAliveCheck = false; // Forcefully disconnect the Client! if (UTearDownAppDomain != null) { string CantDisconnectReason; UTearDownAppDomain(FClientObject.ClientID, String.Format(StrClientFailedToContact, Duration.Hours.ToString() + ':' + Duration.Minutes.ToString() + ':' + Duration.Seconds.ToString()), out CantDisconnectReason); } else { if (TLogging.DL >= 10) { TLogging.Log("TClientStillAliveCheck: FTearDownAppDomain was not assigned -> can't tear down Client's AppDomain!"); } } } } // Thread stops here and doesn't get called again automatically. TLogging.LogAtLevel(12, "TClientStillAliveCheck (for ClientName '" + ClientName + "'): ClientStillAliveCheckThread: Thread stopped!"); }
public static bool ResetDatabase(string AZippedNewDatabaseData) { TDataBase DBConnectionObj = null; List <string> tables = TTableList.GetDBNames(); bool SubmissionResult = false; TDBTransaction ReadWriteTransaction = new TDBTransaction(); SortedList <int, string> CurrencyPerLedger = new SortedList <int, string>(); string ClientID = "ClientID"; try { ClientID = DomainManager.GClientID.ToString(); } catch (Exception) { } try { // Open a separate DB Connection for the importing of the data... DBConnectionObj = DBAccess.Connect("ExportAllTables"); // ...and start a DB Transaction on that separate DB Connection DBConnectionObj.WriteTransaction(ref ReadWriteTransaction, ref SubmissionResult, delegate { try { TProgressTracker.InitProgressTracker(ClientID, Catalog.GetString("Restoring Database..."), tables.Count + 3); tables.Reverse(); // ignore s_session table, to avoid locking during the restore tables.Remove("s_session"); TProgressTracker.SetCurrentState(ClientID, Catalog.GetString("Deleting current data..."), 0); foreach (string table in tables) { ReadWriteTransaction.DataBaseObj.ExecuteNonQuery("DELETE FROM pub_" + table, ReadWriteTransaction); } if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true) { TProgressTracker.FinishJob(ClientID); // As SubmissionResult is still false, a DB Transaction Rollback will get // executed automatically and the Method will be exited with return value 'false'! return; } TSimpleYmlParser ymlParser = new TSimpleYmlParser(PackTools.UnzipString(AZippedNewDatabaseData)); ymlParser.ParseCaptions(); tables.Reverse(); TProgressTracker.SetCurrentState(ClientID, Catalog.GetString("Loading initial tables..."), 1); // one transaction to import the user table and user permissions. otherwise logging in will not be possible if other import fails? bool success = true; success = success && LoadTable("s_user", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); success = success && LoadTable("s_module", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); success = success && LoadTable("s_user_module_access_permission", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); success = success && LoadTable("s_system_defaults", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); success = success && LoadTable("s_system_status", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); // make sure we have the correct database version TFileVersionInfo serverExeInfo = new TFileVersionInfo(TSrvSetting.ApplicationVersion); ReadWriteTransaction.DataBaseObj.ExecuteNonQuery(String.Format( "UPDATE PUB_s_system_defaults SET s_default_value_c = '{0}' WHERE s_default_code_c = 'CurrentDatabaseVersion'", serverExeInfo.ToString()), ReadWriteTransaction); if (!success) { // As SubmissionResult is still TSubmitChangesResult.scrError, a DB Transaction Rollback will get // executed automatically and the Method will be exited with return value 'false'! return; } if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true) { TProgressTracker.FinishJob(ClientID); // As SubmissionResult is still false, a DB Transaction Rollback will get // executed automatically and the Method will be exited with return value 'false'! return; } tables.Remove("s_user"); tables.Remove("s_module"); tables.Remove("s_user_module_access_permission"); tables.Remove("s_system_defaults"); tables.Remove("s_system_status"); int tableCounter = 2; foreach (string table in tables) { TProgressTracker.SetCurrentState(ClientID, String.Format(Catalog.GetString("Loading Table {0}..."), table), tableCounter); tableCounter++; if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true) { TProgressTracker.FinishJob(ClientID); // As SubmissionResult is still false, a DB Transaction Rollback will get // executed automatically and the Method will be exited with return value 'false'! return; } LoadTable(table, ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); } TProgressTracker.SetCurrentState(ClientID, Catalog.GetString("Loading Sequences..."), tables.Count + 5 + 3); // set sequences appropriately, not lagging behind the imported data foreach (string seq in TTableList.GetDBSequenceNames()) { LoadSequence(seq, ymlParser, ReadWriteTransaction); } TProgressTracker.SetCurrentState(ClientID, Catalog.GetString("Finishing Restore..."), tables.Count + 5 + 4); SubmissionResult = true; // reset all cached tables TCacheableTablesManager.GCacheableTablesManager.MarkAllCachedTableNeedsRefreshing(); TProgressTracker.FinishJob(ClientID); } catch (Exception e) { TLogging.Log("Problem in ResetDatabase: " + e.ToString()); TLogging.LogStackTrace(TLoggingType.ToLogfile); throw; } }); } finally { if (DBConnectionObj != null) { DBConnectionObj.CloseDBConnection(); } } return(SubmissionResult); }
/// throws an exception if the current user does not have enough permission to access the method; /// this uses a custom attribute associated with the method of the connector static public string CheckUserPermissionsForMethod(System.Type AConnectorType, string AMethodName, string AParameterTypes, Int32 ALedgerNumber = -1, bool ADontThrowException = false) { MethodInfo[] methods = AConnectorType.GetMethods(); MethodInfo MethodToTest = null; AParameterTypes = AParameterTypes.Replace("[]", ".ARRAY"); foreach (MethodInfo method in methods) { if (method.Name == AMethodName) { string ParameterTypes = ";"; ParameterInfo[] Parameters = method.GetParameters(); foreach (ParameterInfo Parameter in Parameters) { string ParameterName = Parameter.ParameterType.ToString().Replace("&", ""); ParameterName = ParameterName.Replace("System.Collections.Generic.Dictionary`2", "DICTIONARY"); ParameterName = ParameterName.Replace("Ict.Common.", string.Empty); ParameterName = ParameterName.Replace("Ict.Petra.Shared.MCommon.", string.Empty); ParameterName = ParameterName.Replace("System.", string.Empty); if (ParameterName.Contains(".")) { ParameterName = ParameterName.Substring(ParameterName.LastIndexOf(".") + 1); } ParameterName = ParameterName.Replace("`1", string.Empty); ParameterName = ParameterName.Replace("`2", string.Empty); ParameterName = ParameterName.Replace("Boolean", "bool"); ParameterName = ParameterName.Replace("Int32", "int"); ParameterName = ParameterName.Replace("Int64", "long"); ParameterName = ParameterName.Replace("[]", ".Array"); ParameterTypes += ParameterName + ";"; } ParameterTypes = ParameterTypes.ToUpper(); if (ParameterTypes == AParameterTypes) { MethodToTest = method; break; } } } if (MethodToTest != null) { System.Object[] attributes = MethodToTest.GetCustomAttributes(typeof(RequireModulePermissionAttribute), false); if ((attributes != null) && (attributes.Length > 0)) { RequireModulePermissionAttribute requiredModules = (RequireModulePermissionAttribute)attributes[0]; string moduleExpression = requiredModules.RequiredModulesExpression.ToUpper(); if (moduleExpression == "NONE") { return("OK"); } // authenticated user if (moduleExpression == "USER") { if (UserInfo.GetUserInfo() != null && UserInfo.GetUserInfo().UserID != null) { return("OK"); } } try { TSecurityChecks.CheckUserModulePermissions(moduleExpression); if (ALedgerNumber != -1) { TSecurityChecks.CheckUserModulePermissions(SharedConstants.LEDGER_MODULESTRING + ALedgerNumber.ToString("0000")); } } catch (ESecurityModuleAccessDeniedException Exc) { string msg = String.Format(Catalog.GetString( "Module access permission was violated for method '{0}' in Connector class '{1}': Required Module access permission: {2}, UserName: {3}"), AMethodName, AConnectorType, Exc.Module, Exc.UserName); TLogging.Log(msg); Exc.Context = AMethodName + " [raised by ModuleAccessManager]"; if (ADontThrowException) { TVerificationResultCollection VerificationResult = new TVerificationResultCollection(); VerificationResult.Add(new TVerificationResult("error", msg, "", "forms.NotEnoughPermissions", TResultSeverity.Resv_Critical)); return("{" + "\"AVerificationResult\": " + THttpBinarySerializer.SerializeObject(VerificationResult) + "," + "\"result\": false}"); } throw; } catch (ArgumentException argException) { throw new EOPAppException("Problem with ModulePermissions, " + argException.Message + ": '" + moduleExpression + "' for " + AConnectorType.ToString() + "." + AMethodName + "()", argException); } return("OK"); } } // TODO: resolve module permission from namespace? throw new EOPAppException( "Missing definition of access permission for method " + AMethodName + " in Connector class " + AConnectorType); }
private static bool LoadTable(string ATableName, TSimpleYmlParser AYmlParser, TDBTransaction AReadWriteTransaction, ref SortedList <Int32, string> ACurrencyPerLedger) { if (!AYmlParser.StartParseList(StringHelper.UpperCamelCase(ATableName, false, false) + "Table")) { // TLogging.Log("empty table " + ATableName + " " + StringHelper.UpperCamelCase(ATableName, false, false) + "Table"); return(false); } DataTable table = AReadWriteTransaction.DataBaseObj.SelectDT("Select * from " + ATableName, ATableName, AReadWriteTransaction); List <OdbcParameter> Parameters = new List <OdbcParameter>(); string OrigInsertStatement = "INSERT INTO pub_" + ATableName + "() VALUES "; StringBuilder InsertStatement = new StringBuilder(OrigInsertStatement); ConvertColumnNames(table.Columns); SortedList <string, string> RowDetails; int count = 0; while ((RowDetails = AYmlParser.GetNextLineAttributes()) != null) { count++; if (count != 1) { if ((DBAccess.DBType == TDBType.SQLite) || (DBAccess.DBType == TDBType.MySQL) || ((count % 500) == 0)) { // SQLite does not support INSERT of several rows at the same time // MySQL is very slow with INSERT of several rows at the same time try { AReadWriteTransaction.DataBaseObj.ExecuteNonQuery(InsertStatement.ToString(), AReadWriteTransaction, Parameters.ToArray()); } catch (Exception e) { TLogging.Log("error in ResetDatabase, LoadTable " + ATableName + ":" + e.Message); throw; } InsertStatement = new StringBuilder(OrigInsertStatement); Parameters = new List <OdbcParameter>(); } else { InsertStatement.Append(","); } } InsertStatement.Append("("); // needed for workaround for version 0.2.24, AAPDocument.BaseCurrency and AAPPayment.BaseCurrency; if (ATableName == "a_ledger") { ACurrencyPerLedger.Add(Convert.ToInt32(RowDetails["LedgerNumber"]), RowDetails["BaseCurrency"]); } // workaround for 2015.09: a_account_hierarchy_detail.a_report_order_i must not be NULL if (ATableName == "a_account_hierarchy_detail") { if (!RowDetails.ContainsKey("ReportOrder") || RowDetails["ReportOrder"] == string.Empty) { RowDetails["ReportOrder"] = "-1"; } } if (ATableName == "a_gift") { if (!RowDetails.ContainsKey("LinkToPreviousGift") || RowDetails["LinkToPreviousGift"] == string.Empty) { RowDetails["LinkToPreviousGift"] = "false"; } if (!RowDetails.ContainsKey("PrintReceipt") || RowDetails["PrintReceipt"] == string.Empty) { RowDetails["PrintReceipt"] = "true"; } } if (ATableName == "a_recurring_transaction") { if (!RowDetails.ContainsKey("Reference") || RowDetails["Reference"] == string.Empty) { RowDetails["Reference"] = "EMPTY"; } } if (ATableName == "a_transaction") { if (!RowDetails.ContainsKey("Reference") || RowDetails["Reference"] == string.Empty) { RowDetails["Reference"] = "EMPTY"; } } bool firstColumn = true; foreach (DataColumn col in table.Columns) { if (!firstColumn) { InsertStatement.Append(","); } firstColumn = false; if (RowDetails.ContainsKey(col.ColumnName)) { string strValue = RowDetails[col.ColumnName]; if (col.DataType == typeof(DateTime)) { OdbcParameter p; if (strValue.Length == "yyyy-MM-dd".Length) { p = new OdbcParameter(Parameters.Count.ToString(), OdbcType.Date); p.Value = DateTime.ParseExact(strValue, "yyyy-MM-dd", CultureInfo.InvariantCulture); } else { p = new OdbcParameter(Parameters.Count.ToString(), OdbcType.DateTime); p.Value = DateTime.ParseExact(strValue, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); } Parameters.Add(p); } else if (col.DataType == typeof(String)) { OdbcParameter p = new OdbcParameter(Parameters.Count.ToString(), OdbcType.VarChar); p.Value = strValue.Replace(""", "\""); Parameters.Add(p); } else if (col.DataType == typeof(Int32)) { OdbcParameter p = new OdbcParameter(Parameters.Count.ToString(), OdbcType.Int); p.Value = Convert.ToInt32(strValue); Parameters.Add(p); } else if (col.DataType == typeof(Int64)) { OdbcParameter p = new OdbcParameter(Parameters.Count.ToString(), OdbcType.Decimal); p.Value = Convert.ToInt64(strValue); Parameters.Add(p); } else if (col.DataType == typeof(double)) { OdbcParameter p = new OdbcParameter(Parameters.Count.ToString(), OdbcType.Decimal); p.Value = Convert.ToDouble(strValue, CultureInfo.InvariantCulture); Parameters.Add(p); } else if (col.DataType == typeof(bool)) { OdbcParameter p = new OdbcParameter(Parameters.Count.ToString(), OdbcType.Bit); p.Value = Convert.ToBoolean(strValue); Parameters.Add(p); } else if (col.DataType == typeof(Decimal)) { OdbcParameter p = new OdbcParameter(Parameters.Count.ToString(), OdbcType.Decimal); p.Value = Convert.ToDecimal(strValue, CultureInfo.InvariantCulture); Parameters.Add(p); } else { // should not get here? throw new Exception("error in ResetDatabase, LoadTable: " + col.DataType.ToString() + " has not yet been implemented"); } InsertStatement.Append("?"); } else { // the following statements are for the demo databases generated before version 0.2.24. // CurrencyCode was added to a_ap_document and a_ap_payment. // it is impossible during the load, to get the correct currencycode, via the supplier, because a_ap_supplier is loaded after a_ap_document. // as a temporary workaround, and because we are still in Alpha, we are using the Base currency of the ledger if ((ATableName == "a_ap_document") && (col.ColumnName == "CurrencyCode")) { OdbcParameter p = new OdbcParameter(Parameters.Count.ToString(), OdbcType.VarChar); p.Value = ACurrencyPerLedger[Convert.ToInt32(RowDetails["LedgerNumber"])]; Parameters.Add(p); InsertStatement.Append("?"); } else if ((ATableName == "a_ap_payment") && (col.ColumnName == "CurrencyCode")) { OdbcParameter p = new OdbcParameter(Parameters.Count.ToString(), OdbcType.VarChar); p.Value = ACurrencyPerLedger[Convert.ToInt32(RowDetails["LedgerNumber"])]; Parameters.Add(p); InsertStatement.Append("?"); } else { InsertStatement.Append("NULL"); // DEFAULT } } } InsertStatement.Append(")"); } try { AReadWriteTransaction.DataBaseObj.ExecuteNonQuery(InsertStatement.ToString(), AReadWriteTransaction, Parameters.ToArray()); } catch (Exception e) { TLogging.Log("error in ResetDatabase, LoadTable " + ATableName + ":" + e.Message); throw; } return(true); }
/// <summary>Returns an instance of a Page UserControl.</summary> protected UserControl InstantiatePageUC(string AID) { TLogging.Log("SwitchToPage (in TPetraShepherdFormLogic) was called for Page UserControl '" + AID + "'"); return(null); }
public static Boolean SendEmail(string AReportID, string AEmailAddresses, bool AAttachExcelFile, bool AAttachPDF, out TVerificationResultCollection AVerification) { TSmtpSender EmailSender = null; string EmailBody = ""; SReportResultRow Row = GetReportResult(AReportID, null); TParameterList ParameterList = new TParameterList(); AVerification = new TVerificationResultCollection(); if (Row == null) { return(false); } ParameterList.LoadFromJson(Row.ParameterList); HtmlDocument HTMLDocument = new HtmlDocument(); HTMLDocument.LoadHtml(Row.ResultHtml); try { EmailSender = new TSmtpSender(); List <string> FilesToAttach = new List <string>(); if (AAttachExcelFile) { string ExcelFile = TFileHelper.GetTempFileName( ParameterList.Get("currentReport").ToString(), ".xlsx"); if (ExportToExcelFile(ExcelFile, HTMLDocument)) { FilesToAttach.Add(ExcelFile); } } if (AAttachPDF) { string PDFFile = TFileHelper.GetTempFileName( ParameterList.Get("currentReport").ToString(), ".pdf"); if (PrintToPDF(PDFFile, HTMLDocument)) { FilesToAttach.Add(PDFFile); } } if (FilesToAttach.Count == 0) { AVerification.Add(new TVerificationResult( Catalog.GetString("Sending Email"), Catalog.GetString("Missing any attachments, not sending the email"), "Missing Attachments", TResultSeverity.Resv_Critical, new System.Guid())); return(false); } try { EmailSender.SetSender(TUserDefaults.GetStringDefault("SmtpFromAccount"), TUserDefaults.GetStringDefault("SmtpDisplayName")); EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo"); EmailSender.ReplyTo = TUserDefaults.GetStringDefault("SmtpReplyTo"); EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody"); } catch (ESmtpSenderInitializeException e) { AVerification.Add(new TVerificationResult( Catalog.GetString("Sending Email"), String.Format("{0}\n{1}", e.Message, Catalog.GetString("Check the Email tab in User Settings >> Preferences.")), CommonErrorCodes.ERR_MISSINGEMAILCONFIGURATION, TResultSeverity.Resv_Critical, new System.Guid())); if (e.InnerException != null) { TLogging.Log("Email XML Report: " + e.InnerException); } return(false); } if (EmailBody == "") { EmailBody = Catalog.GetString("OpenPetra report attached."); } if (EmailSender.SendEmail( AEmailAddresses, ParameterList.Get("currentReport").ToString(), EmailBody, FilesToAttach.ToArray())) { foreach (string file in FilesToAttach) { File.Delete(file); } return(true); } AVerification.Add(new TVerificationResult( Catalog.GetString("Sending Email"), Catalog.GetString("Problem sending email"), "Server problems", TResultSeverity.Resv_Critical, new System.Guid())); return(false); } // try catch (ESmtpSenderInitializeException e) { AVerification.Add(new TVerificationResult( Catalog.GetString("Sending Email"), e.Message, CommonErrorCodes.ERR_MISSINGEMAILCONFIGURATION, TResultSeverity.Resv_Critical, new System.Guid())); if (e.InnerException != null) { TLogging.Log("Email XML Report: " + e.InnerException); } return(false); } finally { if (EmailSender != null) { EmailSender.Dispose(); } } }