Example #1
0
        /// <summary>
        /// Batch job to send all of the nightly/monthly email.
        /// </summary>
        public async void NightlyRun()
        {
            EventRecorder.LogCall("Starting nightly run");
            try
            {
                if (ActiveBrand == null)
                {
                    ActiveBrand = Branding.CurrentBrand;
                }
                if (TasksToRun == SelectedTasks.All || TasksToRun == SelectedTasks.EmailOnly)
                {
                    SendNightlyEmails();
                }

                // Do any Cloud Storage updates
                if (TasksToRun == SelectedTasks.All || TasksToRun == SelectedTasks.CloudStorageOnly)
                {
                    await BackupToCloud().ConfigureAwait(false);    // we have no httpcontext.current, so no need to save
                }
                // Send out any notices of pending gratuity expirations
                EarnedGratuity.SendRemindersOfExpiringGratuities(UserRestriction);

                if (DateTime.Now.Day == 1)
                {
                    Clubs.Club.SendMonthlyClubReports();
                }
            }
            catch (Exception ex) when(!(ex is OutOfMemoryException))
            {
                EventRecorder.LogCall("Nightly run had exception: {msg}, {stacktrace} ", ex.Message, ex.StackTrace);
            }

            EventRecorder.LogCall("Ended nightly run");
        }
        protected void PreviewData()
        {
            lblError.Text = string.Empty;

            mvPreviewResults.SetActiveView(vwPreviewResults);                                // default to showing results.

            mfbImportAircraft1.CandidatesForImport = Array.Empty <AircraftImportMatchRow>(); // start fresh every time.

            byte[] rgb = CurrentCSVSource;
            if (rgb == null || rgb.Length == 0)
            {
                lblFileRequired.Text = Resources.LogbookEntry.errImportInvalidCSVFile;
                SetWizardStep(wsUpload);
                return;
            }

            int cOriginalSize = rgb.Length;

            pnlConverted.Visible = pnlAudit.Visible = false;

            ExternalFormatConvertResults results = ExternalFormatConvertResults.ConvertToCSV(rgb);

            lblAudit.Text       = results.AuditResult;
            hdnAuditState.Value = results.ResultString;
            CurrentCSVSource    = results.GetConvertedBytes();

            int cConvertedSize = CurrentCSVSource.Length;

            IsPendingOnly = IsPendingOnly || results.IsPendingOnly; // results can change between first preview and import, so if it's true anywhere along the way, preserve that.

            if (!String.IsNullOrEmpty(results.ConvertedName))
            {
                lblFileWasConverted.Text = String.Format(CultureInfo.CurrentCulture, Resources.LogbookEntry.importLabelFileWasConverted, results.ConvertedName);
                pnlConverted.Visible     = true;
            }

            pnlAudit.Visible = (results.IsFixedOrBroken);
            if (results.IsBroken)
            {
                lblAudit.CssClass = "error";
                ExpandoAudit.ExpandoControl.Collapsed   = false;
                ExpandoAudit.ExpandoControl.ClientState = "false";
            }
            else
            {
                lblAudit.CssClass = string.Empty;
                ExpandoAudit.ExpandoControl.Collapsed   = true;
                ExpandoAudit.ExpandoControl.ClientState = "true";
            }

            pnlAudit.Visible = pnlConverted.Visible || !String.IsNullOrEmpty(lblAudit.Text);

            ErrorContext.Clear();
            CSVImporter csvimporter = CurrentImporter = new CSVImporter(mfbImportAircraft1.ModelMapping);

            csvimporter.InitWithBytes(CurrentCSVSource, User.Identity.Name, AddSuccessRow, AddErrorRow, ckAutofill.Checked);

            if (csvimporter.FlightsToImport == null || !String.IsNullOrEmpty(csvimporter.ErrorMessage))
            {
                lblFileRequired.Text = csvimporter.ErrorMessage;
                SetWizardStep(wsUpload);
                return;
            }

            rptPreview.DataSource = csvimporter.FlightsToImport;
            rptPreview.DataBind();
            mvPreview.SetActiveView(csvimporter.FlightsToImport.Count > 0 ? vwPreview : vwNoResults);

            if (wzImportFlights.ActiveStep == wsMissingAircraft)
            {
                EventRecorder.LogCall("Import Preview - User: {user}, Upload size {cbin}, converted size {cbconvert}, flights found: {flightcount}", User.Identity.Name, cOriginalSize, cConvertedSize, csvimporter.FlightsToImport.Count);
            }

            mvMissingAircraft.SetActiveView(vwNoMissingAircraft); // default state.

            if (csvimporter.FlightsToImport.Count > 0)
            {
                if (csvimporter.HasErrors)
                {
                    if (!IsPendingOnly)
                    {
                        lblError.Text = Resources.LogbookEntry.ImportPreviewNotSuccessful;
                    }

                    List <AircraftImportMatchRow> missing = new List <AircraftImportMatchRow>(csvimporter.MissingAircraft);
                    if (missing.Count > 0)
                    {
                        mfbImportAircraft1.CandidatesForImport = missing;
                        mvMissingAircraft.SetActiveView(vwAddMissingAircraft);
                    }

                    ((Button)wzImportFlights.FindControl("FinishNavigationTemplateContainerID$btnNewFile")).Visible = true;
                }

                ((AjaxControlToolkit.ConfirmButtonExtender)wzImportFlights.FindControl("FinishNavigationTemplateContainerID$confirmImportWithErrors")).Enabled = csvimporter.HasErrors;
            }
        }
Example #3
0
        private async Task <bool> BackupToCloud()
        {
            string szBackups        = Path.Combine(Path.GetTempPath(), String.Format(CultureInfo.InvariantCulture, "{0}-CloudBackup.txt", DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
            string szBackupFailures = Path.Combine(Path.GetTempPath(), String.Format(CultureInfo.InvariantCulture, "{0}-CloudBackup-errors.txt", DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));

            if (File.Exists(szBackups))
            {
                File.Delete(szBackups);
            }
            if (File.Exists(szBackupFailures))
            {
                File.Delete(szBackupFailures);
            }

            List <EarnedGratuity> lstUsersWithCloudBackup = EarnedGratuity.GratuitiesForUser(string.Empty, Gratuity.GratuityTypes.CloudBackup);

            if (!String.IsNullOrEmpty(UserRestriction))
            {
                lstUsersWithCloudBackup.RemoveAll(eg => eg.Username.CompareCurrentCultureIgnoreCase(UserRestriction) != 0);
            }

            foreach (EarnedGratuity eg in lstUsersWithCloudBackup)
            {
                StringBuilder sb         = new StringBuilder();
                StringBuilder sbFailures = new StringBuilder();

                StorageID sid = StorageID.None;
                if (eg.UserProfile != null && ((sid = eg.UserProfile.BestCloudStorage) != StorageID.None) && eg.CurrentStatus != EarnedGratuity.EarnedGratuityStatus.Expired)
                {
                    try
                    {
                        Profile       pf = eg.UserProfile;
                        LogbookBackup lb = new LogbookBackup(pf);

                        EventRecorder.LogCall("Nightly run: backing up to {storage} for user {user}", sid.ToString(), eg.Username);

                        switch (sid)
                        {
                        case StorageID.Dropbox:
                            await BackupDropbox(lb, pf, sb, sbFailures).ConfigureAwait(false);

                            break;

                        case StorageID.OneDrive:
                            await BackupOneDrive(lb, pf, sb, sbFailures).ConfigureAwait(false);

                            break;

                        case StorageID.GoogleDrive:
                            await BackupGoogleDrive(lb, pf, sb, sbFailures).ConfigureAwait(false);

                            break;

                        default:
                            break;
                        }
                    }
                    catch (Exception ex) when(!(ex is OutOfMemoryException))
                    {
                        string szError = String.Format(CultureInfo.CurrentCulture, "eg user={0}{1}\r\n\r\n{2}\r\n\r\n{3}", eg == null ? "NULL eg!" : eg.Username, (eg != null && eg.UserProfile == null) ? " NULL PROFILE" : string.Empty, sbFailures.ToString(), sb.ToString());

                        util.NotifyAdminException("ERROR running nightly backup", new MyFlightbookException(szError, ex));
                    }
                    finally
                    {
                        lock (lockObj)
                        {
                            using (StreamWriter swSuccess = new StreamWriter(szBackups, true, Encoding.UTF8))
                                using (StreamWriter swFailure = new StreamWriter(szBackupFailures, true, Encoding.UTF8))
                                {
                                    // Regardless of what happens, write this to the file (in case something dies).
                                    string sz = sb.ToString();
                                    if (!String.IsNullOrWhiteSpace(sz))
                                    {
                                        swSuccess.WriteLine(sz.Trim());
                                    }
                                    sz = sbFailures.ToString();
                                    if (!String.IsNullOrWhiteSpace(sz))
                                    {
                                        swFailure.WriteLine(sz.Trim());
                                    }

                                    swSuccess.Flush();
                                    swFailure.Flush();
                                }
                        }
                    }
                }
            }

            using (StreamReader srSuccess = new StreamReader(szBackups, Encoding.UTF8))
                using (StreamReader srFailure = new StreamReader(szBackupFailures, Encoding.UTF8)) {
                    util.NotifyAdminEvent("Cloud Backup report", srFailure.ReadToEnd() + srSuccess.ReadToEnd(), ProfileRoles.maskCanReport);
                }

            // if we are here, we should be able to delete the temp files
            try
            {
                File.Delete(szBackups);
                File.Delete(szBackupFailures);
            }
            finally {  }

            return(true);
        }