public ActionResult Update_MyAvailableTime([DataSourceRequest]DataSourceRequest request, MeetingViewModel task)
        {
            if (ModelState.IsValid)
            {
                using (var context = new ApplicationDbContext())
                {
                    // Create a new Task entity and set its properties from the posted TaskViewModel
                    var entity = new Meeting
                    {
                        Id = task.Id,
                        Title = task.Title,
                        Start = task.Start,
                        End = task.End,
                        Description = task.Description,
                        RecurrenceRule = task.RecurrenceRule,
                        RecurrenceException = task.RecurrenceException,
                        RecurrenceId = task.RecurrenceId,
                        IsAllDay = task.IsAllDay,
                        InstructorId = task.InstructorId,
                        MeetingTypeId = task.MeetingTypeId
                    };
                    // Attach the entity
                    context.Meetings.Attach(entity);
                    // Change its state to Modified so Entity Framework can update the existing task instead of creating a new one
                    context.Entry(entity).State = EntityState.Modified;
                    // Update the entity in the database
                    try
                    {
                        // Insert the entity in the database
                        context.SaveChanges();
                    }
                    catch (Exception ex)
                    {

                        Log4NetHelper.Log("Error Updating Available Meeting Available Meeting", LogLevel.ERROR, "MeetingsServices", 497, "tester", ex);
                    }
                }
            }
            // Return the updated task. Also return any validation errors.
            return Json(new[] { task }.ToDataSourceResult(request, ModelState));
        }
 public ActionResult Destroy_MyAvailableTime([DataSourceRequest]DataSourceRequest request, MeetingViewModel task)
 {
     if (ModelState.IsValid)
     {
         using (var context = new ApplicationDbContext())
         {
             // Create a new Task entity and set its properties from the posted TaskViewModel
             var meeting = new Meeting
             {
                 Id = task.Id,
                 Title = task.Title,
                 Start = task.Start,
                 End = task.End,
                 Description = task.Description,
                 RecurrenceRule = task.RecurrenceRule,
                 RecurrenceException = task.RecurrenceException,
                 RecurrenceId = task.RecurrenceId,
                 IsAllDay = task.IsAllDay,
                 InstructorId = task.InstructorId
             };
             context.Meetings.Attach(meeting);
             context.Meetings.Remove(meeting);
             context.SaveChanges();
         }
     }
     // Return the removed task. Also return any validation errors.
     return Json(new[] { task }.ToDataSourceResult(request, ModelState));
 }
        public static Meeting CreateMeetingforGtm(MeetingViewModel meeting, string courseTitle, string joinUrl,
            ApplicationUser instructor)
        {
            using (var context = new ApplicationDbContext())
            {
                //Create a new Task entity and set its properties from the posted TaskViewModel
                var newMeeting = new Meeting
                {
                    Title = meeting.Title,
                    Start = meeting.Start,
                    End = meeting.End,
                    Description = meeting.Description,
                    RecurrenceRule = meeting.RecurrenceRule,
                    RecurrenceException = meeting.RecurrenceException,
                    RecurrenceId = meeting.RecurrenceId,
                    IsAllDay = false,
                    CourseId = meeting.CourseId,
                    GtmUrl = joinUrl,
                    InstructorId = instructor.Id,
                    MeetingTypeId = (int) MeetingType.ClassMeeting,
                    StudentId = instructor.Id
                };

                try
                {
                    context.Meetings.Add(newMeeting);
                    context.SaveChanges();
                }
                    //catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
                    //{
                    //    //Exception raise = dbEx;
                    //    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    //    {
                    //        foreach (var validationError in validationErrors.ValidationErrors)
                    //        {
                    //            string errorMessage = string.Format("{0}:{1}",
                    //                validationErrors.Entry.Entity.ToString(),
                    //                validationError.ErrorMessage);
                    //            // raise a new exception nesting
                    //            // the current instance as InnerException
                    //            //raise = new InvalidOperationException(errorMessage, raise);
                    //        }
                    //    }
                    //    Log4NetHelper.Log("Did not save new Class Meeting - Validation Error", LogLevel.ERROR, "MeetingServices", 585, "tester", dbEx);
                    //}


                catch (Exception ex)
                {
                    Log4NetHelper.Log("Did not save new Class Meeting", LogLevel.ERROR, "MeetingServices", 585, "tester",
                        ex);
                }

                // Get the TaskID generated by the database
                meeting.Id = newMeeting.Id;

                return newMeeting;
            }
        }
        private static MailMessage GenerateConfirmationEmailMessage(Meeting bookedMeeting, IEmailService emailService,
            ApplicationUserManager userManager)
        {
            var instructor = userManager.FindById(bookedMeeting.InstructorId);
            var student = userManager.FindById(bookedMeeting.StudentId);
            var subjectLine = "Meeting: " + bookedMeeting.Title + " - " + StarterTimeText(bookedMeeting);
            var bodyText = GenerateBodyText(bookedMeeting, "", student, instructor);

            var confirmationEmailMessage = BuildEmailMessage(student, subjectLine, bodyText);
            return confirmationEmailMessage;
        }
        public static Meeting CreateMyAvailableTime(MeetingViewModel meeting, string currentUserId)
        {
            using (var context = new ApplicationDbContext())
            {
                //Create a new Task entity and set its properties from the posted TaskViewModel
                var entity = new Meeting
                {
                    Id = meeting.Id,
                    Title = meeting.Title,
                    Start = meeting.Start,
                    End = meeting.End,
                    Description = meeting.Description,
                    RecurrenceRule = meeting.RecurrenceRule,
                    RecurrenceException = meeting.RecurrenceException,
                    RecurrenceId = meeting.RecurrenceId,
                    IsAllDay = meeting.IsAllDay,
                    InstructorId = currentUserId,
                    MeetingTypeId = Convert.ToInt32(MeetingType.Available)
                };


                // Add the entity
                context.Meetings.Add(entity);
                try
                {
                    // Insert the entity in the database
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Log4NetHelper.Log("Choked Creating new Available Meeting", LogLevel.ERROR, "MeetingsServices", 497,
                        "tester", ex);
                }

                // Get the TaskID generated by the database
                meeting.Id = entity.Id;

                return entity;
            }
        }
        public static string CreateGtmForAvailableSlot(ApplicationDbContext context, Meeting meeting)
        {
            var gtmKeySet = context.GtmKeySets.First();
            var userId = gtmKeySet.Email;
            var password = gtmKeySet.EmailPassword;


            // a request to login is created and sent. From the response
            // we need to store at least the access token to use for further calls

            var meetingRequestUri = new RequestDirectLogin(gtmKeySet.ConsumerKey, userId, password);
            string output;
            var resp = meetingRequestUri.Send(out output);

            var meetingsApi = new MeetingsApi();
            var newMeeting = new MeetingReqCreate
            {
                subject = meeting.Title,
                starttime = meeting.Start,
                endtime = meeting.End,
                passwordrequired = false,
                conferencecallinfo = "Hybrid",
                timezonekey = "",
                meetingtype = MeetingReqCreate.MeetingtypeEnum.scheduled
            };

            var oauthToken = resp != null ? resp.AccessToken : "";
            try
            {
                var meetingCreated = meetingsApi.createMeeting(oauthToken, newMeeting);
                return meetingCreated.First().joinURL;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Log4NetHelper.Log("Meeting Booking Failed", LogLevel.ERROR, "CreateGtmForAvailableSlot", 572,
                    meeting.Title, ex);
                return "";
            }
        }
        private static string GenerateInvitationText(Meeting checkedMeeting, string courseTitle,
            ApplicationUser recipient, ApplicationUser host)
        {
            var recipientStartTimeText =
                checkedMeeting.Start.AddMinutes(recipient.UtcOffSet).ToString("dddd MMM-d-yyyy h:mm tt");
            var bodyText = host.FirstNameLastInitial + " is inviting " + recipient.FirstNameLastInitial +
                           " to attend an online meeting booked for " + recipientStartTimeText;

            var headHtml = EmailBuilder.Head("Meeting Booked");
            var titleHtml = EmailBuilder.Title(checkedMeeting.Title);
            var courseTitleHtml = EmailBuilder.SubTitle(courseTitle);
            var photoPath = EmailBuilder.PhotoPath(!string.IsNullOrEmpty(host.Photo) ? host.Photo : "male.png");
            var photoHtml = EmailBuilder.HeroImage(photoPath, host.FullName);
            var startTimeHtml = EmailBuilder.StartTime(recipientStartTimeText);
            var bodyTextHtml = EmailBuilder.BodyText(bodyText);
            var button = EmailBuilder.Button(checkedMeeting.GtmUrl, "Launch Meeting");

            var footerHtml = EmailBuilder.Footer("Check30 Integration Inc.<br>Vancouver Canada");

            return headHtml + titleHtml + courseTitleHtml + photoHtml + startTimeHtml + bodyTextHtml + button +
                   footerHtml;
        }
        public static void Send_Private_Booking_Invitation(Meeting meetingBooked, IEmailService emailService,
            ApplicationUserManager userManager)
        {
            var instructor = userManager.FindById(meetingBooked.InstructorId);
            var student = userManager.FindById(meetingBooked.StudentId);
            var subjectLine = "Meeting: " + meetingBooked.Title + " - " + StarterTimeText(meetingBooked);
            var bodyText = GenerateInvitationText(meetingBooked, "", student, instructor);

            var confirmationEmailMessage = BuildEmailMessage(student, subjectLine, bodyText);
            try
            {
                emailService.SendAsync(confirmationEmailMessage);
                Log4NetHelper.Log("Send Message To Student: " + confirmationEmailMessage.To, LogLevel.INFO,
                    "ProcessPrivateMeetingNotifications", meetingBooked.Id,
                    instructor.Email, null);
            }
            catch (Exception ex)
            {
                Log4NetHelper.Log("Send Student Message Failed - ", LogLevel.ERROR, "Meetings", meetingBooked.Id,
                    instructor.Email, ex);
            }
        }
        public static void SendMeetingNotifications(Course course, Meeting meetingBooked, IEmailService emailService,
            ApplicationDbContext context, ApplicationUser instructor)
        {
            var enrollments = context.Enrollments.Include("ApplicationUser").Where(e => e.CourseId == course.Id);
            foreach (var enrollment in enrollments)
            {
                try
                {
                    var bodyText = GenerateBodyText(meetingBooked, course.Title, enrollment.ApplicationUser, instructor);

                    var confirmationEmailMessage = BuildEmailMessage(enrollment.ApplicationUser, meetingBooked.Title,
                        bodyText);
                    emailService.SendAsync(confirmationEmailMessage);
                    var logMessage = "Notice of meeting for " + course.Title + " - " + meetingBooked.Title + " sent to " +
                                     enrollment.ApplicationUser.FullName;
                    Log4NetHelper.Log("logMessage", LogLevel.INFO, "MeetingService", 133,
                        meetingBooked.Instructor.FullName, null);
                }
                catch (Exception ex)
                {
                    Log4NetHelper.Log("Send Student Message Failed - ", LogLevel.ERROR, "ManageMeetings", 342, "Tester",
                        ex);
                }
            }
        }
 private static string StarterTimeText(Meeting meeting)
 {
     return meeting.Start.AddMinutes(TimeDateServices.GetUtcOffSet()).ToString("dddd MMM-d-yyyy h:mm tt");
 }
        public ActionResult Invite(Meeting form, string studentId)
        {
            var meeting = _context.Meetings.Find(form.Id);
            var gtmUrl = MeetingsServices.CreateGtmForAvailableSlot(_context, meeting);

            if(!string.IsNullOrEmpty(gtmUrl))
            {
                meeting.StudentId = studentId;
                meeting.MeetingTypeId = (int)MeetingType.PrivateMeeting;
                var student = _userManager.FindById(studentId);
                meeting.Title += " - " + student.FirstNameLastInitial;
                meeting.GtmUrl = gtmUrl;
                _context.SaveChanges();

                MeetingsServices.Send_Private_Booking_Invitation(meeting, _emailService, _userManager);
                return RedirectToAction("MyEnrollments", "Enrollments");
            }
            else
            {
                return RedirectToAction("Unable");
            }

            
        }