private eLoginEnum LoginInternal(string username, string password, Version AClientVersion, out Int32 AClientID, out string AWelcomeMessage, out Boolean ASystemEnabled, out IPrincipal AUserInfo, out Boolean AMustChangePassword) { AUserInfo = null; ASystemEnabled = true; AWelcomeMessage = string.Empty; AClientID = -1; AMustChangePassword = false; if (DBAccess.GDBAccessObj == null) { TServerManager.TheCastedServerManager.EstablishDBConnection(); } try { TConnectedClient CurrentClient = TClientManager.ConnectClient( username.ToUpper(), password.Trim(), HttpContext.Current.Request.UserHostName, HttpContext.Current.Request.UserHostAddress, AClientVersion, TClientServerConnectionType.csctRemote, out AClientID, out AWelcomeMessage, out ASystemEnabled, out AUserInfo); TSession.SetVariable("LoggedIn", true); // the following values are stored in the session object DomainManager.GClientID = AClientID; DomainManager.CurrentClient = CurrentClient; UserInfo.GUserInfo = (TPetraPrincipal)AUserInfo; DBAccess.GDBAccessObj.UserID = username.ToUpper(); TServerManager.TheCastedServerManager.AddDBConnection(DBAccess.GDBAccessObj); AMustChangePassword = (((TPetraPrincipal)AUserInfo).LoginMessage == SharedConstants.LOGINMUSTCHANGEPASSWORD); return(eLoginEnum.eLoginSucceeded); } catch (Exception e) { TLogging.Log(e.Message); TLogging.Log(e.StackTrace); TSession.SetVariable("LoggedIn", false); if (DBAccess.GDBAccessObj != null) { DBAccess.GDBAccessObj.CloseDBConnection(); } TSession.Clear(); return(TClientManager.LoginErrorFromException(e)); } }
/// <summary> /// check if a file with this security token exists /// </summary> public static bool CheckServerAdminToken(string AServerAdminToken) { string TokenFilename = TAppSettingsManager.GetValue("Server.PathTemp") + Path.DirectorySeparatorChar + "ServerAdminToken" + AServerAdminToken + ".txt"; if (File.Exists(TokenFilename)) { using (StreamReader sr = new StreamReader(TokenFilename)) { string content = sr.ReadToEnd(); sr.Close(); if (content.Trim() == AServerAdminToken) { TSession.SetVariable("ServerAdminToken", AServerAdminToken); return(true); } } } else { TLogging.Log("cannot find security token file " + TokenFilename); } return(false); }
public static bool LoginServerAdmin() { string WelcomeMessage; bool SystemEnabled; Int32 ClientID; Int64 SiteKey; TConnectedClient CurrentClient = TClientManager.ConnectClient( "SYSADMIN", string.Empty, HttpContext.Current.Request.UserHostName, HttpContext.Current.Request.UserHostAddress, TFileVersionInfo.GetApplicationVersion().ToVersion(), TClientServerConnectionType.csctRemote, out ClientID, out WelcomeMessage, out SystemEnabled, out SiteKey); TSession.SetVariable("LoggedIn", true); // the following values are stored in the session object DomainManager.GClientID = ClientID; DomainManager.CurrentClient = CurrentClient; DomainManager.GSiteKey = SiteKey; return(true); }
/// <summary> /// the client can cancel the job /// </summary> /// <param name="AClientID"></param> static public bool CancelJob(string AClientID) { if (TSession.HasVariable(PROGRESSTRACKER + AClientID)) { TProgressState state = ((JObject)TSession.GetVariable(PROGRESSTRACKER + AClientID)).ToObject <TProgressState>(); TLogging.SetStatusBarProcedure(null); if (state.JobFinished == true) { if (TLogging.DebugLevel >= DEBUG_PROGRESS) { TLogging.Log("Cannot cancel the job for " + AClientID + " because the job has already finished"); } } else { state.CancelJob = true; if (TLogging.DebugLevel >= DEBUG_PROGRESS) { TLogging.Log("Cancelled the job for " + AClientID); } TSession.SetVariable(PROGRESSTRACKER + AClientID, state); return(true); } } return(false); }
static private void SetDatabaseForSession(TDataBase database) { if (Thread.CurrentThread.Name == null) { // TLogging.Log("there is a new thread for session " + HttpContext.Current.Session.SessionID); System.Threading.Thread.CurrentThread.Name = "MainThread" + Guid.NewGuid().ToString();; } TSession.SetVariable("DBAccessObj", database); }
/// <summary> /// add or reuse a tracker for the given clientID /// </summary> /// <param name="AClientID"></param> /// <param name="ACaption"></param> /// <param name="AAbsoluteOverallAmount"></param> /// <returns></returns> static public TProgressState InitProgressTracker(string AClientID, string ACaption, decimal AAbsoluteOverallAmount = 100.0m) { TProgressState state = new TProgressState(); state.AbsoluteOverallAmount = AAbsoluteOverallAmount; state.Caption = ACaption; TSession.SetVariable(PROGRESSTRACKER + AClientID, state); return(state); }
private eLoginEnum LoginInternal(string username, string password, Version AClientVersion, out Int32 AClientID, out string AWelcomeMessage, out Boolean ASystemEnabled, out Boolean AMustChangePassword) { ASystemEnabled = true; AWelcomeMessage = string.Empty; AClientID = -1; AMustChangePassword = false; Int64 SiteKey; try { if (username.ToUpper() == "SELFSERVICE") { throw new Exception("Login with user SELFSERVICE is not permitted"); } TConnectedClient CurrentClient = TClientManager.ConnectClient( username.ToUpper(), password.Trim(), HttpContext.Current.Request.UserHostName, HttpContext.Current.Request.UserHostAddress, AClientVersion, TClientServerConnectionType.csctRemote, out AClientID, out AWelcomeMessage, out ASystemEnabled, out SiteKey); TSession.SetVariable("LoggedIn", true); // the following values are stored in the session object DomainManager.GClientID = AClientID; DomainManager.CurrentClient = CurrentClient; DomainManager.GSiteKey = SiteKey; AMustChangePassword = (UserInfo.GetUserInfo().LoginMessage == SharedConstants.LOGINMUSTCHANGEPASSWORD); return(eLoginEnum.eLoginSucceeded); } catch (Exception e) { TLogging.Log(e.Message); TLogging.Log(e.StackTrace); TSession.SetVariable("LoggedIn", false); TSession.CloseSession(); return(TClientManager.LoginErrorFromException(e)); } }
/// <summary> /// add or reuse a tracker for the given clientID /// </summary> /// <param name="AClientID"></param> /// <param name="ACaption"></param> /// <param name="AAbsoluteOverallAmount"></param> /// <returns></returns> static public TProgressState InitProgressTracker(string AClientID, string ACaption, decimal AAbsoluteOverallAmount = 100.0m) { TProgressState state = new TProgressState(); state.AbsoluteOverallAmount = AAbsoluteOverallAmount; state.Caption = ACaption; // First clear all progress trackers. We cannot have too many variables in the session. We only work with one progress tracker per session. TSession.ClearVariables(PROGRESSTRACKER); TSession.SetVariable(PROGRESSTRACKER + AClientID, state); return(state); }
/// <summary> /// set the current state /// </summary> /// <param name="AClientID"></param> /// <param name="AStatusMessage"></param> /// <param name="ACurrentAbsoluteAmount"></param> static public void SetCurrentState(string AClientID, string AStatusMessage, Decimal ACurrentAbsoluteAmount) { if (TSession.HasVariable(PROGRESSTRACKER + AClientID)) { TProgressState state = ((JObject)TSession.GetVariable(PROGRESSTRACKER + AClientID)).ToObject <TProgressState>(); if (AStatusMessage.Length > 0) { state.StatusMessage = AStatusMessage; } state.PercentageDone = Convert.ToInt32((ACurrentAbsoluteAmount / state.AbsoluteOverallAmount) * 100.0m); if (TLogging.DebugLevel >= DEBUG_PROGRESS) { // avoid recursive calls, especially during report calculation Console.WriteLine(state.PercentageDone.ToString() + "%: " + state.StatusMessage); } TSession.SetVariable(PROGRESSTRACKER + AClientID, state); } }
/// <summary> /// the server will set the job to finished /// </summary> static public bool FinishJob(string AClientID) { if (TSession.HasVariable(PROGRESSTRACKER + AClientID)) { TProgressState state = ((JObject)TSession.GetVariable(PROGRESSTRACKER + AClientID)).ToObject <TProgressState>(); state.JobFinished = true; if (TLogging.DebugLevel >= DEBUG_PROGRESS) { TLogging.Log("Finished the job for " + AClientID); } TSession.SetVariable(PROGRESSTRACKER + AClientID, state); TLogging.SetStatusBarProcedure(null); return(true); } return(false); }
public static bool LoginServerAdmin() { // create a new session, with database connection and everything that is needed // see also Ict.Petra.Server.App.WebService.TOpenPetraOrgSessionManager.Login() if (DBAccess.GDBAccessObj == null) { TServerManager.TheCastedServerManager.EstablishDBConnection(); } string WelcomeMessage; bool SystemEnabled; IPrincipal LocalUserInfo; Int32 ClientID; TConnectedClient CurrentClient = TClientManager.ConnectClient( "SYSADMIN", string.Empty, HttpContext.Current.Request.UserHostName, HttpContext.Current.Request.UserHostAddress, TFileVersionInfo.GetApplicationVersion().ToVersion(), TClientServerConnectionType.csctRemote, out ClientID, out WelcomeMessage, out SystemEnabled, out LocalUserInfo); TSession.SetVariable("LoggedIn", true); // the following values are stored in the session object DomainManager.GClientID = ClientID; DomainManager.CurrentClient = CurrentClient; UserInfo.GUserInfo = (TPetraPrincipal)LocalUserInfo; DBAccess.GDBAccessObj.UserID = "SYSADMIN"; TServerManager.TheCastedServerManager.AddDBConnection(DBAccess.GDBAccessObj); return(true); }
/// <summary> /// Find recipient Partner Key and name for all partners who received gifts in the timeframe. /// NOTE - the user can select the PartnerType of the recipient. /// /// With only a little more load on the DB, I can get all the data that the report will need, /// and store it in a DataTable local to this class, so that when more detailed data is requested below, /// I don't need another DB query. /// </summary> /// <returns>RecipientKey, RecipientName</returns> public static DataTable SelectGiftRecipients(TParameterList AParameters, TResultList AResults) { DataTable TotalGiftsPerRecipient = null; Int32 LedgerNum = AParameters.Get("param_ledger_number_i").ToInt32(); Boolean onlySelectedTypes = AParameters.Get("param_type_selection").ToString() == "selected_types"; Boolean onlySelectedFields = AParameters.Get("param_field_selection").ToString() == "selected_fields"; Boolean fromExtract = AParameters.Get("param_recipient").ToString() == "Extract"; Boolean oneRecipient = AParameters.Get("param_recipient").ToString() == "One Recipient"; String period0Start = AParameters.Get("param_from_date_0").ToDate().ToString("yyyy-MM-dd"); String period0End = AParameters.Get("param_to_date_0").ToDate().ToString("yyyy-MM-dd"); String period1Start = AParameters.Get("param_from_date_1").ToDate().ToString("yyyy-MM-dd"); String period1End = AParameters.Get("param_to_date_1").ToDate().ToString("yyyy-MM-dd"); String period2Start = AParameters.Get("param_from_date_2").ToDate().ToString("yyyy-MM-dd"); String period2End = AParameters.Get("param_to_date_2").ToDate().ToString("yyyy-MM-dd"); String period3Start = AParameters.Get("param_from_date_3").ToDate().ToString("yyyy-MM-dd"); String period3End = AParameters.Get("param_to_date_3").ToDate().ToString("yyyy-MM-dd"); String amountFieldName = (AParameters.Get("param_currency").ToString() == "International") ? "detail.a_gift_amount_intl_n" : "detail.a_gift_amount_n"; string SqlQuery = "SELECT DISTINCT " + "gift.p_donor_key_n AS DonorKey, " + "donor.p_partner_short_name_c AS DonorName, donor.p_partner_class_c AS DonorClass, " + "recipient.p_partner_key_n AS RecipientKey, " + "recipient.p_partner_short_name_c AS RecipientName, " + "SUM(CASE WHEN gift.a_date_entered_d BETWEEN '" + period0Start + "' AND '" + period0End + "' " + "THEN " + amountFieldName + " ELSE 0 END )as YearTotal0, " + "SUM(CASE WHEN gift.a_date_entered_d BETWEEN '" + period1Start + "' AND '" + period1End + "' " + "THEN " + amountFieldName + " ELSE 0 END )as YearTotal1, " + "SUM(CASE WHEN gift.a_date_entered_d BETWEEN '" + period2Start + "' AND '" + period2End + "' " + "THEN " + amountFieldName + " ELSE 0 END )as YearTotal2, " + "SUM(CASE WHEN gift.a_date_entered_d BETWEEN '" + period3Start + "' AND '" + period3End + "' " + "THEN " + amountFieldName + " ELSE 0 END )as YearTotal3 " + "FROM PUB_a_gift as gift, PUB_a_gift_detail as detail, PUB_a_gift_batch AS GiftBatch, PUB_p_partner AS donor, PUB_p_partner AS recipient "; if (onlySelectedTypes) { SqlQuery += ", PUB_p_partner_type AS RecipientType "; } if (fromExtract) { String extractName = AParameters.Get("param_extract_name").ToString(); SqlQuery += (", PUB_m_extract AS Extract, PUB_m_extract_master AS ExtractMaster " + "WHERE " + "recipient.p_partner_key_n = Extract.p_partner_key_n " + "AND Extract.m_extract_id_i = ExtractMaster.m_extract_id_i " + "AND ExtractMaster.m_extract_name_c = '" + extractName + "' " + "AND " ); } else { SqlQuery += "WHERE "; } SqlQuery += ("detail.a_ledger_number_i = " + LedgerNum + " " + "AND detail.p_recipient_key_n = recipient.p_partner_key_n " + "AND gift.p_donor_key_n = donor.p_partner_key_n " + "AND detail.a_batch_number_i = gift.a_batch_number_i " + "AND detail.a_gift_transaction_number_i = gift.a_gift_transaction_number_i " + "AND gift.a_date_entered_d BETWEEN '" + period3Start + "' AND '" + period0End + "' " + "AND gift.a_ledger_number_i = " + LedgerNum + " " + "AND GiftBatch.a_batch_status_c = 'Posted' " + "AND GiftBatch.a_batch_number_i = gift.a_batch_number_i " + "AND GiftBatch.a_ledger_number_i = " + LedgerNum + " " ); if (oneRecipient) { String recipientKey = AParameters.Get("param_recipient_key").ToString(); SqlQuery += ("AND recipient.p_partner_key_n = " + recipientKey + " "); } if (onlySelectedFields) { String selectedFieldList = AParameters.Get("param_clbFields").ToString(); selectedFieldList = selectedFieldList.Replace('\'', ' '); SqlQuery += ("AND detail.a_recipient_ledger_number_n IN (" + selectedFieldList + ") "); } if (onlySelectedTypes) { String selectedTypeList = "'" + AParameters.Get("param_clbTypes").ToString() + "'"; selectedTypeList = selectedTypeList.Replace(",", "','"); SqlQuery += ("AND RecipientType.p_partner_key_n = detail.p_recipient_key_n " + "AND RecipientType.p_type_code_c IN (" + selectedTypeList + ") "); } SqlQuery += ( "GROUP by gift.p_donor_key_n, donor.p_partner_short_name_c, donor.p_partner_class_c, recipient.p_partner_key_n, recipient.p_partner_short_name_c " + "ORDER BY recipient.p_partner_short_name_c"); TDBTransaction Transaction = new TDBTransaction(); TDataBase db = DBAccess.Connect("SelectGiftRecipients"); // store the query in the session to be called again in SelectGiftDonors TSession.SetVariable("QueryFinanceReport_SelectGiftRecipients", SqlQuery); db.ReadTransaction( ref Transaction, delegate { TotalGiftsPerRecipient = db.SelectDT(SqlQuery, "result", Transaction); }); // // Ok, I've got a DataTable with ALL THE DATA I need for the report, // but for this calculation I only want a list of partner keys and names... // DataTable resultTable = new DataTable(); resultTable.Columns.Add("RecipientKey", typeof(String)); // These are the names of the variables resultTable.Columns.Add("RecipientName", typeof(String)); // returned by this calculation. Int64 previousPartner = -1; foreach (DataRow Row in TotalGiftsPerRecipient.Rows) { Int64 partnerKey = Convert.ToInt64(Row["RecipientKey"]); if (partnerKey != previousPartner) { previousPartner = partnerKey; DataRow NewRow = resultTable.NewRow(); NewRow["RecipientKey"] = Row["RecipientKey"]; NewRow["RecipientName"] = Row["RecipientName"]; resultTable.Rows.Add(NewRow); } } return(resultTable); } // Select Gift Recipients
static private void SetUserInfoForSession(TPetraPrincipal userinfo) { TSession.SetVariable("UserInfo", userinfo); }
/// <summary> /// This method is called when clients access the Daily Exchange Rate data. /// The Daily Exchange Rate table is unusual in that it doesn't really need to hold any data because the DataSet that the client receives /// contains all the used rates from the GL/Gift tables whether or not those rates are in the DER table itself. Any rates in the DER table /// that are NOT used are also returned, but, of course, because they are not used anywhere they are not very inetresting! /// Additionally, because the GL/Gift tables do not necessarily hold a time or a time that matches the same rate in the DER table, it is possible /// for the DER table to have a rate that is used on the date but at a different time. As a result the client sometimes does not see all rows /// from the DER table - and so has no way of deleting them. /// /// That is the reason why we need to automatically clean the table. /// /// But there is some value in having some 'unused' rows that are work-in-progress. So we delete everything in the DER table that /// applies to dates older than 30 days. In the future this might become a configurable server option. /// </summary> private static void DoDailyExchangeRateClean() { DateTime PreviousDailyExchangeRateAccessTime = DateTime.UtcNow.AddHours(-24); if (TSession.HasVariable("PreviousDailyExchangeRateAccessTime")) { PreviousDailyExchangeRateAccessTime = (DateTime)TSession.GetVariable("PreviousDailyExchangeRateAccessTime"); } DateTime PreviousDailyExchangeRateCleanTime = DateTime.UtcNow.AddDays(-30); if (TSession.HasVariable("PreviousDailyExchangeRateCleanTime")) { PreviousDailyExchangeRateCleanTime = (DateTime)TSession.GetVariable("PreviousDailyExchangeRateCleanTime"); } if ((DateTime.UtcNow - PreviousDailyExchangeRateAccessTime).TotalHours > 8) { // Nobody has opened a DailyExchangeRate screen for 8 hours if ((DateTime.UtcNow - PreviousDailyExchangeRateCleanTime).TotalHours > 24) { // It is more than 24 hours since our last clean TDBTransaction t = new TDBTransaction(); TDataBase db = DBAccess.Connect("DoDailyExchangeRateClean"); bool bSubmissionOk = false; db.WriteTransaction(ref t, ref bSubmissionOk, delegate { string logMsg = String.Empty; int affectedRowCount = 0; // Standard is that we delete rows applicable to dates more than 60 days old string criticalDate = DateTime.Now.AddDays(-60).ToString("yyyy-MM-dd"); try { // Our deletion rule is to delete rows where // either the effective date is too old and we have no info about creation or modification // or the creation date is too old and we have no info about any modification // or the modification date is too old // These rules ensure that if rates are added to a DB that is past its last accounting period (like SA-DB) // we can still continue to use the DER screen to add unused rates because they will have create/modify times // that can be long past the final accounting period because we will keep // any row that has been modified recently, whatever the effective date or creation date // any row that was created recently but not subsequently modified, whatever the effective date // any row where we don't have info about create/modify but where the effective date is recent string sql = String.Format( "DELETE FROM PUB_{0} WHERE (({1}<'{2}') and {3} is NULL and {4} is NULL) or (({3}<'{2}') and {4} is NULL) or ({4}<'{2}')", ADailyExchangeRateTable.GetTableDBName(), ADailyExchangeRateTable.GetDateEffectiveFromDBName(), criticalDate, ADailyExchangeRateTable.GetDateCreatedDBName(), ADailyExchangeRateTable.GetDateModifiedDBName()); affectedRowCount = db.ExecuteNonQuery(sql, t); bSubmissionOk = true; TSession.SetVariable("PreviousDailyExchangeRateCleanTime", DateTime.UtcNow); } catch (Exception ex) { logMsg = "An error occurred while trying to purge the Daily Exchange Rate table of 'aged' rows."; logMsg += String.Format(" The exception message was: {0}", ex.Message); } if ((affectedRowCount > 0) && (logMsg == String.Empty)) { logMsg = String.Format("The Daily Exchange Rate table was purged of {0} entries applicable prior to ", affectedRowCount) + criticalDate; } if (logMsg != String.Empty) { TLogging.Log(logMsg); } }); } } TSession.SetVariable("PreviousDailyExchangeRateAccessTime", DateTime.UtcNow); }
/// <summary>set user information in the session</summary> public static void SetUserInfo(TPetraPrincipal value) { TSession.SetVariable("UserInfo", value); }