protected void gvFlightLogs_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e == null)
        {
            throw new ArgumentNullException(nameof(e));
        }

        if (e.CommandName.CompareOrdinal("_revSig") == 0)
        {
            int idFlight = Convert.ToInt32(e.CommandArgument, CultureInfo.InvariantCulture);
            // Can't edit a LogbookEntryDisplay, so load a logbookentry
            LogbookEntry le = new LogbookEntry();
            if (le.FLoadFromDB(idFlight, User))
            {
                try
                {
                    le.RevokeSignature(Page.User.Identity.Name);
                    FlushCache();
                    BindData(Data);
                }
                catch (InvalidOperationException ex)
                {
                    ((Label)((Control)e.CommandSource).NamingContainer.FindControl("lblErr")).Text = ex.Message;
                }
            }
        }
    }
Example #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.Master.SelectedTab = tabID.tabUnknown;
            int id = util.GetIntParam(Request, "id", -1);
            if (id >= 0)
            {
                LogbookEntry le = new LogbookEntry();
                if (le.FLoadFromDB(id, User.Identity.Name))
                {
                    ViewState[keyFlightEntry] = le;
                }
                else
                {
                    pnlShareOrNot.Visible = false;
                    pnlNotYours.Visible   = true;
                }
            }
        }

        mfbMiniFacebook.FlightEntry = (LogbookEntry)ViewState[keyFlightEntry];
        if (mfbMiniFacebook.FlightEntry != null && mfbMiniFacebook.FlightEntry.fIsPublic)
        {
            Response.Redirect(mfbMiniFacebook.FBRedirURL.OriginalString);
        }
    }
    protected void btnAdminFixSignature_Click(object sender, EventArgs e)
    {
        LogbookEntry le = new LogbookEntry();

        le.FLoadFromDB(FlightID, FlightUser, LogbookEntry.LoadTelemetryOption.None, true);
        le.AdminSignatureSanityFix(false);
        Response.Redirect(Request.Url.OriginalString);
    }
Example #4
0
    protected void mfbEditFlight1_FlightUpdated(object sender, EventArgs e)
    {
        mvFlightToSign.SetActiveView(vwEntrySummary);
        int          idFlight = (int)ViewState[szKeyVSIDFlight];
        LogbookEntry le       = new LogbookEntry();

        le.FLoadFromDB(idFlight, string.Empty, LogbookEntry.LoadTelemetryOption.None, true);
        Flight = le;    // force a refresh
    }
Example #5
0
        protected void UpdateInvalidSigs()
        {
            List <int> lstSigned = new List <int>();

            // Pick up where we left off.
            int offset = Convert.ToInt32(hdnSigOffset.Value, CultureInfo.InvariantCulture);

            const int chunkSize = 250;

            DBHelper dbh = new DBHelper("SELECT idFlight FROM Flights WHERE signatureState<>0 LIMIT ?lim, ?chunk");

            dbh.CommandArgs.Timeout = 300;  // up to 300 seconds.
            dbh.ReadRows((comm) => { comm.Parameters.AddWithValue("lim", offset); comm.Parameters.AddWithValue("chunk", chunkSize); },
                         (dr) => { lstSigned.Add(Convert.ToInt32(dr["idFlight"], CultureInfo.InvariantCulture)); });

            lstSigned.ForEach((idFlight) =>
            {
                LogbookEntry le = new LogbookEntry();
                le.FLoadFromDB(idFlight, string.Empty, LogbookEntry.LoadTelemetryOption.None, true);
                if (le.AdminSignatureSanityCheckState != LogbookEntry.SignatureSanityCheckState.OK)
                {
                    // see if we can auto-fix these.  Auto-fixed = decrypted hash matches case insenstive and trimmed.
                    if (le.DecryptedCurrentHash.Trim().CompareCurrentCultureIgnoreCase(le.DecryptedFlightHash.Trim()) == 0)
                    {
                        lstAutoFix.Add(le);
                        le.AdminSignatureSanityFix(true);
                    }
                    else
                    {
                        lstToFix.Add(le);
                    }
                }
            });

            offset += lstSigned.Count;

            lblSigResults.Text = String.Format(CultureInfo.CurrentCulture, "Found {0} signed flights, {1} appear to have problems, {2} were autofixed (capitalization or leading/trailing whitespace)", offset, lstToFix.Count, lstAutoFix.Count);

            if (lstSigned.Any())
            {
                // we have more to go, so show the progress view that auto-clicks for the next chunk.
                mvCheckSigs.SetActiveView(vwSigProgress);
                hdnSigOffset.Value = offset.ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                mvCheckSigs.SetActiveView(vwInvalidSigs);                                  // stop pressing
                hdnSigOffset.Value             = 0.ToString(CultureInfo.InvariantCulture); // and reset the offset so you can press it again.
                gvInvalidSignatures.DataSource = lstToFix;
                gvInvalidSignatures.DataBind();
                gvAutoFixed.DataSource = lstAutoFix;
                gvAutoFixed.DataBind();
            }
        }
Example #6
0
 protected void lnkDeletedata_Click(object sender, EventArgs e)
 {
     if (FlightID >= 0)
     {
         LogbookEntry le = new LogbookEntry();
         if (le.FLoadFromDB(FlightID, Page.User.Identity.Name))
         {
             le.FlightData = null;
             le.FCommit(true);
             DeleteData();
         }
     }
     else
     {
         DeleteData();
     }
 }
    /// <summary>
    /// Loads the specified flight into m_le, cached to avoid excess DB thrashing.
    /// </summary>
    /// <param name="idFlight">ID of the flight to load</param>
    protected void LoadLogbookEntry(int idFlight)
    {
        string szCacheKey = KeyCacheFlight(idFlight);

        Title = (string)GetLocalResourceObject("PageResource1.Title");

        m_le = null;
        if (!IsPostBack || Session[szCacheKey] == null)
        {
            m_le = new LogbookEntry();

            bool fIsAdmin = (util.GetIntParam(Request, "a", 0) != 0 && MyFlightbook.Profile.GetUser(Page.User.Identity.Name).CanSupport);
            if (m_le.FLoadFromDB(idFlight, User.Identity.Name, LogbookEntry.LoadTelemetryOption.LoadAll, true))
            {
                if (!m_le.HasFlightData)
                {
                    throw new MyFlightbookException(String.Format(CultureInfo.CurrentCulture, Resources.FlightData.errNoDataForFlight, idFlight));
                }

                // check to see if you own the flight.  You own it if:
                // a) Admin
                // b) username=Page identity, or
                // c) authorized by student.
                if (!fIsAdmin && String.Compare(m_le.User, User.Identity.Name, StringComparison.Ordinal) != 0)
                {
                    // check for authorized by student
                    CFIStudentMap     sm      = new CFIStudentMap(Page.User.Identity.Name);
                    InstructorStudent student = sm.GetInstructorStudent(sm.Students, m_le.User);
                    if (student == null || !student.CanViewLogbook)
                    {
                        throw new MyFlightbookException(Resources.SignOff.ViewStudentLogbookUnauthorized);
                    }
                }

                Session[szCacheKey] = m_le;
            }
            else
            {
                throw new MyFlightbookException(String.Format(CultureInfo.CurrentCulture, Resources.FlightData.errCantLoadFlight, idFlight.ToString(CultureInfo.InvariantCulture), m_le.ErrorString));
            }
        }
        else
        {
            m_le = (LogbookEntry)Session[szCacheKey];
        }
    }
Example #8
0
    protected void gvInvalidSignatures_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int idFlight = e.CommandArgument.ToString().SafeParseInt(LogbookEntry.idFlightNone);

        if (idFlight != LogbookEntry.idFlightNone)
        {
            LogbookEntry le = new LogbookEntry();
            le.FLoadFromDB(idFlight, string.Empty, LogbookEntry.LoadTelemetryOption.None, true);
            if (le.AdminSignatureSanityFix(e.CommandName.CompareTo("ForceValidity") == 0))
            {
                List <LogbookEntry> lst = (List <LogbookEntry>)ViewState["InvalidSigs"];
                lst.RemoveAll(l => l.FlightID == idFlight);
                gvInvalidSignatures.DataSource = ViewState["InvalidSigs"] = lst;
                gvInvalidSignatures.DataBind();
            }
        }
    }
Example #9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Master.SelectedTab = tabID.tabUnknown;

            if (!IsPostBack)
            {
                int idFlight = util.GetIntParam(Request, "idFlight", LogbookEntryCore.idFlightNew);
                hdnFlightID.Value = idFlight.ToString(CultureInfo.InvariantCulture);

                // Remember the return URL, but only if it is relative (for security)
                string szReturnURL = util.GetStringParam(Request, "Ret");
                if (Uri.IsWellFormedUriString(szReturnURL, UriKind.Relative))
                {
                    hdnReturnURL.Value = szReturnURL;
                }

                if (idFlight == LogbookEntryCore.idFlightNew)
                {
                    Response.Redirect(hdnReturnURL.Value);
                }

                LogbookEntry le = new LogbookEntry();
                if (!le.FLoadFromDB(idFlight, string.Empty, LogbookEntryCore.LoadTelemetryOption.None, true))
                {
                    lblError.Text = Resources.SignOff.errInvalidFlight;
                }
                else if (!le.CanSignThisFlight(Page.User.Identity.Name, out string szError))
                {
                    lblError.Text = szError;
                }
                else
                {
                    pnlSign.Visible = true;
                    lblHeader.Text  = String.Format(CultureInfo.CurrentCulture, Resources.SignOff.SignFlightHeader, System.Web.HttpUtility.HtmlEncode(MyFlightbook.Profile.GetUser(le.User).UserFullName));

                    mfbSignFlight1.ShowCancel = hdnReturnURL.Value.Length > 0;
                }
                mfbSignFlight1.Flight = le;
            }

            mfbSignFlight1.CFIProfile = Profile.GetUser(Page.User.Identity.Name);
            mfbSignFlight1.PrepSignAndNext();   // show Sign this and next, in case there are other flights to sign.
        }
Example #10
0
    protected void gvFlightLogs_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e == null)
        {
            throw new ArgumentNullException(nameof(e));
        }

        if (e.CommandName.CompareOrdinal("_revSig") == 0)
        {
            int idFlight = Convert.ToInt32(e.CommandArgument, CultureInfo.InvariantCulture);
            // Can't edit a LogbookEntryDisplay, so load a logbookentry
            LogbookEntry le = new LogbookEntry();
            if (le.FLoadFromDB(idFlight, User))
            {
                le.RevokeSignature(Page.User.Identity.Name);
                FlushCache();
                BindData(Data);
            }
        }
    }
Example #11
0
    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
        {
            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 && !EarnedGratuity.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));
    }
Example #12
0
        public static void ToggleIgnore(int idFlight, bool fIgnore)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated || String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
            {
                throw new UnauthorizedAccessException();
            }
            LogbookEntryBase le = new LogbookEntry();

            if (!le.FLoadFromDB(idFlight, HttpContext.Current.User.Identity.Name))
            {
                throw new UnauthorizedAccessException();
            }

            if (le.IsNewFlight) // should never happen.
            {
                throw new InvalidOperationException("Flight doesn't exist");
            }

            SetIgnoreFlagForFlight(le, fIgnore);
            le.CommitRoute();  // Save the change, but hold on to the flight in the list for now so that you can uncheck it.
        }
Example #13
0
        protected void gvInvalidSignatures_RowCommand(object sender, CommandEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException(nameof(e));
            }
            int idFlight = e.CommandArgument.ToString().SafeParseInt(LogbookEntry.idFlightNone);

            if (idFlight != LogbookEntry.idFlightNone)
            {
                LogbookEntry le = new LogbookEntry();
                le.FLoadFromDB(idFlight, string.Empty, LogbookEntry.LoadTelemetryOption.None, true);
                if (le.AdminSignatureSanityFix(e.CommandName.CompareOrdinalIgnoreCase("ForceValidity") == 0))
                {
                    List <LogbookEntry> lst = lstToFix;
                    lst.RemoveAll(l => l.FlightID == idFlight);
                    gvInvalidSignatures.DataSource = lstToFix = lst;
                    gvInvalidSignatures.DataBind();
                }
            }
        }
Example #14
0
    protected void gvData_RowCommand(object sender, CommandEventArgs e)
    {
        if (e == null)
        {
            throw new ArgumentNullException(nameof(e));
        }

        int index = Convert.ToInt32(e.CommandArgument, System.Globalization.CultureInfo.InvariantCulture);
        TelemetryReference ted = BoundData[index];
        LogbookEntry       le  = new LogbookEntry();

        le.FLoadFromDB(ted.FlightID.Value, Page.User.Identity.Name, LogbookEntry.LoadTelemetryOption.LoadAll, true);

        if (e.CommandName == "MapEm")
        {
            using (FlightData fd = new FlightData())
            {
                if (fd.ParseFlightData(le.FlightData))
                {
                    mfbGMapStraight.Map.Path      = fd.GetPath();
                    mfbGMapReconstituded.Map.Path = ted.GoogleData.DecodedPath();
                    pnlMaps.Visible = true;
                }
            }
        }
        else if (e.CommandName == "FromFlights")
        {
            le.Telemetry.Compressed = 0;    // no longer know the compressed
            le.MoveTelemetryFromFlightEntry();
            UpdateElement(index, le.Telemetry);
        }
        else if (e.CommandName == "ToFlights")
        {
            le.MoveTelemetryToFlightEntry();
            UpdateElement(index, le.Telemetry);
        }
    }
Example #15
0
        protected void UpdateInvalidSigs()
        {
            List <LogbookEntry> lst        = new List <LogbookEntry>();
            List <LogbookEntry> lstAutoFix = new List <LogbookEntry>();

            List <int> lstIDs = new List <int>();
            DBHelper   dbh    = new DBHelper("SELECT idFlight FROM Flights WHERE signatureState<>0 ORDER BY Username ASC, Date DESC");

            dbh.CommandArgs.Timeout = 300;  // up to 300 seconds.
            dbh.ReadRows((comm) => { }, (dr) => { lstIDs.Add(Convert.ToInt32(dr["idFlight"], CultureInfo.InvariantCulture)); });

            int cTotalSigned = lstIDs.Count;

            lstIDs.ForEach((idFlight) =>
            {
                LogbookEntry le = new LogbookEntry();
                le.FLoadFromDB(idFlight, string.Empty, LogbookEntry.LoadTelemetryOption.None, true);
                if (le.AdminSignatureSanityCheckState != LogbookEntry.SignatureSanityCheckState.OK)
                {
                    // see if we can auto-fix these.  Auto-fixed = decrypted hash matches case insenstive and trimmed.
                    if (le.DecryptedCurrentHash.Trim().CompareCurrentCultureIgnoreCase(le.DecryptedFlightHash.Trim()) == 0)
                    {
                        lstAutoFix.Add(le);
                        le.AdminSignatureSanityFix(true);
                    }
                    else
                    {
                        lst.Add(le);
                    }
                }
            });

            gvInvalidSignatures.DataSource = ViewState["InvalidSigs"] = lst;
            gvInvalidSignatures.DataBind();

            lblSigResults.Text = String.Format(CultureInfo.CurrentCulture, "Found {0} signed flights, {1} appear to have problems, {2} were autofixed (capitalization or leading/trailing whitespace)", cTotalSigned, lst.Count, lstAutoFix.Count);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.SelectedTab = tabID.tabUnknown;
        string szUser = String.Empty;

        if (!IsPostBack)
        {
            lblErr.Text = String.Empty;
            string szAuthToken = util.GetStringParam(Request, "auth");
            if (!String.IsNullOrEmpty(szAuthToken))
            {
                using (MFBWebService ws = new MFBWebService())
                    szUser = ws.GetEncryptedUser(szAuthToken);
            }

            bool fIsLocalOrSecure = MFBWebService.CheckSecurity(Request);

            // If no valid auth token, fall back to the authenticated name.
            if (String.IsNullOrEmpty(szUser) && Page.User.Identity.IsAuthenticated && fIsLocalOrSecure)
            {
                szUser = Page.User.Identity.Name;
            }

            // Require a secure connection for other than debugging.
            if (!fIsLocalOrSecure && !Request.IsSecureConnection)
            {
                szUser = string.Empty;
            }

            try
            {
                if (String.IsNullOrEmpty(szUser))
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                int idFlight = util.GetIntParam(Request, "idFlight", LogbookEntry.idFlightNew);
                if (idFlight == LogbookEntry.idFlightNew)
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                LogbookEntry le = new LogbookEntry();
                if (!le.FLoadFromDB(idFlight, szUser))
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                mfbSignFlight.Flight = le;
                CFIStudentMap sm = new CFIStudentMap(szUser);
                if (sm.Instructors.Count() == 0)
                {
                    mfbSignFlight.SigningMode = Controls_mfbSignFlight.SignMode.AdHoc;
                    mfbSignFlight.CFIProfile  = null;
                    mvSignFlight.SetActiveView(vwAcceptTerms);
                }
                else
                {
                    cmbInstructors.DataSource = sm.Instructors;
                    cmbInstructors.DataBind();
                    mvSignFlight.SetActiveView(vwPickInstructor);
                }


                lblHeader.Text              = String.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.SignOff.SignFlightHeader, MyFlightbook.Profile.GetUser(le.User).UserFullName);
                lblDisclaimerResponse.Text  = Branding.ReBrand(Resources.SignOff.SignDisclaimerAgreement1);
                lblDisclaimerResponse2.Text = Branding.ReBrand(Resources.SignOff.SignDisclaimerAgreement2);
            }
            catch (MyFlightbookException ex)
            {
                lblErr.Text = ex.Message;
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string szRedirect = string.Empty;

            string szComponents = util.GetStringParam(Request, szParamComponents);
            int    id           = util.GetIntParam(Request, "id", LogbookEntry.idFlightNone);

            if (id != -1)
            {
                Response.Redirect(String.Format(CultureInfo.InvariantCulture, "{0}/{1}{2}", Request.Path, id, String.IsNullOrEmpty(szComponents) ? string.Empty : String.Format(CultureInfo.InvariantCulture, "?{0}={1}", szParamComponents, szComponents)), true);
                return;
            }
            else if (!String.IsNullOrEmpty(Request.PathInfo) && Int32.TryParse(Request.PathInfo.Substring(1), out id))
            {
                id = Convert.ToInt32(Request.PathInfo.Substring(1), CultureInfo.InvariantCulture);
            }

            LogbookEntry le = new LogbookEntry();
            // load the flight, redirect home on any error.
            if (id > 0 && le.FLoadFromDB(id, User.Identity.Name, LogbookEntry.LoadTelemetryOption.MetadataOrDB, true))
            {
                PublicFlight = le;

                hdnID.Value = id.ToString(CultureInfo.InvariantCulture);

                if (!le.fIsPublic && (String.Compare(le.User, User.Identity.Name, StringComparison.OrdinalIgnoreCase) != 0)) // not public and this isn't the owner...
                {
                    szRedirect = "~/public/MapRoute2.aspx?sm=1&Airports=" + HttpUtility.UrlEncode(le.Route);
                }

                SetComponentsDisplay(szComponents);

                lblComments.Text = le.Comment.Linkify();

                fbComment.URI = Branding.PublicFlightURL(id);

                string szRoute = le.Route;
                lnkRoute.Text        = HttpUtility.HtmlEncode(szRoute);
                lnkRoute.NavigateUrl = "~/Public/MapRoute2.aspx?sm=1&Airports=" + HttpUtility.UrlEncode(szRoute);

                Profile pf = MyFlightbook.Profile.GetUser(le.User);
                lnkUser.Text        = pf.UserFullName;
                lnkUser.NavigateUrl = pf.PublicFlightsURL(Request.Url.Host).AbsoluteUri;
                btnEdit.Visible     = (le.User == User.Identity.Name);

                lblHeader.Text = String.Format(CultureInfo.CurrentCulture, Resources.LocalizedText.LocalizedJoinWithDash, le.Date.ToShortDateString(), le.TailNumDisplay);

                SetImages(le);

                string szDescription = le.SocialMediaComment.Length > 0 ? le.SocialMediaComment : Resources.LogbookEntry.PublicFlightHeader;
                this.Master.Title = szDescription;
                this.Master.AddMeta("description", szDescription);
                mfbMiniFacebook.FlightEntry = le;

                lblError.Text = string.Empty;

                this.Master.SelectedTab = tabID.tabHome;

                ShowMap(le);
            }
            else
            {
                szRedirect = "~/Default.aspx";
            }

            if (szRedirect.Length > 0)
            {
                Response.Redirect(szRedirect);
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.SelectedTab = tabID.tabUnknown;

        if (!IsPostBack)
        {
            lblErr.Text = String.Empty;
            string szAuthToken = util.GetStringParam(Request, "auth");
            if (!String.IsNullOrEmpty(szAuthToken))
            {
                Username = MFBWebService.GetEncryptedUser(szAuthToken);
            }

            bool fIsLocalOrSecure = MFBWebService.CheckSecurity(Request);

            // If no valid auth token, fall back to the authenticated name.
            if (String.IsNullOrEmpty(Username) && Page.User.Identity.IsAuthenticated && fIsLocalOrSecure)
            {
                Username = Page.User.Identity.Name;
            }

            // Require a secure connection for other than debugging.
            if (!fIsLocalOrSecure && !Request.IsSecureConnection)
            {
                Username = string.Empty;
            }

            try
            {
                if (String.IsNullOrEmpty(Username))
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                int idFlight = util.GetIntParam(Request, "idFlight", LogbookEntry.idFlightNew);
                if (idFlight == LogbookEntry.idFlightNew)
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                LogbookEntry le = new LogbookEntry();
                if (!le.FLoadFromDB(idFlight, Username))
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                mfbSignFlight.Flight = le;
                CFIStudentMap sm = new CFIStudentMap(Username);

                if (Username == null)
                {
                    throw new MyFlightbookValidationException("No username for previously signed flights");
                }

                Dictionary <string, LogbookEntry> d = PreviouslySignedAdhocFlights;

                // If no instructors, and no previously signed flights, assume ad-hoc and go straight to accept terms.
                if (!sm.Instructors.Any() && d.Keys.Count == 0)
                {
                    mfbSignFlight.SigningMode = Controls_mfbSignFlight.SignMode.AdHoc;
                    mfbSignFlight.CFIProfile  = null;
                    mvSignFlight.SetActiveView(vwAcceptTerms);
                }
                else
                {
                    rptInstructors.DataSource = sm.Instructors;
                    rptInstructors.DataBind();

                    List <string> lstKeys = new List <string>(d.Keys);
                    lstKeys.Sort();
                    List <LogbookEntry> lstPrevInstructors = new List <LogbookEntry>();

                    foreach (string sz in lstKeys)
                    {
                        lstPrevInstructors.Add(d[sz]);
                    }

                    rptPriorInstructors.DataSource = lstPrevInstructors;
                    rptPriorInstructors.DataBind();

                    mvSignFlight.SetActiveView(vwPickInstructor);
                }


                lblHeader.Text              = String.Format(CultureInfo.CurrentCulture, Resources.SignOff.SignFlightHeader, MyFlightbook.Profile.GetUser(le.User).UserFullName);
                lblDisclaimerResponse.Text  = Branding.ReBrand(Resources.SignOff.SignDisclaimerAgreement1);
                lblDisclaimerResponse2.Text = Branding.ReBrand(Resources.SignOff.SignDisclaimerAgreement2);
            }
            catch (MyFlightbookException ex)
            {
                lblErr.Text = ex.Message;
            }
        }
    }
    /// <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 void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string szRedirect = string.Empty;

            int    id           = util.GetIntParam(Request, "id", LogbookEntry.idFlightNone);
            string szComponents = util.GetStringParam(Request, szParamComponents);

            if (id != -1)
            {
                Response.Redirect(String.Format(CultureInfo.InvariantCulture, "{0}/{1}{2}", Request.Path, id, String.IsNullOrEmpty(szComponents) ? string.Empty : String.Format(CultureInfo.InvariantCulture, "?{0}={1}", szParamComponents, szComponents)), true);
                return;
            }
            else if (!String.IsNullOrEmpty(Request.PathInfo) && Int32.TryParse(Request.PathInfo.Substring(1), out id))
            {
                id = Convert.ToInt32(Request.PathInfo.Substring(1), CultureInfo.InvariantCulture);
            }

            LogbookEntry le = new LogbookEntry();
            // load the flight, redirect home on any error.
            if (id > 0 && le.FLoadFromDB(id, User.Identity.Name, LogbookEntry.LoadTelemetryOption.MetadataOrDB, true))
            {
                PublicFlight = le;

                hdnID.Value = id.ToString(CultureInfo.InvariantCulture);

                if (!le.fIsPublic && (String.Compare(le.User, User.Identity.Name, StringComparison.OrdinalIgnoreCase) != 0)) // not public and this isn't the owner...
                {
                    szRedirect = "~/public/MapRoute2.aspx?sm=1&Airports=" + HttpUtility.UrlEncode(le.Route);
                }

                // display only selected components, if necessary
                if (!String.IsNullOrEmpty(szComponents))
                {
                    // turn off the header/footer to display only the requested components
                    this.Master.HasFooter  = this.Master.HasHeader = false;
                    FullPageBottom.Visible = FullPageTop.Visible = false;

                    divImages.Visible = pnlFB.Visible = pnlDetails.Visible = divMap.Visible = mfbAirportServices1.Visible = lnkShowMapOnly.Visible = imgsliderFlights.Visible = mfbVideoEntry1.Visible = false;

                    ShowComponents(szComponents.Split(','));
                }

                lblComments.Text = le.Comment.Linkify();

                fbComment.URI = Branding.PublicFlightURL(id);

                string szRoute = le.Route;
                lnkRoute.Text        = HttpUtility.HtmlEncode(szRoute);
                lnkRoute.NavigateUrl = "~/Public/MapRoute2.aspx?sm=1&Airports=" + HttpUtility.UrlEncode(szRoute);

                Profile pf = MyFlightbook.Profile.GetUser(le.User);
                lnkUser.Text        = pf.UserFullName;
                lnkUser.NavigateUrl = pf.PublicFlightsURL(Request.Url.Host).AbsoluteUri;
                btnEdit.Visible     = (le.User == User.Identity.Name);

                lblHeader.Text = String.Format(CultureInfo.CurrentCulture, Resources.LocalizedText.LocalizedJoinWithDash, le.Date.ToShortDateString(), le.TailNumDisplay);

                if (this.Master.IsMobileSession())
                {
                    mfbIlAirplane.Columns = mfbIlFlight.Columns = 1;
                }

                mfbIlFlight.Key = hdnID.Value;
                mfbIlFlight.Refresh();

                mfbIlAirplane.Key     = le.AircraftID.ToString(CultureInfo.InvariantCulture);
                mfbIlAirplane.AltText = le.TailNumDisplay;

                UserAircraft ua = new UserAircraft(le.User);
                Aircraft     ac = ua.GetUserAircraftByID(le.AircraftID) ?? new Aircraft(le.AircraftID);
                mfbIlAirplane.DefaultImage = ac.DefaultImage;
                mfbIlAirplane.Refresh();

                List <MFBImageInfo> lst = new List <MFBImageInfo>(mfbIlFlight.Images.ImageArray);
                lst.AddRange(mfbIlAirplane.Images.ImageArray);
                imgsliderFlights.Images  = lst;
                imgsliderFlights.Visible = lst.Count > 0;

                string szDescription = le.SocialMediaComment.Length > 0 ? le.SocialMediaComment : Resources.LogbookEntry.PublicFlightHeader;
                this.Master.Title = szDescription;
                this.Master.AddMeta("description", szDescription);
                mfbMiniFacebook.FlightEntry = le;

                lblError.Text = "";

                this.Master.SelectedTab = tabID.tabHome;

                mfbVideoEntry1.Videos.Clear();
                foreach (VideoRef vid in le.Videos)
                {
                    mfbVideoEntry1.Videos.Add(vid);
                }

                ShowMap(le);
            }
            else
            {
                szRedirect = "~/Default.aspx";
            }

            if (szRedirect.Length > 0)
            {
                Response.Redirect(szRedirect);
            }
        }
    }