예제 #1
0
        public async Task <QuestionViewModel> AddQuestion(int id)  // id is of question set
        {
            var qset = await _context.QuestionSet.FirstOrDefaultAsync(qs => qs.QuestionSetId == id);

            if (qset == null)
            {
                return new QuestionViewModel {
                           ErrorCode = QuestionSetError.NotFound
                }
            }
            ;

            if (!UserCanModifyQuestionSet(qset))
            {
                return new QuestionViewModel {
                           ErrorCode = QuestionSetError.NotAuthorized
                }
            }
            ;

            int index = await _context.Question.Where(qs => qs.QuestionSetId == id).CountAsync();

            Question q = new Question
            {
                QuestionSetId = qset.QuestionSetId,
                Name          = "",
                Description   = "",
                ErrorMessage  = "",
                Config        = "{}",
                Options       = new List <QuestionOption>(),
                Required      = false,
                Type          = QuestionType.MultipleChoice,
                Order         = index
            };

            _context.Add(q);
            await _context.SaveChangesAsync();


            var qvm = new QuestionViewModel
            {
                Index     = index,
                ErrorCode = QuestionSetError.NoError,
                Question  = q
            };

            qvm.QuestionForm = await _renderService.RenderToStringAsync("_QuestionEditPartial", qvm);

            qvm.Question.QuestionSet.Questions = null;

            return(qvm);
        }
예제 #2
0
        public async Task <IActionResult> RenderView()
        {
            var viewModel = new Partner
            {
                TileName        = "hello world",
                TileImageUrl    = "hello world",
                TileLink        = "hello world",
                TileDescription = "hello world"
            };

            var result = await _viewRenderService.RenderToStringAsync("Partner", viewModel);

            return(Content(result));
        }
예제 #3
0
        public async Task <object> QuestionFormAjax(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            // The form still needs the answer group Id
            QuestionSet qset = await _dataService.GetQuestionSetWithAnswers((int)id);

            if (qset == null)
            {
                return(NotFound());
            }

            var result = new Dictionary <string, object>
            {
                { "primaryForm", await _viewRenderService.RenderToStringAsync("QuestionFormAjax", qset) }
            };

            Dictionary <string, IEnumerable <object> > files = new Dictionary <string, IEnumerable <object> >();

            foreach (AnswerSet answerset in qset.AnswerSets)
            {
                foreach (Answer answer in answerset.Answers)
                {
                    if (answer.FileAttachmentGroup != null)
                    {
                        var attachments = answer.FileAttachmentGroup.FileAttachments.Select(fa => new
                        {
                            filename = fa.FileName,
                            attachid = fa.FileAttachmentId,
                            uuid     = fa.FileAttachmentUuid,
                            size     = fa.Length,
                            type     = fa.ContentType,
                            url      = Url.ActionLink("Download", "SecureDownload", new { id = fa.FileAttachmentId, filename = fa.FileName }, protocol: "https")
                        }).ToList();
                        files.Add("" + answer.AnswerSetId + "." + answer.QuestionId, attachments);
                    }
                }
            }


            result.Add("attachments", files);

            return(result);
        }
예제 #4
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            model.Categories = dataContext.Categories.ToList();

            if (ModelState.IsValid)
            {
                UserModel user = new UserModel
                {
                    Email           = model.Email,
                    NormalizedEmail = model.Email.ToUpper(),
                    UserName        = model.UserName,
                    FirstName       = model.FirstName,
                    LastName        = model.LastName,
                    Address         = model.Address,
                    City            = model.City,
                    Country         = model.Country,
                    ZIPCode         = model.ZIPCode,
                    Telephone       = model.Telephone
                };
                // добавляем пользователя
                var result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await userManager.AddToRoleAsync(user, "user");

                    await dataContext.SaveChangesAsync();

                    var code = await userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Action(
                        "ConfirmEmail",
                        "Account",
                        new { userId = user.Id, code = code },
                        protocol: HttpContext.Request.Scheme);
                    await EmailService.SendEmailAsync(model.Email, "Подтвердите регистрацию",
                                                      await renderService.RenderToStringAsync("_EmailConfirm", callbackUrl));


                    return(View("_Confirm", new BaseViewModel()
                    {
                        Categories = dataContext.Categories.ToList()
                    }));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
        public void RenderToStringAsync_ReturnString()
        {
            string content = @"<div>Welcome [UserName] to </div>";

            byte[] byteArray = Encoding.UTF8.GetBytes(content);
            var    steam     = new MemoryStream(byteArray);

            var bodyData = new Dictionary <string, string>();

            bodyData.Add("UserName", "userTest");

            var result = _viewRenderService.RenderToStringAsync(steam, bodyData);

            Assert.IsInstanceOf(typeof(string), result.Result);
            Assert.AreEqual("<div>Welcome userTest to </div>", result.Result);
        }
예제 #6
0
        /// <summary>
        /// Renders the facts for display in changeset viewer.
        /// </summary>
        private async Task <string> RenderFactsAsync(PageType pageType, string rawFacts)
        {
            if (string.IsNullOrEmpty(rawFacts))
            {
                return(null);
            }

            var facts = JObject.Parse(rawFacts);
            var vms   = new List <FactGroupVM>();

            foreach (var group in FactDefinitions.Groups[pageType])
            {
                var groupVm = new FactGroupVM {
                    Definition = group, Facts = new List <FactModelBase>()
                };
                foreach (var fact in group.Defs)
                {
                    var key      = group.Id + "." + fact.Id;
                    var factInfo = facts[key]?.ToString();

                    if (string.IsNullOrEmpty(factInfo))
                    {
                        continue;
                    }

                    var factVm = (FactModelBase)JsonConvert.DeserializeObject(factInfo, fact.Kind);
                    factVm.Definition = fact;

                    groupVm.Facts.Add(factVm);
                }

                if (groupVm.Facts.Any())
                {
                    vms.Add(groupVm);
                }
            }

            return(await _viewRenderer.RenderToStringAsync("~/Areas/Admin/Views/Changesets/Facts/FactsList.cshtml", vms));
        }
예제 #7
0
        public async Task CreatePackages()
        {
            string transcriptPath = Configuration.ConfigPath.TranscriptsPath;
            string joboutputPath  = Configuration.ConfigPath.JobOutputPath;

            Log.Information("Beginning generation of application package");

            if (transcriptPath == null)
            {
                Log.Error("Transcripts path configuration variable has not been set by administrator");
                return;
            }

            if (joboutputPath == null)
            {
                Log.Error("Job output path configuration variable has not been set by administrator");
                return;
            }

            try
            {
                Directory.CreateDirectory(joboutputPath);
            }
            catch (Exception e)
            {
                Log.Error(e, "Unable to create directory to store job output");
                return;
            }

            var job = _context.Job.FirstOrDefault(j => !j.Completed && j.Type == "applications");

            if (job != null)
            {
                // Load in the profile picture mask
                PdfDocument pdfTranscriptPhotoOverlay = new PdfDocument("transcript_photo_mask.pdf");
                PdfDocument pdfTranscriptNameOverlay  = new PdfDocument("transcript_name_mask.pdf");

                job.Completed     = true;
                job.Started       = DateTime.Now;
                job.StatusMessage = "Running";
                _context.Update(job);
                _context.SaveChanges();

                var scholarship = await _dataService.GetScholarship(job.ForeignKey);

                List <Application> applications = _context.Application.Include(ap => ap.Profile)
                                                  .Where(s => s.ScholarshipId == job.ForeignKey && s.Submitted)
                                                  .ToList();

                joboutputPath = Path.Combine(joboutputPath, "job" + job.JobId + ".pdf");

                //PdfDocument doc = new PdfDocument(joboutputPath);
                var Renderer = new IronPdf.HtmlToPdf();
                Renderer.PrintOptions.CustomCssUrl =
                    "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css";
                Renderer.PrintOptions.SetCustomPaperSizeInInches(8.5, 11);
                Renderer.PrintOptions.PrintHtmlBackgrounds = true;
                Renderer.PrintOptions.PaperOrientation     = PdfPrintOptions.PdfPaperOrientation.Portrait;
                Renderer.PrintOptions.Title            = "Scholarship Package";
                Renderer.PrintOptions.EnableJavaScript = true;
                Renderer.PrintOptions.RenderDelay      = 50; //ms
                Renderer.PrintOptions.CssMediaType     = PdfPrintOptions.PdfCssMediaType.Screen;
                Renderer.PrintOptions.DPI                    = 300;
                Renderer.PrintOptions.FitToPaperWidth        = true;
                Renderer.PrintOptions.JpegQuality            = 90;
                Renderer.PrintOptions.GrayScale              = false;
                Renderer.PrintOptions.FitToPaperWidth        = true;
                Renderer.PrintOptions.InputEncoding          = Encoding.UTF8;
                Renderer.PrintOptions.Zoom                   = 100;
                Renderer.PrintOptions.CreatePdfFormsFromHtml = false;
                Renderer.PrintOptions.MarginTop              = 40; //millimeters
                Renderer.PrintOptions.MarginLeft             = 20; //millimeters
                Renderer.PrintOptions.MarginRight            = 20; //millimeters
                Renderer.PrintOptions.MarginBottom           = 40; //millimeters
                Renderer.PrintOptions.FirstPageNumber        = 2;  //use 2 if a coverpage  will be appended

                var coverpage = await _viewRenderService.RenderToStringAsync("_scholarshipcoverpagepartial", scholarship, "scholarships");

                PdfDocument doc = Renderer.RenderHtmlAsPdf(coverpage);

                foreach (var app in applications)
                {
                    QuestionSet qset = await _dataService.GetQuestionSetWithAnswers(app.AnswerGroupId, bypassProfileVerification : true);

                    ScholarshipApplyViewModel vm = new ScholarshipApplyViewModel
                    {
                        Application = app,
                        QuestionSet = qset,
                        Scholarship = scholarship
                    };

                    ApplicationPageViewModel applicationPage = new ApplicationPageViewModel();

                    // First render the core general profile
                    try
                    {
                        applicationPage.BasicProfile =
                            await _viewRenderService.RenderToStringAsync("_scholarshipapplicationpartial", vm,
                                                                         "scholarships");
                    }
                    catch (Exception e)
                    {
                        Log.Error(e, "Unable to render scholarship application partial when creating Application Package");
                    }

                    // Next render any additional questions that were provided
                    if (qset.Questions?.Count > 0)
                    {
                        // Render answers to questions
                        try
                        {
                            applicationPage.FormAnswers =
                                await _viewRenderService.RenderToStringAsync("questionsetappviewpartial", vm.QuestionSet,
                                                                             "answergroup");
                        }
                        catch (Exception e)
                        {
                            var serqset = JsonConvert.SerializeObject(vm.QuestionSet, Formatting.Indented, new JsonSerializerSettings
                            {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            });

                            Log.Error(e, "Unable to render answers to questions for application #{0} of scholarship Id {1}", app.ApplicationId, scholarship.ScholarshipId);
                            Log.Information("Serialized Question Set: {0}", serqset);
                        }
                    }

                    string finalApplication =
                        await _viewRenderService.RenderToStringAsync("_scholarshipapplicationfull", applicationPage,
                                                                     "scholarships");

                    PdfDocument page = Renderer.RenderHtmlAsPdf(finalApplication, "https://scholarships.eastonsd.org/");

                    doc.AppendPdf(page);

                    // Next render any file attachments
                    foreach (var answerset in vm.QuestionSet.AnswerSets)
                    {
                        foreach (var answer in answerset.Answers)
                        {
                            if (answer.FileAttachmentGroup == null)
                            {
                                continue;
                            }

                            if (answer.FileAttachmentGroup.FileAttachments != null)
                            {
                                string lastFileTried = ""; // In case of error

                                try
                                {
                                    foreach (var file in answer.FileAttachmentGroup.FileAttachments)
                                    {
                                        var filePath = System.IO.Path.Combine(Configuration.ConfigPath.AttachmentPath,
                                                                              file.FileSubPath,
                                                                              file.SecureFileName);

                                        lastFileTried = filePath;

                                        if (file.ContentType == "application/pdf")
                                        {
                                            if (File.Exists(filePath))
                                            {
                                                PdfDocument pdfAttach = new PdfDocument(filePath);

                                                doc.AppendPdf(pdfAttach);
                                            }
                                        }
                                        else
                                        {
                                            if (File.Exists(filePath))
                                            {
                                                var subpath = Path.Combine(Configuration.ConfigPath.AttachmentPath,
                                                                           file.FileSubPath);
                                                var fullpath = Path.GetFullPath(subpath);

                                                var html =
                                                    "<html style='width:100%;height:100%'><body style='width:100%;height:100%'><img style='max-width: 100%; max-height: 100vh; height: auto;' src='" +
                                                    file.SecureFileName + "'></body></html>";
                                                var pdfImage = Renderer.RenderHtmlAsPdf(html, fullpath);

                                                doc.AppendPdf(pdfImage);
                                            }
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    Log.Error(e, "Unable to fully render attachments to pdf file - Last tried is '{0}'", lastFileTried);
                                }
                            }
                        }
                    }


                    // Last attach transcripts if requested
                    try
                    {
                        if (scholarship.TranscriptsRequired)
                        {
                            // TODO: Attach transcripts

                            int schoolYear   = scholarship.ReleaseDate.Year;
                            int currentMonth = scholarship.ReleaseDate.Month;
                            if (currentMonth > 7)
                            {
                                schoolYear++;
                            }

                            string transcriptProcessPath = Path.Combine(transcriptPath, schoolYear + "");
                            string transcriptSavePath    =
                                Path.Combine(transcriptProcessPath, app.Profile.StudentId + ".pdf");

                            if (File.Exists(transcriptSavePath))
                            {
                                var props = scholarship.ProfileProperties.Select(p => p.ProfileProperty?.PropertyKey).ToList();

                                // TODO: Merge in PDF at transcriptSavePath
                                PdfDocument pdfAttach = new PdfDocument(transcriptSavePath);

                                // Add an overlay on top of the transcript to hide the photo
                                pdfAttach.AddForegroundOverlayPdfToPage(0, pdfTranscriptPhotoOverlay);

                                if (!props.Contains("LastName"))
                                {
                                    // Add an overlay on top of the transcript to hide the student name
                                    pdfAttach.AddForegroundOverlayPdfToPage(0, pdfTranscriptNameOverlay);
                                }

                                doc.AppendPdf(pdfAttach);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Error(e, "Unable to attach transcript to application package");
                    }
                }

                doc.AddFooters(new SimpleHeaderFooter
                {
                    RightText = "Page {page} of {total-pages}",
                    FontSize  = 10
                }, true);

                doc.SaveAs(joboutputPath);

                job.Ended         = DateTime.Now;
                job.StatusMessage = "Completed";
                _context.Update(job);
                _context.SaveChanges();
            }

            Log.Information("Ending creation of application package");
        }
예제 #8
0
        public async Task <ActionResult> JobFinishedAsync(int id, string key, string commit)
        {
            // Validate the key
            if (key != Startup.Configuration["ResultsCallbackKey"])
            {
                return(NotFound());
            }

            // Connect to Azure Batch
            var credentials = new BatchSharedKeyCredentials(
                Startup.Configuration["BatchAccountUrl"],
                Startup.Configuration["BatchAccountName"],
                Startup.Configuration["BatchAccountKey"]);

            using (var batchClient = BatchClient.Open(credentials))
                using (var con = new SqlConnection(Startup.Configuration.GetConnectionString("Sql")))
                {
                    con.Open();

                    // Load the job details from the database
                    var job = Job.Load(con, id);
                    if (job == null)
                    {
                        return(NotFound());
                    }

                    var result      = "";
                    var success     = false;
                    var startTime   = (DateTime?)null;
                    var endTime     = (DateTime?)null;
                    var emailBody   = (string)null;
                    var attachments = new CloudBlob[0];

                    try
                    {
                        var jobName = $"autotune-job-{id}";

                        // Check if the Autotune job finished successfully
                        var autotune = batchClient.JobOperations.GetTask(jobName, "Autotune");
                        success   = autotune.ExecutionInformation.ExitCode == 0;
                        startTime = autotune.ExecutionInformation.StartTime;
                        endTime   = autotune.ExecutionInformation.EndTime;

                        // Connect to Azure Storage
                        var connectionString = Startup.Configuration.GetConnectionString("Storage");
                        var storageAccount   = CloudStorageAccount.Parse(connectionString);
                        var cloudBlobClient  = storageAccount.CreateCloudBlobClient();

                        // Find the log file produced by Autotune
                        var container = cloudBlobClient.GetContainerReference(jobName);

                        if (success)
                        {
                            var blob = container.GetBlobReference("autotune_recommendations.log");

                            using (var stream = new MemoryStream())
                                using (var reader = new StreamReader(stream))
                                {
                                    // Download the log file
                                    blob.DownloadToStream(stream);
                                    stream.Position = 0;

                                    result = reader.ReadToEnd();

                                    // Parse the results
                                    var parsedResults = AutotuneResults.ParseResult(result, job);
                                    parsedResults.Commit = commit;

                                    emailBody = await _viewRenderService.RenderToStringAsync("Results/Success", parsedResults);
                                }
                        }

                        // Get the log files to attach to the email
                        attachments = container.ListBlobs()
                                      .Select(b => new CloudBlockBlob(b.Uri, cloudBlobClient))
                                      .Where(b => b.Name != "autotune_recommendations.log" && b.Name != "profile.json")
                                      .ToArray();
                    }
                    catch (Exception ex)
                    {
                        result  = ex.ToString();
                        success = false;
                    }

                    if (emailBody == null)
                    {
                        emailBody = await _viewRenderService.RenderToStringAsync("Results/Failure", commit);
                    }

                    EmailResults(job.EmailResultsTo, emailBody, attachments);

                    // Update the details in the SQL database
                    using (var cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "UPDATE Jobs SET ProcessingStarted = @ProcessingStarted, ProcessingCompleted = @ProcessingCompleted, Result = @Result, Failed = @Failed WHERE JobID = @Id";
                        cmd.Parameters.AddWithValue("@Id", id);
                        cmd.Parameters.AddWithValue("@ProcessingStarted", (object)startTime ?? DBNull.Value);
                        cmd.Parameters.AddWithValue("@ProcessingCompleted", (object)endTime ?? DBNull.Value);
                        cmd.Parameters.AddWithValue("@Result", result);
                        cmd.Parameters.AddWithValue("@Failed", !success);
                        cmd.ExecuteNonQuery();
                    }

                    // Store the commit hash to identify the version of Autotune that was used
                    using (var cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "UPDATE Settings SET Value = @commit WHERE Name = 'Commit'";
                        cmd.Parameters.AddWithValue("@Commit", commit);
                        cmd.ExecuteNonQuery();
                    }
                }

            return(Content(""));
        }
예제 #9
0
        public async Task <ActionResult> JobFinishedAsync(string partitionKey, string rowKey, string key, string commit)
        {
            // Validate the key
            if (key != Startup.Configuration["ResultsCallbackKey"])
            {
                return(NotFound());
            }

            // Load the job details
            var connectionString    = Startup.Configuration.GetConnectionString("Storage");
            var tableStorageAccount = Microsoft.Azure.Cosmos.Table.CloudStorageAccount.Parse(connectionString);
            var tableClient         = tableStorageAccount.CreateCloudTableClient();
            var table = tableClient.GetTableReference("jobs");

            table.CreateIfNotExists();

            var job = table.CreateQuery <Job>()
                      .Where(j => j.PartitionKey == partitionKey && j.RowKey == rowKey)
                      .FirstOrDefault();

            if (job == null)
            {
                return(NotFound());
            }

            // Connect to Azure Batch
            var credentials = new BatchSharedKeyCredentials(
                Startup.Configuration["BatchAccountUrl"],
                Startup.Configuration["BatchAccountName"],
                Startup.Configuration["BatchAccountKey"]);

            using (var batchClient = BatchClient.Open(credentials))
            {
                var result      = "";
                var success     = false;
                var startTime   = (DateTime?)null;
                var endTime     = (DateTime?)null;
                var emailBody   = (string)null;
                var attachments = new CloudBlob[0];

                try
                {
                    var jobName = $"autotune-job-{rowKey}";

                    // Check if the Autotune job finished successfully
                    var autotune = batchClient.JobOperations.GetTask(jobName, "Autotune");
                    success   = autotune.ExecutionInformation.ExitCode == 0;
                    startTime = autotune.ExecutionInformation.StartTime;
                    endTime   = autotune.ExecutionInformation.EndTime;

                    // Connect to Azure Storage
                    var storageAccount  = Microsoft.Azure.Storage.CloudStorageAccount.Parse(connectionString);
                    var cloudBlobClient = storageAccount.CreateCloudBlobClient();

                    // Find the log file produced by Autotune
                    var container = cloudBlobClient.GetContainerReference(jobName);

                    if (success)
                    {
                        var blob = container.GetBlobReference("autotune_recommendations.log");

                        using (var stream = new MemoryStream())
                            using (var reader = new StreamReader(stream))
                            {
                                // Download the log file
                                blob.DownloadToStream(stream);
                                stream.Position = 0;

                                var recommendations = reader.ReadToEnd();

                                // Parse the results
                                var parsedResults = AutotuneResults.ParseResult(recommendations, job);
                                parsedResults.Commit = commit;

                                emailBody = await _viewRenderService.RenderToStringAsync("Results/Success", parsedResults);
                            }
                    }

                    // Get the log files to attach to the email
                    attachments = container.ListBlobs()
                                  .Select(b => new CloudBlockBlob(b.Uri, cloudBlobClient))
                                  .Where(b => b.Name != "autotune_recommendations.log" && b.Name != "profile.json")
                                  .ToArray();
                }
                catch (Exception ex)
                {
                    result  = ex.ToString();
                    success = false;
                }

                if (emailBody == null)
                {
                    emailBody = await _viewRenderService.RenderToStringAsync("Results/Failure", commit);
                }

                EmailResults(job.EmailResultsTo, emailBody, attachments);

                // Update the details in the table
                job.ProcessingStarted   = startTime;
                job.ProcessingCompleted = endTime;
                job.Result = result;
                job.Failed = !success;
                var update = TableOperation.Replace(job);
                await table.ExecuteAsync(update);

                // Store the commit hash to identify the version of Autotune that was used
                var commitSetting = new Settings();
                commitSetting.PartitionKey = "Commit";
                commitSetting.RowKey       = "";
                commitSetting.Value        = commit;
                var settingTable = tableClient.GetTableReference("settings");
                settingTable.CreateIfNotExists();
                var upsert = TableOperation.InsertOrReplace(commitSetting);
                settingTable.Execute(upsert);
            }

            return(Content(""));
        }
예제 #10
0
        public async Task <IActionResult> Order()
        {
            Cart cart = HttpContext.Session.Get <Cart>("Cart");

            OrderModel order = new OrderModel();

            order.Id            = Guid.NewGuid().ToString();
            order.OrderProducts = new List <OrderProductsModel>();
            order.Date          = System.DateTime.Now;
            order.User_Id       = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            foreach (CartLine line in cart.Lines)
            {
                var product          = dataContext.Products.Find(line.Product_Id);
                OrderProductsModel p = new OrderProductsModel();
                p.Product_Id = line.Product_Id;
                p.Quontity   = line.Quantity;
                order.OrderProducts.Add(p);
            }

            dataContext.Orders.Add(order);
            await dataContext.SaveChangesAsync();

            dataContext.Orders.Include(x => x.User).First(x => x.User_Id == order.User_Id);
            await EmailService.SendEmailAsync(User.FindFirst(ClaimTypes.Email).Value, $"Заказ №{order.Id}", await renderService.RenderToStringAsync("_EmailOrder", order));

            return(Ok());
        }