Ejemplo n.º 1
0
        public ActionResult Buy()
        {
            string userId = string.Empty;

            if (User.Identity.IsAuthenticated)
                userId = User.Identity.GetUserId();
            else
                userId = GetCartId();

            var cart = ShoppingCartHelper.GetCart(userId);

            if (cart == null || !cart.ListItems.Any())
                return RedirectToAction("Index", "Home");

            var lst = cart.ListItems.Select(x => new TransactionItem()
            {
                ImageId = x.Id,
                Value = x.Amount
            }).ToList();

            var transactionHelper = new TransactionsHelper();
            // TypeId = true because is a Buy. We generate the sell with a trigger in the DB
            var transaction = new Transaction()
            {
                UserId = userId,
                DtAdded = DateTime.Now,
                CreatedBy = userId,
                Amount = cart.TotalAmount,
                TransactionItems = lst,
                TypeId = true
            };
            transactionHelper.Add(transaction);

            return RedirectToAction("Index","Transaction");
        }
Ejemplo n.º 2
0
        public (int updatedSubmissionsCount, int updatedParticipantScoresCount) NormalizeAllPointsThatExceedAllowedLimit()
        {
            int updatedSubmissionsCount,
                updatedParticipantScoresCount;

            using (var scope = TransactionsHelper.CreateTransactionScope())
            {
                updatedSubmissionsCount       = this.InternalNormalizeSubmissionPoints();
                updatedParticipantScoresCount = this.InternalNormalizeParticipantScorePoints();

                scope.Complete();
            }

            return(updatedSubmissionsCount, updatedParticipantScoresCount);
        }
        public ActionResult Edit(int id, TestViewModel test)
        {
            if (test == null || !this.ModelState.IsValid)
            {
                ImportAllTypesInTest(test);
                return(this.View(test));
            }

            var existingTest = this.testsData.GetById(id);

            if (existingTest == null)
            {
                this.TempData.AddDangerMessage(Resource.Invalid_test);
                return(this.RedirectToAction(c => c.Problem(id)));
            }

            if (!this.CheckIfUserHasProblemPermissions(existingTest.ProblemId))
            {
                this.RedirectToContestsAdminPanelWithNoPrivilegesMessage();
            }

            using (var scope = TransactionsHelper.CreateTransactionScope(IsolationLevel.RepeatableRead))
            {
                existingTest.InputData   = test.InputData;
                existingTest.OutputData  = test.OutputData;
                existingTest.OrderBy     = test.OrderBy;
                existingTest.IsTrialTest = test.Type == TestType.Trial;
                existingTest.IsOpenTest  = test.Type == TestType.Open;
                existingTest.HideInput   = test.HideInput;

                this.testsData.Update(existingTest);

                this.submissionsData.RemoveTestRunsCacheByProblem(existingTest.ProblemId);
                this.testRunsData.DeleteByProblem(existingTest.ProblemId);

                if (test.RetestProblem)
                {
                    this.problemsBusiness.RetestById(existingTest.ProblemId);
                }

                scope.Complete();
            }

            this.TempData.AddInfoMessage(Resource.Test_edited_successfully);
            return(this.RedirectToAction(c => c.Problem(existingTest.ProblemId)));
        }
Ejemplo n.º 4
0
        private async void ReloadSpentPerCategoryList()
        {
            var categoriesHelper = new TransactionsHelper(new TransactionsRepository());

            try
            {
                var transactions = await categoriesHelper
                                   .GetAmountSpentPerCategory(Domain.Constants.Constants.TestUserId);

                var listViewItems = GetSpentPerCategoryListViewItems(transactions);

                spentPerCategoryList.Items.Clear();
                spentPerCategoryList.Items.AddRange(listViewItems);
            }
            catch (ArgumentNullException ex)
            {
                Error.ShowDialog(ex.Message);
            }
        }
Ejemplo n.º 5
0
        private async void ReloadLastTransactions()
        {
            var transactionHelper = new TransactionsHelper(new TransactionsRepository());

            try
            {
                var transactions = await transactionHelper
                                   .GetLastUserTransactions(Domain.Constants.Constants.TestUserId, 5);

                var listViewItems = GetTransactionsListViewItems(transactions);

                lastTransactions.Items.Clear();
                lastTransactions.Items.AddRange(listViewItems);
            }
            catch (ArgumentNullException ex)
            {
                Error.ShowDialog(ex.Message);
            }
        }
Ejemplo n.º 6
0
        // GET: Transaction
        public ActionResult Index(string userId = null)
        {
            if (string.IsNullOrEmpty(userId))
                userId = User.Identity.GetUserId();

            var transactionHelper = new TransactionsHelper();
            var lstTransaction = transactionHelper.GetMyTransaction(userId);
            if (!lstTransaction.Any())
                return RedirectToAction("Index", "Home");
            var model = lstTransaction.Select(x => new TransactionsDetailsViewModels()
            {
                Id = x.Id,
                Amount = x.Amount,
                Date = x.DtAdded,
                TypeTransaction = x.TypeId ? "Buy" : "Sell"
            }).AsEnumerable();

            return View(model);
        }
Ejemplo n.º 7
0
        // GET: Transaction/Details/5
        public ActionResult Details(int id, string userId = null)
        {
            if (string.IsNullOrEmpty(userId))
                userId = User.Identity.GetUserId();

            var transactionHelper = new TransactionsHelper();
            var transaction = transactionHelper.GetTransaction(id);
            if (transaction == null || transaction.TransactionItems.Count.Equals(0) || !transaction.UserId.Equals(userId))
                return RedirectToAction("Index", "Transaction");

            var model = transaction.TransactionItems.Select(x => new TransactionsDetailsViewModels()
            {
                Id = x.ImageId,
                Name = x.PicPopImage.Name,
                Amount = x.Value,
                Date = x.Transaction.DtAdded
            }).AsEnumerable();

            return View(model);
        }
Ejemplo n.º 8
0
        public virtual ActionResult JournalDetails(int?IdJournal = null)
        {
            try
            {
                if (!IdJournal.HasValue)
                {
                    throw new Exception("Не указан идентификатор журнала.");
                }

                using (var scope = TransactionsHelper.ReadUncommited())
                {
                    var result = AppCore.Get <JournalingManager>().GetJournal(IdJournal.Value);
                    if (!result.IsSuccess)
                    {
                        throw new Exception(result.Message);
                    }

                    var dbAccessor = AppCore.Get <JournalingDB.JournalingManagerDatabaseAccessor <WebApplication> >();

                    using (var db = new JournalingDB.DataContext())
                    {
                        int skip  = 0;
                        int limit = 100;

                        var query = dbAccessor.CreateQueryJournalData(db).Where(x => x.JournalData.IdJournal == result.Result.IdJournal).OrderByDescending(x => x.JournalData.DateEvent).Skip(skip).Take(limit);
                        var data  = dbAccessor.FetchQueryJournalData(query);
                        return(View("JournalDetails.cshtml", new Design.Model.JournalDetails()
                        {
                            JournalName = result.Result,
                            JournalData = data
                        }));
                    }
                }
            }
            catch (Exception ex)
            {
                var answer = JsonAnswer();
                answer.FromException(ex);
                return(ReturnJson(answer));
            }
        }
        public ActionResult Create(ModelType model)
        {
            if (model != null && this.ModelState.IsValid)
            {
                if (model.ProblemId.HasValue)
                {
                    var problem = this.Data.Problems.GetById(model.ProblemId.Value);
                    if (problem != null)
                    {
                        this.ValidateParticipant(model.ParticipantId, problem.ProblemGroup.ContestId);
                    }

                    var submissionType = this.GetSubmissionType(model.SubmissionTypeId.Value);
                    if (submissionType != null)
                    {
                        this.ValidateSubmissionContentLength(model, problem);
                        this.ValidateBinarySubmission(model, problem, submissionType);
                    }
                }

                if (this.ModelState.IsValid)
                {
                    var entity = model.GetEntityModel();
                    entity.Processed = false;

                    using (var scope = TransactionsHelper.CreateTransactionScope())
                    {
                        this.BaseCreate(entity);
                        this.submissionsForProcessingData.AddOrUpdateBySubmission(model.Id.Value);

                        scope.Complete();
                    }

                    this.TempData.AddInfoMessage(Resource.Successful_creation_message);
                    return(this.RedirectToAction(GlobalConstants.Index));
                }
            }

            this.ViewBag.SubmissionAction = "Create";
            return(this.View(model));
        }
Ejemplo n.º 10
0
        private List <ChainedHeaderBlock> AddBlocksToBlockStoreQueue(int blocksCount = 500)
        {
            var chainedHeaderBlocks = new List <ChainedHeaderBlock>(blocksCount);

            for (int i = 0; i < blocksCount; i++)
            {
                Block block = TransactionsHelper.CreateDummyBlockWithTransaction(this.network, this.chainIndexer.Tip);

                var header = new ChainedHeader(block.Header, block.GetHash(), this.chainIndexer.Tip);

                this.chainIndexer.SetTip(header);
                chainedHeaderBlocks.Add(new ChainedHeaderBlock(block, header));
            }

            foreach (ChainedHeaderBlock chainedHeaderBlock in chainedHeaderBlocks)
            {
                this.blockStoreQueue.AddToPending(chainedHeaderBlock);
            }

            return(chainedHeaderBlocks);
        }
Ejemplo n.º 11
0
        public void CreateCSVFile(List <TransactionsList> list, string saveDir)
        {
            int index      = 1;
            int percentage = 0;

            foreach (var item in list)
            {
                string savePath = saveDir + "\\" + item.Name + ".csv";
                percentage = TransactionsHelper.GetPercentage(index, list.Count);
                Console.WriteLine("INFO: Creating File " + index + " of " + list.Count + "(" + percentage + "% Completed)\r");
                using (StreamWriter sw = new StreamWriter(savePath))
                {
                    sw.WriteLine(String.Join(Settings.GetSettings.Delimiter, headers));
                    foreach (var entity in item.TransactionEntity)
                    {
                        string line = String.Join(Settings.GetSettings.Delimiter, new string[] { entity.TransactionDate.ToShortDateString(), entity.TransactionType, entity.TransactionDescription,
                                                                                                 entity.TransactionAmount.ToString(), entity.TransactionBalance.ToString() });
                        sw.WriteLine(line);
                    }
                }

                index++;
            }
        }
Ejemplo n.º 12
0
        private void CreateExcelDocument(List <TransactionsList> list, ExcelModel excelModel, string saveDir)
        {
            string savePath   = string.Empty;
            string format     = "yyyy/MM/dd";
            int    percentage = 0;
            int    index      = 1;

            foreach (var sheet in list)
            {
                using (ExcelPackage excelPackage = new ExcelPackage())
                {
                    savePath   = saveDir + "\\" + sheet.Name + ".xlsx";
                    percentage = TransactionsHelper.GetPercentage(index, list.Count);
                    string message = "INFO: Creating File " + index + " of " + list.Count + " (" + percentage + "% Completed)";
                    ConsoleHelper.Write(message);
                    foreach (var entity in sheet.TransactionEntity)
                    {
                        char   delimiter = Settings.GetSettings.Delimiter;
                        string text      =
                            entity.TransactionDate.ToString(format) + delimiter +
                            entity.TransactionType + delimiter +
                            entity.TransactionDescription + delimiter +
                            entity.TransactionAmount + delimiter +
                            entity.TransactionBalance;

                        ExcelTextFormat excelTextFormat = new ExcelTextFormat();
                        excelTextFormat.Delimiter = Settings.GetSettings.Delimiter;

                        int    row        = 1;
                        string name       = "Other" + sheet.Name;
                        Sheets excelSheet = excelModel.Sheets.Where(p => p.Items.Any(entity.TransactionType.ToLower().Contains) ||
                                                                    p.Items.Any(entity.TransactionDescription.ToLower().Contains)).FirstOrDefault();
                        if (excelSheet != null)
                        {
                            if (excelPackage.Workbook.Worksheets[excelSheet.Name] == null)
                            {
                                excelPackage.Workbook.Worksheets.Add(excelSheet.Name);
                            }

                            name = excelSheet.Name;
                        }
                        else
                        {
                            if (excelPackage.Workbook.Worksheets[name] == null)
                            {
                                excelPackage.Workbook.Worksheets.Add(name);
                            }
                        }

                        var worksheet = excelPackage.Workbook.Worksheets[name];
                        if (worksheet.Dimension == null)
                        {
                            row = 1;
                        }
                        else
                        {
                            row = worksheet.Dimension.End.Row + 1;
                        }

                        worksheet.Cells[row, 1, row, headers.Length].LoadFromText(text, excelTextFormat);
                        worksheet.Cells[row, 1].Style.Numberformat.Format = format;
                    }

                    FileInfo excelFile = new FileInfo(savePath);
                    excelPackage.SaveAs(excelFile);
                    index++;
                }
            }
            Console.WriteLine("INFO: " + percentage + "% Completed, Saved file(s) to directory ");
        }
Ejemplo n.º 13
0
        public void RecalculatePointsByProblem(int problemId)
        {
            using (var scope = TransactionsHelper.CreateTransactionScope())
            {
                var problemSubmissions = this.submissionsData
                                         .GetAllByProblem(problemId)
                                         .Include(s => s.TestRuns)
                                         .Include(s => s.TestRuns.Select(tr => tr.Test))
                                         .ToList();

                var submissionResults = problemSubmissions
                                        .Select(s => new
                {
                    s.Id,
                    s.ParticipantId,
                    CorrectTestRuns = s.TestRuns.Count(t =>
                                                       t.ResultType == TestRunResultType.CorrectAnswer &&
                                                       !t.Test.IsTrialTest),
                    AllTestRuns = s.TestRuns.Count(t => !t.Test.IsTrialTest),
                    MaxPoints   = s.Problem.MaximumPoints
                })
                                        .ToList();

                var problemSubmissionsById = problemSubmissions.ToDictionary(s => s.Id);
                var topResults             = new Dictionary <int, ParticipantScoreModel>();

                foreach (var submissionResult in submissionResults)
                {
                    var submission = problemSubmissionsById[submissionResult.Id];
                    var points     = 0;
                    if (submissionResult.AllTestRuns != 0)
                    {
                        points = (submissionResult.CorrectTestRuns * submissionResult.MaxPoints) /
                                 submissionResult.AllTestRuns;
                    }

                    submission.Points = points;
                    submission.CacheTestRuns();

                    if (!submissionResult.ParticipantId.HasValue)
                    {
                        continue;
                    }

                    var participantId = submissionResult.ParticipantId.Value;

                    if (!topResults.ContainsKey(participantId) || topResults[participantId].Points < points)
                    {
                        topResults[participantId] = new ParticipantScoreModel
                        {
                            Points       = points,
                            SubmissionId = submission.Id
                        };
                    }
                    else if (topResults[participantId].Points == points)
                    {
                        if (topResults[participantId].SubmissionId < submission.Id)
                        {
                            topResults[participantId].SubmissionId = submission.Id;
                        }
                    }
                }

                this.submissions.SaveChanges();

                var participants = topResults.Keys.ToList();

                var existingScores = this.participantScoresData
                                     .GetAllByProblem(problemId)
                                     .Where(p => participants.Contains(p.ParticipantId))
                                     .ToList();

                foreach (var existingScore in existingScores)
                {
                    var topScore = topResults[existingScore.ParticipantId];

                    existingScore.Points       = topScore.Points;
                    existingScore.SubmissionId = topScore.SubmissionId;
                }

                this.submissions.SaveChanges();

                scope.Complete();
            }
        }
        public ActionResult Retest(int id)
        {
            var submission = this.Data.Submissions.GetById(id);

            if (!this.ModelState.IsValid)
            {
                var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);
                foreach (var modelStateError in modelStateErrors)
                {
                    this.TempData.AddDangerMessage(modelStateError.ErrorMessage);
                }

                return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = string.Empty }));
            }

            if (submission == null)
            {
                this.TempData.AddDangerMessage(Resource.Invalid_submission_message);
                return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = string.Empty }));
            }

            var problemIdIsValid   = submission.ProblemId.HasValue;
            var userOwnsSubmission = this.CheckIfUserOwnsSubmission(id);

            if (!problemIdIsValid ||
                (!this.CheckIfUserHasProblemPermissions(submission.ProblemId.Value) &&
                 !userOwnsSubmission))
            {
                return(this.RedirectToContestsAdminPanelWithNoPrivilegesMessage());
            }

            if (this.CheckIfUserHasProblemPermissions(submission.ProblemId.Value) ||
                (string.IsNullOrEmpty(submission.TestRunsCache) &&
                 userOwnsSubmission &&
                 submission.Processed))
            {
                if (!submission.ParticipantId.HasValue)
                {
                    this.TempData[GlobalConstants.DangerMessage] = "Потребителя не съществува!";
                    return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = "Administration" }));
                }

                if (this.IsSubmissionProcessing(submission))
                {
                    this.TempData[GlobalConstants.DangerMessage] = Resource.Submission_is_processing;
                    return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = "Administration" }));
                }

                var submissionProblemId     = submission.ProblemId.Value;
                var submissionParticipantId = submission.ParticipantId.Value;

                using (var scope = TransactionsHelper.CreateTransactionScope())
                {
                    submission.Processed = false;

                    this.submissionsForProcessingData.AddOrUpdateBySubmission(submission.Id);

                    var submissionIsBestSubmission = this.IsBestSubmission(
                        submissionProblemId,
                        submissionParticipantId,
                        submission.Id);

                    if (submissionIsBestSubmission)
                    {
                        this.participantScoresBusiness.RecalculateForParticipantByProblem(
                            submissionParticipantId,
                            submissionProblemId);
                    }

                    this.Data.SaveChanges();

                    scope.Complete();
                }

                this.TempData.AddInfoMessage(Resource.Retest_successful);
                return(this.RedirectToAction("View", "Submissions", new { area = "Contests", id }));
            }

            this.TempData[GlobalConstants.DangerMessage] = "Решението не може да бъде ретествано в момента";
            return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = string.Empty }));
        }
        public ActionResult Update(ModelType model)
        {
            if (model.Id.HasValue)
            {
                if (!model.ProblemId.HasValue || !this.CheckIfUserHasProblemPermissions(model.ProblemId.Value))
                {
                    this.TempData[GlobalConstants.DangerMessage] = "Нямате привилегиите за това действие";
                    return(this.RedirectToAction("Index", "Contests", new { area = "Administration" }));
                }

                var submission = this.Data.Submissions.GetById(model.Id.Value);
                if (model.SubmissionTypeId.HasValue)
                {
                    var submissionType = this.Data.SubmissionTypes.GetById(model.SubmissionTypeId.Value);
                    if (submissionType.AllowBinaryFilesUpload && model.FileSubmission == null)
                    {
                        model.Content       = submission.Content;
                        model.FileExtension = submission.FileExtension;
                        if (this.ModelState.ContainsKey("Content"))
                        {
                            this.ModelState["Content"].Errors.Clear();
                        }
                    }
                }

                if (this.ModelState.IsValid)
                {
                    var problem = this.Data.Problems.GetById(model.ProblemId.Value);
                    if (problem != null)
                    {
                        this.ValidateParticipant(model.ParticipantId, problem.ProblemGroup.ContestId);
                    }

                    var submissionType = this.GetSubmissionType(model.SubmissionTypeId.Value);
                    if (submissionType != null)
                    {
                        this.ValidateSubmissionContentLength(model, problem);
                        this.ValidateBinarySubmission(model, problem, submissionType);
                    }

                    if (this.ModelState.IsValid)
                    {
                        if (this.IsSubmissionProcessing(submission))
                        {
                            this.TempData[GlobalConstants.DangerMessage] = Resource.Submission_is_processing;
                            return(this.RedirectToAction(nameof(this.Update), "Submissions", new { area = "Administration" }));
                        }

                        var submissionProblemId     = model.ProblemId.Value;
                        var submissionParticipantId = model.ParticipantId.Value;

                        using (var scope = TransactionsHelper.CreateTransactionScope())
                        {
                            submission.Processed = false;

                            this.submissionsForProcessingData.AddOrUpdateBySubmission(submission.Id);

                            var submissionIsBestSubmission = this.IsBestSubmission(
                                submissionProblemId,
                                submissionParticipantId,
                                submission.Id);

                            if (submissionIsBestSubmission)
                            {
                                this.participantScoresBusiness.RecalculateForParticipantByProblem(
                                    submissionParticipantId,
                                    submissionProblemId);
                            }

                            this.Data.SaveChanges();

                            this.UpdateAuditInfoValues(model, submission);
                            this.BaseUpdate(model.GetEntityModel(submission));

                            scope.Complete();
                        }

                        this.TempData.AddInfoMessage(Resource.Successful_edit_message);
                        return(this.RedirectToAction(GlobalConstants.Index));
                    }
                }
            }

            this.ViewBag.SubmissionAction = "Update";
            return(this.View(model));
        }
Ejemplo n.º 16
0
        public async Task <ActionResult> EqualizeUserIdFromSulsAndJudgeByUserName(string userName)
        {
            var userInfoResponse = await this.httpRequester.GetAsync <ExternalUserInfoModel>(
                new { userName },
                string.Format(UrlConstants.GetUserInfoByUsernameApiFormat, Settings.SulsPlatformBaseUrl),
                Settings.ApiKey);

            if (!userInfoResponse.IsSuccess || userInfoResponse.Data == null)
            {
                return(this.Content($"Cannot get user info from SoftUni Platform for user \"{userName}\""));
            }

            var correctUserId = userInfoResponse.Data.Id;

            var user = this.Data.Users.GetByUsername(userName);

            if (user == null)
            {
                return(this.Content($"Cannot find user with UserName: \"{userName}\" in the database"));
            }

            if (user.Id == correctUserId)
            {
                return(this.Content($"User \"{userName}\" has the same Id as in SoftUni Platform"));
            }

            var tempUserIdToStoreParticipants = this.Data.Users.GetByUsername("gogo4ds")?.Id;

            if (string.IsNullOrEmpty(tempUserIdToStoreParticipants))
            {
                return(this.Content("Invalid temp UserId to store participants"));
            }

            var participantsForUser = this.participantsData.GetAllByUser(user.Id);

            var participantIdsForUser = participantsForUser.Select(x => x.Id).ToList();

            using (var scope = TransactionsHelper.CreateTransactionScope())
            {
                this.participantsData.Update(
                    participantsForUser,
                    _ => new Participant
                {
                    UserId = tempUserIdToStoreParticipants,
                });

                this.Data.Users.Update(
                    u => u.UserName == userName,
                    _ => new UserProfile
                {
                    Id = correctUserId,
                });

                if (participantIdsForUser.Any())
                {
                    participantsForUser = this.participantsData
                                          .GetAll()
                                          .Where(p => participantIdsForUser.Contains(p.Id));

                    this.participantsData.Update(
                        participantsForUser,
                        _ => new Participant
                    {
                        UserId = correctUserId,
                    });
                }

                scope.Complete();
            }

            return(this.Content(
                       $@"Done. Changed Id of User ""{userName}"" to match the Id from Suls that is ""{correctUserId}"" 
                and modified his {participantIdsForUser.Count} Participants to point to the new Id"));
        }
Ejemplo n.º 17
0
        public ActionResult Import(string problemId, HttpPostedFileBase file, bool retestTask, bool deleteOldFiles)
        {
            if (!int.TryParse(problemId, out var id))
            {
                this.TempData.AddDangerMessage(Resource.Invalid_problem);
                return(this.RedirectToAction(c => c.Index()));
            }

            var problem = this.problemsData.GetById(id);

            if (problem == null)
            {
                this.TempData.AddDangerMessage(Resource.Invalid_problem);
                return(this.RedirectToAction(c => c.Index()));
            }

            if (!this.CheckIfUserHasProblemPermissions(id))
            {
                this.TempData.AddDangerMessage(GeneralResource.No_privileges_message);
                return(this.Json("No premissions"));
            }

            if (file == null || file.ContentLength == 0)
            {
                this.TempData.AddDangerMessage(Resource.No_empty_file);
                return(this.RedirectToAction(c => c.Problem(id)));
            }

            var extension = Path.GetExtension(file.FileName);

            if (extension != ".zip")
            {
                this.TempData.AddDangerMessage(Resource.Must_be_zip);
                return(this.RedirectToAction(c => c.Problem(id)));
            }

            TestsParseResult parsedTests;

            using (var memory = new MemoryStream())
            {
                file.InputStream.CopyTo(memory);
                memory.Position = 0;

                try
                {
                    parsedTests = ZippedTestsParser.Parse(memory);
                }
                catch
                {
                    this.TempData.AddDangerMessage(Resource.Zip_damaged);
                    return(this.RedirectToAction(c => c.Problem(id)));
                }
            }

            if (!ZippedTestsParser.AreTestsParsedCorrectly(parsedTests))
            {
                this.TempData.AddDangerMessage(Resource.Invalid_tests);
                return(this.RedirectToAction(c => c.Problem(id)));
            }

            int addedTestsCount;

            using (var scope = TransactionsHelper.CreateTransactionScope(IsolationLevel.RepeatableRead))
            {
                this.submissionsData.RemoveTestRunsCacheByProblem(problem.Id);

                if (deleteOldFiles)
                {
                    this.testRunsData.DeleteByProblem(problem.Id);
                    this.testsData.DeleteByProblem(problem.Id);
                }

                addedTestsCount = ZippedTestsParser.AddTestsToProblem(problem, parsedTests);

                this.problemsData.Update(problem);

                if (retestTask)
                {
                    this.problemsBusiness.RetestById(problem.Id);
                }

                scope.Complete();
            }

            this.TempData.AddInfoMessage(string.Format(Resource.Tests_added_to_problem, addedTestsCount));
            return(this.RedirectToAction(c => c.Problem(id)));
        }
Ejemplo n.º 18
0
        public async Task <List <TransactionsList> > ReadFileAsync(string filePath)
        {
            string[] data      = new string[] { };
            int      lineCount = 0;
            string   messages  = string.Empty;

            if (File.Exists(filePath))
            {
                using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8))
                {
                    string line = await sr.ReadLineAsync();

                    Console.WriteLine("INFO: ============== Reading File ==============");
                    Console.WriteLine("INFO: Delimiter =  " + Settings.GetSettings.Delimiter);
                    List <TransactionsList> transactionsList = new List <TransactionsList>();
                    string[] lines = await File.ReadAllLinesAsync(filePath);

                    lineCount = lines.Count();
                    int index = 1;
                    while ((line = await sr.ReadLineAsync()) != null)
                    {
                        index++;

                        int percentage = TransactionsHelper.GetPercentage(index, lineCount);
                        ConsoleHelper.Write("INFO: Reading Line " + index + " of " + lineCount + " (" + percentage + "% completed)");

                        data = line.Split(Settings.GetSettings.Delimiter, StringSplitOptions.RemoveEmptyEntries);

                        if (data.Length >= 5)
                        {
                            TransactionEntity transactionEntity = new TransactionEntity();
                            DateTime          transactionDate   = new DateTime();

                            transactionEntity.TransactionDate        = data[0].Clean().ConvertStringToDate();
                            transactionEntity.TransactionType        = data[1].Clean();
                            transactionEntity.TransactionDescription = data[2].Clean();
                            transactionEntity.TransactionAmount      = data[3].ConvertToDecimal();
                            transactionEntity.TransactionBalance     = data[4].ConvertToDecimal();

                            if (transactionEntity.TransactionDate != DateTime.MinValue)
                            {
                                transactionDate = transactionEntity.TransactionDate;
                                string sheetName = transactionDate.ToString("MMM-yyyy");

                                TransactionsList findExisting = transactionsList.Find(t => t.Name == sheetName);

                                if (findExisting != null)
                                {
                                    findExisting.TransactionEntity.Add(transactionEntity);
                                }
                                else
                                {
                                    TransactionsList newMonthlyTransaction = new TransactionsList();
                                    newMonthlyTransaction.Name = sheetName;
                                    newMonthlyTransaction.Date = transactionDate;
                                    newMonthlyTransaction.TransactionEntity.Add(transactionEntity);

                                    transactionsList.Add(newMonthlyTransaction);
                                }
                            }
                            else
                            {
                                messages += "WARNING:Line " + index + " can't parse date and time\n";
                            }
                        }
                        else
                        {
                            messages += "WARNING:Line " + index + " skipped invalid or empty data";
                            if (index != lineCount)
                            {
                                messages += "\n";
                            }
                        }
                    }
                    Console.WriteLine();
                    Console.WriteLine(messages);
                    return(transactionsList);
                }
            }
            else
            {
                Console.WriteLine("FATAL ERROR: Can't find file " + filePath);
            }

            return(null);
        }