Ejemplo n.º 1
0
        public void TestAnnualReceipt()
        {
            CommonNUnitFunctions.ResetDatabase();

            // import a test gift batch
            TVerificationResultCollection VerificationResult;

            if (!ImportAndPostGiftBatch(FLedgerNumber, out VerificationResult))
            {
                Assert.Fail("ImportAndPostGiftBatch failed: " + VerificationResult.BuildVerificationResultString());
            }

            // TODO test reversed gifts

            string formletterTemplateFile = TAppSettingsManager.GetValue("ReceiptTemplate.file",
                                                                         "../../csharp/ICT/Testing/lib/MFinance/SampleData/AnnualReceiptTemplate.html");
            Encoding     encodingOfHTMLfile = TTextFile.GetFileEncoding(formletterTemplateFile);
            StreamReader sr          = new StreamReader(formletterTemplateFile, encodingOfHTMLfile, false);
            string       FileContent = sr.ReadToEnd();

            sr.Close();

            string formletterExpectedFile = TAppSettingsManager.GetValue("ReceiptExptected.file",
                                                                         "../../csharp/ICT/Testing/lib/MFinance/SampleData/AnnualReceiptExpected.html");

            Catalog.Init("de-DE", "de-DE");
            sr = new StreamReader(formletterExpectedFile, encodingOfHTMLfile, false);
            string ExpectedFormletterContent = sr.ReadToEnd().
                                               Replace("#TODAY#", DateTime.Now.ToString("d. MMMM yyyy")).
                                               Replace("#THISYEAR#", DateTime.Today.Year.ToString());

            sr.Close();

            StreamWriter sw = new StreamWriter(formletterExpectedFile + ".updated", false, encodingOfHTMLfile);

            sw.WriteLine(ExpectedFormletterContent);
            sw.Close();

            TLanguageCulture.SetLanguageAndCulture("de-DE", "de-DE");

            //TODO: Calendar vs Financial Date Handling - Check if this should use financial year start/end and not assume calendar
            string receipts =
                TReceiptingWebConnector.CreateAnnualGiftReceipts(FLedgerNumber,
                                                                 new DateTime(DateTime.Today.Year, 1, 1), new DateTime(DateTime.Today.Year, 12, 31), FileContent);

            sw = new StreamWriter(formletterExpectedFile + ".new", false, encodingOfHTMLfile);
            sw.WriteLine(receipts);
            sw.WriteLine();
            sw.Close();

            Assert.IsTrue(
                TTextFile.SameContent(formletterExpectedFile + ".updated", formletterExpectedFile + ".new"),
                "receipt was not printed as expected, check " + formletterExpectedFile + ".new");

            File.Delete(formletterExpectedFile + ".new");
            File.Delete(formletterExpectedFile + ".updated");
        }
        public static bool SetLanguageAndCulture(string ALanguageCode, string ACultureCode)
        {
            TLanguageCulture.SetLanguageAndCulture(ALanguageCode, ACultureCode);

            TUserDefaults.SetDefault(MSysManConstants.USERDEFAULT_UILANGUAGE, ALanguageCode, false);
            TUserDefaults.SetDefault(MSysManConstants.USERDEFAULT_UICULTURE, ACultureCode, false);

            TUserDefaults.SaveUserDefaultsFromServerSide();

            return(true);
        }
        public static bool LoadLanguageAndCultureFromUserDefaults()
        {
            if (TUserDefaults.HasDefault(MSysManConstants.USERDEFAULT_UILANGUAGE))
            {
                string LanguageCode = TUserDefaults.GetStringDefault(MSysManConstants.USERDEFAULT_UILANGUAGE);
                string CultureCode  = TUserDefaults.GetStringDefault(MSysManConstants.USERDEFAULT_UICULTURE);
                TLanguageCulture.SetLanguageAndCulture(LanguageCode, CultureCode);
                return(true);
            }

            return(false);
        }
Ejemplo n.º 4
0
        public void TestSingleReceipt()
        {
            CommonNUnitFunctions.ResetDatabase();

            // import a test gift batch
            TVerificationResultCollection VerificationResult;

            if (!TGiftAnnualReceiptTest.ImportAndPostGiftBatch(FLedgerNumber, out VerificationResult))
            {
                Assert.Fail("ImportAndPostGiftBatch failed: " + VerificationResult.BuildVerificationResultString());
            }

            string formletterTemplateFile = TAppSettingsManager.GetValue("ReceiptTemplate.file",
                                                                         "../../csharp/ICT/Testing/lib/MFinance/SampleData/SingleGiftReceiptTemplate.html");
            Encoding     encodingOfHTMLfile = TTextFile.GetFileEncoding(formletterTemplateFile);
            StreamReader sr          = new StreamReader(formletterTemplateFile, encodingOfHTMLfile, false);
            string       FileContent = sr.ReadToEnd();

            sr.Close();

            string formletterExpectedFile = TAppSettingsManager.GetValue("ReceiptExptected.file",
                                                                         "../../csharp/ICT/Testing/lib/MFinance/SampleData/SingleGiftReceiptExpected.html");

            Catalog.Init("de-DE", "de-DE");

            TLanguageCulture.SetLanguageAndCulture("de-DE", "de-DE");

            string receipts =
                TReceiptingWebConnector.CreateAnnualGiftReceipts(FLedgerNumber,
                                                                 new DateTime(DateTime.Today.Year, 1, 1), new DateTime(DateTime.Today.Year, 12, 31), FileContent);
            StreamWriter sw = new StreamWriter(formletterExpectedFile + ".new", false, encodingOfHTMLfile);

            sw.WriteLine(receipts);
            sw.WriteLine();
            sw.Close();

            SortedList <string, string> ToReplace = new SortedList <string, string>();

            ToReplace.Add("#TODAY#", DateTime.Now.ToString("d. MMMM yyyy"));
            ToReplace.Add("#THISYEAR#", DateTime.Today.Year.ToString());

            Assert.IsTrue(
                TTextFile.SameContent(formletterExpectedFile, formletterExpectedFile + ".new", true, ToReplace, true),
                "receipt was not printed as expected, check " + formletterExpectedFile + ".new");

            File.Delete(formletterExpectedFile + ".new");
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Starts the Petra Server.
        ///
        /// </summary>
        /// <returns>void</returns>
        public void Startup()
        {
            try
            {
                //
                // Uncomment the following lines to see which DLL's are loaded into the Default AppDomain at application start.
                // It can help in identifying which DLL's are loaded later in addition to those that were loaded at application start.

/*
 *          Console.WriteLine("Loaded Assemblies in AppDomain " + Thread.GetDomain().FriendlyName + " (at Server start):");
 *          foreach (Assembly tmpAssembly in Thread.GetDomain().GetAssemblies())
 *          {
 *              Console.WriteLine(tmpAssembly.FullName);
 *          }
 */
                new TAppSettingsManager();

                TLanguageCulture.Init();

                TheServerManager = new TServerManager();

                // Ensure Logging and an 'ordered cooperative shutdown' in case of an Unhandled Exception
                TheServerManager.HookupProperShutdownProcessing();

                Console.WriteLine();
                TLogging.Log(TheServerManager.ServerInfoVersion);
                TLogging.Log(Catalog.GetString("Configuration file: " + TheServerManager.ConfigurationFileName));

                //
                // Connect to main Database
                //
                try
                {
                    TheServerManager.EstablishDBConnection();
                }
                catch (FileNotFoundException ex)
                {
                    TLogging.Log(ex.Message);
                    TLogging.Log("Please check your OpenPetra.build.config file ...");
                    TLogging.Log("Maybe a nant initConfigFile helps ...");
                    throw new EOPAppException();
                }
                catch (Exception ex)
                {
                    TLogging.Log(ex.Message);
                    throw;
                }

                // Setup Server Timed Processing
                try
                {
                    TheServerManager.SetupServerTimedProcessing();
                }
                catch (Exception)
                {
                    throw;
                }

                //
                // Remote the remoteable objects
                //
                try
                {
                    if (TAppSettingsManager.HasValue("LifetimeServices.LeaseTimeInSeconds"))
                    {
                        TLogging.Log(Catalog.GetString("Reading parameters for server remote configuration from config file..."));

                        BinaryServerFormatterSinkProvider TCPSink = new BinaryServerFormatterSinkProvider();
                        TCPSink.TypeFilterLevel = TypeFilterLevel.Low;
                        IServerChannelSinkProvider EncryptionSink = TCPSink;

                        if (TAppSettingsManager.GetValue("Server.ChannelEncryption.PrivateKeyfile", "", false).Length > 0)
                        {
                            EncryptionSink      = new EncryptionServerSinkProvider();
                            EncryptionSink.Next = TCPSink;
                        }

                        Hashtable ChannelProperties = new Hashtable();
                        ChannelProperties.Add("port", TAppSettingsManager.GetValue("Server.Port"));

                        string SpecificIPAddress = TAppSettingsManager.GetValue("ListenOnIPAddress", "", false);

                        if (SpecificIPAddress.Length > 0)
                        {
                            ChannelProperties.Add("machineName", SpecificIPAddress);
                        }

                        TcpChannel Channel = new TcpChannel(ChannelProperties, null, EncryptionSink);
                        ChannelServices.RegisterChannel(Channel, false);

                        RemotingConfiguration.RegisterWellKnownServiceType(typeof(Ict.Petra.Server.App.Core.TServerManager),
                                                                           "Servermanager", WellKnownObjectMode.Singleton);
                        RemotingConfiguration.RegisterWellKnownServiceType(typeof(Ict.Common.Remoting.Server.TClientManager),
                                                                           "Clientmanager", WellKnownObjectMode.Singleton);
                        RemotingConfiguration.RegisterWellKnownServiceType(typeof(TCrossDomainMarshaller),
                                                                           TClientManager.CROSSDOMAINURL, WellKnownObjectMode.Singleton);

                        LifetimeServices.LeaseTime            = TimeSpan.FromSeconds(TAppSettingsManager.GetDouble("LifetimeServices.LeaseTimeInSeconds", 5.0f));
                        LifetimeServices.RenewOnCallTime      = TimeSpan.FromSeconds(TAppSettingsManager.GetDouble("LifetimeServices.RenewOnCallTime", 5.0f));
                        LifetimeServices.LeaseManagerPollTime =
                            TimeSpan.FromSeconds(TAppSettingsManager.GetDouble("LifetimeServices.LeaseManagerPollTime", 1.0f));
                    }
                    else
                    {
                        TLogging.Log(Catalog.GetString("Reading server remote configuration from config file..."));

                        if (TheServerManager.ConfigurationFileName == "")
                        {
                            RemotingConfiguration.Configure(Environment.GetCommandLineArgs()[0] + ".config", false);
                        }
                        else
                        {
                            RemotingConfiguration.Configure(TheServerManager.ConfigurationFileName, false);
                        }

                        RemotingConfiguration.RegisterWellKnownServiceType(typeof(TCrossDomainMarshaller),
                                                                           TClientManager.CROSSDOMAINURL, WellKnownObjectMode.Singleton);
                    }
                }
                catch (RemotingException rex)
                {
                    if (rex.Message.IndexOf("SocketException") > 1)
                    {
                        TLogging.Log("A SocketException has been thrown.");
                        TLogging.Log("Most probably problem is that the address port is used twice!");
                        throw new EOPAppException();
                    }
                    else
                    {
                        throw;
                    }
                }
                catch (Exception)
                {
                    throw;
                }

                Thread.Sleep(50);
                TrackingServices.RegisterTrackingHandler(new TRemotingTracker());

                // Display information that the Server is ready to accept .NET Remoting requests
                TLogging.Log(TheServerManager.ServerInfoState);

                //
                // Server startup done.
                // From now on just listen on .NET Remoting Framework object invocations or on
                // menu commands...
                //

                bool RunWithoutMenu = TAppSettingsManager.GetBoolean("RunWithoutMenu", false);

                if ((!RunWithoutMenu))
                {
                    Console.WriteLine(Environment.NewLine + Catalog.GetString("-> Press \"m\" for menu."));
                    WriteServerPrompt();
                }

                // All exceptions that are raised from various parts of the Server are handled below.
                // Note: The Server stops after handling these exceptions!!!
                if (RunWithoutMenu)
                {
                    RunInBackground();
                }
                else
                {
                    RunMenu();
                }

                // THE VERY END OF THE SERVER :(
            }
            catch (System.Net.Sockets.SocketException exp)
            {
                TLogging.Log(
                    Environment.NewLine + "Unable to start the Server: The IP Port " + TSrvSetting.IPBasePort.ToString() +
                    " is being used by a different instance of the Server or some other application." + Environment.NewLine + exp.ToString());
            }
            catch (System.Runtime.Remoting.RemotingException exp)
            {
                System.Diagnostics.Debug.WriteLine(exp.ToString());
                TLogging.Log(Environment.NewLine + "Exception occured while setting up Remoting Framework:" + Environment.NewLine + exp.ToString());
            }
            catch (EOPAppException)
            {
                // This Exception is used if no more messages shall be done ...
            }
            catch (Exception exp)
            {
                TLogging.Log(Environment.NewLine + "Exception occured:" + Environment.NewLine + exp.ToString());
            }
        }
Ejemplo n.º 6
0
        /// <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);
        }
Ejemplo n.º 7
0
        public static string CreateAnnualGiftReceipts(Int32 ALedgerNumber,
                                                      DateTime AStartDate,
                                                      DateTime AEndDate,
                                                      string AHTMLTemplate,
                                                      bool ADeceasedFirst = false,
                                                      string AExtract     = null,
                                                      Int64 ADonorKey     = 0)
        {
            TLanguageCulture.LoadLanguageAndCulture();

            // get BaseCurrency
            System.Type  typeofTable    = null;
            TCacheable   CachePopulator = new TCacheable();
            ALedgerTable LedgerTable    = (ALedgerTable)CachePopulator.GetCacheableTable(TCacheableFinanceTablesEnum.LedgerDetails,
                                                                                         "",
                                                                                         false,
                                                                                         ALedgerNumber,
                                                                                         out typeofTable);
            string BaseCurrency = LedgerTable[0].BaseCurrency;

            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);

            try
            {
                // get the local country code
                string    LocalCountryCode = TAddressTools.GetCountryCodeFromSiteLedger(Transaction);
                DataTable donorkeys        = new DataTable();
                string    SqlStmt          = "";

                if (ADonorKey != 0)
                {
                    TPartnerClass Class;
                    string        ShortName;
                    TPartnerServerLookups.GetPartnerShortName(ADonorKey, out ShortName, out Class);

                    donorkeys.Columns.Add(new DataColumn("DonorKey"));
                    donorkeys.Columns.Add(new DataColumn("DonorName"));
                    DataRow SingleRow = donorkeys.NewRow();
                    SingleRow[0] = ADonorKey;
                    SingleRow[1] = ShortName;

                    donorkeys.Rows.Add(SingleRow);
                }
                else
                {
                    SortedList <string, string> Defines = new SortedList <string, string>();

                    if (!string.IsNullOrEmpty(AExtract))
                    {
                        Defines.Add("BYEXTRACT", string.Empty);
                    }

                    // first get all donors in the given date range
                    SqlStmt = TDataBase.ReadSqlFile("Gift.ReceiptPrinting.GetDonors.sql", Defines);

                    OdbcParameter[] parameters = new OdbcParameter[4];
                    parameters[0]       = new OdbcParameter("LedgerNumber", OdbcType.Int);
                    parameters[0].Value = ALedgerNumber;
                    parameters[1]       = new OdbcParameter("StartDate", OdbcType.Date);
                    parameters[1].Value = AStartDate;
                    parameters[2]       = new OdbcParameter("EndDate", OdbcType.Date);
                    parameters[2].Value = AEndDate;
                    parameters[3]       = new OdbcParameter("Extract", OdbcType.VarChar);
                    parameters[3].Value = AExtract;

                    donorkeys = DBAccess.GDBAccessObj.SelectDT(SqlStmt, "DonorKeys", Transaction, parameters);

                    // put deceased partner's at the front (still sorted alphabetically)
                    if (ADeceasedFirst)
                    {
                        // create a new datatable with same structure as donorkeys
                        DataTable temp = donorkeys.Clone();
                        temp.Clear();

                        // add deceased donors to the temp table and delete from donorkeys
                        for (int i = 0; i < donorkeys.Rows.Count; i++)
                        {
                            if (SharedTypes.StdPartnerStatusCodeStringToEnum(donorkeys.Rows[i][2].ToString()) == TStdPartnerStatusCode.spscDIED)
                            {
                                temp.Rows.Add((object[])donorkeys.Rows[i].ItemArray.Clone());
                                donorkeys.Rows[i].Delete();
                            }
                        }

                        // add remaining partners to temp table
                        donorkeys.AcceptChanges();
                        temp.Merge(donorkeys);

                        donorkeys = temp;
                    }
                }

                string ResultDocument = "";
                SqlStmt = TDataBase.ReadSqlFile("Gift.ReceiptPrinting.GetDonationsOfDonor.sql");

                foreach (DataRow donorrow in donorkeys.Rows)
                {
                    Int64  donorKey  = Convert.ToInt64(donorrow[0]);
                    string donorName = donorrow[1].ToString();

                    OdbcParameter[] parameters = new OdbcParameter[4];
                    parameters[0]       = new OdbcParameter("LedgerNumber", OdbcType.Int);
                    parameters[0].Value = ALedgerNumber;
                    parameters[1]       = new OdbcParameter("StartDate", OdbcType.Date);
                    parameters[1].Value = AStartDate;
                    parameters[2]       = new OdbcParameter("EndDate", OdbcType.Date);
                    parameters[2].Value = AEndDate;
                    parameters[3]       = new OdbcParameter("DonorKey", OdbcType.BigInt);
                    parameters[3].Value = donorKey;

                    // TODO: should we print each gift detail, or just one row per gift?
                    DataTable donations = DBAccess.GDBAccessObj.SelectDT(SqlStmt, "Donations", Transaction, parameters);

                    if (donations.Rows.Count > 0)
                    {
                        string letter = FormatLetter(donorKey, donorName, donations, BaseCurrency, AHTMLTemplate, LocalCountryCode, Transaction);

                        if (TFormLettersTools.AttachNextPage(ref ResultDocument, letter))
                        {
                            // TODO: store somewhere that the receipt has been printed?
                            // TODO also store each receipt with the donor in document management, and in contact management?
                        }
                    }
                }

                TFormLettersTools.CloseDocument(ref ResultDocument);

                return(ResultDocument);
            }
            finally
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
            }
        }