Exemplo n.º 1
0
        private void NotifyConflictingItems()
        {
            List <string> lst = new List <string>();
            Dictionary <string, Profile> dictAffectedUsers = new Dictionary <string, Profile>();

            ConflictingItems.ForEach((s) =>
            {
                if (!dictAffectedUsers.ContainsKey(s.OwningUser))
                {
                    dictAffectedUsers.Add(s.OwningUser, Profile.GetUser(s.OwningUser));
                }
                lst.Add(String.Format("{0}: {1:d} {2:t} ({3}){4}", dictAffectedUsers[s.OwningUser].UserFullName, s.LocalStart, s.LocalStart, s.DurationDisplay, String.IsNullOrEmpty(s.Body) ? string.Empty : String.Format(" - {0}", s.Body)));
            });

            if (ResourceAircraft == null)
            {
                ResourceAircraft = Club.ClubWithID(ClubID).MemberAircraft.FirstOrDefault(ca => ca.AircraftID.ToString().CompareTo(ResourceID) == 0);
            }

            string szMsgBody = Branding.ReBrand(Resources.Schedule.Resourcedoublebooked.Replace("<% ScheduleDetail %>", String.Join("  \r\n  ", lst.ToArray())).Replace("<% Creator %>", dictAffectedUsers[OwningUser].UserFullName).Replace("<% Resource %>", ResourceAircraft == null ? string.Empty : ResourceAircraft.DisplayTailnumber));

            foreach (string sz in dictAffectedUsers.Keys)
            {
                Profile pf = dictAffectedUsers[sz];
                util.NotifyUser(Branding.ReBrand(Resources.Schedule.DoubleBookNotificationSubject), szMsgBody, new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), false, false);
            }
        }
Exemplo n.º 2
0
    protected static bool IsValidCaller(int idClub, PrivilegeLevel level = PrivilegeLevel.ReadWrite)
    {
        // Check that you are authenticated - prevent cross-site scripting
        if (HttpContext.Current == null || HttpContext.Current.User == null || HttpContext.Current.User.Identity == null || !HttpContext.Current.User.Identity.IsAuthenticated || String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
        {
            throw new MyFlightbookException("You must be authenticated to make this call");
        }

        if (idClub == Club.ClubIDNew)
        {
            throw new MyFlightbookException("Each scheduled item must be in the context of a club.");
        }

        Club c = Club.ClubWithID(idClub);

        if (c == null)
        {
            throw new MyFlightbookException("Invalid club specification - no such club.");
        }

        // Check that the user is a member of the specified club
        if (!c.HasMember(HttpContext.Current.User.Identity.Name))
        {
            throw new MyFlightbookException("You must be a member of the club to make this call");
        }

        if (level == PrivilegeLevel.ReadWrite && !c.CanWrite)
        {
            throw new MyFlightbookException(Branding.ReBrand(c.Status == Club.ClubStatus.Expired ? Resources.Club.errClubPromoExpired : Resources.Club.errClubInactive));
        }

        return(true);
    }
Exemplo n.º 3
0
        /// <summary>
        /// Can the specified user edit this item?
        /// </summary>
        /// <param name="szUser">Username</param>
        /// <returns>True if the user is the owner of the appointment or a member of the club</returns>
        public bool CanEdit(string szUser, Club c = null)
        {
            if (c == null)
            {
                c = Club.ClubWithID(ClubID);
            }

            bool fIsAdmin = c.HasAdmin(szUser);
            bool fIsOwner = String.Compare(szUser, OwningUser, StringComparison.Ordinal) == 0;

            // If restricted to admins, then, well, you gotta be an admin
            switch (c.EditingPolicy)
            {
            case Club.EditPolicy.AdminsOnly:
                return(fIsAdmin);

            case Club.EditPolicy.OwnersAndAdmins:
                return(fIsAdmin || fIsOwner);

            case Club.EditPolicy.AllMembers:
                return(c.HasMember(szUser));

            default:
                throw new InvalidOperationException("Unknown editing policy: " + c.EditingPolicy.ToString());
            }
        }
Exemplo n.º 4
0
    public static string CreateEvent(DateTime start, DateTime end, string id, string text, string resource, int clubID = Club.ClubIDNew)
    {
        try
        {
            if (IsValidCaller(clubID))
            {
                if (clubID == Club.ClubIDNew)
                {
                    throw new MyFlightbookException("Attempt to schedule with a non-existant club");
                }

                TimeZoneInfo tzi = Club.ClubWithID(clubID).TimeZone;

                // timezoneOffset is UTC time minus local time, so in Seattle it is 420 or 480 (depending on time of year)
                ScheduledEvent se = new ScheduledEvent(ScheduledEvent.ToUTC(start, tzi), ScheduledEvent.ToUTC(end, tzi), text, id, HttpContext.Current.User.Identity.Name, resource, clubID, tzi);
                if (!se.FCommit())
                {
                    throw new MyFlightbookException(se.LastError);
                }

                Club.ClubWithID(se.ClubID).NotifyAdd(se, HttpContext.Current.User.Identity.Name);
            }
        }
        catch (MyFlightbookException ex)
        {
            return(ex.Message);
        }
        return(string.Empty);
    }
Exemplo n.º 5
0
 protected void btnUpdateMaintenance_Click(object sender, EventArgs e)
 {
     // flush the cache to pick up any aircraft changes
     CurrentClub = Club.ClubWithID(CurrentClub.ID, true);
     gvMaintenance.DataSource = CurrentClub.MemberAircraft;
     gvMaintenance.DataBind();
     btnDownloadMaintenance.Visible = true;
 }
Exemplo n.º 6
0
    public static string PopulateClub(int idClub)
    {
        StringBuilder sb = new StringBuilder();

        try
        {
            // We have no Page, so things like Page_Load don't get called.
            // We fix this by faking a page and calling Server.Execute on it.  This sets up the form and - more importantly - causes Page_load to be called on loaded controls.
            using (Page p = new FormlessPage())
            {
                p.Controls.Add(new HtmlForm());
                using (StringWriter sw1 = new StringWriter(CultureInfo.InvariantCulture))
                    HttpContext.Current.Server.Execute(p, sw1, false);

                HttpRequest r = HttpContext.Current.Request;
                if (!r.IsLocal && !r.UrlReferrer.Host.EndsWith(Branding.CurrentBrand.HostName, StringComparison.OrdinalIgnoreCase))
                {
                    throw new MyFlightbookException("Unauthorized attempt to populate club! {0}, {1}");
                }

                Club c = Club.ClubWithID(idClub);
                if (c == null)
                {
                    return(string.Empty);
                }

                Controls_ClubControls_ViewClub vc = (Controls_ClubControls_ViewClub)p.LoadControl("~/Controls/ClubControls/ViewClub.ascx");
                vc.LinkToDetails = true;
                vc.ActiveClub    = c;
                p.Form.Controls.Add(vc);

                // Now, write it out.
                StringWriter sw = null;
                try
                {
                    sw = new StringWriter(sb, CultureInfo.InvariantCulture);
                    using (HtmlTextWriter htmlTW = new HtmlTextWriter(sw))
                    {
                        sw = null;
                        vc.RenderControl(htmlTW);
                    }
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Dispose();
                    }
                }
            }
        }
        catch (MyFlightbookException ex)
        {
            sb.Append(ex.Message);
        }

        return(sb.ToString());
    }
Exemplo n.º 7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.SelectedTab = tabID.actMyClubs;

        try
        {
            if (Request.PathInfo.Length > 0 && Request.PathInfo.StartsWith("/", StringComparison.OrdinalIgnoreCase))
            {
                if (!IsPostBack)
                {
                    CurrentClub = Club.ClubWithID(Convert.ToInt32(Request.PathInfo.Substring(1), CultureInfo.InvariantCulture));
                    if (CurrentClub == null)
                    {
                        throw new MyFlightbookException(Resources.Club.errNoSuchClub);
                    }

                    Master.Title       = CurrentClub.Name;
                    lblClubHeader.Text = CurrentClub.Name;

                    ClubMember cm = CurrentClub.GetMember(Page.User.Identity.Name);

                    if (!IsManager)
                    {
                        throw new MyFlightbookException(Resources.Club.errNotAuthorizedToManage);
                    }

                    gvMembers.DataSource = CurrentClub.Members;
                    gvMembers.DataBind();
                    vcEdit.ShowDelete = (cm.RoleInClub == ClubMember.ClubMemberRole.Owner);

                    cmbClubAircraft.DataSource = CurrentClub.MemberAircraft;
                    cmbClubAircraft.DataBind();
                    cmbClubMembers.DataSource = CurrentClub.Members;
                    cmbClubMembers.DataBind();

                    dateStart.Date      = (Request.Cookies[szCookieLastStart] != null && DateTime.TryParse(Request.Cookies[szCookieLastStart].Value, out DateTime dtStart)) ? dtStart : CurrentClub.CreationDate;
                    dateEnd.Date        = (Request.Cookies[szCookieLastEnd] != null && DateTime.TryParse(Request.Cookies[szCookieLastEnd].Value, out DateTime dtEnd)) ? dtEnd : DateTime.Now;
                    dateEnd.DefaultDate = DateTime.Now;
                    RefreshAircraft();

                    lblManageheader.Text        = String.Format(CultureInfo.CurrentCulture, Resources.Club.LabelManageThisClub, CurrentClub.Name);
                    lnkReturnToClub.NavigateUrl = String.Format(CultureInfo.InvariantCulture, "~/Member/ClubDetails.aspx/{0}", CurrentClub.ID);

                    vcEdit.ActiveClub = CurrentClub;    // do this at the end so that all of the above (like ShowDelete) are captured
                }
            }
            else
            {
                throw new MyFlightbookException(Resources.Club.errNoClubSpecified);
            }
        }
        catch (MyFlightbookException ex)
        {
            lblErr.Text             = ex.Message;
            lnkReturnToClub.Visible = tabManage.Visible = false;
        }
    }
Exemplo n.º 8
0
 /// <summary>
 /// Initializes the request from a string (mirrors ToString())
 /// </summary>
 /// <param name="sz">The string</param>
 private void InitFromString(string sz)
 {
     string[] rgParams = sz.Split(';');
     Requestedrole  = (RoleType)Convert.ToInt32(rgParams[0], CultureInfo.InvariantCulture);
     RequestingUser = rgParams[1];
     TargetUser     = rgParams[2];
     ClubToJoin     = null;
     if (rgParams.Length > 2 && (Requestedrole == RoleType.RoleInviteJoinClub || Requestedrole == RoleType.RoleRequestJoinClub) &&
         Int32.TryParse(rgParams[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out int id))
     {
         ClubToJoin = Club.ClubWithID(id);
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Can the specified user edit this item?
        /// </summary>
        /// <param name="szUser">Username</param>
        /// <returns>True if the user is the owner of the appointment or a member of the club</returns>
        public bool CanEdit(string szUser, Club c = null)
        {
            // owner/creator of the object can always edit it
            if (String.Compare(szUser, OwningUser, StringComparison.Ordinal) == 0)
            {
                return(true);
            }

            // else fall through to the club
            if (c == null)
            {
                c = Club.ClubWithID(ClubID);
            }
            return(c.RestrictEditingToOwnersAndAdmins ? c.HasAdmin(szUser) : c.HasMember(szUser));
        }
Exemplo n.º 10
0
    public static ScheduledEvent[] ReadEvents(DateTime dtStart, DateTime dtEnd, int clubID = Club.ClubIDNew, string resourceName = null)
    {
        if (!IsValidCaller(clubID, PrivilegeLevel.ReadOnly))
        {
            return(null);
        }

        Club                  c   = Club.ClubWithID(clubID);
        TimeZoneInfo          tzi = c.TimeZone;
        List <ScheduledEvent> lst = ScheduledEvent.AppointmentsInTimeRange(ScheduledEvent.ToUTC(dtStart, tzi), ScheduledEvent.ToUTC(dtEnd, tzi), resourceName, clubID, tzi);

        // Fix up the owner's name
        lst.ForEach((se) => {
            se.OwnerProfile = c.PrependsScheduleWithOwnerName ? c.Members.FirstOrDefault(cm => cm.UserName.CompareTo(se.OwningUser) == 0) : null;
            se.ReadOnly     = !se.CanEdit(HttpContext.Current.User.Identity.Name, c);
        });
        return(lst.ToArray());
    }
Exemplo n.º 11
0
        public static string UpdateEvent(DateTime start, DateTime end, string id, string text, string resource, int clubID)
        {
            try
            {
                if (IsValidCaller(clubID))
                {
                    Club           c                  = Club.ClubWithID(clubID);
                    TimeZoneInfo   tzi                = c.TimeZone;
                    ScheduledEvent scheduledevent     = ScheduledEvent.AppointmentByID(id, tzi);
                    ScheduledEvent scheduledeventOrig = new ScheduledEvent();

                    if (!scheduledevent.CanEdit(HttpContext.Current.User.Identity.Name))
                    {
                        throw new MyFlightbookException(Resources.Schedule.ErrUnauthorizedEdit);
                    }

                    if (scheduledevent != null)
                    {
                        util.CopyObject(scheduledevent, scheduledeventOrig);    // hold on to the original version, at least for now.

                        scheduledevent.StartUtc = ScheduledEvent.ToUTC(start, tzi);
                        scheduledevent.EndUtc   = ScheduledEvent.ToUTC(end, tzi);
                        text = HttpUtility.HtmlDecode(text);
                        scheduledevent.Body = (String.IsNullOrWhiteSpace(text) && c.PrependsScheduleWithOwnerName) ? MyFlightbook.Profile.GetUser(scheduledevent.OwningUser).UserFullName : text;
                        if (!String.IsNullOrEmpty(resource))
                        {
                            scheduledevent.ResourceID = resource;
                        }
                        if (!scheduledevent.FCommit())
                        {
                            throw new MyFlightbookException(scheduledevent.LastError);
                        }

                        Club.ClubWithID(scheduledevent.ClubID).NotifyOfChange(scheduledeventOrig, scheduledevent, HttpContext.Current.User.Identity.Name);
                    }
                }
            }
            catch (MyFlightbookException ex)
            {
                return(ex.Message);
            }

            return(string.Empty);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Is the current user able to double book an item?
        /// </summary>
        /// <param name="szUser">Username</param>
        /// <param name="c">Club in question (or the  owning club for this item, if null)</param>
        /// <returns></returns>
        public bool CanDoubleBook(string szUser, Club c = null)
        {
            // else fall through to the club
            if (c == null)
            {
                c = Club.ClubWithID(ClubID);
            }

            switch (c.DoubleBookRoleRestriction)
            {
            case Club.DoubleBookPolicy.Admins:
                return(c.HasAdmin(szUser));

            case Club.DoubleBookPolicy.None:
                return(false);

            case Club.DoubleBookPolicy.WholeClub:
                return(true);
            }
            return(false);
        }
Exemplo n.º 13
0
    public static string DeleteEvent(string id)
    {
        try
        {
            ScheduledEvent scheduledevent = ScheduledEvent.AppointmentByID(id, TimeZoneInfo.Utc);
            if (scheduledevent == null)
            {
                return(Resources.Schedule.errItemNotFound);
            }

            string szUser = HttpContext.Current.User.Identity.Name;

            if (!scheduledevent.CanEdit(szUser))
            {
                throw new MyFlightbookException(Resources.Schedule.ErrUnauthorizedEdit);
            }

            if (scheduledevent.FDelete())
            {
                // Send any notifications - but do it on a background thread so that we can return quickly
                new Thread(() =>
                {
                    Club c = Club.ClubWithID(scheduledevent.ClubID);
                    c.NotifyOfDelete(scheduledevent, szUser);
                }).Start();
            }
            else
            {
                throw new MyFlightbookException(scheduledevent.LastError);
            }
        }
        catch (MyFlightbookException ex)
        {
            return(ex.Message);
        }
        return(string.Empty);
    }
Exemplo n.º 14
0
        /// <summary>
        /// Initializes the request from a string (mirrors ToString())
        /// </summary>
        /// <param name="sz">The string</param>
        private void InitFromString(string sz)
        {
            if (sz == null)
            {
                return;
            }

            string[] rgParams = sz.Split(';');

            if (rgParams.Length < 3)
            {
                throw new ArgumentException("Invalid request relationship request string: " + sz);
            }

            Requestedrole  = (RoleType)Convert.ToInt32(rgParams[0], CultureInfo.InvariantCulture);
            RequestingUser = rgParams[1];
            TargetUser     = rgParams[2];
            ClubToJoin     = null;
            if (rgParams.Length > 2 && (Requestedrole == RoleType.RoleInviteJoinClub || Requestedrole == RoleType.RoleRequestJoinClub) &&
                Int32.TryParse(rgParams[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out int id))
            {
                ClubToJoin = Club.ClubWithID(id);
            }
        }
Exemplo n.º 15
0
 public void Refresh()
 {
     gvSchedSummary.DataSource = Club.ClubWithID(ClubID).GetUpcomingEvents(10, ResourceName, UserName);
     gvSchedSummary.DataBind();
 }
Exemplo n.º 16
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!Page.User.Identity.IsAuthenticated)
            {
                throw new MyFlightbookException("Unauthorized!");
            }

            int idClub = util.GetIntParam(Request, "c", 0);
            if (idClub == 0)
            {
                throw new MyFlightbookException("Invalid club");
            }

            Club c = Club.ClubWithID(idClub);

            if (c == null)
            {
                throw new MyFlightbookException(String.Format(System.Globalization.CultureInfo.InvariantCulture, "Invalid club: {0}", idClub));
            }

            string   szIDs  = util.GetStringParam(Request, "sid");
            string[] rgSIDs = szIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (rgSIDs.Length == 0)
            {
                throw new MyFlightbookException("No scheduled events to download specified");
            }

            bool fIsAdmin = c.HasAdmin(Page.User.Identity.Name);

            Calendar ic = new Calendar();
            ic.Calendar.AddTimeZone(c.TimeZone);

            string szTitle = string.Empty;

            foreach (string sid in rgSIDs)
            {
                ScheduledEvent se = ScheduledEvent.AppointmentByID(sid, c.TimeZone);

                if (se == null)
                {
                    throw new MyFlightbookException(String.Format(System.Globalization.CultureInfo.InvariantCulture, "Invalid scheduled event ID: {0}", sid));
                }

                if (!fIsAdmin && Page.User.Identity.Name.CompareOrdinal(se.OwningUser) != 0)
                {
                    throw new MyFlightbookException("Attempt to download appointment that you don't own!");
                }

                ClubAircraft ca = c.MemberAircraft.FirstOrDefault(ca2 => ca2.AircraftID.ToString(System.Globalization.CultureInfo.InvariantCulture).CompareOrdinal(se.ResourceID) == 0);

                szTitle = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}{1}", ca == null ? string.Empty : String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} - ", ca.DisplayTailnumber), se.Body);
                CalendarEvent ev = new CalendarEvent()
                {
                    Uid         = se.ID,
                    IsAllDay    = false,
                    Start       = new CalDateTime(se.StartUtc, TimeZoneInfo.Utc.Id),
                    End         = new CalDateTime(se.EndUtc, TimeZoneInfo.Utc.Id),
                    Description = szTitle,
                    Summary     = szTitle,
                    Location    = c.HomeAirport == null ? c.HomeAirportCode : String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} - {1}", c.HomeAirportCode, c.HomeAirport.Name)
                };
                ev.Start.HasTime = ev.End.HasTime = true;  // has time is false if the ultimate time is midnight.

                Alarm a = new Alarm()
                {
                    Action      = AlarmAction.Display,
                    Description = ev.Summary,
                    Trigger     = new Trigger()
                    {
                        DateTime         = ev.Start.AddMinutes(-30),
                        AssociatedObject = ic
                    }
                };
                ev.Alarms.Add(a);
                ic.Calendar.Events.Add(ev);
                ic.Calendar.Method = "PUBLISH";
            }

            string szFormat = util.GetStringParam(Request, "fmt");

            switch (szFormat.ToUpperInvariant())
            {
            case "ICAL":
            default:
                WriteICal(ic);
                break;

            case "G":
                WriteGoogle(ic, c.TimeZone);
                break;

            case "Y":
                WriteYahoo(ic, c.TimeZone);
                break;
            }
        }
    }
Exemplo n.º 17
0
        public static IDictionary <int, bool[]> ComputeAvailabilityMap(DateTime dtStart, int clubID, out Club club, int limitAircraft = Aircraft.idAircraftUnknown, int cDays = 1, int minuteInterval = 15)
        {
            if (cDays < 1 || cDays > 7)
            {
                throw new InvalidOperationException("Can only do 1 to 7 days of availability");
            }

            if (minuteInterval <= 0)
            {
                throw new InvalidOperationException("Invalid minute interval");
            }

            double IntervalsPerHour = 60.0 / minuteInterval;
            int    IntervalsPerDay  = (int)(24 * IntervalsPerHour);

            if (IntervalsPerDay != (24 * IntervalsPerHour))
            {
                throw new InvalidOperationException("Minute interval must align on 24-hour boundaries");
            }

            int totalIntervals = IntervalsPerDay * cDays;

            Dictionary <int, bool[]> d = new Dictionary <int, bool[]>();

            club = Club.ClubWithID(clubID);

            foreach (Aircraft ac in club.MemberAircraft)
            {
                if (limitAircraft == Aircraft.idAircraftUnknown || ac.AircraftID == limitAircraft)
                {
                    d[ac.AircraftID] = new bool[totalIntervals];
                }
            }

            DateTime     dtStartLocal = new DateTime(dtStart.Year, dtStart.Month, dtStart.Day, 0, 0, 0, DateTimeKind.Unspecified);
            TimeZoneInfo tzi          = club.TimeZone;
            DateTime     dtStartUtc   = ToUTC(dtStartLocal, tzi);

            // we need to request the appointments in UTC, even though we will display them in local time.
            List <ScheduledEvent> lst = AppointmentsInTimeRange(dtStartUtc, dtStartUtc.AddDays(cDays), clubID, tzi);

            foreach (ScheduledEvent e in lst)
            {
                if (!int.TryParse(e.ResourceID, out int idAircraft))
                {
                    continue;
                }

                // Block off any scheduled time that's in our window, rounding up and down as appropriate
                bool[] rg = d[idAircraft];

                int startingInterval = (int)Math.Floor(e.LocalStart.Subtract(dtStartLocal).TotalHours *IntervalsPerHour);
                int endingInterval   = (int)Math.Ceiling(e.LocalEnd.Subtract(dtStartLocal).TotalHours *IntervalsPerHour);

                for (int interval = Math.Max(0, startingInterval); interval < endingInterval && interval < rg.Length; interval++)
                {
                    rg[interval] = true;
                }
            }

            return(d);
        }
Exemplo n.º 18
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!Page.User.Identity.IsAuthenticated)
            {
                throw new MyFlightbookException("Unauthorized!");
            }

            int idClub = util.GetIntParam(Request, "c", 0);
            if (idClub == 0)
            {
                throw new MyFlightbookException("Invalid club");
            }

            Club c = Club.ClubWithID(idClub);

            if (c == null)
            {
                throw new MyFlightbookException(String.Format(System.Globalization.CultureInfo.InvariantCulture, "Invalid club: {0}", idClub));
            }

            string   szIDs  = util.GetStringParam(Request, "sid");
            string[] rgSIDs = szIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (rgSIDs.Length == 0)
            {
                throw new MyFlightbookException("No scheduled events to download specified");
            }

            bool fIsAdmin = c.HasAdmin(Page.User.Identity.Name);

            using (Ical.Net.Calendar ic = new Ical.Net.Calendar())
            {
                ic.AddTimeZone(new VTimeZone(c.TimeZone.Id));

                string szTitle = string.Empty;

                foreach (string sid in rgSIDs)
                {
                    ScheduledEvent se = ScheduledEvent.AppointmentByID(sid, c.TimeZone);

                    if (se == null)
                    {
                        throw new MyFlightbookException(String.Format(System.Globalization.CultureInfo.InvariantCulture, "Invalid scheduled event ID: {0}", sid));
                    }

                    if (!fIsAdmin && Page.User.Identity.Name.CompareOrdinal(se.OwningUser) != 0)
                    {
                        throw new MyFlightbookException("Attempt to download appointment that you don't own!");
                    }

                    ClubAircraft ca = c.MemberAircraft.FirstOrDefault(ca2 => ca2.AircraftID.ToString(System.Globalization.CultureInfo.InvariantCulture).CompareOrdinal(se.ResourceID) == 0);

                    Event ev = ic.Create <Event>();
                    ev.Uid           = se.ID;
                    ev.IsAllDay      = false;
                    ev.Start         = new CalDateTime(se.StartUtc, TimeZoneInfo.Utc.Id);
                    ev.End           = new CalDateTime(se.EndUtc, TimeZoneInfo.Utc.Id);
                    ev.Start.HasTime = ev.End.HasTime = true;   // has time is false if the ultimate time is midnight.
                    szTitle          = ev.Description = ev.Summary = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}{1}", ca == null ? string.Empty : String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} - ", ca.DisplayTailnumber), se.Body);
                    ev.Location      = c.HomeAirport == null ? c.HomeAirportCode : String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} - {1}", c.HomeAirportCode, c.HomeAirport.Name);

                    Alarm a = new Alarm();
                    a.Action           = AlarmAction.Display;
                    a.Description      = ev.Summary;
                    a.Trigger          = new Trigger();
                    a.Trigger.DateTime = ev.Start.AddMinutes(-30);
                    ev.Alarms.Add(a);

                    ic.Method = "PUBLISH";
                }

                CalendarSerializer s = new CalendarSerializer();

                string output = s.SerializeToString(ic);
                Page.Response.Clear();
                Page.Response.ContentType = "text/calendar";
                Response.AddHeader("Content-Disposition", String.Format(System.Globalization.CultureInfo.InvariantCulture, "inline;filename={0}", Branding.ReBrand(String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}appt.ics", szTitle)).Replace(" ", "-")));
                Response.Write(output);
                Response.Flush();
                Response.End();
            }
        }
    }
 public void Refresh(int clubID)
 {
     // flush the cache to pick up any aircraft changes
     gvMaintenance.DataSource = Club.ClubWithID(clubID, true).MemberAircraft;
     gvMaintenance.DataBind();
 }
Exemplo n.º 20
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.SelectedTab = tabID.actMyClubs;

        if (Request.PathInfo.Length > 0 && Request.PathInfo.StartsWith("/", StringComparison.OrdinalIgnoreCase))
        {
            if (!IsPostBack)
            {
                try
                {
                    CurrentClub = Club.ClubWithID(Convert.ToInt32(Request.PathInfo.Substring(1), CultureInfo.InvariantCulture));
                    if (CurrentClub == null)
                    {
                        throw new MyFlightbookException(Resources.Club.errNoSuchClub);
                    }

                    Master.Title       = CurrentClub.Name;
                    lblClubHeader.Text = CurrentClub.Name;

                    ClubMember cm = CurrentClub.GetMember(Page.User.Identity.Name);

                    DateTime dtClub = ScheduledEvent.FromUTC(DateTime.UtcNow, CurrentClub.TimeZone);
                    lblCurTime.Text      = String.Format(CultureInfo.InvariantCulture, Resources.LocalizedText.LocalizedJoinWithSpace, dtClub.ToShortDateString(), dtClub.ToShortTimeString());
                    lblTZDisclaimer.Text = String.Format(CultureInfo.CurrentCulture, Resources.Club.TimeZoneDisclaimer, CurrentClub.TimeZone.StandardName);

                    bool fIsAdmin = util.GetIntParam(Request, "a", 0) != 0 && (MyFlightbook.Profile.GetUser(Page.User.Identity.Name)).CanManageData;
                    if (fIsAdmin && cm == null)
                    {
                        cm = new ClubMember(CurrentClub.ID, Page.User.Identity.Name, ClubMember.ClubMemberRole.Admin);
                    }
                    bool fIsManager = fIsAdmin || (cm != null && cm.IsManager);
                    lnkManageClub.NavigateUrl = String.Format(CultureInfo.InvariantCulture, "~/Member/ClubManage.aspx/{0}", CurrentClub.ID);
                    mvMain.SetActiveView(cm == null ? vwMainGuest : vwSchedules);
                    mvTop.SetActiveView(cm == null ? vwTopGuest : (fIsManager ? vwTopAdmin : vwTopMember));

                    if (cm == null)
                    {
                        accClub.SelectedIndex = 0;
                        acpMembers.Visible    = acpSchedules.Visible = false;
                    }

                    pnlLeaveGroup.Visible = (cm != null && !cm.IsManager);

                    switch (CurrentClub.Status)
                    {
                    case Club.ClubStatus.Promotional:
                        mvPromoStatus.SetActiveView(vwPromotional);
                        string szTemplate = (Page.User.Identity.Name.CompareOrdinal(Page.User.Identity.Name) == 0) ? Resources.Club.clubStatusTrialOwner : Resources.Club.clubStatusTrial;
                        lblPromo.Text = String.Format(CultureInfo.CurrentCulture, Branding.ReBrand(szTemplate), CurrentClub.ExpirationDate.Value.ToShortDateString());
                        break;

                    case Club.ClubStatus.Expired:
                    case Club.ClubStatus.Inactive:
                        mvPromoStatus.SetActiveView(vwInactive);
                        lblInactive.Text = Branding.ReBrand(CurrentClub.Status == Club.ClubStatus.Inactive ? Resources.Club.errClubInactive : Resources.Club.errClubPromoExpired);
                        break;

                    default:
                        mvPromoStatus.Visible = false;
                        break;
                    }

                    // Initialize from the cookie, if possible.
                    rbScheduleMode.SelectedValue = SchedulePreferences.DefaultScheduleMode.ToString();

                    if (CurrentClub.PrependsScheduleWithOwnerName)
                    {
                        mfbEditAppt1.DefaultTitle = MyFlightbook.Profile.GetUser(Page.User.Identity.Name).UserFullName;
                    }

                    RefreshAircraft();

                    if (cm != null)
                    {
                        gvMembers.DataSource = CurrentClub.Members;
                        gvMembers.DataBind();
                        // Hack - trim the last column if not showing mobiles.  This is fragile.
                        if (CurrentClub.HideMobileNumbers)
                        {
                            gvMembers.Columns[gvMembers.Columns.Count - 1].Visible = false;
                        }
                    }
                }
                catch (MyFlightbookException ex)
                {
                    lblErr.Text = ex.Message;
                }
            }

            // Do this every time - if it's a postback in an update panel, it's a non-issue, but if it's full-page, this keeps things from going away.
            RefreshSummary();
        }
    }