Example #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.SelectedTab = tabID.actMyClubs;

        if (!IsPostBack)
        {
            expandoCreateClub.ExpandoLabel.Font.Bold = true;
            UserState = Page.User.Identity.IsAuthenticated ? (EarnedGrauity.UserQualifies(Page.User.Identity.Name, Gratuity.GratuityTypes.CreateClub) ? AuthState.Authorized : AuthState.Unauthorized) : AuthState.Unauthenticated;

            vcNew.ActiveClub = new Club();

            switch (UserState)
            {
            case AuthState.Unauthenticated:
                pnlCreateClub.Visible = pnlYourClubs.Visible = false;
                lblTrialStatus.Text   = Branding.ReBrand(Resources.Club.MustBeMember);
                break;

            case AuthState.Unauthorized:
                lblTrialStatus.Text     = Branding.ReBrand(Resources.Club.ClubCreateTrial);
                vcNew.ActiveClub.Status = Club.ClubStatus.Promotional;
                break;

            case AuthState.Authorized:
                lblTrialStatus.Text     = Branding.ReBrand(Resources.Club.ClubCreateNoTrial);
                vcNew.ActiveClub.Status = Club.ClubStatus.OK;
                break;
            }

            Refresh();
        }
    }
        /// <summary>
        /// Batch job to send all of the nightly/monthly email.
        /// </summary>
        public async void NightlyRun()
        {
            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();
            }

            // Send out any notices of pending gratuity expirations
            List <EarnedGrauity> lstEg = EarnedGrauity.GratuitiesForUser(string.Empty, Gratuity.GratuityTypes.Unknown);

            if (!String.IsNullOrEmpty(UserRestriction))
            {
                lstEg.RemoveAll(eg => eg.Username.CompareCurrentCultureIgnoreCase(UserRestriction) != 0);
            }
            lstEg.ForEach((eg) => { eg.SendReminderIfNeeded(); });
        }
    private void InitDonations()
    {
        List <Gratuity> lstKnownGratuities = new List <Gratuity>(Gratuity.KnownGratuities);

        lstKnownGratuities.Sort((g1, g2) => { return(g1.Threshold.CompareTo(g2.Threshold)); });
        rptAvailableGratuities.DataSource = lstKnownGratuities;
        rptAvailableGratuities.DataBind();

        pnlPaypalCanceled.Visible = util.GetStringParam(Request, "pp").CompareCurrentCultureIgnoreCase("canceled") == 0;
        pnlPaypalSuccess.Visible  = util.GetStringParam(Request, "pp").CompareCurrentCultureIgnoreCase("success") == 0;
        lblDonatePrompt.Text      = Branding.ReBrand(Resources.LocalizedText.DonatePrompt);
        gvDonations.DataSource    = Payment.RecordsForUser(User.Identity.Name);
        gvDonations.DataBind();

        List <EarnedGrauity> lst = EarnedGrauity.GratuitiesForUser(User.Identity.Name, Gratuity.GratuityTypes.Unknown);

        lst.RemoveAll(eg => eg.CurrentStatus == EarnedGrauity.EarnedGratuityStatus.Expired);
        if (pnlEarnedGratuities.Visible = (lst.Count > 0))
        {
            rptEarnedGratuities.DataSource = lst;
            rptEarnedGratuities.DataBind();
        }
    }
Example #4
0
    protected override MFBImageInfo UploadForUser(string szUser, HttpPostedFile pf, string szComment)
    {
        string szTail     = Request.Form["txtAircraft"];
        int    idAircraft = Aircraft.idAircraftUnknown;
        bool   fUseID     = util.GetIntParam(Request, "id", 0) != 0;

        if (String.IsNullOrEmpty(szTail))
        {
            throw new MyFlightbookException(Resources.WebService.errBadTailNumber);
        }
        if (fUseID)
        {
            if (!int.TryParse(szTail, out idAircraft) || idAircraft == Aircraft.idAircraftUnknown)
            {
                throw new MyFlightbookException(Resources.WebService.errBadTailNumber);
            }
        }
        else if (szTail.Length > Aircraft.maxTailLength || szTail.Length < 3)
        {
            throw new MyFlightbookException(Resources.WebService.errBadTailNumber);
        }

        // Check if authorized for videos
        if (MFBImageInfo.ImageTypeFromFile(pf) == MFBImageInfo.ImageFileType.S3VideoMP4 && !EarnedGrauity.UserQualifies(szUser, Gratuity.GratuityTypes.Videos))
        {
            throw new MyFlightbookException(Branding.ReBrand(Resources.LocalizedText.errNotAuthorizedVideos));
        }

        UserAircraft ua = new UserAircraft(szUser);

        ua.InvalidateCache();   // in case the aircraft was added but cache is not refreshed.
        Aircraft[] rgac = ua.GetAircraftForUser();

        Aircraft ac = null;

        if (fUseID)
        {
            ac = new Aircraft(idAircraft);
        }
        else
        {
            string szTailNormal = Aircraft.NormalizeTail(szTail);

            // Look for the aircraft in the list of the user's aircraft (that way you get the right version if it's a multi-version aircraft and no ID was specified
            // Hack for backwards compatibility with mobile apps and anonymous aircraft
            // Look to see if the tailnumber matches the anonymous tail
            ac = Array.Find <Aircraft>(rgac, uac =>
                                       (String.Compare(Aircraft.NormalizeTail(szTailNormal), Aircraft.NormalizeTail(uac.TailNumber), StringComparison.CurrentCultureIgnoreCase) == 0 ||
                                        String.Compare(szTail, uac.HackDisplayTailnumber, StringComparison.CurrentCultureIgnoreCase) == 0));
        }

        if (ac == null || !ua.CheckAircraftForUser(ac))
        {
            throw new MyFlightbookException(Resources.WebService.errNotYourAirplane);
        }

        mfbImageAircraft.Key = ac.AircraftID.ToString(System.Globalization.CultureInfo.InvariantCulture);
        return(new MFBImageInfo(MFBImageInfo.ImageClass.Aircraft, mfbImageAircraft.Key, pf, szComment, null));
    }
        private async Task <bool> BackupToCloud()
        {
            System.Text.StringBuilder sb         = new System.Text.StringBuilder();
            System.Text.StringBuilder sbFailures = new System.Text.StringBuilder();
            List <EarnedGrauity>      lstUsersWithCloudBackup = EarnedGrauity.GratuitiesForUser(string.Empty, Gratuity.GratuityTypes.CloudBackup);

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

            foreach (EarnedGrauity eg in lstUsersWithCloudBackup)
            {
                StorageID sid = StorageID.None;
                if (eg.UserProfile != null && ((sid = eg.UserProfile.BestCloudStorage) != StorageID.None) && eg.CurrentStatus != EarnedGrauity.EarnedGratuityStatus.Expired)
                {
                    Profile pf = eg.UserProfile;

                    LogbookBackup lb = new LogbookBackup(pf);

                    switch (sid)
                    {
                    case StorageID.Dropbox:
                    {
                        MFBDropbox.TokenStatus ts = new MFBDropbox().ValidateDropboxToken(pf, true, true);
                        if (ts == MFBDropbox.TokenStatus.None)
                        {
                            continue;
                        }

                        try
                        {
                            Dropbox.Api.Files.FileMetadata result = null;
                            result = await lb.BackupToDropbox(Branding.CurrentBrand);

                            sb.AppendFormat(CultureInfo.CurrentCulture, "Dropbox: user {0} ", pf.UserName);
                            if (ts == MFBDropbox.TokenStatus.oAuth1)
                            {
                                sb.Append("Token UPDATED from oauth1! ");
                            }
                            sb.AppendFormat(CultureInfo.CurrentCulture, "Logbook backed up for user {0}...", pf.UserName);
                            System.Threading.Thread.Sleep(0);
                            result = await lb.BackupImagesToDropbox(Branding.CurrentBrand);

                            System.Threading.Thread.Sleep(0);
                            sb.AppendFormat(CultureInfo.CurrentCulture, "and images backed up for user {0}.\r\n \r\n", pf.UserName);
                        }
                        catch (Dropbox.Api.ApiException <Dropbox.Api.Files.UploadError> ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (Dropbox.Api.ApiException<Dropbox.Api.Files.UploadError) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            string szMessage = (ex.ErrorResponse.IsPath && ex.ErrorResponse.AsPath != null && ex.ErrorResponse.AsPath.Value.Reason.IsInsufficientSpace) ? Resources.LocalizedText.DropboxErrorOutOfSpace : ex.Message;
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, szMessage, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (Dropbox.Api.AuthException ex)
                        {
                            // De-register dropbox.
                            pf.DropboxAccessToken = string.Empty;
                            pf.FCommit();
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (AuthException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (Dropbox.Api.BadInputException ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (BadInputException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), false, false);
                        }
                        catch (Dropbox.Api.HttpException ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (HttpException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (Dropbox.Api.AccessException ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (AccessException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (Dropbox.Api.DropboxException ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (Base dropbox exception) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            // De-register dropbox.
                            pf.DropboxAccessToken = string.Empty;
                            pf.FCommit();
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (UnauthorizedAccess) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (MyFlightbookException ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (MyFlightbookException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (System.IO.FileNotFoundException ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user: FileNotFoundException, no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message);
                        }
                        catch (Exception ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (Unknown Exception), no notification sent {0}: {1} {2}\r\n\r\n{3}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message, ex.StackTrace);
                            if (ex.InnerException != null)
                            {
                                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Inner exception: {0}\r\n{1}", ex.InnerException.Message, ex.InnerException.StackTrace);
                            }
                        }
                    }
                    break;

                    case StorageID.OneDrive:
                    {
                        try
                        {
                            if (pf.OneDriveAccessToken == null)
                            {
                                throw new UnauthorizedAccessException();
                            }

                            Microsoft.OneDrive.Sdk.Item item = null;
                            OneDrive od = new OneDrive(pf.OneDriveAccessToken);
                            item = await lb.BackupToOneDrive(od);

                            sb.AppendFormat(CultureInfo.CurrentCulture, "OneDrive: user {0} ", pf.UserName);
                            sb.AppendFormat(CultureInfo.CurrentCulture, "Logbook backed up for user {0}...", pf.UserName);
                            System.Threading.Thread.Sleep(0);
                            item = await lb.BackupImagesToOneDrive(od, Branding.CurrentBrand);

                            System.Threading.Thread.Sleep(0);
                            sb.AppendFormat(CultureInfo.CurrentCulture, "and images backed up for user {0}.\r\n \r\n", pf.UserName);

                            // if we are here we were successful, so save the updated refresh token
                            if (String.Compare(pf.OneDriveAccessToken.RefreshToken, od.AuthState.RefreshToken, StringComparison.Ordinal) != 0)
                            {
                                pf.OneDriveAccessToken.RefreshToken = od.AuthState.RefreshToken;
                                pf.FCommit();
                            }
                        }
                        catch (Microsoft.OneDrive.Sdk.OneDriveException ex)
                        {
                            string szMessage = OneDrive.MessageForException(ex);
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (OneDriveException) {0}: {1}\r\n\r\n", pf.UserName, szMessage + " " + ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.OneDriveFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.OneDriveFailure, pf.UserFullName, szMessage, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (MyFlightbookException ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (MyFlightbookException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.OneDriveFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.OneDriveFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            // De-register oneDrive.
                            pf.OneDriveAccessToken = null;
                            pf.FCommit();
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (UnauthorizedAccess) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.OneDriveFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.OneDriveFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (System.IO.FileNotFoundException ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user: FileNotFoundException, no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message);
                        }
                        catch (Exception ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (Unknown Exception), no notification sent {0}: {1} {2}\r\n\r\n{3}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message, ex.StackTrace);
                        }
                    }
                    break;

                    case StorageID.GoogleDrive:
                    {
                        try
                        {
                            if (pf.GoogleDriveAccessToken == null)
                            {
                                throw new UnauthorizedAccessException();
                            }

                            GoogleDrive gd         = new GoogleDrive(pf.GoogleDriveAccessToken);
                            bool        fRefreshed = await gd.RefreshAccessToken();

                            sb.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive: user {0} ", pf.UserName);
                            IReadOnlyDictionary <string, string> meta = await lb.BackupToGoogleDrive(gd, Branding.CurrentBrand);

                            if (meta != null)
                            {
                                sb.AppendFormat(CultureInfo.CurrentCulture, "Logbook backed up for user {0}...", pf.UserName);
                            }
                            System.Threading.Thread.Sleep(0);
                            meta = await lb.BackupImagesToGoogleDrive(gd, Branding.CurrentBrand);

                            System.Threading.Thread.Sleep(0);
                            if (meta != null)
                            {
                                sb.AppendFormat(CultureInfo.CurrentCulture, "and images backed up for user {0}.\r\n \r\n", pf.UserName);
                            }

                            // if we are here we were successful, so save the updated refresh token
                            if (fRefreshed)
                            {
                                pf.FCommit();
                            }
                        }
                        catch (MyFlightbookException ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user (MyFlightbookException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.GoogleDriveFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.GoogleDriveFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            // De-register GoogleDrive.
                            pf.GoogleDriveAccessToken = null;
                            pf.FCommit();
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user (UnauthorizedAccess) {0}: {1}\r\n\r\n", pf.UserName, ex.Message);
                            util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.GoogleDriveFailureSubject, ActiveBrand),
                                            Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.GoogleDriveFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false);
                        }
                        catch (System.IO.FileNotFoundException ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user: FileNotFoundException, no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message);
                        }
                        catch (Exception ex)
                        {
                            sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user (Unknown Exception), no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message);
                        }
                    }
                    break;

                    case StorageID.iCloud:
                        break;

                    default:
                        break;
                    }
                }
            }
            ;

            util.NotifyAdminEvent("Dropbox report", sbFailures.ToString() + sb.ToString(), ProfileRoles.maskCanReport);
            return(true);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        byte[] param      = Request.BinaryRead(Request.ContentLength);
        string strRequest = Encoding.ASCII.GetString(param);

        bool   fSandbox    = util.GetStringParam(Request, "sandbox").Length > 0;
        string strResponse = PayPalIPN.VerifyResponse(fSandbox, strRequest);

        string szUser            = util.GetStringParam(Request, "custom");
        string szProductID       = util.GetStringParam(Request, "os1");
        string szAmount          = util.GetStringParam(Request, "mc_gross");
        string szTransactionID   = util.GetStringParam(Request, "txn_id");
        string szTransactionType = util.GetStringParam(Request, "txn_type");
        string szCurrency        = util.GetStringParam(Request, "mc_currency");
        string szReasonCode      = util.GetStringParam(Request, "reason_code");
        string szParentTxnID     = util.GetStringParam(Request, "parent_txn_id");
        string szFee             = util.GetStringParam(Request, "mc_fee");

        if (strResponse == "VERIFIED")
        {
            //check the payment_status is Completed
            //check that txn_id has not been previously processed
            //check that receiver_email is your Primary PayPal email
            //check that payment_amount/payment_currency are correct
            //process payment

            StringBuilder sbErr = new StringBuilder();
            decimal       d;
            if (!Decimal.TryParse(szAmount, NumberStyles.Any, CultureInfo.InvariantCulture, out d))
            {
                sbErr.AppendFormat(CultureInfo.CurrentCulture, "Invalid payment amount: {0}\r\n\r\n", szAmount);
                d = 0.0M;
            }

            if (d == 0.0M)
            {
                sbErr.AppendFormat(CultureInfo.CurrentCulture, "Payment amount of 0.0!\r\n\r\n");
            }
            Payment.TransactionType transType = (d > 0) ? Payment.TransactionType.Payment : Payment.TransactionType.Refund;

            decimal fee = 0.0M;
            if (!Decimal.TryParse(szFee, NumberStyles.Any, CultureInfo.InvariantCulture, out fee))
            {
                fee = 0.0M;
            }

            if (String.IsNullOrEmpty(szTransactionID))
            {
                sbErr.AppendFormat(CultureInfo.CurrentCulture, "No transaction ID is specified!\r\n\r\n");
            }

            Collection <Payment> lst = Payment.RecordsWithID(szTransactionID);
            // Note: it's possible via e-check to get two notifications, one that is pending and one that is completed.
            // Pending shows as payment_status: Pending, completed shows as payment_status=Completed
            if (lst.Count > 0)
            {
                sbErr.AppendFormat(CultureInfo.CurrentCulture, "Duplicate transaction ID: {0}\r\n\r\n", szTransactionID);
            }

            switch (transType)
            {
            case Payment.TransactionType.Payment:
                if (String.Compare(szTransactionType, "web_accept", StringComparison.OrdinalIgnoreCase) != 0)
                {
                    sbErr.AppendFormat(CultureInfo.CurrentCulture, "Unknown transaction type: {0}\r\n\r\n", szTransactionType);
                }
                break;

            case Payment.TransactionType.Refund:
            {
                if (String.IsNullOrEmpty(szReasonCode))
                {
                    sbErr.AppendFormat(CultureInfo.CurrentCulture, "Refund with no reason code?\r\n\r\n");
                }
                if (String.IsNullOrEmpty(szParentTxnID))
                {
                    sbErr.AppendFormat(CultureInfo.CurrentCulture, "Refund with no parent transaction\r\n\r\n");
                }
                lst = Payment.RecordsWithID(szParentTxnID);
                if (lst.Count > 1)
                {
                    sbErr.AppendFormat(CultureInfo.CurrentCulture, "Multiple records found for parent transaction of refund\r\n\r\n");
                }
                else if (lst.Count == 0)
                {
                    sbErr.AppendFormat(CultureInfo.CurrentCulture, "No parent record found for parent transaction of refund\r\n\r\n");
                }
                szUser = lst[0].Username;
            }
            break;

            default:
                break;
            }

            // Check for a valid user
            Profile pf = MyFlightbook.Profile.GetUser(szUser);
            if (String.IsNullOrEmpty(pf.UserName))
            {
                sbErr.AppendFormat(CultureInfo.CurrentCulture, "Transaction request for invalid user: {0}\r\n\r\n", szUser);
            }

            if (String.Compare(szCurrency, "USD", StringComparison.OrdinalIgnoreCase) != 0)
            {
                sbErr.AppendFormat(CultureInfo.CurrentCulture, "Invalid currency: {0}\r\n\r\n", szCurrency);
            }

            if (sbErr.Length > 0)
            {
                sbErr.AppendFormat(CultureInfo.CurrentCulture, "\r\n\r\nData:{0}", strRequest);
                util.NotifyAdminEvent("Paypal Payment failed", sbErr.ToString(), ProfileRoles.maskSiteAdminOnly);
            }
            else
            {
                try
                {
                    Payment p = new Payment(DateTime.Now, szUser, d, fee, transType, string.Empty, szTransactionID, strRequest);
                    if (fSandbox)
                    {
                        util.NotifyAdminEvent("Sandbox Trnasaction", "payment = " + Newtonsoft.Json.JsonConvert.SerializeObject(p), ProfileRoles.maskSiteAdminOnly);
                        return;
                    }
                    p.Commit();

                    EarnedGrauity.UpdateEarnedGratuities(p.Username, true);
                }
                catch (InvalidOperationException ex)
                {
                    util.NotifyAdminEvent("Paypal payment failed", String.Format(CultureInfo.InvariantCulture, "User: {0}, Amount: {1:C} TransactionID: {2} \r\n\r\nRaw data:\r\n\r\n {3}\r\n\r\nException:{4}\r\n{5}", szUser, d, szTransactionID, strRequest, ex.Message, ex.StackTrace), ProfileRoles.maskSiteAdminOnly);
                }
                finally
                {
                    util.NotifyAdminEvent(String.Format(CultureInfo.CurrentCulture, "{1}: {0:C}!", d, transType.ToString()), String.Format(CultureInfo.CurrentCulture, "User '{0}' ({1}, {2}) has donated {3:C}!\r\n\r\nAdditional Data:\r\n\r\n{4}", pf.UserName, pf.UserFullName, pf.Email, d, strRequest), ProfileRoles.maskCanManageMoney);

                    // Send a thank-you for payment to the donor
                    if (transType == Payment.TransactionType.Payment)
                    {
                        util.NotifyUser(Branding.ReBrand(Resources.LocalizedText.DonateThankYouTitle), String.Format(CultureInfo.CurrentCulture, Branding.ReBrand(Resources.EmailTemplates.DonationThankYou), pf.UserFullName), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), false, false);
                    }
                }
            }
        }
        else if (strResponse == "INVALID")
        {
            //log for manual investigation
            util.NotifyAdminEvent("Paypal Event INVALID", String.Format(CultureInfo.InvariantCulture, "Paypal event was Invalid: User={1}, productID={2}, amount=${3:#,#.00}\r\n\r\nstrRequest=\"{0}\"", strRequest, szUser, szProductID, szAmount), ProfileRoles.maskSiteAdminOnly);
        }
        else
        {
            //log response/ipn data for manual investigation
            util.NotifyAdminEvent("Paypal Event UNKNOWN", String.Format(CultureInfo.InvariantCulture, "Paypal event was UNKNOWN:\r\n\r\nstrRequest=\"{0}\"", strRequest), ProfileRoles.maskSiteAdminOnly);
        }
    }
    /// <summary>
    /// Initialize the edit form for a new flight (blank fields) or for editing of an existing flight
    /// </summary>
    /// <param name="idFlight">-1 for a new flight, otherwise the ID of the flight to load</param>
    /// <param name="fForceLoad">True to force load (e.g., an admin mode, or CFI editing a user's flight)</param>
    public void SetUpNewOrEdit(int idFlight, bool fForceLoad = false)
    {
        LogbookEntry le = new LogbookEntry()
        {
            User = Page.User.Identity.Name
        };

        InitBasicControls();

        // Initialize our logbook entry from the db or make it a new entry
        bool fAdminMode = (CurrentUser.CanSupport && (util.GetStringParam(Request, "a").Length > 0));

        IsAdmin = fForceLoad || fAdminMode;

        FlightID = idFlight;

        if (!le.FLoadFromDB(FlightID, Page.User.Identity.Name, LogbookEntry.LoadTelemetryOption.LoadAll, IsAdmin))
        {
            // if this isn't found, try again with a new flight (but tell the user of the error)
            lblError.Text = le.ErrorString;
            FlightID      = (le = new LogbookEntry()
            {
                User = Page.User.Identity.Name
            }).FlightID;
        }

        // check for CFI signing mode
        if (fForceLoad && !le.IsNewFlight)
        {
            if (le.User.CompareOrdinal(Page.User.Identity.Name) != 0 && le.CanEditThisFlight(Page.User.Identity.Name))
            {
                pnlPublic.Visible = pnlPictures.Visible = false;
                FlightUser        = le.User; // save the name of the owner of the flight.
            }
            else
            {
                throw new MyFlightbookException(String.Format(CultureInfo.InvariantCulture, "attempt by {0} to edit non-owned flight (owned by {1}) by non-instructor!", Page.User.Identity.Name, le.User));
            }
        }

        // Enable Admin Signature fix-up
        if (!le.IsNewFlight && le.CFISignatureState != LogbookEntryBase.SignatureState.None)
        {
            lblSigSavedHash.Text   = le.DecryptedFlightHash;
            lblSigCurrentHash.Text = le.DecryptedCurrentHash;

            if (le.CFISignatureState == LogbookEntry.SignatureState.Invalid)
            {
                pnlSigEdits.Visible = true;
                LogbookEntry leNew   = LogbookEntry.LogbookEntryFromHash(lblSigCurrentHash.Text);
                LogbookEntry leSaved = LogbookEntry.LogbookEntryFromHash(lblSigSavedHash.Text);
                rptDiffs.DataSource = leSaved.CompareTo(leNew, CurrentUser.UsesHHMM);
                rptDiffs.DataBind();
            }

            if (fAdminMode)
            {
                LogbookEntry.SignatureSanityCheckState sscs = le.AdminSignatureSanityCheckState;
                pnlAdminFixSignature.Visible = true;
                lblSigSavedState.Text        = le.CFISignatureState.ToString();
                lblSigSanityCheck.Text       = sscs.ToString();
            }
        }

        // If the user has entered another flight this session, default to that date rather than today
        if (Session[keyLastEntryDate] != null && FlightID == LogbookEntry.idFlightNew)
        {
            le.Date = (DateTime)Session[keyLastEntryDate];
        }

        // see if we have a pending in-progress flight
        if (FlightID == LogbookEntry.idFlightNew && Session[keySessionInProgress] != null)
        {
            le = (LogbookEntry)Session[keySessionInProgress];
        }
        Session[keySessionInProgress] = null; // clear it out regardless.

        UseLastTail = true;

        // If a repeat or a reverse is requested, then clone and/or reverse it.
        le = CloneOrReverse(le);

        // If this is a shared flight, initialize from that.
        le = SharedFlight(le);

        // If we're setting up a new flight and last flight had an ending hobbs, initialize with that
        // clear the cookie, if present, regardless.
        HttpCookie c = Request.Cookies[keyCookieLastEndingHobbs];

        if (c != null)
        {
            if (le.IsNewFlight)
            {
                decimal hobbsEnd;
                if (decimal.TryParse(c.Value.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out hobbsEnd))
                {
                    le.HobbsStart = hobbsEnd;
                }
            }
            Response.Cookies[keyCookieLastEndingHobbs].Expires = DateTime.Now.AddDays(-1);   // clear it.
        }

        SetUpAircraftForFlight(le);

        InitFormFromLogbookEntry(le);

        bool fCanDoVideo = EarnedGrauity.UserQualifies(Page.User.Identity.Name, Gratuity.GratuityTypes.Videos);

        mfbMFUFlightImages.IncludeVideos = fCanDoVideo;
        mfbVideoEntry1.CanAddVideos      = fCanDoVideo;
        mfbVideoEntry1.FlightID          = le.FlightID;
        lblPixForFlight.Text             = fCanDoVideo ? Resources.LogbookEntry.HeaderImagesVideosForFlight : Resources.LogbookEntry.HeaderImagesForFlight;

        FinalizeSetupForFlight(le);

        mfbDate.Focus();
    }
    protected override MFBImageInfo UploadForUser(string szUser, HttpPostedFile pf, string szComment)
    {
        int idFlight = Convert.ToInt32(Request.Form["idFlight"], CultureInfo.InvariantCulture);

        if (idFlight <= 0)
        {
            throw new MyFlightbookException(Resources.WebService.errInvalidFlight);
        }

        LogbookEntry le = new LogbookEntry();

        le.FlightID = idFlight;
        if (!le.FLoadFromDB(le.FlightID, szUser, LogbookEntry.LoadTelemetryOption.None))
        {
            throw new MyFlightbookException(Resources.WebService.errFlightDoesntExist);
        }
        if (le.User != szUser)
        {
            throw new MyFlightbookException(Resources.WebService.errFlightNotYours);
        }

        // Check if authorized for videos
        if (MFBImageInfo.ImageTypeFromFile(pf) == MFBImageInfo.ImageFileType.S3VideoMP4 && !EarnedGrauity.UserQualifies(szUser, Gratuity.GratuityTypes.Videos))
        {
            throw new MyFlightbookException(Branding.ReBrand(Resources.LocalizedText.errNotAuthorizedVideos));
        }

        LatLong ll    = null;
        string  szLat = Request.Form["txtLat"];
        string  szLon = Request.Form["txtLon"];

        if (!String.IsNullOrEmpty(szLat) && !String.IsNullOrEmpty(szLon))
        {
            ll = LatLong.TryParse(szLat, szLon, CultureInfo.InvariantCulture);
        }

        mfbImageFlight.Key = le.FlightID.ToString(CultureInfo.InvariantCulture);
        return(new MFBImageInfo(MFBImageInfo.ImageClass.Flight, mfbImageFlight.Key, pf, szComment, ll));
    }