Example #1
0
        public void WriteMail(EmailBase template)
        {
            HttpContext.Current = new HttpContext(
                new HttpRequest(null, "https://sim-planner.com", null),
                new HttpResponse(new StringWriter())
                );

            // User is logged in
            HttpContext.Current.User = TestICal.GetTestAllRolesPrincipal();

            using (var msg = new MailMessage("[email protected]", HttpContext.Current.User.Identity.Name))
            {
                string dir = Path.GetFullPath("TestEmails");
                Directory.CreateDirectory(dir);
                msg.CreateHtmlBody(template);
                using (SmtpClient client = new SmtpClient("mysmtphost"))
                {
                    client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                    client.PickupDirectoryLocation = dir;
                    client.Send(msg);
                }
                string fileName = ((object)template).GetType().Name;
                File.WriteAllText(Path.Combine(dir, fileName + ".txt"), msg.Body);
                var htmlStream = msg.AlternateViews.First(av => av.ContentType.MediaType == MediaTypeNames.Text.Html).ContentStream;
                using (var fileStream = File.Create(Path.Combine(dir, fileName + ".html")))
                {
                    htmlStream.Seek(0, SeekOrigin.Begin);
                    htmlStream.CopyTo(fileStream);
                }
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="course"></param>
        /// <param name="user"></param>
        /// <returns>a lookup true = successfully emailed, false = email failed</returns>
        public static async Task<ILookup<bool, CourseParticipant>> SendEmail(Course course, IPrincipal user)
        {
            using (var cal = Appointment.CreateCourseAppointment(course, user.Identity))
            {
                using (var appt = new AppointmentStream(cal))
                {
                    var map = ((Expression<Func<CourseParticipant, CourseParticipantDto>>)new CourseParticipantMaps().MapToDto).Compile();
                    var faculty = course.CourseParticipants.Where(cp => !map(cp).IsEmailed)
                        .ToLookup(cp => cp.IsFaculty);

                    IEnumerable<Attachment> attachments = new Attachment[0];
                    using (var client = new SmtpClient())
                    {
                        var mailMessages = new List<ParticipantMail>();
                        var sendMail = new Action<CourseParticipant>(cp =>
                        {
                            var mail = new MailMessage();
                            mail.To.AddParticipants(cp.Participant);
                            var confirmEmail = new CourseInvite { CourseParticipant = cp };
                            mail.CreateHtmlBody(confirmEmail);
                            appt.AddAppointmentsTo(mail);
                            foreach (var a in attachments)
                            {
                                a.ContentStream.Position = 0;
                                mail.Attachments.Add(a);
                            }
                            mailMessages.Add(new ParticipantMail { Message = mail, SendTask = client.SendMailAsync(mail), CourseParticipant = cp });
                        });

                        foreach (var cp in faculty[false])
                        {
                            sendMail(cp);
                        }
                        if (faculty[true].Any())
                        {
                            if (course.FacultyMeetingUtc.HasValue)
                            {
                                using (var fm = Appointment.CreateFacultyCalendar(course))
                                {
                                    appt.Add(fm);
                                }
                            }
                            attachments = GetFilePaths(course).Select(fp => new Attachment(fp.Value, System.Net.Mime.MediaTypeNames.Application.Zip) { Name = fp.Key })
                                .Concat(new[] { new Attachment(CreateDocxTimetable.CreateTimetableDocx(course, WebApiConfig.DefaultTimetableTemplatePath), OpenXmlDocxExtensions.DocxMimeType) { Name = CreateDocxTimetable.TimetableName(course)} });
                            foreach (var cp in faculty[true])
                            {
                                sendMail(cp);
                            }
                        }
                        await Task.WhenAll(mailMessages.Select(mm => mm.SendTask));
                        mailMessages.ForEach(mm => mm.Message.Dispose());
                        return mailMessages.ToLookup(k => k.SendTask.Status == TaskStatus.RanToCompletion, v => v.CourseParticipant);
                    }
                }
            }
        }
        public async Task<IHttpActionResult> Rsvp(RsvpBindingModel model)
        {
            var find = model.Auth.HasValue ? new[] { model.Auth.Value, model.ParticipantId }
                : new[] { model.ParticipantId };
            var cps = await Repo.CourseParticipants.Include("Participant").Include("Course")
                .Where(cp=>cp.CourseId == model.CourseId && find.Contains(cp.ParticipantId)).ToListAsync();

            var part = cps.First(cp => cp.ParticipantId == model.ParticipantId);

            CourseParticipant auth = null;
            if (model.Auth.HasValue)
            {
                auth = cps.First(cp => cp.ParticipantId == model.Auth && cp.IsOrganiser);
            }

            if (part.Course.StartUtc < DateTime.UtcNow)
            {
                return Ok("Confirmation status cannot be changed after the course has commenced.");
            }

            string userName = part.Participant.FullName;
            var returnString = "registered as " + (model.IsAttending ? "attending" : "unable to attend");
            if (model.IsAttending == part.IsConfirmed && !model.Auth.HasValue)
            {
                return Ok(userName + " is already " + returnString);
            }
            if (model.Auth.HasValue)
            {
                bool wasConfirmed = part.IsConfirmed.Value;
                part.IsConfirmed = model.IsAttending;
                await Repo.SaveChangesAsync();
                using (var client = new SmtpClient())
                {
                    using (var mail = new MailMessage())
                    {
                        mail.To.AddParticipants(part.Participant);
                        mail.CC.AddParticipants((from cp in part.Course.CourseParticipants
                                                    where cp.IsOrganiser
                                                    select cp.Participant).ToArray());
                        var confirmEmail = new AuthConfirmationResult
                        {
                            CourseParticipant = part,
                            Auth = auth.Participant,
                            IsChanged = wasConfirmed != model.IsAttending
                        };
                        mail.CreateHtmlBody(confirmEmail);
                        await client.SendMailAsync(mail);
                    }
                }
                return Ok(userName + " is now " + returnString + ". A confirmation email has been sent, with copies to the course organisers.");
            }
            if (!part.IsConfirmed.HasValue || part.IsOrganiser)
            {
                part.IsConfirmed = model.IsAttending;
                await Repo.SaveChangesAsync();
                return Ok(userName + " is now " + returnString);
            }

            using (var client = new SmtpClient())
            {
                foreach (var org in part.Course.CourseParticipants.Where(p=>p.IsOrganiser))
                {
                    using (var mail = new MailMessage())
                    {
                        mail.To.AddParticipants(org.Participant);
                        var confirmEmail = new ReverseConfirmation
                        {
                            CourseParticipant = part,
                            AuthorizationToken = org.ParticipantId.ToString("N")
                        };
                        mail.CreateHtmlBody(confirmEmail);
                        await client.SendMailAsync(mail);
                    }
                }
            }
            return Ok(userName + " had been confirmed as " + (part.IsConfirmed.Value ? "attending" : "not attending")
                + ", but would like to change to being " + returnString + ". An email has been sent to the course organiser(s), who will be able to confirm this change.");
        }
Example #4
0
        public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var participant = await UserManager.FindByEmailAsync(model.Email);

            if (participant != null)
            {
                if (participant.SecurityStamp == null)
                {
                    var ir = await UserManager.UpdateSecurityStampAsync(participant.Id);
                    if (!ir.Succeeded)
                    {
                        throw new FieldAccessException("Could not UpdateSecurityStampAsync - following errors:" + string.Join("\r\n",ir.Errors));
                    }
                }
                var resetEmail = new ForgotPasswordTemplate
                {
                    Token = await UserManager.GeneratePasswordResetTokenAsync(participant.Id),
                    UserId = participant.Id
                };

                using (var mail = new MailMessage())
                {
                    mail.To.Add(model.Email);
                    mail.CreateHtmlBody(resetEmail);
                    using (var client = new SmtpClient())
                    {
                        client.Send(mail);
                    }
                }

            }
            //return GetErrorResult(result);

            return Ok();
        }