Exemplo n.º 1
0
        /// <summary>
        /// This is the main routine to import tax data from clipboard or file
        /// </summary>
        private void BtnOK_Click(Object Sender, EventArgs e)
        {
            if (!ValidateInputs())
            {
                return;
            }

            TDlgSelectCSVSeparator dialog = new TDlgSelectCSVSeparator(chkFirstRowIsHeader.Checked);

            if (rbtFromClipboard.Checked)
            {
                dialog.CSVData           = Clipboard.GetText(TextDataFormat.UnicodeText);
                dialog.SelectedSeparator = "\t";
            }
            else
            {
                if (dialog.OpenCsvFile(txtFileName.Text) == false)
                {
                    MessageBox.Show(Catalog.GetString("Could not open the file you have chosen.  Maybe it is already open somewhere else."),
                                    this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }

            // work out what the separator is...
            String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

            string separator = StringHelper.GetCSVSeparator(dialog.FileContent) ??
                               ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";");
            string numberFormat = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;

            // Now we need to convert the multi-column file/clipboard data to a simple two column list
            string twoColumnImport;

            if (ConvertInputTextToTwoColumns(dialog.FileContent, separator, Convert.ToInt16(nudPartnerKeyColumn.Value - 1),
                                             Convert.ToInt16(nudTaxCodeColumn.Value - 1), out twoColumnImport) == false)
            {
                // We got an error
                return;
            }

            dialog.CSVData = twoColumnImport;

            dialog.SelectedSeparator = separator;
            dialog.DateFormat        = "";  // This will make the combo box empty

            // Show the Preview dialog
            DialogResult dialogResult = dialog.ShowDialog();

            // Save the settings whether the result was OK or cancel
            TUserDefaults.SetDefault("Imp Options", dialog.SelectedSeparator + numberFormat);
            TUserDefaults.SaveChangedUserDefaults();

            if (dialogResult != DialogResult.OK)
            {
                // It was cancelled
                return;
            }

            // Set up the inputs for the call to the server to do the actual import
            string importString      = dialog.FileContent;
            string selectedSeparator = dialog.SelectedSeparator;
            int    emptyCodeAction   = rbtFailEmptyTaxCode.Checked ? 0 : rbtSkipEmptyTaxCode.Checked ? 1 : rbtDeleteEmptyTaxCode.Checked ? 2 : -1;

            Hashtable requestParams = new Hashtable();

            requestParams.Add("Delimiter", dialog.SelectedSeparator);
            requestParams.Add("FirstRowIsHeader", chkFirstRowIsHeader.Checked);
            requestParams.Add("FailIfNotPerson", chkFailIfNotPerson.Checked);
            requestParams.Add("FailIfInvalidPartner", chkFailInvalidPartner.Checked);
            requestParams.Add("OverwriteExistingTaxCode", chkOverwriteExistingTaxCode.Checked);
            requestParams.Add("CreateExtract", chkCreateExtract.Checked);
            requestParams.Add("ExtractName", txtExtractName.Text);
            requestParams.Add("ExtractDescription", txtExtractDescription.Text);
            requestParams.Add("CreateOutFile", chkCreateOutFile.Checked);
            requestParams.Add("EmptyTaxCode", emptyCodeAction);
            requestParams.Add("TaxCodeType", FTaxGovIdKeyName);
            // we include partner details if the user does not want a output file because we will write a sneaky one in the logs folder
            requestParams.Add("IncludePartnerDetails",
                              (chkCreateOutFile.Checked && chkIncludePartnerDetails.Checked) || (chkCreateOutFile.Checked == false));

            // Get the server to parse the file and return our results
            bool success = false;
            TVerificationResultCollection errorMessages = null;
            List <string> outputLines          = null;
            bool          newExtractCreated    = false;
            int           newExtractId         = -1;
            int           newExtractKeyCount   = -1;
            int           taxCodesImported     = -1;
            int           taxCodesDeleted      = -1;
            int           taxCodeMismatchCount = -1;

            // Do the import on the server
            Thread ImportThread = new Thread(() => ImportPartnerTaxCodes(
                                                 requestParams, importString, out success, out errorMessages, out outputLines, out newExtractCreated,
                                                 out newExtractId, out newExtractKeyCount, out taxCodesImported, out taxCodesDeleted, out taxCodeMismatchCount));

            // Show the progress dialog so that the user can cancel
            using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
            {
                ImportDialog.ShowDialog();
            }

            if (success)
            {
                // Import was successful
                string msg = Catalog.GetString("The Import was successful.  ");

                msg += string.Format(Catalog.GetPluralString("{0} tax code was imported.  ",
                                                             "{0} tax codes were imported.  ",
                                                             taxCodesImported, true), taxCodesImported);
                msg += string.Format(Catalog.GetPluralString("{0} tax code was deleted.  ",
                                                             "{0} tax codes were deleted.  ",
                                                             taxCodesDeleted, true), taxCodesDeleted);

                if (taxCodeMismatchCount > 0)
                {
                    msg +=
                        string.Format(Catalog.GetPluralString(
                                          "{0} tax code was not imported because it did not match the existing code for the Partner.  ",
                                          "{0} tax codes were not imported because they did not match the existing code for the Partner.  ",
                                          taxCodeMismatchCount, true), taxCodeMismatchCount);
                }

                if (chkCreateOutFile.Checked)
                {
                    //msg += "  ";
                    msg += Catalog.GetString("You can see full details in the output file.");
                }

                if (chkCreateExtract.Checked)
                {
                    msg += Environment.NewLine + Environment.NewLine;

                    if (newExtractCreated)
                    {
                        msg += string.Format(Catalog.GetString("In addition an extract was created containing {0} keys."), newExtractKeyCount);
                    }
                    else
                    {
                        msg += "WARNING! The creation of a new extract failed.  Maybe the name was already in use.";
                    }
                }

                MessageBox.Show(msg, this.Text, MessageBoxButtons.OK);
            }
            else
            {
                // Import failed
                if (TVerificationHelper.ResultsContainErrorCode(errorMessages, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                {
                    TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                    return;
                }
                else if (errorMessages.HasCriticalErrors)
                {
                    // A failed import should contain some critical errors.
                    // Concatenate them and show them in an extended message box with scroll bar
                    string msg = Catalog.GetString("The import failed") + Environment.NewLine + Environment.NewLine;

                    for (int i = 0; i < errorMessages.Count; i++)
                    {
                        msg += string.Format("[{0}] - {1}", errorMessages[i].ResultContext, errorMessages[i].ResultText);
                        msg += Environment.NewLine;
                    }

                    msg += Catalog.GetString("No data was imported into the database.");

                    TFrmExtendedMessageBox msgBox = new TFrmExtendedMessageBox(this);
                    msgBox.ShowDialog(msg, this.Text, "", TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiInformation);
                }
                else
                {
                    // Should not end up wit a failed import and no error messages
                    MessageBox.Show("Import failed", this.Text, MessageBoxButtons.OK);
                }
            }

            string pathToOutFile = null;

            if (chkCreateOutFile.Checked)
            {
                pathToOutFile = txtOutputFileName.Text;
            }
            else
            {
                // we try and write a log file anyway in the log folder
                string logPath = TAppSettingsManager.GetValue("OpenPetra.PathLog", "");

                if (logPath.Length > 0)
                {
                    pathToOutFile = logPath + Path.DirectorySeparatorChar + "ImportPartnerTaxCodes.log";
                }
            }

            if (pathToOutFile != null)
            {
                // Write the output file
                using (StreamWriter sw = new StreamWriter(pathToOutFile))
                {
                    for (int i = 0; i < outputLines.Count; i++)
                    {
                        sw.WriteLine(outputLines[i]);
                    }

                    sw.Close();
                }
            }

            if (chkCreateExtract.Checked)
            {
                // Tell the client about the new extract
                // refresh extract master screen if it is open
                TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcExtractCreated);

                BroadcastMessage.SetMessageDataName(txtExtractName.Text);
                TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);
            }

            // Save the GUI settings
            SaveGUISettings();
        }
        /// <summary>
        /// Saves any changed preferences to s_user_defaults
        /// </summary>
        /// <returns>void</returns>
        public DialogResult SaveGeneralTab()
        {
            // First, we need to show any dialogs that may result in Cancel
            if (chkSaveWindowProperties.Checked && !WasSaveWindowPropertiesInitiallyChecked)
            {
                // The user wants to start saving the window positions etc.
                // If we have some information about this that we stored previously, we can offer to use it again...
                string localAppDataPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    CommonFormsResourcestrings.StrFolderOrganisationName,
                    System.Diagnostics.FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductName);
                string settingsFileName = String.Format(CommonFormsResourcestrings.StrScreenPositionsFileName, UserInfo.GUserInfo.UserID);
                string settingsPath     = Path.Combine(localAppDataPath, settingsFileName);

                if (File.Exists(settingsPath))
                {
                    string msg = String.Format("{0}{1}{2}{3}{4}",
                                               CommonFormsResourcestrings.StrReuseScreenPositionsMessage1,
                                               CommonFormsResourcestrings.StrReuseScreenPositionsMessage2,
                                               Environment.NewLine,
                                               Environment.NewLine,
                                               CommonFormsResourcestrings.StrReuseScreenPositionsMessage3);
                    DialogResult result = MessageBox.Show(msg,
                                                          CommonFormsResourcestrings.StrReuseScreenPositionsTitle,
                                                          MessageBoxButtons.YesNoCancel,
                                                          MessageBoxIcon.Question);

                    if (result == DialogResult.Cancel)
                    {
                        return(result);
                    }

                    if (result == DialogResult.No)
                    {
                        try
                        {
                            // Delete the old file
                            File.Delete(settingsPath);
                        }
                        catch (Exception ex)
                        {
                            TLogging.Log(String.Format("Exception occurred while deleting the window position file '{0}': {1}",
                                                       settingsPath,
                                                       ex.Message), TLoggingType.ToLogfile);
                        }
                    }

                    if (result == DialogResult.Yes)
                    {
                        // Load the information we have already
                        PetraUtilsObject.LoadWindowPositionsFromFile();
                    }
                }
            }

            if (LanguageChanged)
            {
                string LanguageCode = cmbLanguage.GetSelectedString();
                string CultureCode  = cmbCulture.GetSelectedString();

                // send to server
                TRemote.MSysMan.Maintenance.WebConnectors.SetLanguageAndCulture(LanguageCode, CultureCode);

                // set local settings for client
                Catalog.Init(LanguageCode, CultureCode);

                // TODO: can we reload the main window with the new language?
                MessageBox.Show(Catalog.GetString("Please restart the OpenPetra client to see the new language"),
                                Catalog.GetString("Restart the client"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }

            TUserDefaults.SetDefault(MSysManConstants.USERDEFAULT_NUMBEROFRECENTPARTNERS, nudNumberOfPartners.Value);
            TUserDefaults.SetDefault(TUserDefaults.NamedDefaults.USERDEFAULT_ESC_CLOSES_SCREEN, chkEscClosesScreen.Checked);
            TUserDefaults.SetDefault(TUserDefaults.NamedDefaults.USERDEFAULT_SAVE_WINDOW_POS_AND_SIZE, chkSaveWindowProperties.Checked);

            return(DialogResult.OK);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Called by TFrmPetraUtils during the TFrmPetra_Closing event
        /// </summary>
        public void TForm_Closing()
        {
            // Deal with the window positions which are stored on the local file system
            string localAppDataPath = Path.Combine(
                TAppSettingsManager.GetLocalAppDataPath(),
                CommonFormsResourcestrings.StrFolderOrganisationName,
                System.Diagnostics.FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductName);
            string settingsFileName = String.Format(CommonFormsResourcestrings.StrScreenPositionsFileName, UserInfo.GUserInfo.UserID);
            string settingsPath     = Path.Combine(localAppDataPath, settingsFileName);

            if (TUserDefaults.GetBooleanDefault(TUserDefaults.NamedDefaults.USERDEFAULT_SAVE_WINDOW_POS_AND_SIZE, true))
            {
                // This is where we 'remember' the window position information
                if (FWinForm.Name == "TFrmMainWindowNew")
                {
                    // we are closing the main window
                    // Get our own window position properties
                    GetWindowPositionProperties();

                    // Now save all the properties for all windows we know about
                    try
                    {
                        if (!Directory.Exists(localAppDataPath))
                        {
                            Directory.CreateDirectory(localAppDataPath);
                        }

                        using (StreamWriter sw = new StreamWriter(settingsPath))
                        {
                            foreach (string key in FWindowPositions.Keys)
                            {
                                sw.WriteLine("{0}={1}", key, FWindowPositions[key]);
                            }

                            sw.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        TLogging.Log(String.Format("Exception occurred while saving the window position file '{0}': {1}", settingsPath,
                                                   ex.Message), TLoggingType.ToLogfile);
                    }
                }
                else if (FAlwaysSaveFormsList.Contains(FWinForm.Name))
                {
                    // We always save the settings for these forms - they can be launched from the main window or from Partner/Find or several other ways
                    GetWindowPositionProperties();
                }
                else if ((FCallerForm != null) && (FCallerForm.Name == "TFrmMainWindowNew") && !FWinForm.Modal)
                {
                    // we were opened by the main window
                    GetWindowPositionProperties();
                }
            }
            else
            {
                // We are closing a screen and not saving window positions (or no longer saving them)
                FWindowPositions.Clear();
                FWindowPositionsLoaded = false;
            }
        }
Exemplo n.º 4
0
        // Button 'Login' pressed
        private void BtnLoginClick(System.Object sender, System.EventArgs e)
        {
            FConnectionEstablished = false;

            // Get the selected User Name and Password
            FSelUserName = this.txtUserName.Text.ToUpper();
            FSelPassWord = (this.txtPassword.Text);

            if ((FSelUserName.Length == 0) || (FSelPassWord.Length == 0))
            {
                MessageBox.Show(Catalog.GetString("Please enter a User ID and a Password to log in into OpenPetra."),
                                StrPetraLoginFormTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                SetFocusToCredentials();

                return;
            }

            // don't waste a try for authentication if the CapsLock is on; otherwise the user is retired quite quickly
            if (Control.IsKeyLocked(Keys.CapsLock))
            {
                MessageBox.Show(Catalog.GetString("The Caps Lock key is ON. Please switch it off and try to login again"),
                                StrPetraLoginFormTitle);

                SetFocusToCredentials();

                return;
            }

            /* Now authenticate User against the Petra Server.
             *
             * Note: Authenticate has to establish a connection to the Petra Server first
             */
            String ConnectionError;

            this.Cursor = Cursors.WaitCursor;

            StoreUserName(FSelUserName);

            UpdateUI(true);

            if (ConnectToPetraServer(FSelUserName, FSelPassWord, out ConnectionError))
            {
                prbLogin.Value = 90;
                bool MustChangePassword = false;

                // Show any message that is returned after successful login (eg. 'Petra is currently disabled due to xxx. Proceed with caution.')
                if (UserInfo.GUserInfo.LoginMessage != null)
                {
                    // If the user is required to change their password before using OpenPetra.
                    // (This LoginMessage is set in Ict.Petra.Server.MSysMan.Security.UserManager.WebConnectors.TUserManagerWebConnector)
                    MustChangePassword = (UserInfo.GUserInfo.LoginMessage == Catalog.GetString("You need to change your password immediately."));

                    if (!MustChangePassword)
                    {
                        MessageBox.Show(UserInfo.GUserInfo.LoginMessage,
                                        StrPetraLoginFormTitle,
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }

                TUserDefaults.InitUserDefaults();
                prbLogin.Value          = 100;
                FConnectionEstablished  = true;
                this.Cursor             = Cursors.Default;
                TLogging.UserNamePrefix = UserInfo.GUserInfo.UserID + '_' +
                                          TConnectionManagement.GConnectionManagement.ClientID.ToString();

                UpdateUI(false);

                if (MustChangePassword)
                {
                    if (!CreateNewPassword(this, FSelUserName, FSelPassWord, true))
                    {
                        // do nothing if password has not been successfully changed
                        return;
                    }
                }

                DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
            else
            {
                this.Cursor = Cursors.Default;

                UpdateUI(false);

                // TODORemoting do not show the error code???
                if ((ConnectionError.Length > 0) && (ConnectionError.IndexOf(" ") != -1))
                {
                    // this message box shows if the password is wrong
                    // otherwise there has already been a message box usually
                    MessageBox.Show(ConnectionError, StrPetraLoginFormTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop);

                    SetFocusToCredentials();
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Create new partner, family, location and PartnerLocation records in MainDS
        /// </summary>
        private static Int64 CreateNewFamily(XmlNode ANode, out int ALocationKey, ref PartnerImportExportTDS AMainDS,
                                             TDBTransaction ATransaction)
        {
            PPartnerRow newPartner = AMainDS.PPartner.NewRowTyped();

            AMainDS.PPartner.Rows.Add(newPartner);

            newPartner.PartnerKey   = (AMainDS.PPartner.Rows.Count + 1) * -1;
            newPartner.PartnerClass = MPartnerConstants.PARTNERCLASS_FAMILY;
            newPartner.StatusCode   = MPartnerConstants.PARTNERSTATUS_ACTIVE;
            newPartner.Comment      = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_NOTESFAMILY);

            String AcquisitionCode = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_AQUISITION);

            newPartner.AcquisitionCode = (AcquisitionCode.Length > 0) ? AcquisitionCode : MPartnerConstants.PARTNERIMPORT_AQUISITION_DEFAULT;

            newPartner.AddresseeTypeCode = MPartnerConstants.ADDRESSEETYPE_DEFAULT;

            if (TXMLParser.HasAttribute(ANode, MPartnerConstants.PARTNERIMPORT_ADDRESSEE_TYPE))
            {
                newPartner.AddresseeTypeCode = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_ADDRESSEE_TYPE);
            }
            else
            {
                string gender = GetGenderCode(ANode);

                if (gender == MPartnerConstants.GENDER_MALE)
                {
                    newPartner.AddresseeTypeCode = MPartnerConstants.ADDRESSEETYPE_MALE;
                }
                else if (gender == MPartnerConstants.GENDER_FEMALE)
                {
                    newPartner.AddresseeTypeCode = MPartnerConstants.ADDRESSEETYPE_FEMALE;
                }
            }

            if (TXMLParser.HasAttribute(ANode, MPartnerConstants.PARTNERIMPORT_LANGUAGE))
            {
                newPartner.LanguageCode = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_LANGUAGE);
            }
            else if (TUserDefaults.HasDefault(MSysManConstants.PARTNER_LANGUAGECODE))
            {
                newPartner.LanguageCode = TUserDefaults.GetStringDefault(MSysManConstants.PARTNER_LANGUAGECODE);
            }

            string[] giftReceiptingDefaults = TSystemDefaults.GetSystemDefault("GiftReceiptingDefaults", ",no").Split(new char[] { ',' });
            newPartner.ReceiptLetterFrequency = giftReceiptingDefaults[0];
            newPartner.ReceiptEachGift        = giftReceiptingDefaults[1] == "YES" || giftReceiptingDefaults[1] == "TRUE";


            PFamilyRow newFamily = AMainDS.PFamily.NewRowTyped();

            AMainDS.PFamily.Rows.Add(newFamily);

            newFamily.PartnerKey    = newPartner.PartnerKey;
            newFamily.FirstName     = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_FIRSTNAME);
            newFamily.FamilyName    = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_FAMILYNAME);
            newFamily.MaritalStatus = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_MARITALSTATUS);
            newFamily.Title         = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_TITLE);
            newFamily.MaritalStatus = GetMaritalStatusCode(ANode);

            newPartner.PartnerShortName = Calculations.DeterminePartnerShortName(newFamily.FamilyName, newFamily.Title, newFamily.FirstName);
            PLocationRow newLocation = AMainDS.PLocation.NewRowTyped(true);

            AMainDS.PLocation.Rows.Add(newLocation);
            newLocation.LocationKey = TPartnerImportCSV.FLocationKey;
            newLocation.Locality    = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_LOCALITY);
            newLocation.StreetName  = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_STREETNAME);
            newLocation.Address3    = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_ADDRESS);
            newLocation.PostalCode  = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_POSTALCODE);
            newLocation.City        = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_CITY);
            newLocation.County      = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_COUNTY);
            newLocation.CountryCode = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_COUNTRYCODE);

            PPartnerLocationRow partnerlocation = AMainDS.PPartnerLocation.NewRowTyped(true);

            TPartnerContactDetails_LocationConversionHelper.AddOldDBTableColumnsToPartnerLocation(AMainDS.PPartnerLocation);

            partnerlocation.LocationKey   = TPartnerImportCSV.FLocationKey;
            partnerlocation.SiteKey       = 0;
            partnerlocation.PartnerKey    = newPartner.PartnerKey;
            partnerlocation.DateEffective = DateTime.Now.Date;
            partnerlocation.LocationType  = MPartnerConstants.LOCATIONTYPE_HOME;
            partnerlocation.SendMail      = true;

            partnerlocation["p_email_address_c"] =
                TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_EMAIL);        // Important: Do not use 'partnerlocation.EmailAddress' as this Column will get removed once Contact Details conversion is finished!
            partnerlocation["p_telephone_number_c"] =
                TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_PHONE);        // Important: Do not use 'partnerlocation.TelephoneNumber' as this Column will get removed once Contact Details conversion is finished!
            partnerlocation["p_mobile_number_c"] =
                TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_MOBILEPHONE);  // Important: Do not use 'partnerlocation.MobileNumber' as this Column will get removed once Contact Details conversion is finished!

            AMainDS.PPartnerLocation.Rows.Add(partnerlocation);

            ALocationKey = TPartnerImportCSV.FLocationKey;
            TPartnerImportCSV.FLocationKey--;

            return(newPartner.PartnerKey);
        }
        /// <summary>
        /// Imports budgets from a file
        /// </summary>
        /// <param name="ACurrentBudgetYear"></param>
        /// <param name="AMainDS"></param>
        public void ImportBudget(int ACurrentBudgetYear, ref BudgetTDS AMainDS)
        {
            TVerificationResultCollection Messages = new TVerificationResultCollection();

            int BudgetsImported = 0;
            int BudgetsAdded    = 0;
            int BudgetsUpdated  = 0;
            int BudgetsFailed   = 0;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to post
                MessageBox.Show(Catalog.GetString("Please save before trying to import!"), Catalog.GetString(
                                    "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            String         DateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
            OpenFileDialog OFDialog         = new OpenFileDialog();

            string ExportPath = TClientSettings.GetExportPath();
            string FullPath   = TUserDefaults.GetStringDefault("Imp Filename",
                                                               ExportPath + Path.DirectorySeparatorChar + "import.csv");

            TImportExportDialogs.SetOpenFileDialogFilePathAndName(OFDialog, FullPath, ExportPath);

            OFDialog.Title  = Catalog.GetString("Import budget(s) from CSV file");
            OFDialog.Filter = Catalog.GetString("Text Files(*.txt) | *.txt | Delimited Files(*.csv) | *.csv");
            String ImportOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

            // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
            TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(FullPath));

            if (OFDialog.ShowDialog() == DialogResult.OK)
            {
                TFrmStatusDialog dlgStatus = new TFrmStatusDialog(FPetraUtilsObject.GetForm());

                FdlgSeparator = new TDlgSelectCSVSeparator(false);

                try
                {
                    string  fileTitle   = OFDialog.SafeFileName;
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(OFDialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                                        Catalog.GetString("Budget Import"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Stop);
                        return;
                    }

                    FdlgSeparator.DateFormat = DateFormatString;

                    if (ImportOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = ImportOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = ImportOptions.Substring(0, 1);

                    if (FdlgSeparator.ShowDialog() == DialogResult.OK)
                    {
                        string[] FdlgSeparatorVal = new string[] {
                            FdlgSeparator.SelectedSeparator, FdlgSeparator.DateFormat, FdlgSeparator.NumberFormat
                        };

                        Application.UseWaitCursor = true;

                        //New set of budgets to be loaded
                        dlgStatus.Show();
                        dlgStatus.Heading       = Catalog.GetString("Budget Import");
                        dlgStatus.CurrentStatus = Catalog.GetString("Importing budgets from '" + fileTitle + "' ...");

                        // read contents of file
                        string ImportString = File.ReadAllText(OFDialog.FileName);

                        //TODO return the budget from the year, and -99 for fail
                        BudgetsImported = TRemote.MFinance.Budget.WebConnectors.ImportBudgets(FLedgerNumber,
                                                                                              ImportString,
                                                                                              OFDialog.FileName,
                                                                                              FdlgSeparatorVal,
                                                                                              ref AMainDS,
                                                                                              out BudgetsAdded,
                                                                                              out BudgetsUpdated,
                                                                                              out BudgetsFailed,
                                                                                              out Messages);

                        dlgStatus.Visible = false;

                        Application.UseWaitCursor = false;
                        ShowMessages(Messages, BudgetsImported, BudgetsAdded, BudgetsUpdated, BudgetsFailed);
                    }

                    // We save the defaults even if ok is false - because the client will probably want to try and import
                    //   the same file again after correcting any errors
                    SaveUserDefaults(OFDialog, ImportOptions);
                }
                catch (Exception ex)
                {
                    TLogging.LogException(ex, Utilities.GetMethodSignature());
                    throw;
                }
                finally
                {
                    Application.UseWaitCursor = false;
                }

                // update grid
                if ((BudgetsAdded + BudgetsUpdated) > 0)
                {
                    try
                    {
                        dlgStatus.CurrentStatus = Catalog.GetString("Updating budget period data...");
                        dlgStatus.Visible       = true;

                        Application.UseWaitCursor = true;
                        UpdateABudgetPeriodAmounts(AMainDS, ACurrentBudgetYear);
                        FUserControl.SetBudgetDefaultView(AMainDS);
                    }
                    finally
                    {
                        Application.UseWaitCursor = false;
                        dlgStatus.Close();
                    }

                    FPetraUtilsObject.SetChangedFlag();
                }
                else
                {
                    dlgStatus.Close();
                }
            }
        }
        private static void AddNavigationForEachLedger(XmlNode AMenuNode, ALedgerTable AAvailableLedgers, bool ADontUseDefaultLedger)
        {
            XmlNode      childNode = AMenuNode.FirstChild;
            int          PotentialCurrentLedger;
            ALedgerRow   ProcessedLedger;
            XmlAttribute enabledAttribute;
            bool         LedgersAvailableToUserCreatedInThisIteration = false;

            //Iterate through all children nodes of the node
            while (childNode != null)
            {
                if (TXMLParser.GetAttribute(childNode, "DependsOnLedger").ToLower() == "true")
                {
                    // If there is more than one Ledger in the system, show a 'Select Ledger' Collapsible Panel with a Task (=LinkLabel)
                    // for each Ledger.
                    if (AAvailableLedgers.Rows.Count > 1)
                    {
                        LedgersAvailableToUserCreatedInThisIteration = false;
                        AAvailableLedgers.DefaultView.Sort           = ALedgerTable.GetLedgerNumberDBName() + " ASC";

                        FMultiLedgerSite = true;

                        // Create 'Select Ledger' Node
                        XmlAttribute LabelAttributeLedger = childNode.OwnerDocument.CreateAttribute("Label");
                        XmlElement   SelLedgerElmnt       = childNode.OwnerDocument.CreateElement("SelectLedger");
                        XmlNode      SelectLedgerNode     = childNode.AppendChild(SelLedgerElmnt);
                        SelectLedgerNode.Attributes.Append(LabelAttributeLedger);
                        SelectLedgerNode.Attributes["Label"].Value = Catalog.GetString("Select Ledger");

                        // Create 1..n 'Ledger xyz' Nodes
                        foreach (DataRowView Drv in AAvailableLedgers.DefaultView)
                        {
                            ProcessedLedger = (ALedgerRow)Drv.Row;

                            XmlElement   SpecificLedgerElmnt          = childNode.OwnerDocument.CreateElement("Ledger" + ProcessedLedger.LedgerNumber);
                            XmlNode      SpecificLedgerNode           = SelectLedgerNode.AppendChild(SpecificLedgerElmnt);
                            XmlAttribute LabelAttributeSpecificLedger = childNode.OwnerDocument.CreateAttribute("Label");
                            SpecificLedgerNode.Attributes.Append(LabelAttributeSpecificLedger);
                            XmlAttribute ledgerNumberAttribute = childNode.OwnerDocument.CreateAttribute("LedgerNumber");
                            ledgerNumberAttribute.Value = ProcessedLedger.LedgerNumber.ToString();
                            SpecificLedgerNode.Attributes.Append(ledgerNumberAttribute);
                            XmlAttribute ledgerNameAttribute = childNode.OwnerDocument.CreateAttribute("LedgerName");
                            ledgerNameAttribute.Value = ProcessedLedger.LedgerName;
                            SpecificLedgerNode.Attributes.Append(ledgerNameAttribute);

                            if (ProcessedLedger.LedgerName != String.Empty)
                            {
                                SpecificLedgerNode.Attributes["Label"].Value = String.Format(Catalog.GetString(
                                                                                                 "Ledger {0} (#{1})"), ProcessedLedger.LedgerName, ProcessedLedger.LedgerNumber);
                            }
                            else
                            {
                                SpecificLedgerNode.Attributes["Label"].Value = String.Format(Catalog.GetString(
                                                                                                 "Ledger #{0}"), ProcessedLedger.LedgerNumber);
                            }

                            // Check access permission for Ledger
                            if (!HasAccessPermission(SpecificLedgerNode, UserInfo.GUserInfo.UserID, true))
                            {
                                enabledAttribute       = childNode.OwnerDocument.CreateAttribute("Enabled");
                                enabledAttribute.Value = "false";
                                SpecificLedgerNode.Attributes.Append(enabledAttribute);
                            }
                            else
                            {
                                if (FLedgersAvailableToUser == null)
                                {
                                    // (Re-)Calculate which Ledgers the user has access to
                                    FLedgersAvailableToUser = new List <string>();
                                    LedgersAvailableToUserCreatedInThisIteration = true;
                                }

                                if (LedgersAvailableToUserCreatedInThisIteration)
                                {
                                    // Add Ledger to the List of Ledgers that are available to the user
                                    if (!FLedgersAvailableToUser.Contains(FormatLedgerNumberForModuleAccess(ProcessedLedger.LedgerNumber)))
                                    {
                                        FLedgersAvailableToUser.Add(FormatLedgerNumberForModuleAccess(ProcessedLedger.LedgerNumber));
                                    }
                                }
                            }
                        }

                        if ((LedgersAvailableToUserCreatedInThisIteration) ||
                            (FLedgersAvailableToUser == null))
                        {
                            if (!ADontUseDefaultLedger)
                            {
                                // Set the 'Current Ledger' to the users' Default Ledger, or if he/she hasn't got one, to the first Ledger of the Site.
                                PotentialCurrentLedger = TUserDefaults.GetInt32Default(TUserDefaults.FINANCE_DEFAULT_LEDGERNUMBER,
                                                                                       ((ALedgerRow)AAvailableLedgers.DefaultView[0].Row).LedgerNumber);

                                if ((FLedgersAvailableToUser != null) &&
                                    (FLedgersAvailableToUser.Contains(FormatLedgerNumberForModuleAccess(PotentialCurrentLedger))))
                                {
                                    FCurrentLedger = PotentialCurrentLedger;
                                }
                                else
                                {
                                    if (FLedgersAvailableToUser != null)
                                    {
                                        FCurrentLedger = Convert.ToInt32(FLedgersAvailableToUser[0].Substring(6)); // Skip "LEDGER"
                                    }
                                    else                                                                           // = no Ledgers available to the user at all!
                                    {
                                        FCurrentLedger = TLstFolderNavigation.LEDGERNUMBER_NO_ACCESS_TO_ANY_LEDGER;
                                    }
                                }
                            }
                        }
                    }
                    else if (AAvailableLedgers.Rows.Count == 1)
                    {
                        // Dynamically add Attribute 'SkipThisLevel' to the next child, which would be the child for the Collapsible Panel,
                        // which we don't need/want for a 'Single Ledger' Site!
                        XmlAttribute LabelSkipCollapsibleLevel = childNode.OwnerDocument.CreateAttribute("SkipThisLevel");
                        childNode.ChildNodes[0].Attributes.Append(LabelSkipCollapsibleLevel);
                        childNode.ChildNodes[0].Attributes["SkipThisLevel"].Value = "true";

                        // Check access permission for Ledger
                        if (UserInfo.GUserInfo.IsInModule(FormatLedgerNumberForModuleAccess(AAvailableLedgers[0].LedgerNumber)))
                        {
                            // Set the 'Current Ledger' to the only Ledger of the Site.
                            FCurrentLedger = AAvailableLedgers[0].LedgerNumber;
                        }
                        else   // = no Ledgers available to the user at all!
                        {
                            FCurrentLedger = TLstFolderNavigation.LEDGERNUMBER_NO_ACCESS_TO_ANY_LEDGER;
                        }
                    }
                    else   // = no Ledgers available to the user at all!
                    {
                        FCurrentLedger = TLstFolderNavigation.LEDGERNUMBER_NO_ACCESS_TO_ANY_LEDGER;
                    }

                    childNode = childNode.NextSibling;
                }
                else
                {
                    // Recurse into deeper levels!
                    AddNavigationForEachLedger(childNode, AAvailableLedgers, ADontUseDefaultLedger);

                    childNode = childNode.NextSibling;
                }
            }
        }
        /// <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>
        public void ImportBatches(TGiftImportDataSourceEnum AImportSource)
        {
            bool           ok = false;
            String         importString;
            String         impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to post
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                                    "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportSource == TGiftImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                                    Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData           = importString;
                FdlgSeparator.DateFormat        = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportSource == TGiftImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                string exportPath = TClientSettings.GetExportPath();
                string fullPath   = TUserDefaults.GetStringDefault("Imp Filename",
                                                                   exportPath + Path.DirectorySeparatorChar + "import.csv");
                TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath);

                dialog.Title  = Catalog.GetString("Import Batches from CSV File");
                dialog.Filter = Catalog.GetString("Text Files(*.txt) | *.txt | Gift Batch Files(*.csv) | *.csv");
                impOptions    = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
                TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath));

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                                        Catalog.GetString("Gift Import"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Stop);
                        return;
                    }

                    importString = File.ReadAllText(dialog.FileName, Encoding.Default);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions   = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);

                bool Repeat = true;

                while (Repeat)
                {
                    Repeat = false;

                    TVerificationResultCollection AMessages = new TVerificationResultCollection();
                    GiftBatchTDSAGiftDetailTable  NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable();

                    Thread ImportThread = new Thread(() => ImportGiftBatches(
                                                         requestParams,
                                                         importString,
                                                         out AMessages,
                                                         out ok,
                                                         out NeedRecipientLedgerNumber));

                    using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                    {
                        ImportDialog.ShowDialog();
                    }

                    // If NeedRecipientLedgerNumber contains data then AMessages will only ever contain
                    // one message alerting the user that no data has been imported.
                    // We do not want to show this as we will be displaying another more detailed message.
                    if (NeedRecipientLedgerNumber.Rows.Count == 0)
                    {
                        ShowMessages(AMessages);
                    }

                    // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination
                    // then the import will have failed and we need to alert the user
                    if (NeedRecipientLedgerNumber.Rows.Count > 0)
                    {
                        bool OfferToRunImportAgain            = true;
                        bool DoNotShowMessageBoxEverytime     = false;
                        TFrmExtendedMessageBox.TResult Result = TFrmExtendedMessageBox.TResult.embrUndefined;
                        int count = 1;

                        // for each gift in which the recipient needs a Git Destination
                        foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows)
                        {
                            if (!DoNotShowMessageBoxEverytime)
                            {
                                string CheckboxText = string.Empty;

                                // only show checkbox if there is at least one more occurance of this error
                                if (NeedRecipientLedgerNumber.Rows.Count - count > 0)
                                {
                                    CheckboxText = string.Format(
                                        Catalog.GetString("Do this for all further occurances ({0})?"), NeedRecipientLedgerNumber.Rows.Count - count);
                                }

                                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FPetraUtilsObject.GetForm());

                                extendedMessageBox.ShowDialog(string.Format(
                                                                  Catalog.GetString(
                                                                      "Gift Import has been cancelled as the recipient '{0}' ({1}) has no Gift Destination assigned."),
                                                                  Row.RecipientDescription, Row.RecipientKey) +
                                                              "\n\r\n\r\n\r" +
                                                              Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"),
                                                              Catalog.GetString("Import Errors"),
                                                              CheckboxText,
                                                              TFrmExtendedMessageBox.TButtons.embbYesNo, TFrmExtendedMessageBox.TIcon.embiWarning);
                                Result = extendedMessageBox.GetResult(out DoNotShowMessageBoxEverytime);
                            }

                            if (Result == TFrmExtendedMessageBox.TResult.embrYes)
                            {
                                // allow the user to assign a Gift Destingation
                                TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey);
                                GiftDestinationForm.ShowDialog();
                            }
                            else
                            {
                                OfferToRunImportAgain = false;

                                if (DoNotShowMessageBoxEverytime)
                                {
                                    break;
                                }
                            }

                            count++;
                        }

                        // if the user has clicked yes to assigning Gift Destinations then offer to restart the import
                        if (OfferToRunImportAgain &&
                            (MessageBox.Show(Catalog.GetString("Would you like to import this Gift Batch again?"),
                                             Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                             MessageBoxDefaultButton.Button2)
                             == DialogResult.Yes))
                        {
                            Repeat = true;
                        }
                    }
                }

                // We save the defaults even if ok is false - because the client will probably want to try and import
                //   the same file again after correcting any errors
                SaveUserDefaults(dialog, impOptions);
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                                Catalog.GetString("Gift Import"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);

                FMyUserControl.LoadBatchesForCurrentYear();
                FPetraUtilsObject.DisableSaveButton();
            }
        }
        }  // Load Hosa Report Data

        private Boolean LoadStewardshipReportData(TRptCalculator ACalc)
        {
            Dictionary <String, TVariant> paramsDictionary = InitialiseDictionary(ACalc);
            DataTable ReportTable = TRemote.MReporting.WebConnectors.GetReportDataTable("Stewardship", paramsDictionary);

            if (this.IsDisposed)
            {
                return(false);
            }

            if (ReportTable == null)
            {
                FPetraUtilsObject.WriteToStatusBar("Report Cancelled.");
                return(false);
            }

            MyFastReportsPlugin.RegisterData(ReportTable, "Stewardship");

            Boolean HasData = (ReportTable.Rows.Count > 0);

            if (!HasData)
            {
                FStatusMsg += Catalog.GetString("No Stewardship entries found for selected Run Number.");
            }

            TParameterList Params = ACalc.GetParameters();

            if ((!Params.Get("param_design_template").ToBool()) &&
                (rbtEmailStewardship.Checked))
            {
                // This gets email defaults from the user settings table
                TUC_EmailPreferences.LoadEmailDefaults();

                // This gets some of the settings from the server configuration.  We no longer get these items from local PC.
                // SmtpUsername and SmtpPassword will usually be null
                string smtpHost, smtpUsername, smtpPassword;
                int    smtpPort;
                bool   smtpUseSSL;
                TRemote.MSysMan.Application.WebConnectors.GetServerSmtpSettings(out smtpHost,
                                                                                out smtpPort,
                                                                                out smtpUseSSL,
                                                                                out smtpUsername,
                                                                                out smtpPassword);

                if ((smtpHost == string.Empty) || (smtpPort < 0))
                {
                    FStatusMsg += Catalog.GetString(
                        "\r\nCannot send email because 'smtpHost' and/or 'smtpPort' are not configured in the OP server configuration file.");
                    return(false);
                }

                TSmtpSender EmailSender = new TSmtpSender(smtpHost, smtpPort, smtpUseSSL, smtpUsername, smtpPassword, "");

                EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo");
                EmailSender.ReplyTo        = TUserDefaults.GetStringDefault("SmtpReplyTo");

                if (!EmailSender.FInitOk)
                {
                    FStatusMsg += String.Format(
                        Catalog.GetString(
                            "\r\nFailed to set up the email server.\n    Please check the settings in Preferences / Email.\n    Message returned: \"{0}\""),
                        EmailSender.FErrorStatus
                        );
                    return(false);
                }

                String MyCostCentreCode = String.Format("{0:##00}00", FLedgerNumber);
                String PeriodEnd        = Params.Get("param_end_date").ToDate().ToString("dd/MM/yyyy");
                Int32  RunNumber        = Params.Get("param_cmbICHNumber").ToInt32();
                String CsvAttachment    = String.Format("\"{0}\",{1},\"{2}\",{3},\"{4}\",{5}\n", // "** Header **",30/11/2014,\"0200\",09/12/2014,\"USD\",0"

                                                        "** Header **",                          // software originator and version ID
                                                        PeriodEnd,
                                                        MyCostCentreCode,                        // Field Cost Centre Code
                                                        DateTime.Now.ToString("dd/MM/yyyy"),
                                                        FLedgerRow.BaseCurrency,                 // Stewardship Report CSV always in Base Currency
                                                        RunNumber                                // Run number
                                                        );

                foreach (DataRow Row in ReportTable.Rows)
                {
                    CsvAttachment += String.Format("\"{0}\",{1},{2},{3}\n",
                                                   Row["CostCentreCode"].ToString(),
                                                   Convert.ToDecimal(Row["Income"]).ToString("0.00", CultureInfo.InvariantCulture), // Stewardship Report CSV always in Base Currency
                                                   Convert.ToDecimal(Row["Expense"]).ToString("0.00", CultureInfo.InvariantCulture),
                                                   Convert.ToDecimal(Row["Xfer"]).ToString("0.00", CultureInfo.InvariantCulture)
                                                   );
                }

                // Andrea wants this systemj default to be manually added to database when we are ready for a system to send ICH emails
                if (!TSystemDefaults.IsSystemDefaultDefined(STEWARDSHIP_EMAIL_ADDRESS))
                {
                    FStatusMsg += Catalog.GetString("\r\n Stewardship email address not configured in System Defaults.");
                    return(false);
                }

                String EmailRecipient = TSystemDefaults.GetStringDefault(STEWARDSHIP_EMAIL_ADDRESS);

                String EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody");
                EmailSender.AttachFromStream(new MemoryStream(Encoding.ASCII.GetBytes(CsvAttachment)), "Stewardship_" + MyCostCentreCode + ".csv");
                Boolean SentOk = EmailSender.SendEmail(
                    TUserDefaults.GetStringDefault("SmtpFromAccount"),
                    TUserDefaults.GetStringDefault("SmtpDisplayName"),
                    EmailRecipient, //[email protected]
                    "Stewardship Report [" + MyCostCentreCode + "] Period end: " + PeriodEnd + " Run#: " + RunNumber,
                    EmailBody);

                if (SentOk)
                {
                    FStatusMsg += Catalog.GetString("\r\nStewardship report emailed to ICH.");
                }
                else
                {
                    FStatusMsg += Catalog.GetString("\r\nFailed to send Stewardship email to ICH.");
                }

                return(false);
            }

            return(HasData);
        } // Load Stewardship Report Data
Exemplo n.º 10
0
 private static String GetTipsUserDefaultValueInternal(String ATipsUserDefault)
 {
     // MessageBox.Show('TUserTips.GetTipsUserDefaultValueInternal  ATipsUserDefault: ' + ATipsUserDefault);
     return(TUserDefaults.GetStringDefault(ATipsUserDefault, new String(Tips.TIPNOTSETVALUE, 250)));
 }
        /// <summary>
        /// Import a transactions file or a clipboard equivalent
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch to import to</param>
        /// <param name="AImportSource">The import source - eg File or Clipboard</param>
        /// <returns>True if the import was successful</returns>
        public bool ImportTransactions(AGiftBatchRow ACurrentBatchRow, TGiftImportDataSourceEnum AImportSource)
        {
            bool           ok = false;
            String         importString;
            String         impOptions;
            OpenFileDialog dialog      = null;
            Boolean        IsPlainText = false;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                                    "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                MessageBox.Show(Catalog.GetString("Please select an unposted batch to import transactions."), Catalog.GetString(
                                    "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            if (ACurrentBatchRow.LastGiftNumber > 0)
            {
                if (MessageBox.Show(Catalog.GetString(
                                        "The current batch already contains some gift transactions.  Do you really want to add more transactions to this batch?"),
                                    Catalog.GetString("Gift Transaction Import"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return(false);
                }
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportSource == TGiftImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                                    Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData           = importString;
                FdlgSeparator.DateFormat        = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportSource == TGiftImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                string exportPath = TClientSettings.GetExportPath();
                string fullPath   = TUserDefaults.GetStringDefault("Imp Filename",
                                                                   exportPath + Path.DirectorySeparatorChar + "import.csv");
                TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath);

                dialog.Title  = Catalog.GetString("Import Transactions from CSV File");
                dialog.Filter = Catalog.GetString("Gift Transactions files (*.csv)|*.csv|Text Files (*.txt)|*.txt");
                impOptions    = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
                TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath));

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                                        Catalog.GetString("Gift Import"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Stop);
                        return(false);
                    }

                    importString = File.ReadAllText(dialog.FileName, Encoding.Default);
                    IsPlainText  = (Path.GetExtension(dialog.FileName).ToLower() == ".txt");

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions   = String.Empty;
                importString = String.Empty;
            }

            if (IsPlainText || (FdlgSeparator.ShowDialog() == DialogResult.OK))
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);

                bool Repeat = true;

                while (Repeat)
                {
                    Repeat = false;

                    TVerificationResultCollection AMessages = new TVerificationResultCollection();
                    GiftBatchTDSAGiftDetailTable  NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable();

                    Thread ImportThread = new Thread(() => ImportGiftTransactions(
                                                         requestParams,
                                                         importString,
                                                         ACurrentBatchRow.BatchNumber,
                                                         out AMessages,
                                                         out ok,
                                                         out NeedRecipientLedgerNumber));

                    using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                    {
                        ImportDialog.ShowDialog();
                    }

                    ShowMessages(AMessages);

                    // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination
                    // then the import will have failed and we need to alert the user
                    if (NeedRecipientLedgerNumber.Rows.Count > 0)
                    {
                        bool OfferToRunImportAgain = true;

                        // for each gift in which the recipient needs a Git Destination
                        foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows)
                        {
                            if (MessageBox.Show(string.Format(
                                                    Catalog.GetString(
                                                        "Gift Import has been cancelled as the recipient '{0}' ({1}) has no Gift Destination assigned."),
                                                    Row.RecipientDescription, Row.RecipientKey) +
                                                "\n\n" +
                                                Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"),
                                                Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                                == DialogResult.Yes)
                            {
                                // allow the user to assign a Gift Destingation
                                TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey);
                                GiftDestinationForm.ShowDialog();
                            }
                            else
                            {
                                OfferToRunImportAgain = false;
                            }
                        }

                        // if the user has clicked yes to assigning Gift Destinations then offer to restart the import
                        if (OfferToRunImportAgain &&
                            (MessageBox.Show(Catalog.GetString("Would you like to import these Gift Transactions again?"),
                                             Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                             MessageBoxDefaultButton.Button1)
                             == DialogResult.Yes))
                        {
                            Repeat = true;
                        }
                    }
                }

                // We save the defaults even if ok is false - because the client will probably want to try and import
                //   the same file again after correcting any errors
                SaveUserDefaults(dialog, impOptions);
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                                Catalog.GetString("Gift Import"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);

                //FMyUserControl.LoadBatchesForCurrentYear();
                FPetraUtilsObject.DisableSaveButton();
            }

            return(ok);
        }
Exemplo n.º 12
0
 /// <summary>
 /// Set the user default if the Menu Item "Wrap Column" is checked
 /// </summary>
 /// <param name="AWrap"></param>
 public void SaveWrapOption(bool AWrap)
 {
     TUserDefaults.SetDefault("RptSettingWrapColumn", AWrap);
 }
Exemplo n.º 13
0
 /// <summary>
 /// Get the user default if the Menu Item "Wrap Column" is checked
 /// </summary>
 /// <returns></returns>
 public bool GetWrapOption()
 {
     return(TUserDefaults.GetBooleanDefault("RptSettingWrapColumn", true));
 }
Exemplo n.º 14
0
        /// <summary>
        /// The report will be sent to a list of email addresses derived from the Cost Centres in the supplied CostCentreFilter.
        /// </summary>
        /// <returns>Status string that should be shown to the user</returns>
        public static String AutoEmailReports(TFrmPetraReportingUtils FormUtils, FastReportsWrapper ReportEngine,
                                              TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter)
        {
            Int32  SuccessfulCount = 0;
            String NoEmailAddr     = "";
            String FailedAddresses = "";
            String SendReport      = "";

            //
            // I need to find the email addresses for the linked partners I'm sending to.
            DataTable LinkedPartners = null;

            LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter);
            LinkedPartners.DefaultView.Sort = "CostCentreCode";

            foreach (DataRowView rv in LinkedPartners.DefaultView)
            {
                DataRow LinkedPartner = rv.Row;

                if (LinkedPartner["EmailAddress"].ToString() != "")
                {
                    ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString());
                    FormUtils.WriteToStatusBar("Generate " + ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"]);
                    MemoryStream ReportStream = ReportEngine.ExportToStream(ACalc, FastReportsWrapper.ReportExportType.Html);

                    if (ReportStream.Position < 1000)
                    {
                        continue; // Don't send an empty report
                    }

                    ReportStream.Position = 0;

                    TUC_EmailPreferences.LoadEmailDefaults();
                    TSmtpSender EmailSender = new TSmtpSender(
                        TUserDefaults.GetStringDefault("SmtpHost"),
                        TUserDefaults.GetInt16Default("SmtpPort"),
                        TUserDefaults.GetBooleanDefault("SmtpUseSsl"),
                        TUserDefaults.GetStringDefault("SmtpUser"),
                        TUserDefaults.GetStringDefault("SmtpPassword"),
                        "");
                    EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo");
                    EmailSender.ReplyTo        = TUserDefaults.GetStringDefault("SmtpReplyTo");

                    if (!EmailSender.FInitOk)
                    {
                        return(String.Format(
                                   Catalog.GetString(
                                       "Failed to set up the email server.\n    Please check the settings in Preferences / Email.\n    Message returned : \"{0}\""),
                                   EmailSender.FErrorStatus));
                    }

                    String EmailBody = "";

                    if (TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment"))
                    {
                        EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody");
                        EmailSender.AttachFromStream(ReportStream, ReportEngine.FReportName + ".html");
                    }
                    else
                    {
                        StreamReader sr = new StreamReader(ReportStream);
                        EmailBody = sr.ReadToEnd();
                    }

                    Boolean SentOk = EmailSender.SendEmail(
                        TUserDefaults.GetStringDefault("SmtpFromAccount"),
                        TUserDefaults.GetStringDefault("SmtpDisplayName"),
                        "*****@*****.**", //LinkedPartner["EmailAddress"]
                        ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"] + ", Address=" + LinkedPartner["EmailAddress"],
                        EmailBody);

                    if (SentOk)
                    {
                        SuccessfulCount++;
                    }
                    else // Email didn't send for some reason
                    {
                        SendReport += String.Format(
                            Catalog.GetString("\r\nFailed to send to {0}. Message returned: \"{1}\"."),
                            LinkedPartner["EmailAddress"],
                            EmailSender.FErrorStatus
                            );

                        FailedAddresses += ("\r\n    " + LinkedPartner["EmailAddress"]);
                    }
                }
                else // No Email Address for this Partner
                {
                    NoEmailAddr += ("\r\n    " + LinkedPartner["PartnerKey"] + " " + LinkedPartner["PartnerShortName"]);
                }
            }

            if (SuccessfulCount > 0)
            {
                SendReport +=
                    String.Format(Catalog.GetString("\r\n{0} emailed to {1} addresses."), ReportEngine.FReportName, SuccessfulCount) + "\r\n\r\n";
            }

            if (NoEmailAddr != "")
            {
                SendReport += (Catalog.GetString("\r\nThese Partners have no email addresses:") + NoEmailAddr + "\r\n");
            }

            if (FailedAddresses != "")
            {
                SendReport += (Catalog.GetString("Failed to send email to these addresses:") + FailedAddresses + "\r\n\r\n");
            }

            FormUtils.WriteToStatusBar("");
            return(SendReport);
        } // AutoEmailReports
Exemplo n.º 15
0
        /// <summary>
        /// Saves any changed preferences to s_user_defaults
        /// </summary>
        /// <returns>void</returns>
        public DialogResult SaveGeneralTab()
        {
            // First, we need to show any dialogs that may result in Cancel
            if (chkSaveWindowProperties.Checked && !WasSaveWindowPropertiesInitiallyChecked)
            {
                // The user wants to start saving the window positions etc.
                // If we have some information about this that we stored previously, we can offer to use it again...
                string localAppDataPath = Path.Combine(
                    TAppSettingsManager.GetLocalAppDataPath(),
                    CommonFormsResourcestrings.StrFolderOrganisationName,
                    System.Diagnostics.FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductName);
                string settingsFileName = String.Format(CommonFormsResourcestrings.StrScreenPositionsFileName, UserInfo.GUserInfo.UserID);
                string settingsPath     = Path.Combine(localAppDataPath, settingsFileName);

                if (File.Exists(settingsPath))
                {
                    string msg = String.Format("{0}{1}{1}{2}",
                                               CommonFormsResourcestrings.StrReuseScreenPositionsMessage1,
                                               Environment.NewLine,
                                               CommonFormsResourcestrings.StrReuseScreenPositionsMessage2);

                    bool DoNotShowMessageBoxEverytime = false;

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FPetraUtilsObject.GetForm());

                    // customise button text
                    extendedMessageBox.YesButtonText = Catalog.GetString("Keep");
                    extendedMessageBox.NoButtonText  = Catalog.GetString("Discard");

                    extendedMessageBox.ShowDialog(msg,
                                                  CommonFormsResourcestrings.StrReuseScreenPositionsTitle,
                                                  string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbYesNoCancel, TFrmExtendedMessageBox.TIcon.embiQuestion);
                    TFrmExtendedMessageBox.TResult result = extendedMessageBox.GetResult(out DoNotShowMessageBoxEverytime);

                    if (result == TFrmExtendedMessageBox.TResult.embrCancel)
                    {
                        return(DialogResult.Cancel);
                    }
                    else if (result == TFrmExtendedMessageBox.TResult.embrNo)
                    {
                        try
                        {
                            // Delete the old file
                            File.Delete(settingsPath);
                        }
                        catch (Exception ex)
                        {
                            TLogging.Log(String.Format("Exception occurred while deleting the window position file '{0}': {1}",
                                                       settingsPath,
                                                       ex.Message), TLoggingType.ToLogfile);
                        }
                    }
                    else if (result == TFrmExtendedMessageBox.TResult.embrYes)
                    {
                        // Load the information we have already
                        PetraUtilsObject.LoadWindowPositionsFromFile();
                    }
                }
            }

            if (LanguageChanged)
            {
                string LanguageCode = cmbLanguage.GetSelectedString();
                string CultureCode  = cmbCulture.GetSelectedString();

                // send to server
                TRemote.MSysMan.Maintenance.WebConnectors.SetLanguageAndCulture(LanguageCode, CultureCode);

                // set local settings for client
                Catalog.Init(LanguageCode, CultureCode);

                // TODO: can we reload the main window with the new language?
                MessageBox.Show(Catalog.GetString("Please restart the OpenPetra client to see the new language"),
                                Catalog.GetString("Restart the client"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }

            TUserDefaults.SetDefault(TTextFileEncoding.ALLOW_MBCS_TEXT_ENCODING, chkImportAsianANSI.Checked);
            TUserDefaults.SetDefault(MSysManConstants.USERDEFAULT_NUMBEROFRECENTPARTNERS, nudNumberOfPartners.Value);
            TUserDefaults.SetDefault(TUserDefaults.NamedDefaults.USERDEFAULT_ESC_CLOSES_SCREEN, chkEscClosesScreen.Checked);
            TUserDefaults.SetDefault(TUserDefaults.NamedDefaults.USERDEFAULT_SAVE_WINDOW_POS_AND_SIZE, chkSaveWindowProperties.Checked);
            TUserDefaults.SetDefault(TUserDefaults.NamedDefaults.MODULE_TO_OPEN_AT_STARTUP, cmbInitialSelectedModule.GetSelectedString());

            return(DialogResult.OK);
        }
Exemplo n.º 16
0
        private void LoadUserDefaults()
        {
            // This is for compatibility with old Petra
            txtFilename.Text = TUserDefaults.GetStringDefault("Imp Filename",
                                                              TClientSettings.GetExportPath() + Path.DirectorySeparatorChar + "export.csv");
            String expOptions = TUserDefaults.GetStringDefault("Exp Options", "DU-T-X-DTrans");

            // This is for compatibility with old Petra
            if (expOptions.StartsWith("D"))
            {
                rbtDetail.Checked = true;
            }
            else
            {
                rbtSummary.Checked = true;
            }

            if (expOptions.EndsWith("Trans"))
            {
                rbtOriginalTransactionCurrency.Checked = true;
            }
            else
            {
                rbtBaseCurrency.Checked = true;
            }

            if (expOptions.Length > 11)
            {
                // Extended options
                if (expOptions[1] == 'U')
                {
                    chkIncludeUnposted.Checked = (expOptions[2] == '+');
                }

                if (expOptions[3] == 'T')
                {
                    chkTransactionsOnly.Checked = (expOptions[4] == '+');
                }

                if (expOptions[5] == 'X')
                {
                    FGiftExtraColumnsUserDefault = expOptions[6];
                }

                if (expOptions[7] == 'N')
                {
                    rbtBatchNumberSelection.Checked = true;
                }
                else
                {
                    rbtDateRange.Checked = true;
                }
            }

            CultureInfo myCulture         = Thread.CurrentThread.CurrentCulture;
            string      defaultImpOptions = myCulture.TextInfo.ListSeparator + TDlgSelectCSVSeparator.NUMBERFORMAT_EUROPEAN;

            if (myCulture.EnglishName.EndsWith("-US"))
            {
                defaultImpOptions = myCulture.TextInfo.ListSeparator + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;
            }

            String impOptions = TUserDefaults.GetStringDefault("Imp Options", defaultImpOptions);

            if (impOptions.Length > 0)
            {
                cmbDelimiter.SelectedItem = ConvertDelimiter(impOptions.Substring(0, 1), true);
            }

            if (impOptions.Length > 1)
            {
                cmbNumberFormat.SelectedIndex = impOptions.Substring(1) == TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN ? 0 : 1;
            }

            string DateFormat = TUserDefaults.GetStringDefault("Imp Date", "yyyy-MM-dd");

            // mdy and dmy have been the old default settings in Petra 2.x
            if (DateFormat.ToLower() == "mdy")
            {
                DateFormat = "MM/dd/yyyy";
            }

            if (DateFormat.ToLower() == "dmy")
            {
                DateFormat = "dd/MM/yyyy";
            }

            cmbDateFormat.SetSelectedString(DateFormat);
        }
Exemplo n.º 17
0
 /// <summary>
 /// Retrieves a boolean user default value from the TUserDefaults.
 /// </summary>
 /// <returns></returns>
 public static Boolean RetrieveUserDefaultBoolean(String AKey, Boolean ADefault)
 {
     return(TUserDefaults.GetBooleanDefault(AKey, ADefault));
 }
Exemplo n.º 18
0
        /// <summary>
        /// The report will be sent to a list of email addresses derived from the Cost Centres in the supplied CostCentreFilter.
        /// </summary>
        /// <returns>Status string that should be shown to the user</returns>
        public static String AutoEmailReports(TFrmPetraReportingUtils FormUtils, FastReportsWrapper ReportEngine,
                                              TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter)
        {
            Int32  SuccessfulCount = 0;
            String NoEmailAddr     = "";
            String FailedAddresses = "";
            String SendReport      = "Auto Email\r\n";

            //
            // FastReport will use a temporary folder to store HTML files.
            // I need to ensure that the CurrectDirectory is somewhere writable:
            String prevCurrentDir = Directory.GetCurrentDirectory();


            //Get a path in the Public Documents folder
            String newDir = Path.Combine(Environment.GetFolderPath(
                                             Environment.SpecialFolder.CommonDocuments), "OpenPetraOrg");

            //Check it exists, and if not create it
            if (!Directory.Exists(newDir))
            {
                try
                {
                    Directory.CreateDirectory(newDir);
                }
                catch (Exception ex)
                {
                    //could not create the path so return useful debugging information:
                    SendReport += Catalog.GetString("\r\nError - could not create directory: " + newDir);
                    SendReport += Catalog.GetString("\r\n" + newDir);
                    SendReport += ex.Message;

                    return(SendReport);
                }
            }

            Directory.SetCurrentDirectory(newDir);

            //
            // I need to find the email addresses for the linked partners I'm sending to.
            DataTable LinkedPartners = null;

            LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter);
            LinkedPartners.DefaultView.Sort = "CostCentreCode";

            foreach (DataRowView rv in LinkedPartners.DefaultView)
            {
                DataRow LinkedPartner = rv.Row;

                if (LinkedPartner["EmailAddress"].ToString() != "")
                {
                    ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString());
                    FormUtils.WriteToStatusBar("Generate " + ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"]);
                    MemoryStream ReportStream = ReportEngine.ExportToStream(ACalc, FastReportsWrapper.ReportExportType.Html);

                    // in OpenSource OpenPetra, we do not have and use the FastReport dlls
                    // if (ReportEngine.FfastReportInstance.ReportInfo.Description == "Empty")
                    // {
                    //    continue; // Don't send an empty report
                    // }

                    ReportStream.Position = 0;

                    // This gets email defaults from the user settings table
                    TUC_EmailPreferences.LoadEmailDefaults();

                    // This gets some of the settings from the server configuration.  We no longer get these items from local PC.
                    // SmtpUsername and SmtpPassword will usually be null
                    string smtpHost, smtpUsername, smtpPassword;
                    int    smtpPort;
                    bool   smtpUseSSL;
                    TRemote.MSysMan.Application.WebConnectors.GetServerSmtpSettings(out smtpHost,
                                                                                    out smtpPort,
                                                                                    out smtpUseSSL,
                                                                                    out smtpUsername,
                                                                                    out smtpPassword);

                    if ((smtpHost == string.Empty) || (smtpPort < 0))
                    {
                        return(Catalog.GetString(
                                   "Cannot send email because 'smtpHost' and/or 'smtpPort' are not configured in the OP server configuration file."));
                    }

                    TSmtpSender EmailSender = new TSmtpSender(smtpHost, smtpPort, smtpUseSSL, smtpUsername, smtpPassword, "");

                    EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo");
                    EmailSender.ReplyTo        = TUserDefaults.GetStringDefault("SmtpReplyTo");

                    if (!EmailSender.FInitOk)
                    {
                        return(String.Format(
                                   Catalog.GetString(
                                       "Failed to set up the email server.\n    Please check the settings in Preferences / Email.\n    Message returned : \"{0}\""),
                                   EmailSender.FErrorStatus));
                    }

                    String EmailBody = "";

                    if (TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment"))
                    {
                        EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody");
                        EmailSender.AttachFromStream(ReportStream, ReportEngine.FReportName + ".html");
                    }
                    else
                    {
                        StreamReader sr = new StreamReader(ReportStream);
                        EmailBody = sr.ReadToEnd();
                    }

                    Boolean SentOk = EmailSender.SendEmail(
                        TUserDefaults.GetStringDefault("SmtpFromAccount"),
                        TUserDefaults.GetStringDefault("SmtpDisplayName"),
                        LinkedPartner["EmailAddress"].ToString(),
                        ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"] + ", Address=" + LinkedPartner["EmailAddress"],
                        EmailBody);

                    if (SentOk)
                    {
                        SuccessfulCount++;
                    }
                    else // Email didn't send for some reason
                    {
                        SendReport += String.Format(
                            Catalog.GetString("\r\nFailed to send to {0}. Message returned: \"{1}\"."),
                            LinkedPartner["EmailAddress"],
                            EmailSender.FErrorStatus
                            );

                        FailedAddresses += ("\r\n    " + LinkedPartner["EmailAddress"]);
                    }
                }
                else // No Email Address for this Partner
                {
                    NoEmailAddr += ("\r\n    " + LinkedPartner["PartnerKey"] + " " + LinkedPartner["PartnerShortName"]);
                }
            }

            if (SuccessfulCount > 0)
            {
                SendReport +=
                    String.Format(Catalog.GetString("\r\n{0} emailed to {1} addresses."), ReportEngine.FReportName, SuccessfulCount) + "\r\n\r\n";
            }
            else
            {
                SendReport += Catalog.GetString("\r\nError - no page had a linked email address.");
            }

            if (NoEmailAddr != "")
            {
                SendReport += (Catalog.GetString("\r\nThese Partners have no email addresses:") + NoEmailAddr + "\r\n");
            }

            if (FailedAddresses != "")
            {
                SendReport += (Catalog.GetString("Failed to send email to these addresses:") + FailedAddresses + "\r\n\r\n");
            }

            FormUtils.WriteToStatusBar("");
            Directory.SetCurrentDirectory(prevCurrentDir);
            return(SendReport);
        } // AutoEmailReports
Exemplo n.º 19
0
        // displays information about the currently selected conference in the navigation panel
        private static void AddConferenceInformation(XmlNode AMenuNode)
        {
            FConferenceKey = TUserDefaults.GetInt64Default("LASTCONFERENCEWORKEDWITH");

            // Set PartnerKey in conference setup screens for selected conference
            Ict.Petra.Client.MConference.Gui.TConferenceMain.FPartnerKey = FConferenceKey;

            XmlNode      childNode = AMenuNode.FirstChild;
            XmlAttribute enabledAttribute;

            while (childNode != null)
            {
                if ((TXMLParser.GetAttribute(childNode, "DependsOnConference").ToLower() == "true") && (FConferenceKey != 0))
                {
                    FConferenceSelected = true; // node only displayed if this is true

                    // Create 'Select Conference' Node
                    XmlAttribute LabelAttributeConference = childNode.OwnerDocument.CreateAttribute("Label");
                    XmlElement   SelConferenceElmnt       = childNode.OwnerDocument.CreateElement("ConferenceInfo");
                    XmlNode      SelectConferenceNode     = childNode.AppendChild(SelConferenceElmnt);
                    SelectConferenceNode.Attributes.Append(LabelAttributeConference);
                    SelectConferenceNode.Attributes["Label"].Value = Catalog.GetString("Current Conference");

                    // Create conference details Node
                    XmlElement   SpecificConferenceElmnt = childNode.OwnerDocument.CreateElement("Conference" + FConferenceKey);
                    XmlNode      SpecificConferenceNode  = SelectConferenceNode.AppendChild(SpecificConferenceElmnt);
                    XmlAttribute AttributeConferenceName = childNode.OwnerDocument.CreateAttribute("Label");
                    SpecificConferenceNode.Attributes.Append(AttributeConferenceName);

                    // Disable clicking on node
                    enabledAttribute       = childNode.OwnerDocument.CreateAttribute("Enabled");
                    enabledAttribute.Value = "false";
                    SpecificConferenceNode.Attributes.Append(enabledAttribute);

                    // Get conference name
                    string        ConferenceName;
                    TPartnerClass PartnerClass;
                    TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetPartnerShortName(FConferenceKey, out ConferenceName, out PartnerClass);

                    if (ConferenceName != String.Empty)
                    {
                        const int BreakPoint = 28;
                        SpecificConferenceNode.Attributes["Label"].Value = "";

                        // splits the name over multiple lines if it too long
                        while (ConferenceName.Length > BreakPoint)
                        {
                            int IndexOfSpace     = ConferenceName.IndexOf(" ", 0);
                            int LastIndexOfSpace = 0;

                            // searches for the last breakpoint for a line
                            while (IndexOfSpace <= BreakPoint && IndexOfSpace != -1)
                            {
                                LastIndexOfSpace = IndexOfSpace;
                                IndexOfSpace     = ConferenceName.IndexOf(" ", LastIndexOfSpace + 1);
                            }

                            SpecificConferenceNode.Attributes["Label"].Value += ConferenceName.Substring(0, LastIndexOfSpace) + "\n";

                            ConferenceName = ConferenceName.Remove(0, LastIndexOfSpace + 1);
                        }

                        SpecificConferenceNode.Attributes["Label"].Value += ConferenceName + "\n";
                    }
                    else
                    {
                        SpecificConferenceNode.Attributes["Label"].Value = "Conference Key: " + FConferenceKey;
                    }

                    // Set node values
                    SpecificConferenceNode.Attributes["Label"].Value = SpecificConferenceNode.Attributes["Label"].Value;

                    // only dispay dates if they are valid
                    DateTime StartDate = TRemote.MConference.Conference.WebConnectors.GetStartDate(FConferenceKey);
                    DateTime EndDate   = TRemote.MConference.Conference.WebConnectors.GetEndDate(FConferenceKey);

                    if (StartDate != DateTime.MinValue)
                    {
                        SpecificConferenceNode.Attributes["Label"].Value = SpecificConferenceNode.Attributes["Label"].Value +
                                                                           "\nStart: " + StartDate.ToLongDateString();
                    }

                    if (EndDate != DateTime.MinValue)
                    {
                        SpecificConferenceNode.Attributes["Label"].Value = SpecificConferenceNode.Attributes["Label"].Value +
                                                                           "\nEnd: " + EndDate.ToLongDateString();
                    }

                    childNode = childNode.NextSibling;
                }
                else
                {
                    // Recurse into deeper levels!
                    AddConferenceInformation(childNode);

                    childNode = childNode.NextSibling;
                }
            }
        }
        /// <summary>
        /// this supports the transaction export files from Petra 2.x.
        /// Lines do NOT start with T for transaction
        /// </summary>
        public void ImportTransactions(ABatchRow ACurrentBatchRow, AJournalRow ACurrentJournalRow, TImportDataSourceEnum AImportDataSource)
        {
            bool           ok = false;
            String         importString;
            String         impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges && !FMyForm.SaveChanges())
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save your changes before Importing new transactions"), Catalog.GetString(
                                    "Import GL Transactions"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if ((ACurrentBatchRow == null) ||
                (ACurrentJournalRow == null) ||
                (ACurrentJournalRow.JournalStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                MessageBox.Show(Catalog.GetString("Please select an unposted journal to import transactions."),
                                Catalog.GetString("Import GL Transactions"));
                return;
            }

            if (ACurrentJournalRow.LastTransactionNumber > 0)
            {
                if (MessageBox.Show(Catalog.GetString(
                                        "The current journal already contains some transactions.  Do you really want to add more transactions to this journal?"),
                                    Catalog.GetString("Import GL Transactions"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportDataSource == TImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                                    Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData           = importString;
                FdlgSeparator.DateFormat        = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportDataSource == TImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                string exportPath = TClientSettings.GetExportPath();
                string fullPath   = TUserDefaults.GetStringDefault("Imp Filename",
                                                                   exportPath + Path.DirectorySeparatorChar + "import.csv");
                TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath);

                dialog.Title  = Catalog.GetString("Import Transactions from CSV File");
                dialog.Filter = Catalog.GetString("GL Transactions files (*.csv)|*.csv|Text Files (*.txt)|*.txt");
                impOptions    = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
                TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath));

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                                        Catalog.GetString("Transaction Import"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Stop);
                        return;
                    }

                    importString = File.ReadAllText(dialog.FileName, Encoding.Default);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions   = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);

                TVerificationResultCollection AMessages = new TVerificationResultCollection();

                Thread ImportThread = new Thread(() => ImportGLTransactions(requestParams,
                                                                            importString,
                                                                            ACurrentBatchRow.BatchNumber,
                                                                            ACurrentJournalRow.JournalNumber,
                                                                            out AMessages,
                                                                            out ok));

                using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                {
                    ImportDialog.ShowDialog();
                }

                // It is important to save user defaults here, even if there were errors
                //   because in that case the user will want to import the same file again after fixing it.
                SaveUserDefaults(dialog, impOptions);
                ShowMessages(AMessages);
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                                Catalog.GetString("Transactions Import"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);

                // Update the client side with new information from the server
                FMyForm.Cursor = Cursors.WaitCursor;
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAJournal(FLedgerNumber, ACurrentBatchRow.BatchNumber));
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionATransAnalAttrib(FLedgerNumber,
                                                                                                 ACurrentBatchRow.BatchNumber, ACurrentJournalRow.JournalNumber));
                FMainDS.AcceptChanges();
                FMyForm.Cursor = Cursors.Default;

                FMyForm.GetTransactionsControl().SelectRow(1);
            }
        }
Exemplo n.º 21
0
        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();
                }
            }
        }
        /// <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
        /// The code handles importing from file or clipboard
        /// </summary>
        public void ImportBatches(TImportDataSourceEnum AImportDataSource)
        {
            bool           ok = false;
            String         importString;
            String         impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                                    "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportDataSource == TImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                                    Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData           = importString;
                FdlgSeparator.DateFormat        = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportDataSource == TImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                string exportPath = TClientSettings.GetExportPath();
                string fullPath   = TUserDefaults.GetStringDefault("Imp Filename",
                                                                   exportPath + Path.DirectorySeparatorChar + "import.csv");
                TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath);

                dialog.Title  = Catalog.GetString("Import Batches from CSV File");
                dialog.Filter = Catalog.GetString("Text Files(*.txt) | *.txt | GL Batch Files(*.csv) | *.csv");
                impOptions    = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
                TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath));

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                                        Catalog.GetString("Batch Import"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Stop);
                        return;
                    }

                    importString = File.ReadAllText(dialog.FileName, Encoding.Default);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions   = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);


                TVerificationResultCollection AMessages = new TVerificationResultCollection();

                Thread ImportThread = new Thread(() => ImportGLBatches(
                                                     requestParams,
                                                     importString,
                                                     out AMessages,
                                                     out ok));

                using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                {
                    ImportDialog.ShowDialog();
                }

                // We save the defaults even if ok is false - because the client will probably want to try and import
                //   the same file again after correcting any errors
                SaveUserDefaults(dialog, impOptions);
                ShowMessages(AMessages);
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                                Catalog.GetString("Batch Import"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);

                FMyUserControl.ReloadBatches();
                FPetraUtilsObject.DisableSaveButton();
            }
        }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Opens the partner edit screen with the last partner worked on.
        /// Checks if the partner is merged.
        /// </summary>
        public static void OpenLastUsedPartnerEditScreenByContext(Form AParentForm, string AContext = null)
        {
            string ValidContexts;
            string Context;
            long   MergedPartnerKey = 0;
            long   LastPartnerKey;
            string NoPartnerAvailableStr = Catalog.GetString("You have not edited a Partner yet.");

            if (AContext != null)
            {
                ValidContexts = TUserDefaults.USERDEFAULT_LASTPARTNERMAILROOM + ";" + TUserDefaults.USERDEFAULT_LASTPERSONPERSONNEL + ";" +
                                TUserDefaults.USERDEFAULT_LASTUNITPERSONNEL + ";" + TUserDefaults.USERDEFAULT_LASTPERSONCONFERENCE + ";";

                if (!ValidContexts.Contains(AContext + ";"))
                {
                    throw new ArgumentException("AContext \"" + AContext + "\" is not a valid context. Valid contexts: " + ValidContexts);
                }
                else
                {
                    Context = AContext;
                }
            }
            else
            {
                Context = TUserDefaults.USERDEFAULT_LASTPARTNERMAILROOM;
            }

            LastPartnerKey = TUserDefaults.GetInt64Default(Context, 0);

            // we don't need to validate the partner key
            // because it's done in the mnuFile_Popup function.
            // If we don't have a valid partner key, this code can't be called from the file menu.

            // now that this function is called from the main menu, we need to check for LastPartnerKey != 0
            if (LastPartnerKey == 0)
            {
                if (Context == TUserDefaults.USERDEFAULT_LASTPERSONPERSONNEL)
                {
                    NoPartnerAvailableStr = Catalog.GetString("You have not yet worked with a Person in the Personnel Module.");
                }

                MessageBox.Show(Catalog.GetString(NoPartnerAvailableStr),
                                Catalog.GetString("No Last Partner"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return;
            }

            if (MergedPartnerHandling(LastPartnerKey, out MergedPartnerKey))
            {
                // work with the merged partner
                LastPartnerKey = MergedPartnerKey;
            }
            else if (MergedPartnerKey > 0)
            {
                // The partner is merged but user cancelled the action
                return;
            }

            // Open the Partner Edit screen
            TFrmPartnerEdit frmPEDS;

            AParentForm.Cursor = Cursors.WaitCursor;

            frmPEDS = new TFrmPartnerEdit(AParentForm);

            if (Context == TUserDefaults.USERDEFAULT_LASTPERSONPERSONNEL)
            {
                frmPEDS.SetParameters(TScreenMode.smEdit, LastPartnerKey, TPartnerEditTabPageEnum.petpPersonnelIndividualData);
            }
            else
            {
                frmPEDS.SetParameters(TScreenMode.smEdit, LastPartnerKey);
            }

            frmPEDS.Show();

            AParentForm.Cursor = Cursors.Default;
        }
 /// <summary>
 /// Saves any changed preferences to s_user_defaults
 /// </summary>
 /// <returns>void</returns>
 public void SavePartnerTab()
 {
     TUserDefaults.SetDefault(TUserDefaults.PARTNER_ACQUISITIONCODE, cmbAcquisitionCode.GetSelectedString());
     TUserDefaults.SetDefault(TUserDefaults.PARTNER_LANGUAGECODE, cmbLanguageCode.GetSelectedString());
 }
Exemplo n.º 26
0
        /// <summary>
        /// Opens the Partner Find screen (or activates it in case a non-modal instance was already open and
        /// ARestrictToPartnerClasses is null). If ARestrictToPartnerClasses isn't null then the screen is opened modally.
        /// </summary>
        /// <remarks>
        /// For NUnit tests that just try to open the Partner Find screen but which don't instantiate a Main Form
        /// we need to ignore the <paramref name="AParentForm" /> Argument as it will be null in those cases!
        /// </remarks>
        /// <returns>void</returns>
        public static void FindPartnerOfClass(Form AParentForm,
                                              string ARestrictToPartnerClasses = null,
                                              TPartnerEditTabPageEnum APreferredInitialTabPage = TPartnerEditTabPageEnum.petpAddresses)
        {
            if (ARestrictToPartnerClasses == null)
            {
                // No Cursor change if run from within NUnit Test without Main Form instance...
                if (AParentForm != null)
                {
                    AParentForm.Cursor = Cursors.WaitCursor;
                }

                TPartnerFindScreen PartnerFindForm = new TPartnerFindScreen(AParentForm);
                PartnerFindForm.SetParameters(false, -1);
                PartnerFindForm.Show();

                // No Cursor change if run from within NUnit Test without Main Form instance...
                if (AParentForm != null)
                {
                    AParentForm.Cursor = Cursors.Default;
                }
            }
            else
            {
                long          PartnerKey;
                string        ShortName;
                TPartnerClass?PartnerClass;
                TLocationPK   LocationPK;

                if (TPartnerFindScreenManager.OpenModalForm(ARestrictToPartnerClasses, out PartnerKey, out ShortName, out PartnerClass,
                                                            out LocationPK, AParentForm))
                {
                    // Open the Partner Edit screen
                    TFrmPartnerEdit PartnerEditForm;

                    // No Cursor change if run from within NUnit Test without Main Form instance...
                    if (AParentForm != null)
                    {
                        AParentForm.Cursor = Cursors.WaitCursor;
                    }

                    PartnerEditForm = new TFrmPartnerEdit(AParentForm);

                    if (APreferredInitialTabPage == TPartnerEditTabPageEnum.petpAddresses)
                    {
                        PartnerEditForm.SetParameters(TScreenMode.smEdit, PartnerKey, LocationPK.SiteKey, LocationPK.LocationKey);
                    }
                    else
                    {
                        PartnerEditForm.SetParameters(TScreenMode.smEdit, PartnerKey, APreferredInitialTabPage);
                    }

                    PartnerEditForm.Show();

                    if (ARestrictToPartnerClasses.Split(new Char[] { (',') })[0] == "PERSON")
                    {
                        TUserDefaults.SetDefault(TUserDefaults.USERDEFAULT_LASTPERSONPERSONNEL, PartnerKey);
                    }
                    else
                    {
                        TUserDefaults.SetDefault(TUserDefaults.USERDEFAULT_LASTPARTNERMAILROOM, PartnerKey);
                    }

                    // No Cursor change if run from within NUnit Test without Main Form instance...
                    if (AParentForm != null)
                    {
                        AParentForm.Cursor = Cursors.Default;
                    }
                }
            }
        }
        private void InitializeManualCode()
        {
            DataTable CultureTable = new DataTable();

            CultureTable.Columns.Add("Value", typeof(string));
            CultureTable.Columns.Add("Display", typeof(string));

            foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
            {
                if (!ci.IsNeutralCulture)
                {
                    DataRow row = CultureTable.NewRow();
                    row[0] = ci.Name;
                    row[1] = ci.EnglishName;
                    CultureTable.Rows.Add(row);
                }
            }

            CultureTable.DefaultView.Sort = "Display";

            cmbCulture.DisplayMember = "Display";
            cmbCulture.ValueMember   = "Value";
            cmbCulture.DataSource    = CultureTable.DefaultView;

            // load languages from names of language sub directories
            string[] LanguageDirectories = Directory.GetDirectories(TAppSettingsManager.ApplicationDirectory);

            string LanguagesAvailable = "en-EN";

            foreach (String directory in LanguageDirectories)
            {
                if (File.Exists(directory + Path.DirectorySeparatorChar + "OpenPetra.resources.dll"))
                {
                    LanguagesAvailable = StringHelper.AddCSV(
                        LanguagesAvailable,
                        directory.Substring(
                            directory.LastIndexOf(Path.DirectorySeparatorChar) + 1));
                }
            }

            cmbLanguage.SetDataSourceStringList(LanguagesAvailable);

            // for the moment default to english, because translations are not fully supported, and the layout does not adjust
            string LanguageCode = "en-EN";
            string CultureCode  = CultureInfo.CurrentCulture.Name;

            TRemote.MSysMan.Maintenance.WebConnectors.GetLanguageAndCulture(ref LanguageCode, ref CultureCode);

            cmbCulture.SetSelectedString(CultureCode);
            cmbLanguage.SetSelectedString(LanguageCode);

            llbLaunchpadLink.Click += LaunchpadLinkClicked;

            // Get the number of recent partners that the user has set, if not found take 10 as default value.
            nudNumberOfPartners.Value   = TUserDefaults.GetInt16Default(MSysManConstants.USERDEFAULT_NUMBEROFRECENTPARTNERS, 10);
            nudNumberOfPartners.Maximum = 10;

            // Other preferences
            chkEscClosesScreen.Checked      = TUserDefaults.GetBooleanDefault(TUserDefaults.NamedDefaults.USERDEFAULT_ESC_CLOSES_SCREEN, true);
            chkSaveWindowProperties.Checked = TUserDefaults.GetBooleanDefault(TUserDefaults.NamedDefaults.USERDEFAULT_SAVE_WINDOW_POS_AND_SIZE, true);

            WasSaveWindowPropertiesInitiallyChecked = chkSaveWindowProperties.Checked;
        }
        /// <summary>
        /// Imports budgets from a file
        /// </summary>
        /// <param name="ASelectedBudgetYear"></param>
        /// <param name="AMainDS"></param>
        public void ImportBudget(int ASelectedBudgetYear, ref BudgetTDS AMainDS)
        {
            TVerificationResultCollection Messages = new TVerificationResultCollection();

            int NumBudgetsToImport = 0;
            int NumRecsUpdated     = 0;
            int NumRowsFailed      = 0;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to post
                MessageBox.Show(Catalog.GetString("Please save before trying to import!"), Catalog.GetString(
                                    "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            String         DateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
            OpenFileDialog OFDialog         = new OpenFileDialog();

            string ExportPath = TClientSettings.GetExportPath();
            string FullPath   = TUserDefaults.GetStringDefault("Imp Filename",
                                                               ExportPath + Path.DirectorySeparatorChar + "import.csv");

            TImportExportDialogs.SetOpenFileDialogFilePathAndName(OFDialog, FullPath, ExportPath);

            OFDialog.Title  = Catalog.GetString("Import budget(s) from csv file");
            OFDialog.Filter = Catalog.GetString("Budget files (*.csv)|*.csv");
            String ImportOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

            // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
            TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(FullPath));

            if (OFDialog.ShowDialog() == DialogResult.OK)
            {
                FdlgSeparator = new TDlgSelectCSVSeparator(false);

                try
                {
                    FParentForm.UseWaitCursor = true;

                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(OFDialog.FileName);

                    if (!fileCanOpen)
                    {
                        throw new Exception(String.Format(Catalog.GetString("File {0} cannot be opened."), OFDialog.FileName));
                    }

                    FdlgSeparator.DateFormat = DateFormatString;

                    if (ImportOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = ImportOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = ImportOptions.Substring(0, 1);

                    if (FdlgSeparator.ShowDialog() == DialogResult.OK)
                    {
                        string[] FdlgSeparatorVal = new string[] {
                            FdlgSeparator.SelectedSeparator, FdlgSeparator.DateFormat, FdlgSeparator.NumberFormat
                        };

                        // read contents of file
                        string ImportString = File.ReadAllText(OFDialog.FileName);

                        //TODO return the budget from the year, and -99 for fail
                        NumBudgetsToImport = TRemote.MFinance.Budget.WebConnectors.ImportBudgets(FLedgerNumber,
                                                                                                 ASelectedBudgetYear,
                                                                                                 ImportString,
                                                                                                 OFDialog.FileName,
                                                                                                 FdlgSeparatorVal,
                                                                                                 ref AMainDS,
                                                                                                 out NumRecsUpdated,
                                                                                                 out NumRowsFailed,
                                                                                                 out Messages);

                        ShowMessages(Messages, NumBudgetsToImport, NumRecsUpdated, NumRowsFailed);
                    }
                }
                catch (Exception ex)
                {
                    NumBudgetsToImport = -1;
                    MessageBox.Show(ex.Message, Catalog.GetString("Budget Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    // We save the defaults even if ok is false - because the client will probably want to try and import
                    //   the same file again after correcting any errors
                    SaveUserDefaults(OFDialog, ImportOptions);

                    FParentForm.UseWaitCursor = false;
                }

                // update grid
                if (NumBudgetsToImport > 0)
                {
                    FParentForm.UseWaitCursor = true;
                    UpdateABudgetPeriodAmounts(AMainDS, ASelectedBudgetYear);
                    FUserControl.SetBudgetDefaultView();
                    FParentForm.UseWaitCursor = false;

                    FUserControl.SelectRowInGrid(1);

                    FPetraUtilsObject.SetChangedFlag();
                }
                else if (NumBudgetsToImport <= 0)
                {
                    FUserControl.SelectRowInGrid(1);
                }
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// load the history of a combobox for auto completion from the user defaults
 /// </summary>
 /// <param name="AComboBox"></param>
 public void LoadComboBoxHistory(TCmbAutoComplete AComboBox)
 {
     AComboBox.SetDataSourceStringList(TUserDefaults.GetStringDefault("CmbHistory" + AComboBox.Name, ""));
 }
Exemplo n.º 30
0
        /// <summary>
        /// Initialize the Petra server and connect to the database
        /// </summary>
        /// <param name="AConfigName">just provide the server config file, plus AutoLogin and AutoLoginPasswd</param>
        public static TServerManager Connect(string AConfigName)
        {
            TDBTransaction LoginTransaction;
            bool           CommitLoginTransaction = false;
            bool           SystemEnabled;
            string         WelcomeMessage;
            IPrincipal     ThisUserInfo;
            Int32          ClientID;

            if (File.Exists(AConfigName))
            {
                new TAppSettingsManager(AConfigName);
            }
            else if (AConfigName.Length > 0)
            {
                TLogging.Log("cannot find config file " + Path.GetFullPath(AConfigName));
                Environment.Exit(-1);
            }
            else
            {
                new TAppSettingsManager();
            }

            new TLogging(TAppSettingsManager.GetValue("Server.LogFile"));

            CommonNUnitFunctions.InitRootPath();

            Catalog.Init();
            TServerManager.TheServerManager = new TServerManager();

            DBAccess.GDBAccessObj = new TDataBase();
            DBAccess.GDBAccessObj.EstablishDBConnection(TSrvSetting.RDMBSType,
                                                        TSrvSetting.PostgreSQLServer, TSrvSetting.PostgreSQLServerPort,
                                                        TSrvSetting.PostgreSQLDatabaseName,
                                                        TSrvSetting.DBUsername, TSrvSetting.DBPassword, "",
                                                        "Ict.Testing.NUnitPetraServer.TPetraServerConnector.Connect DB Connection");

            LoginTransaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.RepeatableRead,
                                                                      ATransactionName: "Ict.Testing.NUnitPetraServer.TPetraServerConnector.Connect (Unit Test Login)");

            try
            {
                TClientManager.PerformLoginChecks(TAppSettingsManager.GetValue("AutoLogin").ToUpper(),
                                                  TAppSettingsManager.GetValue("AutoLoginPasswd"),
                                                  "NUNITTEST", "127.0.0.1", out SystemEnabled, LoginTransaction);

                CommitLoginTransaction = true;
            }
            catch (EPetraSecurityException)
            {
                // We need to set this flag to true here to get the failed login to be stored in the DB!!!
                CommitLoginTransaction = true;
            }
            finally
            {
                if (CommitLoginTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                }
                else
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }
            }

            TConnectedClient CurrentClient = TClientManager.ConnectClient(
                TAppSettingsManager.GetValue("AutoLogin").ToUpper(),
                TAppSettingsManager.GetValue("AutoLoginPasswd"),
                "NUNITTEST", "127.0.0.1",
                TFileVersionInfo.GetApplicationVersion().ToVersion(),
                TClientServerConnectionType.csctLocal,
                out ClientID,
                out WelcomeMessage,
                out SystemEnabled,
                out ThisUserInfo);

            // the following values are stored in the session object
            DomainManager.GClientID     = ClientID;
            DomainManager.CurrentClient = CurrentClient;
            UserInfo.GUserInfo          = (TPetraPrincipal)ThisUserInfo;

            TSetupDelegates.Init();
            TSystemDefaultsCache.GSystemDefaultsCache = new TSystemDefaultsCache();
            DomainManager.GetSiteKeyFromSystemDefaultsCacheDelegate =
                @TSystemDefaultsCache.GSystemDefaultsCache.GetSiteKeyDefault;

            TUserDefaults.InitializeUnit();

            StringHelper.CurrencyFormatTable = DBAccess.GDBAccessObj.SelectDT("SELECT * FROM PUB_a_currency", "a_currency", null);

            return((TServerManager)TServerManager.TheServerManager);
        }