/// <summary>
 /// Initializes a new instance of the <see cref="AvailabilityTelemetry"/> class by cloning an existing instance.
 /// </summary>
 /// <param name="source">Source instance of <see cref="AvailabilityTelemetry"/> to clone from.</param>
 private AvailabilityTelemetry(AvailabilityTelemetry source)
 {
     this.Data      = source.Data.DeepClone();
     this.context   = source.context.DeepClone(this.Data.properties);
     this.Sequence  = source.Sequence;
     this.Timestamp = source.Timestamp;
 }
Example #2
0
        public AvailabilityData UpdatePlayerAvailability(int playerId, AvailabilityData availability)
        {
            using (var entities = Database.GetEntities())
            {
                var playerAbDataList = entities.AvailabilityDatas.Where(x => x.PlayerId == playerId && x.EventId == availability.EventId);

                if (playerAbDataList.Count() == 0) // Create new one
                {
                    entities.AvailabilityDatas.AddObject(new AvailabilityData
                    {
                        PlayerId      = availability.PlayerId,
                        EventId       = availability.EventId,
                        AdminStatus   = availability.AdminStatus,
                        RepliedStatus = availability.RepliedStatus
                    });
                    entities.SaveChanges();
                    return(availability);
                }

                if (playerAbDataList.Count() > 1) // Remove extra (rare but can happen)
                {
                    foreach (var extraAbData in playerAbDataList.OrderBy(x => x.Id).Skip(1))
                    {
                        entities.DeleteObject(extraAbData);
                    }
                }

                var abData = playerAbDataList.FirstOrDefault();
                abData.AdminStatus   = availability.AdminStatus;
                abData.RepliedStatus = availability.RepliedStatus;
                abData.EmailSent     = availability.EmailSent;
                entities.SaveChanges();
                return(abData);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AvailabilityTelemetry"/> class with empty properties.
 /// </summary>
 public AvailabilityTelemetry()
 {
     this.Data    = new AvailabilityData();
     this.context = new TelemetryContext(this.Data.properties);
     this.Data.id = Convert.ToBase64String(BitConverter.GetBytes(WeakConcurrentRandom.Instance.Next()));
     this.Success = true;
 }
Example #4
0
 public Availability(AvailabilityData data)
 {
     EventId       = data.EventId;
     PlayerId      = data.PlayerId;
     EmailSent     = data.EmailSent;
     Token         = data.Token;
     AdminStatus   = data.AdminStatus;
     RepliedStatus = data.RepliedStatus;
 }
Example #5
0
        public JsonResult SetAvailability(AvailabilityData availability)
        {
            if (availability.RepliedStatus == 0 || availability.RepliedStatus > 3)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Invalid reply status");
            }

            availability = _playerService.SetPlayerAvailability(availability.Token, (short)availability.RepliedStatus);
            return(Json(availability));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AvailabilityTelemetry"/> class with empty properties.
 /// </summary>
 public AvailabilityTelemetry(string name, DateTimeOffset timeStamp, TimeSpan duration, string runLocation, bool success, string message = null)
 {
     this.Data               = new AvailabilityData();
     this.context            = new TelemetryContext(this.Data.properties);
     this.Data.testTimeStamp = timeStamp.ToString("o", CultureInfo.InvariantCulture);
     this.Data.testName      = name;
     this.Data.testRunId     = Convert.ToBase64String(BitConverter.GetBytes(WeakConcurrentRandom.Instance.Next()));
     this.Data.duration      = duration.ToString(string.Empty, CultureInfo.InvariantCulture);
     this.Data.result        = success ? TestResult.Pass : TestResult.Fail;
     this.Data.runLocation   = runLocation;
     this.Data.message       = message;
 }
Example #7
0
        /// <summary>
        ///   Index rendering.
        /// </summary>
        /// <returns>
        ///   The action result instance <see cref="ActionResult" />.
        /// </returns>
        public ActionResult Index()
        {
            AvailabilityData data = this.repository.FormReport(this.ReportingPeriod);

            this.ViewBag.ReportData = new JavaScriptSerializer().Serialize(data);

            AvailabilityData dailyData = this.repository.FormReport(24 * 7);

            this.ViewBag.DailyReportData = new JavaScriptSerializer().Serialize(dailyData);

            this.ViewBag.ReportPeriodInfo = string.Format("LAST {0} {1} ", data.Statistics.Length, data.PeriodType == AvailabilityData.PeriodTypeEnum.Day ? "DAYS" : "HOURS");

            return(this.View());
        }
Example #8
0
        public GetUserAvailabilityResults LoadRoomSchedule(List <Room> rooms, DateTime startDate, DateTime endDate)
        {
            //TimeWindow timeWindow = new TimeWindow(DateTime.Now.ToUniversalTime().Date, DateTime.Now.ToUniversalTime().Date.AddDays(1));
            TimeWindow timeWindow = new TimeWindow(startDate.ToUniversalTime().Date, startDate.ToUniversalTime().Date.AddDays(1));

            // We want to know if the room is free or busy.
            AvailabilityData    availabilityData    = AvailabilityData.FreeBusy;
            AvailabilityOptions availabilityOptions = new AvailabilityOptions();

            availabilityOptions.RequestedFreeBusyView    = FreeBusyViewType.FreeBusy;
            availabilityOptions.MaximumSuggestionsPerDay = 0;

            // Get the availability of the room.
            var result = service.GetUserAvailability(from n in rooms
                                                     select n.AttendeeInfo,
                                                     timeWindow,
                                                     availabilityData,
                                                     availabilityOptions);

            // Use the schedule to determine if a room is available for the next
            DetermineRoomAvailability(rooms, result, startDate, endDate);
            return(result);
        }
Example #9
0
        public JsonResult UpdateAvailability(int teamId, int playerId, AvailabilityData availability)
        {
            var activeUser = this.GetActiveUser(this.Request);

            if (activeUser == null || !_teamService.CanEdit(teamId, activeUser.Id))
            {
                throw new HttpException((int)HttpStatusCode.Unauthorized, "Not authorized to edit this team");
            }

            var knownPlayer = _playerService.GetPlayer(playerId);

            if (knownPlayer != null)
            {
                var playerGroup = _playerService.GetPlayerGroup(knownPlayer.GroupId);
                if (playerGroup.TeamId != teamId)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, "Not authorized to edit this player");
                }
            }

            if (availability.EventId == 0)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "No event ID was given");
            }

            var knownEvent = _gameService.GetGame(availability.EventId);

            if (teamId != knownEvent.HomeTeamId)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Team ID mismatch");
            }

            availability = _playerService.UpdatePlayerAvailability(knownPlayer.Id, availability);

            return(Json(availability));
        }
Example #10
0
        public bool IsBroken()
        {
            foreach (var workerGroup in availabilities.GroupBy(a => a.EmployeeId))
            {
                int skipCount = 1;

                foreach (var availability in workerGroup)
                {
                    if (workerGroup
                        .Skip(skipCount)
                        .Any(a =>
                             a.StartTime <= availability.StartTime &&
                             a.EndTime <= availability.EndTime))
                    {
                        incorrectAvailability = availability;
                        return(true);
                    }

                    skipCount++;
                }
            }

            return(false);
        }
Example #11
0
 public HostelGroup(string groupName)
 {
     Hostels      = new List <Hostel>();
     Availability = new AvailabilityData();
     Name         = groupName;
 }
Example #12
0
        /// <summary>
        /// Parse the response data for a particual month and add it to the availability data
        /// </summary>
        /// <param name="responseData"></param>
        /// <param name="monthName"></param>
        /// <param name="availability"></param>
        static void SaveAvailabiltyForHostelMonth(List <string> dates, List <string> availabilities, AvailabilityData availability, int hostelCount)
        {
            // Enumerate the results
            int index = 0;

            List <string> .Enumerator enumerator = dates.GetEnumerator();
            while (enumerator.MoveNext() == true)
            {
                string date = enumerator.Current;

                // Format is 'yyyy-mm-dd'
                if (date.Length == 10)
                {
                    DateTime fullDate = DateTime.Parse(date);

                    // Add an entry for this date to the dictionary if not already there
                    if (availabilities != null)
                    {
                        availability.AddAvailability(
                            string.Format("{0}, {1} {2}, 2019", fullDate.DayOfWeek.ToString().Substring(0, 3), fullDate.ToString("MMM"), fullDate.Day),
                            (availabilities[index].Length > 6) && (availabilities[index][0] == '&'), hostelCount);
                    }
                    else
                    {
                        availability.AddAvailability(
                            string.Format("{0}, {1} {2}, 2019", fullDate.DayOfWeek.ToString().Substring(0, 3), fullDate.ToString("MMM"), fullDate.Day), false, hostelCount);
                    }
                }

                index++;
            }
        }
Example #13
0
        private void GetAvailabilityButton_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                // Get AttendeeInfo from AttendeeList
                List <AttendeeInfo> attendees = null;
                if (!this.TryGetAttendeesFromList(out attendees))
                {
                    ErrorDialog.ShowWarning("There must be at least one attendee listed to retrieve availability for.");
                    return;
                }

                // Get TimeWindow from input
                TimeWindow window = new TimeWindow(
                    this.StartWindowDate.Value.ToUniversalTime(),
                    this.EndWindowDate.Value.ToUniversalTime());

                // Get RequestedData from input
                AvailabilityData requestedData = AvailabilityData.FreeBusy;
                if (this.availDataCombo.SelectedItem.HasValue)
                {
                    requestedData = this.availDataCombo.SelectedItem.Value;
                }

                // Collect AvailabilityOptions from form input
                AvailabilityOptions options = new AvailabilityOptions();
                if (this.CurrentMeetingCheck.Checked)
                {
                    options.CurrentMeetingTime = this.CurrentMeetingDate.Value;
                }
                else
                {
                    options.CurrentMeetingTime = null;
                }

                options.MeetingDuration           = Convert.ToInt32(this.MeetingDurationText.Text);
                options.DetailedSuggestionsWindow = new TimeWindow(
                    this.StartDetailDate.Value,
                    this.EndDetailDate.Value);
                options.GlobalObjectId          = this.GlobalObjectIdText.Text;
                options.GoodSuggestionThreshold = Convert.ToInt32(this.GoodSuggestThresholdText.Text);
                options.MaximumNonWorkHoursSuggestionsPerDay = Convert.ToInt32(this.MaxNonWorkSuggestText.Text);
                options.MaximumSuggestionsPerDay             = Convert.ToInt32(this.MaxSuggestPerDayText.Text);
                options.MergedFreeBusyInterval = Convert.ToInt32(this.MergeFBIntervalText.Text);

                if (this.minSuggestQualCombo.SelectedItem.HasValue)
                {
                    options.MinimumSuggestionQuality = this.minSuggestQualCombo.SelectedItem.Value;
                }

                if (this.requestFBViewCombo.SelectedItem.HasValue)
                {
                    options.RequestedFreeBusyView = this.requestFBViewCombo.SelectedItem.Value;
                }

                // Remember which attendee was selected in the AttendeeList
                int selectedIndex = -1;
                if (this.AttendeeList.SelectedItems != null &&
                    this.AttendeeList.SelectedItems.Count == 1)
                {
                    selectedIndex = this.AttendeeList.SelectedItems[0].Index;
                    this.AttendeeList.Items[selectedIndex].Selected = false;
                }

                // Make the EWS request
                GetUserAvailabilityResults results = this.CurrentService.GetUserAvailability(
                    attendees,
                    window,
                    requestedData,
                    options);

                // Enable result lists
                this.AttendeeAvailabilityList.Enabled = true;
                this.CalEventsList.Enabled            = true;
                this.SuggestionsList.Enabled          = true;

                // Attach AttendeeAvailability to the associated attendee in the ListView.
                // It can be assumed that the order of the AttendeesAvailability and Suggestions
                // results arrays correspond to the order of the attendees.
                for (int i = 0; i < attendees.Count; i++)
                {
                    AttendeeAvailability availResult = null;
                    if (results.AttendeesAvailability != null &&
                        results.AttendeesAvailability[i] != null)
                    {
                        availResult = results.AttendeesAvailability[i];
                    }

                    this.AddResultsToAttendee(attendees[i], availResult);
                }

                if (results.Suggestions != null)
                {
                    // Display the Suggestion in the ListView
                    foreach (Suggestion suggest in results.Suggestions)
                    {
                        foreach (TimeSuggestion time in suggest.TimeSuggestions)
                        {
                            ListViewItem timeItem = this.SuggestionsList.Items.Add(suggest.Date.ToShortDateString());
                            timeItem.SubItems.Add(suggest.Quality.ToString());
                            timeItem.SubItems.Add(time.MeetingTime.ToShortTimeString());
                            timeItem.SubItems.Add(time.Quality.ToString());
                            timeItem.SubItems.Add(time.Conflicts.Count.ToString());
                            timeItem.SubItems.Add(time.IsWorkTime.ToString());
                        }
                    }
                }

                // Reset the selected Attendee and display the results or show a message
                // to inform the user how to display results.
                if (selectedIndex > -1)
                {
                    this.AttendeeList.Items[selectedIndex].Selected = true;
                }
                else
                {
                    //this.AttendeeAvailabilityGroup.Text = "Select an attendee in the list to display availability results.";
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
Example #14
0
        public Message EmailMessage(Message message)
        {
            var contentBody = new StringBuilder();

            // Start the body off with the 'message'
            if (!string.IsNullOrWhiteSpace(message.Content))
            {
                contentBody.Append(string.Format("<h2>Message from {0}</h2>", message.TeamName));

                var paragraphs = Regex.Split(message.Content, "\n\n");

                foreach (var p in paragraphs)
                {
                    var formattedParagraph = System.Web.HttpUtility.HtmlEncode(p);
                    formattedParagraph = Regex.Replace(formattedParagraph, "\n", "<br/>");
                    contentBody.Append(string.Format("<p>{0}</p>", formattedParagraph));
                }
            }

            var abBody = new StringBuilder();

            // Then add the availability parts
            if (message.RequestAvailability)
            {
                const string replyEmail = "https://teamkeep.com/rsvp?token=TEAMKEEPRSVPTOKEN";

                Game.EventType type;
                Enum.TryParse(message.AvailabilityEvent.Type.ToString(CultureInfo.InvariantCulture), out type);

                switch (type)
                {
                case Game.EventType.Game:
                    abBody.Append(string.IsNullOrEmpty(message.AvailabilityEvent.OpponentName)
                                          ? string.Format("<h2>{0} vs. [To Be Determined]</h2>", message.TeamName)
                                          : string.Format("<h2>{0} vs. {1}</h2>", message.TeamName, message.AvailabilityEvent.OpponentName));
                    break;

                case Game.EventType.Practice:
                    abBody.Append(string.IsNullOrEmpty(message.AvailabilityEvent.OpponentName)
                                          ? "<h2>Practice</h2>"
                                          : string.Format("<h2>Practice &mdash; {0}</h2>", message.AvailabilityEvent.OpponentName));
                    break;

                case Game.EventType.Meeting:
                    abBody.Append(string.IsNullOrEmpty(message.AvailabilityEvent.OpponentName)
                                          ? "<h2>Meeting</h2>"
                                          : string.Format("<h2>Meeting &mdash; {0}</h2>", message.AvailabilityEvent.OpponentName));
                    break;

                case Game.EventType.Party:
                    abBody.Append(string.IsNullOrEmpty(message.AvailabilityEvent.OpponentName)
                                          ? "<h2>Party</h2>"
                                          : string.Format("<h2>Party &mdash; {0}</h2>", message.AvailabilityEvent.OpponentName));
                    break;

                default:
                    abBody.Append(string.IsNullOrEmpty(message.AvailabilityEvent.OpponentName)
                                          ? string.Format("<h2>{0}</h2>", message.TeamName)
                                          : string.Format("<h2>{0} &mdash; {1}</h2>", message.TeamName, message.AvailabilityEvent.OpponentName));
                    break;
                }

                abBody.Append("<table>");
                if (message.AvailabilityEvent.When != null)
                {
                    abBody.Append(string.Format("<tr><td style='width: 80px'>When:</td><td>{0}</tr>", message.AvailabilityEvent.When));
                }
                if (message.AvailabilityEvent.Where != null)
                {
                    abBody.Append(string.Format("<tr><td>Where:</td><td>{0}</td></tr>", message.AvailabilityEvent.Where));
                }
                else
                {
                    abBody.Append(string.Format("<tr><td>Where:</td><td>{0}</td></tr>", "To Be Determined"));
                }
                if (message.AvailabilityEvent.Location != null && !string.IsNullOrWhiteSpace(message.AvailabilityEvent.Location.InternalLocation))
                {
                    abBody.Append(string.Format("<tr><td>Arena:</td><td>{0}</tr>", message.AvailabilityEvent.Location.InternalLocation));
                }
                abBody.Append("</table>");

                abBody.Append("<h4>Can you make it?</h4>");
                abBody.Append("<p style='overflow: hidden'>");
                abBody.Append(string.Format("<a style='float: left; display: block; width: 70px; border: solid #666 1px; padding: 8px 5px; margin-right: 7px; text-align: center;' href='{0}'>Yes</a>", replyEmail + "&reply=1"));
                abBody.Append(string.Format("<a style='float: left; display: block; width: 70px; border: solid #666 1px; padding: 8px 5px; margin-right: 7px; text-align: center;' href='{0}'>No</a>", replyEmail + "&reply=2"));
                abBody.Append(string.Format("<a style='float: left; display: block; width: 70px; border: solid #666 1px; padding: 8px 5px; margin-right: 7px; text-align: center;' href='{0}'>Maybe</a>", replyEmail + "&reply=3"));
                abBody.Append("</p>");
            }

            // Finally, add the footer
            string footer = string.Format("<hr/><p>This message sent on behalf of {0} by Teamkeep.com</p>", message.TeamName);

            using (var entities = Database.GetEntities())
            {
                var sentToEmails = new List <string>();
                foreach (var recipentId in message.RecipientPlayerIds)
                {
                    var playerData = entities.PlayerDatas.Single(x => x.Id == recipentId);
                    var teamId     = entities.PlayerGroupDatas.Single(x => x.Id == playerData.GroupId).TeamId;

                    if (message.TeamId != teamId)
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(playerData.Email))
                    {
                        continue;
                    }
                    if (sentToEmails.Contains(playerData.Email, StringComparer.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    var finishedBody = contentBody.ToString() + abBody + footer; // ensures a copy is made

                    if (message.RequestAvailability)
                    {
                        var abData = new AvailabilityData
                        {
                            EventId   = message.AvailabilityEventId,
                            PlayerId  = playerData.Id,
                            Token     = AuthToken.GenerateKey(playerData.Email),
                            EmailSent = DateTime.Now
                        };
                        entities.AvailabilityDatas.AddObject(abData);

                        finishedBody = finishedBody.Replace("TEAMKEEPRSVPTOKEN", abData.Token); // generate and replace TEAMKEEPRSVPTOKEN
                    }

                    Enqueue(playerData.Email, "[" + message.TeamName + "] " + message.Subject, finishedBody, "*****@*****.**", message.From);
                    sentToEmails.Add(playerData.Email);
                }

                // Store sent email in db as MessageData
                string to = sentToEmails.Aggregate("", (current, sentTo) => current + (sentTo + "; ")).Trim();

                var messageData = new MessageData
                {
                    TeamId  = message.TeamId,
                    Date    = DateTime.Now,
                    To      = to,
                    Subject = message.Subject,
                    Content = contentBody.ToString()
                };
                entities.MessageDatas.AddObject(messageData);
                entities.SaveChanges();

                message.Id      = messageData.Id;
                message.To      = messageData.To;
                message.Date    = messageData.Date;
                message.Subject = messageData.Subject;
                message.Content = messageData.Content;
            }

            if (AutomaticallySend)
            {
                SendQueuedMessages();
            }

            return(message);
        }