Esempio n. 1
0
 /// <summary>
 /// Renders a partial MVC view to the given writer. Use this method to render
 /// a partial view that doesn't merge with _Layout and doesn't fire
 /// _ViewStart.
 /// </summary>
 /// <param name="viewPath">
 /// The path to the view to render. Either in same controller, shared by
 /// name or as fully qualified ~/ path including extension
 /// </param>
 /// <param name="model">The model to pass to the viewRenderer</param>
 /// <param name="controllerContext">Active Controller context</param>
 /// <param name="writer">Writer to render the view to</param>
 /// <param name="errorMessage">optional out parameter that captures an error message instead of throwing</param>
 /// <returns>String of the rendered view or null on error</returns>
 public static void RenderView(string viewPath, object model, TextWriter writer,
                               ControllerContext controllerContext,
                               out string errorMessage)
 {
     errorMessage = null;
     try
     {
         ViewRenderer renderer = new ViewRenderer(controllerContext);
         renderer.RenderView(viewPath, model, writer);
     }
     catch (Exception ex)
     {
         errorMessage = ex.GetBaseException().Message;
     }
 }
Esempio n. 2
0
 public override void WriteToStream(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content)
 {
     using (var writer = new StreamWriter(writeStream))
     {
         var lp = value as LearningPlanDTO;
         if (lp == null)
         {
             throw new InvalidOperationException("Cannot serialize type");
         }
         var converter = new SelectPdf.HtmlToPdf();
         var html      = ViewRenderer.RenderView("~/Views/LearningPlanPDF.cshtml", lp);
         converter.Options.MarginTop    = 35;
         converter.Options.MarginBottom = 35;
         var doc = converter.ConvertHtmlString(html);
         doc.Save(writeStream);
     }
 }
Esempio n. 3
0
        /// <summary>
        /// Renders the view.
        /// </summary>
        /// <param name="StatusCode">The status code.</param>
        /// <returns></returns>
        private string RenderView(int StatusCode)
        {
            var technicalContactEmail = System.Configuration.ConfigurationManager.AppSettings["TechnicalContactEmail"];

            var ErrorList = new List <HttpErrorPage>();

            ErrorList.Add(new HttpErrorPage()
            {
                ErrorCode = 400, ErrorTitle = "Bad Request ", ErrorDescription = "The server cannot process the request due to something that is perceived to be a client error.", TechnicalContact = technicalContactEmail
            });
            ErrorList.Add(new HttpErrorPage()
            {
                ErrorCode = 401, ErrorTitle = "Unauthorized", ErrorDescription = "The requested resource requires authentication.", TechnicalContact = technicalContactEmail
            });
            ErrorList.Add(new HttpErrorPage()
            {
                ErrorCode = 500, ErrorTitle = "Webservice currently unavailable ", ErrorDescription = "An unexpected condition was encountered.Our service team has been dispatched to bring it back online.", TechnicalContact = technicalContactEmail
            });

            var response = HttpContext.Current.Response;

            var z = ErrorList.Where(x => x.ErrorCode == StatusCode).FirstOrDefault();

            if (z == null)
            {
                z = new HttpErrorPage()
                {
                    ErrorCode        = StatusCode,
                    ErrorTitle       = "Unknown Error",
                    ErrorDescription = "An unknown error has occured.",
                    TechnicalContact = technicalContactEmail
                };
            }


            // Create an arbitrary controller instance
            var controller = ViewRenderer.CreateController <FakeController>();

            string html = ViewRenderer.RenderView(
                string.Format("~/views/shared/HttpErrorPages/Error.cshtml", StatusCode.ToString()),
                z,
                controller.ControllerContext);

            return(html);
        }
Esempio n. 4
0
        private static MailMessage GetMailMessage(this ErrorModel ex, string from, string to)
        {
            // Construct the alternate body as HTML.
            // Partial template
            string body = ViewRenderer.RenderView("~/Views/Email/ErrorMail.cshtml", ex);
            //ViewRend.RenderPartialViewToString<EmailController>("ErrorMail", ex);

            var mail = new MailMessage
            {
                From       = new MailAddress(from),
                Subject    = $"{ex.AppName} v{ex.Version} at {ex.ErrorTime}",
                Body       = body,
                To         = { new MailAddress(to) }, //mail.To.Add(new MailAddress(bugTrackerAddress));
                IsBodyHtml = true
            };

            return(mail);
        }
        protected override void RenderCustomException(CustomException exception)
        {
            //Application.Context.RewritePath(ErrorViewPath);

            var model = new ErrorModel()
            {
                Message     = exception.Message,
                FullMessage = exception.ToString(),
                StackTrace  = exception.StackTrace,
                Url         = Application.Request.RawUrl,
                StatusCode  = Application.Response.StatusCode,
            };

            Trace.TraceWarning("Rendering razor view: {0}", ErrorViewPath);
            var html = ViewRenderer.RenderView(ErrorViewPath, model);

            Application.Response.Write(html);
        }
        public async Task <IHttpActionResult> DeleteCoachingSession(int id)
        {
            var currentUser     = AppUserManager.FindById(User.Identity.GetUserId());
            var coachingSession = AppDb.CoachingSessions
                                  .Include(i => i.CoachingProgram.Coach)
                                  .Include(i => i.CoachingProgram.Coachee)
                                  .FirstOrDefault(i => i.Id == id);
            var subject = String.Format("right.now. Coaching Session with {0} and {1}", coachingSession.CoachingProgram.Coach.GetFullName(), coachingSession.CoachingProgram.Coachee.GetFullName());

            coachingSession.Sequence += 1;
            var ical       = GetiCal(coachingSession, subject, "CANCELLED");
            var attachment = System.Net.Mail.Attachment.CreateAttachmentFromString(ical, String.Format("{0}.ics", subject));

            if (coachingSession == null)
            {
                return(NotFound());
            }
            var emailContentCoach = ViewRenderer.RenderView("~/Views/Email/Session Deleted.cshtml",
                                                            new System.Web.Mvc.ViewDataDictionary {
                { "Session", coachingSession },
                { "Url", String.Format("{0}/program/{1}/", Request.RequestUri.Authority, coachingSession.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(coachingSession.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(coachingSession.CoachingProgram.Coach.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(coachingSession.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(coachingSession.CoachingProgram.Coach.Timezone)) },
            });
            var coachEmail          = coachingSession.CoachingProgram.Coach.Email;
            var emailContentCoachee = ViewRenderer.RenderView("~/Views/Email/Session Deleted.cshtml",
                                                              new System.Web.Mvc.ViewDataDictionary {
                { "Session", coachingSession },
                { "Url", String.Format("{0}/program/{1}/", Request.RequestUri.Authority, coachingSession.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(coachingSession.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(coachingSession.CoachingProgram.Coachee.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(coachingSession.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(coachingSession.CoachingProgram.Coachee.Timezone)) },
            });
            var coacheeEmail = coachingSession.CoachingProgram.Coachee.Email;

            AppDb.CoachingSessions.Remove(coachingSession);
            await AppDb.SaveChangesAsync();

            EmailSender.SendEmail(coachEmail, "right.now. Video Coaching Session Cancelled", emailContentCoach, attachment);
            EmailSender.SendEmail(coacheeEmail, "right.now. Video Coaching Session Cancelled", emailContentCoachee, attachment);

            return(Ok(coachingSession));
        }
Esempio n. 7
0
        public IHttpActionResult PutSendInvoiceForCoachingProgram(int id, Decimal amount)
        {
            var currentUser     = AppUserManager.FindById(User.Identity.GetUserId());
            var coachingProgram = GetCoachingPrograms(currentUser)
                                  .Include(i => i.CoachingSessions)
                                  .Include(i => i.Coach)
                                  .Include(i => i.Coachee)
                                  .FirstOrDefault(i => i.Id == id);

            if (coachingProgram == null || coachingProgram.IsClosed || coachingProgram.InvoiceAmount > 0)
            {
                return(BadRequest("Program Not Found"));
            }

            coachingProgram.InvoiceAmount = amount;
            AppDb.Entry(coachingProgram).Property(i => i.InvoiceAmount).IsModified = true;
            coachingProgram.UpdatedAt = DateTime.Now;
            AppDb.Entry(coachingProgram).Property(i => i.UpdatedAt).IsModified = true;

            var html = ViewRenderer.RenderView("~/Views/Email/Send Invoice.cshtml",
                                               new System.Web.Mvc.ViewDataDictionary {
                { "Program", coachingProgram },
            });

            try
            {
                AppDb.SaveChanges();
                EmailSender.SendEmail(ConfigurationManager.AppSettings["AdminEmail"], "right.now. Coaching Invoice - " + coachingProgram.Coach.FirstName + " " + coachingProgram.Coach.LastName, html, null, coachingProgram.Coach.Email, coachingProgram.Coach.FirstName + " " + coachingProgram.Coach.LastName);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CoachingProgramExists(id, currentUser))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(StatusCode(HttpStatusCode.NoContent));
        }
        public void GettingStartedLocalInstallMobile(string outDir, string filePath)
        {
            GettingStartedViewModel model = ViewModelFactory.CreateGettingStartedViewModel(this.PathHelper, this.TableOfContentsRepository, this.HelpContentRepository,
                                                                                           this.ControlRepository, this.SampleRepository, filePath, MemoryCache.Default);

            string sample = ViewRenderer.RenderView("~/Views/Shared/GettingStarted.cshtml", model,
                                                    ControllerContext);

            string        gettingStartedMobile         = sample.Replace("href=\"~/", rootHref).Replace(rootHref, "href=\"./").Replace(rootSrc, "src=\"./").Replace("src=\"./../igniteui/", "src=\"./igniteui/");
            string        gettingStartedMobileFileName = Path.Combine(outDir, "getting-started-mobile.html");
            List <string> iframeSrcs = new List <string>();

            foreach (Sample s in model.GettingStartedContent.Samples)
            {
                this.CreateMobileSamplePage(outDir, s.Control.PathID, s.PathID);
                iframeSrcs.Add(s.Control.PathID + "/" + s.PathID);
            }
            gettingStartedMobile = parser.AddFileExtentionToIFrames(gettingStartedMobile, iframeSrcs);
            parser.ChangeNavLinks(gettingStartedMobile, gettingStartedMobileFileName);
        }
        public HttpResponseMessage CreateComment([FromBody] ActivitiesEditInputModel inputModel)
        {
            inputModel.Source = "W";
            HttpResponseMessage     response  = null;
            ActivitiesEditViewModel viewModel = new ActivitiesModelBuilder().CreateActivityComment(inputModel);

            if (viewModel.Error.HasError)
            {
                response         = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(viewModel.Error.ErrorMessage);
            }
            else
            {
                response = new HttpResponseMessage(HttpStatusCode.OK);
                string result = ViewRenderer.RenderView("~/Views/PartialViews/_ActivitiesComment.cshtml", viewModel, null);
                response.Content = new StringContent(result);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
            }
            return(response);
        }
        public async Task <ActionResult> SendMail(PrivateMessage privateMessage)
        {
            var currentUserId = User.GetPrincipal()?.User.Id;
            var currentUser   = db.Users.Find(currentUserId);

            if (currentUser == null)
            {
                return(HttpNotFound());
            }

            var receiver = db.Users.Find(privateMessage.Receiver.Id);

            if (receiver == null)
            {
                return(HttpNotFound());
            }

            db.PrivateMessages.Add(new PrivateMessage
            {
                Content    = privateMessage.Content,
                DateSent   = DateTime.Now,
                IsRead     = false,
                ReceiverId = privateMessage.Receiver.Id,
                SenderId   = currentUserId
            });
            db.SaveChanges();

            var mail = new MailMessage(new MailAddress("*****@*****.**"), new MailAddress(receiver.Email))
            {
                Subject = currentUser.FullName() + " kullanıcısından yeni mesaj",
                Body    = ViewRenderer.RenderView("~/Views/Mail/NewMessage.cshtml", new ViewDataDictionary()
                {
                    { "content", privateMessage.Content },
                    { "sender", currentUser.FullName() }
                })
            };

            await ms.SendAsync(mail);

            return(RedirectToAction("MailBox"));
        }
        public async Task <IHttpActionResult> PostForgotPassword(string email)
        {
            if (ModelState.IsValid)
            {
                var user = await AppUserManager.FindByNameAsync(email);

                if (user == null || !(await AppUserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    return(Ok("Please check your Inbox to reset your password"));
                }
                string code = await AppUserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = String.Format("{0}/passwordrecovery/?email={1}&token={2}", Request.RequestUri.GetLeftPart(UriPartial.Authority), email, HttpUtility.UrlEncode(code));
                var emailHtml   = ViewRenderer.RenderView("~/Views/Email/Forgot Password.cshtml",
                                                          new System.Web.Mvc.ViewDataDictionary {
                    { "Url", callbackUrl },
                });
                EmailSender.SendEmail(user.UserName, "right.now. - Reset your Password", emailHtml);
                return(Ok("Please check your Inbox to reset your password"));
            }
            return(Ok("Please check your Inbox to reset your password"));
        }
Esempio n. 12
0
        public async Task <IHttpActionResult> ResendConfirmationEmail()
        {
            UserProfile user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var callbackUrl = Url.Link("ConfirmEmail", new { userId = user.Id, code = code });

            var notification = new AccountNotificationModel
            {
                Code        = code,
                Url         = callbackUrl,
                UserId      = user.Id,
                Email       = user.Email,
                DisplayName = user.UserName
            };

            string body = ViewRenderer.RenderView("~/Views/Mailer/NewAccount.cshtml", notification);
            await UserManager.SendEmailAsync(user.Id, "DurandalAuth account confirmation", body);

            return(Ok());
        }
        public async Task <HttpResponseMessage> ForgotPassword([FromBody] ForgotPasswordRequest request)
        {
            if (!((request.UserName.IsMatch(x => request.UserName, RegexPattern.UserName, ActionContext, ModelState) &&
                   Validation.StringLength(request.UserName, x => request.UserName, 6, 30, ActionContext, ModelState)) ||
                  request.UserName.IsMatch(x => request.UserName, RegexPattern.Email, ActionContext, ModelState)))
            {
                return(ActionContext.Response);
            }

            var response = await _accountService.ForgotPassword(request.UserName);

            if (response.Status.IsOperationSuccessful())
            {
                var html = ViewRenderer.RenderView("~/Views/Home/OutMail/_ForgotPasswordTemplatePartial.cshtml",
                                                   response.Data);
                Helper.SendMail(response.Data.Email, "Reset your iLoop password", html,
                                bodyImages: new List <string> {
                    "~/Images/iLoop.png"
                });
            }
            return(Request.SystemResponse <string>(response.Status));
        }
        public async Task <ActionResult> ResendConfirmation(string userId)
        {
            var code        = _authService.GetEmailVerificationCode(userId);
            var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = userId, code = code }, protocol: Request.Url.Scheme);

            var user = _authService.GetUser(userId);

            var mail = new MailMessage {
                Subject = "PLE Hesap Onayı",
                Body    = ViewRenderer.RenderView("~/Views/Mail/ConfirmEmail.cshtml", new ViewDataDictionary()
                {
                    { "confirmUrl", callbackUrl },
                    { "userName", user.FullName() }
                }),
                IsBodyHtml = true
            };

            mail.Bcc.Add(user.Email);

            await new EmailService().SendAsync(mail);

            return(RedirectToAction("WaitingConfirmation", new { userId = userId }));
        }
Esempio n. 15
0
        public IHttpActionResult PostSendEmailWithPDF(int id, PostSendEmailWithPDFRequest request)
        {
            var currentUser = AppUserManager.FindById(User.Identity.GetUserId());
            var program     = GetCoachingPrograms(currentUser)
                              .FirstOrDefault(i => i.Id == id);
            var lp = new LearningPlanDTO
            {
                Id              = program.Id,
                LearningPlan    = program.LearningPlan,
                UpdatedAt       = program.UpdatedAt,
                CoachingProgram = program,
            };

            var emailHtml = ViewRenderer.RenderView("~/Views/Email/Send Learning Plan as PDF.cshtml",
                                                    new System.Web.Mvc.ViewDataDictionary {
                { "Program", program },
            });

            using (var fileStream = new MemoryStream())
            {
                var coacheeName = String.Format("{0} {1}", currentUser.FirstName, currentUser.LastName);
                var subject     = String.Format("right.now. Coaching Learning Plan for {0}", coacheeName);

                var html      = ViewRenderer.RenderView("~/Views/LearningPlanPDF.cshtml", lp);
                var converter = new SelectPdf.HtmlToPdf();
                converter.Options.MarginTop    = 35;
                converter.Options.MarginBottom = 35;
                var doc = converter.ConvertHtmlString(html);
                doc.Save(fileStream);
                fileStream.Position = 0;
                var attachment = new Attachment(fileStream, subject, "application/pdf");

                EmailSender.SendEmail(request.recipients, subject, emailHtml, attachment);
            }
            return(StatusCode(HttpStatusCode.NoContent));
        }
        public HttpResponseMessage Get(int index)
        {
            int id = index - 1;

            if (id < 0 || id >= _returnValues.Length)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            string accept = Request.Headers.GetValues("Accept").FirstOrDefault();

            if (!string.IsNullOrEmpty(accept) && accept.ToLower().Contains("text/html"))
            {
                dynamic             html    = ViewRenderer.RenderView("~/views/Values/Test.cshtml", _returnValues[id]);
                HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(html, Encoding.UTF8,
                                                "text/html")
                };
                return(message);
            }

            return(Request.CreateResponse(HttpStatusCode.BadRequest, new { html = string.Empty }));
        }
        private async Task <HttpResponseMessage> SignUpPerson(SignUpRequestPerson request)
        {
            var response = await _accountService.SignUpPerson(request);

            if (response.Status.IsOperationSuccessful())
            {
                var registration = new AccountInternal
                {
                    Email               = request.Email,
                    FirstName           = request.FirstName,
                    UserName            = request.UserName,
                    ImageServerAddress  = SystemConstants.ImageServerAddress.ToString(),
                    UrlRegistrationLink =
                        new Uri(new Uri(SystemConstants.WebUrl.Value),
                                "index.html#/activation/" +
                                HttpUtility.UrlEncode(Convert.ToBase64String(Encoding.UTF8.GetBytes(request.UserName))) + "/" +
                                HttpUtility.UrlEncode((Convert.ToBase64String(Encoding.UTF8.GetBytes(response.Data.UserGuid)))))
                        .ToString(),
                    UrlVerificationLink =
                        new Uri(new Uri(SystemConstants.WebUrl.Value),
                                "index.html#/activation/" +
                                HttpUtility.UrlEncode(Convert.ToBase64String(Encoding.UTF8.GetBytes(request.UserName))) + "/")
                        .ToString(),
                    UserGuid = response.Data.UserGuid,
                    UserId   = response.Data.UserId
                };

                var html = ViewRenderer.RenderView("~/Views/Home/OutMail/_RegistrationTemplatePartial.cshtml",
                                                   registration);
                Helper.SendMail(registration.Email, "Activation Mail", html,
                                bodyImages: new List <string> {
                    "~/Images/iLoop.png"
                });
            }
            return(Request.SystemResponse <string>(response.Status));
        }
Esempio n. 18
0
        public string ViewRenderer()
        {
            var renderer = new ViewRenderer();

            return(renderer.RenderView("~/Views/Utilities/ScriptVariables.cshtml", null));
        }
 public string IndexLocalInstall(IndexViewModel model)
 {
     model.LocalZipInstall = true;
     return(ViewRenderer.RenderView("~/Views/Shared/Index.cshtml", model,
                                    ControllerContext));
 }
        public async Task <IHttpActionResult> PutCoachingSession(int id, CoachingSession dto)
        {
            var currentUser = AppUserManager.FindById(User.Identity.GetUserId());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var isAdmin         = AppUserManager.IsInRole(currentUser.Id, "Admin");
            var coachingSession = AppDb.CoachingSessions
                                  .Where(i =>
                                         i.CoachingProgram.Coach.Id == currentUser.Id ||
                                         i.CoachingProgram.Coachee.Id == currentUser.Id ||
                                         isAdmin)
                                  .FirstOrDefault(i => i.Id == id);

            if (coachingSession == null)
            {
                return(BadRequest("Session Not Found"));
            }

            var updateICal = coachingSession.StartedAt != dto.StartedAt || coachingSession.FinishedAt != dto.FinishedAt;

            if (updateICal)
            {
                coachingSession.Sequence += 1;
            }
            coachingSession.StartedAt  = dto.StartedAt;
            coachingSession.FinishedAt = dto.FinishedAt;
            coachingSession.IsClosed   = dto.IsClosed;
            coachingSession.UpdatedAt  = DateTime.Now;

            try
            {
                await AppDb.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CoachingSessionExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            var newRecord = AppDb.CoachingSessions
                            .Include(i => i.CoachingProgram.Coach)
                            .Include(i => i.CoachingProgram.Coachee)
                            .FirstOrDefault(i => i.Id == coachingSession.Id);
            var subject           = String.Format("right.now. Coaching Session with {0} and {1}", newRecord.CoachingProgram.Coach.GetFullName(), newRecord.CoachingProgram.Coachee.GetFullName());
            var ical              = GetiCal(newRecord, subject, "REQUEST");
            var attachment        = System.Net.Mail.Attachment.CreateAttachmentFromString(ical, String.Format("{0}.ics", subject));
            var emailContentCoach = ViewRenderer.RenderView("~/Views/Email/Session Updated.cshtml",
                                                            new System.Web.Mvc.ViewDataDictionary {
                { "Session", newRecord },
                { "Url", String.Format("{0}/#/program/{1}/", Request.RequestUri.Authority, newRecord.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coach.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coach.Timezone)) },
            });

            EmailSender.SendEmail(newRecord.CoachingProgram.Coach.Email, "right.now. Video Coaching Session Updated", emailContentCoach, updateICal ? attachment : null);
            var emailContentCoachee = ViewRenderer.RenderView("~/Views/Email/Session Updated.cshtml",
                                                              new System.Web.Mvc.ViewDataDictionary {
                { "Session", newRecord },
                { "Url", String.Format("{0}/#/program/{1}/", Request.RequestUri.Authority, newRecord.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coachee.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coachee.Timezone)) },
            });

            EmailSender.SendEmail(newRecord.CoachingProgram.Coachee.Email, "right.now. Video Coaching Session Updated", emailContentCoachee, updateICal ? attachment : null);

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public async Task <IHttpActionResult> PostCoachingSession(CoachingSession coachingSession)
        {
            var currentUser = AppUserManager.FindById(User.Identity.GetUserId());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var db = AppDb.Database.BeginTransaction())
            {
                try
                {
                    var start = coachingSession.StartedAt;
                    var end   = coachingSession.FinishedAt;
                    // check if the coach is double booked
                    //var dbCoach = AppDb.CoachingSessions
                    //    .Where(i => i.CoachingProgram.Coach.Id == coachingSession.CoachingProgram.CoachId)
                    //    .Where(i => (i.StartedAt >= start && i.StartedAt < end) || (i.FinishedAt > start && i.FinishedAt <= end))
                    //    .ToList();
                    //if (dbCoach.Count() > 0)
                    //{
                    //    throw new Exception("Coach cannot be double booked");
                    //}

                    // check if the coachee is double booked
                    //var dbCoachee = AppDb.CoachingSessions
                    //    .Where(i => i.CoachingProgram.Coachee.Id == coachingSession.CoachingProgram.CoacheeId)
                    //    .OnAtSameTime(coachingSession.StartedAt, coachingSession.FinishedAt);
                    //if (dbCoach.Count() > 0)
                    //{
                    //    throw new Exception("Coachee cannot be double booked");
                    //}

                    AppDb.CoachingSessions.Add(coachingSession);
                    await AppDb.SaveChangesAsync();

                    db.Commit();
                }
                catch (Exception)
                {
                    db.Rollback();
                }
            }

            var newRecord = AppDb.CoachingSessions
                            .Include(i => i.CoachingProgram.Coach)
                            .Include(i => i.CoachingProgram.Coachee)
                            .FirstOrDefault(i => i.Id == coachingSession.Id);
            var subject           = String.Format("right.now. Coaching Session with {0} and {1}", newRecord.CoachingProgram.Coach.GetFullName(), newRecord.CoachingProgram.Coachee.GetFullName());
            var ical              = GetiCal(newRecord, subject);
            var attachment        = System.Net.Mail.Attachment.CreateAttachmentFromString(ical, String.Format("{0}.ics", subject));
            var emailContentCoach = ViewRenderer.RenderView("~/Views/Email/Session Created.cshtml",
                                                            new System.Web.Mvc.ViewDataDictionary {
                { "Session", newRecord },
                { "Url", String.Format("{0}/#/program/{1}/", Request.RequestUri.Authority, newRecord.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coach.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coach.Timezone)) },
            });

            EmailSender.SendEmail(newRecord.CoachingProgram.Coach.Email, "right.now. Video Coaching Session Created", emailContentCoach, attachment);
            var emailContentCoachee = ViewRenderer.RenderView("~/Views/Email/Session Created.cshtml",
                                                              new System.Web.Mvc.ViewDataDictionary {
                { "Session", newRecord },
                { "Url", String.Format("{0}/#/program/{1}/", Request.RequestUri.Authority, newRecord.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coachee.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coachee.Timezone)) },
            });

            EmailSender.SendEmail(newRecord.CoachingProgram.Coachee.Email, "right.now. Video Coaching Session Created", emailContentCoachee, attachment);

            return(CreatedAtRoute("DefaultApi", new { id = coachingSession.Id }, coachingSession));
        }
        public async Task <IHttpActionResult> PutCoachingSession(int id)
        {
            var currentUser = AppUserManager.FindById(User.Identity.GetUserId());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var isAdmin         = AppUserManager.IsInRole(currentUser.Id, "Admin");
            var coachingSession = AppDb.CoachingSessions
                                  .Where(i =>
                                         i.CoachingProgram.Coach.Id == currentUser.Id ||
                                         i.CoachingProgram.Coachee.Id == currentUser.Id ||
                                         isAdmin)
                                  .FirstOrDefault(i => i.Id == id);

            if (coachingSession == null)
            {
                return(BadRequest("Session Not Found"));
            }

            coachingSession.IsClosed  = true;
            coachingSession.UpdatedAt = DateTime.Now;

            try
            {
                await AppDb.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CoachingSessionExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            var newRecord = AppDb.CoachingSessions
                            .Include(i => i.CoachingProgram.Coach)
                            .Include(i => i.CoachingProgram.Coachee)
                            .FirstOrDefault(i => i.Id == coachingSession.Id);
            var emailContentCoach = ViewRenderer.RenderView("~/Views/Email/Session Updated.cshtml",
                                                            new System.Web.Mvc.ViewDataDictionary {
                { "Session", newRecord },
                { "Url", String.Format("{0}/#/program/{1}/", Request.RequestUri.Authority, newRecord.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coach.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coach.Timezone)) },
            });

            EmailSender.SendEmail(newRecord.CoachingProgram.Coach.Email, "right.now. Video Coaching Session Updated", emailContentCoach);
            var emailContentCoachee = ViewRenderer.RenderView("~/Views/Email/Session Updated.cshtml",
                                                              new System.Web.Mvc.ViewDataDictionary {
                { "Session", newRecord },
                { "Url", String.Format("{0}/#/program/{1}/", Request.RequestUri.Authority, newRecord.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coachee.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coachee.Timezone)) },
            });

            EmailSender.SendEmail(newRecord.CoachingProgram.Coachee.Email, "right.now. Video Coaching Session Updated", emailContentCoachee);

            return(StatusCode(HttpStatusCode.NoContent));
        }
Esempio n. 23
0
        public ActionResult Index(int reportID)
        {
            ViewBag.reportID = reportID;

            List <vm_dailyReportByReportID> dailyReportByID = new List <vm_dailyReportByReportID>();
            List <string> recipientList = new List <string>();

            string        mainconn = ConfigurationManager.ConnectionStrings["allpaxServiceRecordEntities"].ConnectionString;
            SqlConnection sqlconn  = new SqlConnection(mainconn);

            sqlconn.Open();

            string sqlquery1 =
                "SELECT tbl_dailyReport.dailyReportID, tbl_dailyReport.jobID, tbl_subJobTypes.description, tbl_dailyReport.date, " +
                "tbl_Jobs.customerContact,tbl_customers.customerName, tbl_customers.address, tbl_dailyReport.equipment, " +
                "tbl_dailyReport.startTime, tbl_dailyReport.endTime, tbl_dailyReport.lunchHours, tbl_customers.customerCode " +

                "FROM tbl_dailyReport " +

                "INNER JOIN " +
                "tbl_Jobs ON tbl_Jobs.jobID = tbl_dailyReport.jobID " +
                "INNER JOIN " +
                "tbl_customers ON tbl_customers.customerCode = tbl_Jobs.customerCode " +
                "INNER JOIN " +
                "tbl_jobSubJobs ON tbl_jobSubJobs.jobID = tbl_Jobs.jobID " +
                "INNER JOIN " +
                "tbl_subJobTypes ON tbl_subJobTypes.subJobID = tbl_jobSubJobs.subJobID " +

                "WHERE " +

                "tbl_dailyReport.subJobID = tbl_subJobTypes.subJobID " +
                "AND " +
                "tbl_dailyReport.dailyReportID LIKE @reportID";

            SqlCommand sqlcomm1 = new SqlCommand(sqlquery1, sqlconn);

            sqlcomm1.Parameters.AddWithValue("@reportID", reportID);
            SqlDataAdapter sda1 = new SqlDataAdapter(sqlcomm1);
            DataTable      dt1  = new DataTable();

            sda1.Fill(dt1);
            foreach (DataRow dr1 in dt1.Rows)
            {
                vm_dailyReportByReportID vm_dailyReportByReportID = new vm_dailyReportByReportID();

                vm_dailyReportByReportID.dailyReportID   = (int)dr1[0];
                vm_dailyReportByReportID.jobID           = dr1[1].ToString();
                vm_dailyReportByReportID.description     = dr1[2].ToString();
                vm_dailyReportByReportID.date            = String.Format("{0:yyyy-MM-dd}", dr1[3]);
                vm_dailyReportByReportID.customerContact = dr1[4].ToString();
                vm_dailyReportByReportID.customerName    = dr1[5].ToString();
                vm_dailyReportByReportID.address         = dr1[6].ToString();
                vm_dailyReportByReportID.equipment       = dr1[7].ToString();
                vm_dailyReportByReportID.startTime       = dr1[8].ToString();
                vm_dailyReportByReportID.endTime         = dr1[9].ToString();
                vm_dailyReportByReportID.lunchHours      = (int)dr1[10];
                vm_dailyReportByReportID.customerCode    = dr1[11].ToString();
                vm_dailyReportByReportID.names           = namesByTimeEntryID(vm_dailyReportByReportID.dailyReportID);
                vm_dailyReportByReportID.shortNames      = shortNamesByTimeEntryID(vm_dailyReportByReportID.dailyReportID);

                vm_dailyReportByReportID.jobCorrespondentName  = jobCrspdtNameByJobID(vm_dailyReportByReportID.jobID);
                vm_dailyReportByReportID.jobCorrespondentEmail = jobCorrespondentEmailByTimeEntryID(vm_dailyReportByReportID.jobID);

                recipientList = vm_dailyReportByReportID.jobCorrespondentEmail;

                dailyReportByID.Add(vm_dailyReportByReportID);
            }

            sqlconn.Close();

            string recipientListStr = string.Join(", ", recipientList);

            string html = ViewRenderer.RenderView("~/views/dailyReportByReportIDPrint/index.cshtml", dailyReportByID);

            SmtpClient smtp = new SmtpClient();

            smtp.Host                  = "smtp.gmail.com";
            smtp.Port                  = 587;
            smtp.EnableSsl             = true;
            smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials           = new NetworkCredential("*****@*****.**", "Allpax_1234");

            string body = html;

            using (var message = new MailMessage("*****@*****.**", recipientListStr))
            {
                message.Subject    = "Test";
                message.Body       = body;
                message.IsBodyHtml = true;
                smtp.Send(message);
            }

            return(View(dailyReportByID));
        }
 public string RenderView()
 {
     return(ViewRenderer.RenderView("~/Views/Utilities/ScriptVariables.cshtml", null));
 }
Esempio n. 25
0
        public sealed override string RenderToString(Guid contactId)
        {
            var model = GetModel(contactId);

            return(ViewRenderer.RenderView(GetFullViewPath(model), model));
        }
        public async Task <ActionResult> Create(AssignmentForm model)
        {
            var course = db.Courses.Find(model.CourseId);

            if (!course.IsCourseActive)
            {
                return(RedirectToAction("Index", "Home"));
            }

            if (!isCourseCreator(course))
            {
                return(RedirectToAction("Index", "Home"));
            }

            else if (ModelState.IsValid)
            {
                var assignment = new Assignment {
                    DateAdded   = DateTime.Now,
                    Title       = model.Title,
                    Description = model.Description,
                    Deadline    = model.Deadline
                };
                db.Assignments.Add(assignment);

                course.Assignments.Add(assignment);
                db.Entry(course).State = EntityState.Modified;

                db.SaveChanges();

                var emails = db.UserCourses
                             .Where(uc => uc.CourseId == model.CourseId && uc.IsActive && uc.DateJoin != null)
                             .Include(uc => uc.User)
                             .Select(uc => uc.User)
                             .Select(u => u.Email);

                //Send email to participants if there any
                if (emails != null || emails.Any())
                {
                    var mail = new MailMessage()
                    {
                        Subject = course.Heading + " dersine " + model.Title + " ödevi eklendi.",
                        Body    = ViewRenderer.RenderView("~/Views/Mail/NewAssignment.cshtml", new ViewDataDictionary()
                        {
                            { "title", model.Title },
                            { "deadline", model.Deadline },
                            { "description", model.Description },
                            { "course", course.Heading },
                            { "courseId", assignment.Id }
                        })
                    };

                    mail.IsBodyHtml = true;
                    foreach (var receiver in emails.ToList())
                    {
                        mail.Bcc.Add(receiver);
                    }

                    await ms.SendAsync(mail);
                }

                return(RedirectToAction("Index", "Assignment", new { id = model.CourseId }));
            }

            return(View(model));
        }
        // GET: Employees/GenerateCV/5
        public ActionResult GenerateCV(int?id)
        {
            Employee employee      = db.Employees.Find(id);
            string   profilePicUrl = "";

            //getting the picture ready
            Common.CreateSkillTemplates(employee);
            if (employee.File != null)
            {
                profilePicUrl         = Utils.Common.SaveImgLocally(db, employee.File.FileID.ToString());
                ViewBag.profilePicUrl = profilePicUrl;
            }
            else
            {
                ViewBag.profilePicUrl = System.Web.HttpContext.Current.Server.MapPath("~/Content/Pictures/");
            }

            //getting the projects for this employee
            List <Task>    tasks    = db.Tasks.Include(x => x.Sprint).Where(x => x.EmployeeID == employee.EmployeeID).ToList();
            List <Project> projects = (from t in db.Tasks
                                       join s in db.Sprints on t.SprintID equals s.SprintID
                                       join p in db.Projects on s.ProjectID equals p.ProjectID
                                       where t.EmployeeID == employee.EmployeeID
                                       select p).Distinct().ToList();

            foreach (Project p in projects)
            {
                //selecting the correct tasks for each project
                List <Task> projectTasks = tasks.Where(x => x.Sprint != null && x.Sprint.ProjectID == p.ProjectID).ToList();
                foreach (Task t in projectTasks)
                {
                    if (t.Estimation.HasValue)
                    {
                        p.ManHoursEffort += t.Estimation.Value;
                    }
                }
            }


            ViewBag.projects   = projects;
            ViewBag.headertext = "CV: " + employee.FirstName + " " + employee.LastName;

            //initialize baseUrl
            string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
                             Request.ApplicationPath.TrimEnd('/') + "/";

            ViewBag.baseUrl = baseUrl;

            //initializing CV
            employee.SkillLevelsList = employee.SkillLevels.ToList();
            ViewBag.SkillCategories  = db.SkillCategories.OrderByDescending(x => x.Skills.Count).ToList();


            //generating the main body
            string generatedPDFHtml = ViewRenderer.RenderView("~/Views/Employees/PdfCVGenerator.cshtml", employee,
                                                              ControllerContext);
            //generating the header
            string headertext = ViewRenderer.RenderView("~/Views/Employees/PdfCVHeader.cshtml", employee,
                                                        ControllerContext);

            byte[] pdfBuffer = PdfGenerator.ConvertHtmlToPDF(generatedPDFHtml, headertext);

            //delete the temporary generated file
            if (!String.IsNullOrEmpty(profilePicUrl))
            {
                Utils.Common.DeleteLocalImage(profilePicUrl);
            }


            //sending the pdf file to download
            this.HttpContext.Response.ContentType = "application/pdf";
            this.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + "EmployeeCV.pdf");
            this.HttpContext.Response.BinaryWrite(pdfBuffer);
            this.HttpContext.Response.Flush();
            this.HttpContext.Response.Close();

            return(View(employee));
        }