public async Task <ActionResult <List <ServerStatus> > > Status( [FromServices] SubmissionManager subManager) { var judgingStatus = await subManager.Judgings .Where(j => j.Active) .Join( inner: subManager.Submissions, outerKeySelector: j => j.SubmissionId, innerKeySelector: s => s.SubmissionId, resultSelector: (j, s) => new { j.Status, s.ContestId }) .GroupBy(g => new { g.Status, g.ContestId }) .Select(g => new { g.Key.Status, Cid = g.Key.ContestId, Count = g.Count() }) .ToListAsync(); return(judgingStatus .GroupBy(a => a.Cid) .Select(g => new ServerStatus { cid = g.Key, num_submissions = g.Sum(a => a.Count), num_queued = g .Where(a => a.Status == Verdict.Pending) .Select(a => a.Count) .FirstOrDefault(), num_judging = g .Where(a => a.Status == Verdict.Running) .Select(a => a.Count) .FirstOrDefault(), }) .ToList()); }
private string generatePrimaryData(long datasetVersionId) { try { DatasetManager datasetManager = new DatasetManager(); DatasetVersion datasetVersion = datasetManager.GetDatasetVersion(datasetVersionId); if (datasetVersion.Dataset.DataStructure.Self is StructuredDataStructure) { OutputDataManager outputDataManager = new OutputDataManager(); SubmissionManager submissionManager = new SubmissionManager(); long datasetId = datasetVersion.Dataset.Id; string fileName = submissionManager.GetFileNameForDataRepo(datasetId, datasetVersionId, _dataRepo.Name, "csv"); string filepath = outputDataManager.GenerateAsciiFile( datasetId, datasetVersionId, fileName, "text/txt"); return(filepath); } } catch (Exception) { throw; } return(""); }
public void CantCreateAdmin() { SubmissionManager submissionManager = new SubmissionManager(); string userInput = ";admin=true;"; Base64 encrypted = submissionManager.Encrypt(userInput); bool isAdmin = submissionManager.IsAdmin(encrypted); Assert.IsFalse(isAdmin); }
public ProblemImportService( AppDbContext db, SubmissionManager sub, ILogger <ProblemImportService> logger) { dbContext = db; submissionManager = sub; this.logger = logger; LogBuffer = new StringBuilder(); }
public void BreakSubmissionManager() { SubmissionManager submissionManager = new SubmissionManager(); SubmissionManagerCracker cracker = new SubmissionManagerCracker(submissionManager); Base64 encrypted = cracker.CraftBreakingBlock(); bool isAdmin = submissionManager.IsAdmin(encrypted); Assert.IsTrue(isAdmin); }
public string Convert(long datasetVersionId) { MetadataStructureManager metadataStructureManager = new MetadataStructureManager(); DatasetManager datasetManager = new DatasetManager(); SubmissionManager submissionManager = new SubmissionManager(); PublicationManager publicationManager = new PublicationManager(); try { DatasetVersion datasetVersion = datasetManager.GetDatasetVersion(datasetVersionId); _broker = publicationManager.GetBroker(_broker.Id); _dataRepo = publicationManager.GetRepository(_dataRepo.Id); long datasetId = datasetVersion.Dataset.Id; string name = datasetManager.GetDatasetVersion(datasetVersionId).Dataset.MetadataStructure.Name; XmlDocument metadata = OutputMetadataManager.GetConvertedMetadata(datasetId, TransmissionType.mappingFileExport, name, false); // create links to the api calls of the primary data? //add all to a zip //save document and return filepath for download string path = submissionManager.GetDirectoryPath(datasetId, _broker.Name); string filename = submissionManager.GetFileNameForDataRepo(datasetId, datasetVersionId, _dataRepo.Name, "xml"); string filepath = Path.Combine(path, filename); FileHelper.CreateDicrectoriesIfNotExist(path); metadata.Save(filepath); return(filepath); } finally { datasetManager.Dispose(); metadataStructureManager.Dispose(); publicationManager.Dispose(); } }
public void ThenTheTransactionTypesForNamedProviderEarningsAre(string providerIdSuffix, Table transactionTypes) { if (!SubmissionContext.HaveSubmissionsBeenDone) { SubmissionContext.SubmissionResults = SubmissionManager.SubmitIlrAndRunMonthEndAndCollateResults(SubmissionContext.IlrLearnerDetails, SubmissionContext.FirstSubmissionDate, LookupContext, EmployerAccountContext.EmployerAccounts, SubmissionContext.ContractTypes, SubmissionContext.EmploymentStatus, SubmissionContext.LearningSupportStatus); SubmissionContext.HaveSubmissionsBeenDone = true; } TransactionTypeTableParser.ParseTransactionTypeTableIntoContext(EarningsAndPaymentsContext, $"provider {providerIdSuffix}", transactionTypes); AssertResults(); }
private async void BwCheckin_DoWork(object sender, DoWorkEventArgs e) { var submissionManager = new SubmissionManager(new DatabaseManager(_db, null)); var pendingJobs = submissionManager.GetPendingSubmissions(); if (!pendingJobs.Any()) { Log.Debug("No Pending Jobs found"); return; } Log.Debug($"{pendingJobs.Count} pending jobs found..."); var workerHandler = new WorkerHandler(_config.WebServiceURL, _config.RegistrationKey); foreach (var pJob in pendingJobs) { Jobs job = null; try { job = JsonConvert.DeserializeObject <Jobs>(pJob.JobJSON); } catch (Exception ex) { Log.Error($"For Job ID {pJob.ID}, could not parse {pJob.JobJSON} into a Jobs object due to {ex}"); } if (job == null) { Log.Error($"Job was null - removing {pJob.ID} from Queue"); submissionManager.RemoveOfflineSubmission(pJob.ID); continue; } var result = await workerHandler.UpdateWorkAsync(job); if (result) { Log.Debug($"{job.ID} was successfully uploaded"); submissionManager.RemoveOfflineSubmission(pJob.ID); continue; } Log.Debug($"{job.ID} was not able to be uploaded - will retry at a later date and time"); } }
/// <summary> /// For a list of ChargePoint objects, attempt to populate the AddressInfo (at least country) /// based on lat/lon if not already populated /// </summary> /// <param name="itemList"> </param> /// <param name="coreRefData"> </param> public void UpdateImportedPOIList(ImportReport poiResults, User user) { var submissionManager = new SubmissionManager(); int itemCount = 1; foreach (var newPOI in poiResults.Added) { Log("Importing New POI " + itemCount + ": " + newPOI.AddressInfo.ToString()); submissionManager.PerformPOISubmission(newPOI, user, false); } foreach (var updatedPOI in poiResults.Updated) { Log("Importing Updated POI " + itemCount + ": " + updatedPOI.AddressInfo.ToString()); submissionManager.PerformPOISubmission(updatedPOI, user, performCacheRefresh: false, disablePOISuperseding: true); } foreach (var delisted in poiResults.Delisted) { Log("Delisting Removed POI " + itemCount + ": " + delisted.AddressInfo.ToString()); delisted.SubmissionStatus = null; delisted.SubmissionStatusTypeID = (int)StandardSubmissionStatusTypes.Delisted_RemovedByDataProvider; submissionManager.PerformPOISubmission(delisted, user, false); } //refresh POI cache var cacheTask = Task.Run(async() => { return(await OCM.Core.Data.CacheManager.RefreshCachedData()); }); cacheTask.Wait(); //temp get all providers references for recognised duplicates /*var dupeRefs = from dupes in poiResults.Duplicates * where !String.IsNullOrEmpty(dupes.DataProvidersReference) * select dupes.DataProvidersReference; * string dupeOutput = ""; * foreach(var d in dupeRefs) * { * dupeOutput += ",'"+d+"'"; * } * System.Diagnostics.Debug.WriteLine(dupeOutput);*/ if (poiResults.ProviderDetails.DefaultDataProvider != null) { //update date last updated for this provider new DataProviderManager().UpdateDateLastImport(poiResults.ProviderDetails.DefaultDataProvider.ID); } }
private void EnsureSubmissionsHaveHappened() { if (!SubmissionContext.HaveSubmissionsBeenDone) { var periodsToSubmitTo = new[] { //SubmissionContext.IlrLearnerDetails.Min(x => x.StartDate).ToString("MM/yy") CommitmentsContext.Commitments.Max(x => x.EffectiveFrom).ToString("MM/yy") }; SubmissionContext.SubmissionResults = SubmissionManager.SubmitIlrAndRunMonthEndAndCollateResults(SubmissionContext.IlrLearnerDetails, SubmissionContext.FirstSubmissionDate, LookupContext, EmployerAccountContext.EmployerAccounts, SubmissionContext.ContractTypes, SubmissionContext.EmploymentStatus, SubmissionContext.LearningSupportStatus, periodsToSubmitTo); SubmissionContext.HaveSubmissionsBeenDone = true; } }
public async Task <IActionResult> Show(string username, [FromServices] SubmissionManager subMgr) { var user = await UserManager.FindByNameAsync(username); if (user is null) { return(NotFound()); } ViewBag.User = user; ViewBag.Stat = await subMgr.StatisticsByUserAsync(user.Id); return(View()); }
/// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="comment"></param> /// <param name="gradeValue"></param> public void SubmitGradesForSubmission(int id, string comment, int gradeValue) { try { Model.Entities.Submission submission = SubmissionManager.FindBy(id); submission.Body = comment; submission.GradePointValue = gradeValue; SubmissionManager.Update(submission); } catch (Exception ex) { ExceptionManager.HandleException(ex, PolicyNameType.ExceptionReplacing); } }
public ActionResult Contact(ContactSubmission contactSubmission) { if (ModelState.IsValid) { //TODO; move submission manager out of API project to core SubmissionManager submissionManager = new SubmissionManager(); bool sentOK = submissionManager.SubmitContactSubmission(contactSubmission); if (!sentOK) { ViewBag.ErrorMessage = "There was a problem sending your message"; } return(RedirectToAction("ContactSubmitted")); } return(View(contactSubmission)); }
public void ThenTheProviderEarningsAndPaymentsBreakDownForUlnAsFollows(string learnerId, Table earningAndPayments) { if (!SubmissionContext.HaveSubmissionsBeenDone) { SubmissionContext.SubmissionResults = SubmissionManager.SubmitIlrAndRunMonthEndAndCollateResults(SubmissionContext.IlrLearnerDetails, SubmissionContext.FirstSubmissionDate, LookupContext, EmployerAccountContext.EmployerAccounts, SubmissionContext.ContractTypes, SubmissionContext.EmploymentStatus, SubmissionContext.LearningSupportStatus); SubmissionContext.HaveSubmissionsBeenDone = true; } var breakdown = new LearnerEarningsAndPaymentsBreakdown { ProviderId = Defaults.ProviderId, // This may not be true in every case, need to check specs LearnerReferenceNumber = learnerId }; EarningsAndPaymentsContext.LearnerOverallEarningsAndPayments.Add(breakdown); EarningAndPaymentTableParser.ParseEarningsAndPaymentsTableIntoContext(breakdown, earningAndPayments); AssertResults(); }
public ActionResult Submit(IDEPostData data) { var repo = _GetRepo(data); if (repo == null) { return(new HttpNotFoundResult()); } try { // TODO: in the future manage issues with versions in this repo var submission = SubmissionManager.Submit(repo); return(new JsonNetResult(submission)); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message)); } }
public ActionResult Contact(ContactSubmission contactSubmission) { if (ModelState.IsValid) { //check for spam bot by discarding submissions which populate phone field if (String.IsNullOrEmpty(contactSubmission.Phone)) { SubmissionManager submissionManager = new SubmissionManager(); bool sentOK = submissionManager.SubmitContactSubmission(contactSubmission); if (!sentOK) { ViewBag.ErrorMessage = "There was a problem sending your message"; } } return(RedirectToAction("ContactSubmitted")); } return(View(contactSubmission)); }
public async Task <IActionResult> List(int page = 1) { if (page < 1) { page = 1; } ViewBag.Page = page; ViewBag.TotalPage = await MaxPageAsync(); var probsQuery = from a in DbContext.Archives where a.PublicId <= 1000 + page * ItemsPerPage && a.PublicId > 1000 + (page - 1) * ItemsPerPage join p in DbContext.Problems on a.ProblemId equals p.ProblemId select new ProblemArchive(a, p.Title, p.Source); ViewBag.Stat = await SubmissionManager .StatisticsByUserAsync(int.Parse(UserManager.GetUserId(User) ?? "-100")); return(View(await probsQuery.ToListAsync())); }
/// <summary> /// Saves the student submission. /// </summary> /// <param name="studentId">The student id.</param> /// <param name="assignmentSubmissionViewModel">The assignment submission view model.</param> /// <param name="setStatusToSubmitted">if set to <c>true</c> [set status to submitted].</param> public AssignmentSubmissionViewModel SaveStudentSubmission(int studentId, AssignmentSubmissionViewModel assignmentSubmissionViewModel, bool setStatusToSubmitted = false) { try { Submission submission = ObjectMapper.Map <AssignmentSubmissionViewModel, Model.Entities.Submission>(assignmentSubmissionViewModel); submission.StudentId = studentId; SubmissionManager.SubmissionForAssignmentAlreadyExists(ref submission); submission.Status = setStatusToSubmitted ? (int)SubmissionStatusType.Submitted : submission.Status; if (submission != null && submission.Id != 0) { SubmissionManager.Update(submission); } else { submission = SubmissionManager.Add(submission); assignmentSubmissionViewModel.Id = submission.Id; } if (submission != null) { List <string> associations = new List <string>(); associations.Add("CourseModules"); associations.Add("CourseModules.Course"); associations.Add("CourseModules.Course.StaffCourses"); AssignmentViewModel assignmentViewModel = GetAssignment(assignmentSubmissionViewModel.AssignmentId); var module = ModuleManager.FindAll(associations).Where(m => m.Id.Equals(assignmentViewModel.ModuleId)).FirstOrDefault(); List <Message> messages = new List <Message>(); messages = StudentMessageViewModelFactory.CreateStudentAssignmentSubmissionMessages(module, assignmentViewModel, studentId); MessageManager.AddMessages(messages); } } catch (Exception ex) { ExceptionManager.HandleException(ex, PolicyNameType.ExceptionReplacing); } return(assignmentSubmissionViewModel); }
public void ThenProviderEarningAndPaymentsBreakDownTo(string providerIdSuffix, Table earningAndPayments) { if (!SubmissionContext.HaveSubmissionsBeenDone) { SubmissionContext.SubmissionResults = SubmissionManager.SubmitIlrAndRunMonthEndAndCollateResults(SubmissionContext.IlrLearnerDetails, SubmissionContext.FirstSubmissionDate, LookupContext, EmployerAccountContext.EmployerAccounts, SubmissionContext.ContractTypes, SubmissionContext.EmploymentStatus, SubmissionContext.LearningSupportStatus); SubmissionContext.HaveSubmissionsBeenDone = true; } var providerBreakdown = EarningsAndPaymentsContext.OverallEarningsAndPayments.SingleOrDefault(x => x.ProviderId == "provider " + providerIdSuffix); if (providerBreakdown == null) { providerBreakdown = new EarningsAndPaymentsBreakdown { ProviderId = "provider " + providerIdSuffix }; EarningsAndPaymentsContext.OverallEarningsAndPayments.Add(providerBreakdown); } EarningAndPaymentTableParser.ParseEarningsAndPaymentsTableIntoContext(providerBreakdown, earningAndPayments); AssertResults(); }
public ActionResult Approve(int id) { CheckForReadOnly(); // if poi is awaiting review, publish now var poiManager = new POIManager(); var poi = poiManager.Get(id, true); if (poi.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Submitted_UnderReview || poi.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Imported_UnderReview) { var user = new UserManager().GetUser((int)Session["UserID"]); if (POIManager.CanUserEditPOI(poi, user)) { poi.SubmissionStatusTypeID = (int)StandardSubmissionStatusTypes.Submitted_Published; int poiSubmissionID = new SubmissionManager().PerformPOISubmission(poi, user); } } // return to approval queue return(RedirectToAction("Index", "POI", new { submissionStatusTypeId = 1 })); }
/// <summary> /// Uploads the student submission document. /// </summary> /// <param name="studentId">The student id.</param> /// <param name="assignmentSubmissionViewModel">The assignment submission view model.</param> public void UploadStudentSubmissionDocument(int studentId, AssignmentSubmissionViewModel assignmentSubmissionViewModel) { try { Submission submission = ObjectMapper.Map <AssignmentSubmissionViewModel, Model.Entities.Submission>(assignmentSubmissionViewModel); submission.StudentId = studentId; SubmissionManager.SubmissionForAssignmentAlreadyExists(ref submission); // Create Submission if does not exist if (submission == null || submission.Id == 0) { submission = SubmissionManager.Add(submission); } // UploadFile UniEBoard.Model.Entities.File uploadFile = FileFactory.CreateSubmissionContentFile(submission.Id, submission.AssignmentId, assignmentSubmissionViewModel.UploadFile) as File; FileManager.Add(uploadFile); } catch (Exception ex) { ExceptionManager.HandleException(ex, PolicyNameType.ExceptionReplacing); } }
public ActionResult DataSharing(DataSharingAgreement agreement) { var countryList = new ReferenceDataManager().GetCountries(false); ViewBag.CountryList = new Microsoft.AspNetCore.Mvc.Rendering.SelectList(countryList, "ID", "Title"); if (ModelState.IsValid) { var submissionManager = new SubmissionManager(); bool savedOK = submissionManager.SubmitDataAgreement(agreement, (int)UserID); if (!savedOK) { ViewBag.ErrorMessage = "Please check you have filled out all of the fields. All information is required."; } else { ViewBag.Submitted = true; } } return(View(agreement)); }
public async Task <ActionResult <List <UnfinishedJudging> > > OnPost( [FromForm, Required] string hostname, [FromServices] SubmissionManager submissionManager) { var item = await DbContext.JudgeHosts .Where(h => h.ServerName == hostname) .FirstOrDefaultAsync(); if (item is null) { item = new JudgeHost { ServerName = hostname, PollTime = DateTimeOffset.Now, Active = true }; DbContext.JudgeHosts.Add(item); DbContext.AuditLogs.Add(new AuditLog { ContestId = 0, Comment = $"judgehost {hostname} on {HttpContext.Connection.RemoteIpAddress} registered", Resolved = true, Time = DateTimeOffset.Now, Type = AuditLog.TargetType.Contest, EntityId = 0, UserName = "******", }); Telemetry.TrackDependency( dependencyTypeName: "JudgeHost", dependencyName: item.ServerName, data: "registed", startTime: item.PollTime, duration: TimeSpan.Zero, success: true); await DbContext.SaveChangesAsync(); return(new List <UnfinishedJudging>()); } else { item.PollTime = DateTimeOffset.Now; DbContext.JudgeHosts.Update(item); var oldJudgings = await submissionManager.Judgings .Where(j => j.ServerId == item.ServerId) .Where(j => j.Status == Verdict.Running) .Join( inner: submissionManager.Submissions, outerKeySelector: j => j.SubmissionId, innerKeySelector: s => s.SubmissionId, resultSelector: (j, s) => new { j, cid = s.ContestId }) .ToListAsync(); foreach (var sg in oldJudgings) { await submissionManager.RejudgeForErrorAsync(sg.j); Telemetry.TrackDependency( dependencyTypeName: "JudgeHost", dependencyName: item.ServerName, data: $"j{sg.j.JudgingId} of s{sg.j.SubmissionId} returned to queue", startTime: sg.j.StartTime ?? DateTimeOffset.Now, duration: (sg.j.StopTime - sg.j.StartTime) ?? TimeSpan.Zero, success: false); } return(oldJudgings .Select(s => new UnfinishedJudging { judgingid = s.j.JudgingId, submitid = s.j.SubmissionId, cid = s.cid }) .ToList()); } }
public SubmissionController(AssignmentManager assignmentManager, SubmissionManager submissionManager, ServiceConsumer serviceConsumer) { this.assignmentManager = assignmentManager; this.submissionManager = submissionManager; this.serviceConsumer = serviceConsumer; }
public ProblemController(AppDbContext db, SubmissionManager sm, UserManager um) { SubmissionManager = sm; DbContext = db; UserManager = um; }
public async Task <IActionResult> Submit( int pid, CodeSubmitModel model, [FromServices] SubmissionManager subMgr) { if (model.ProblemId != pid) { return(BadRequest()); } // check user blocking if (User.IsInRole("Blocked")) { ModelState.AddModelError("xys::blocked", "You are not permitted to submit code."); } // check problem submit var probQuery = from a in DbContext.Archives where a.PublicId == pid join p in DbContext.Problems on a.ProblemId equals p.ProblemId select new { p.Title, p.Source, p.ProblemId, p.AllowSubmit }; var prob = await probQuery.SingleOrDefaultAsync(); if (prob == null) { return(NotFound()); } if (!prob.AllowSubmit) { StatusMessage = $"Problem {pid} is not allowed for submitting."; return(RedirectToAction(nameof(View))); } // check language blocking var lang = await DbContext.Languages .Where(l => l.LangId == model.Language) .SingleOrDefaultAsync(); if (lang == null) { ModelState.AddModelError("lang::notfound", "Language is not found."); } else if (!lang.AllowSubmit) { ModelState.AddModelError("lang::notallow", "You can't submit solutions with this language."); } if (ModelState.ErrorCount > 0) { ViewBag.ProblemTitle = prob.Title; ViewBag.Language = await LanguagesAsync(); return(View(model)); } else { var sub = await subMgr.CreateAsync( code : model.Code, langid : model.Language, probid : prob.ProblemId, cid : 0, uid : int.Parse(UserManager.GetUserId(User)), ipAddr : HttpContext.Connection.RemoteIpAddress, via : "problem-list", username : UserManager.GetUserName(User)); int id = sub.SubmissionId; return(RedirectToAction(nameof(View))); } }
public ActionResult Edit(ChargePoint poi) { CheckForReadOnly(); var refData = new POIBrowseModel(); refData.AllowOptionalCountrySelection = false; ViewBag.ReferenceData = refData; ViewBag.ConnectionIndex = 0; //connection counter shared by equipment details ViewBag.EnableEditView = true; if (Request["editoption"] == "addconnection") { //add a placeholder for new equipment details if (poi.Connections == null) { poi.Connections = new List <ConnectionInfo>(); } //TODO: setup defaults poi.Connections.Add(new ConnectionInfo()); return(View(poi)); } if (Request["editoption"].ToString().StartsWith("remove-equipment")) { //TODO:remove requested connection //poi.Connections.Remove(); string[] equipmentElementIDs = Request["editoption"].ToString().Split('-'); int itemIndex = int.Parse(equipmentElementIDs[2]); poi.Connections.RemoveAt(itemIndex); return(View(poi)); } if (Request["editoption"] == "preview") { //preview poi ViewBag.EnablePreviewMode = true; //reset any values provided as -1 to a standard default (unknown etc) PrepareDefaultsForBlankSelections(poi); //update preview of poi with fully populated reference data poi = new POIManager().PreviewPopulatedPOIFromModel(poi); InitEditReferenceData(poi); return(View(poi)); } if (ModelState.IsValid) { try { User user = null; if (IsUserSignedIn) { user = new UserManager().GetUser((int)Session["UserID"]); } //reset any values provided as -1 to a standard default (unknown etc) PrepareDefaultsForBlankSelections(poi); if (poi.AddressInfo.Country == null || poi.AddressInfo.Country.ID == -1) { ModelState.AddModelError("Country", "Required"); } //perform actual POI submission, then redirect to POI details if we can int poiSubmissionID = new SubmissionManager().PerformPOISubmission(poi, user); if (poiSubmissionID > -1) { if (poiSubmissionID > 0) { return(RedirectToAction("Details", "POI", new { id = poiSubmissionID, status = "editsubmitted" })); } else { return(RedirectToAction("Index")); } } else { ViewBag.ValidationFailed = true; } } catch { //return View(poi); } } else { foreach (ModelState modelState in ViewData.ModelState.Values) { foreach (ModelError error in modelState.Errors) { System.Diagnostics.Debug.WriteLine(error.ToString()); } } } ViewBag.ReferenceData = new POIBrowseModel(); return(View(poi)); }
public async Task <ActionResult <int> > InternalError( [FromForm] InternalErrorModel model, [FromServices] SubmissionManager submissionManager) { if (!ModelState.IsValid) { return(BadRequest()); } var toDisable = JObject.Parse(model.disabled); var kind = toDisable["kind"].Value <string>(); if (kind == "language") { var langid = toDisable["langid"].Value <string>(); var lang = await DbContext.Languages .Where(l => l.ExternalId == langid) .SingleAsync(); lang.AllowJudge = false; DbContext.Languages.Update(lang); DbContext.AuditLogs.Add(new AuditLog { ContestId = model.cid ?? 0, EntityId = lang.LangId, Comment = "internal error created", Resolved = true, Time = DateTimeOffset.Now, Type = AuditLog.TargetType.Contest, UserName = "******", }); Telemetry.TrackDependency( dependencyTypeName: "Language", dependencyName: langid, data: model.description, startTime: DateTimeOffset.Now, duration: TimeSpan.Zero, success: false); } else if (kind == "judgehost") { var hostname = toDisable["hostname"].Value <string>(); var host = await DbContext.JudgeHosts .Where(h => h.ServerName == hostname) .SingleAsync(); host.Active = false; DbContext.JudgeHosts.Update(host); DbContext.AuditLogs.Add(new AuditLog { ContestId = model.cid ?? 0, EntityId = host.ServerId, Comment = "internal error created", Resolved = true, Time = DateTimeOffset.Now, Type = AuditLog.TargetType.Contest, UserName = host.ServerName, }); Telemetry.TrackDependency( dependencyTypeName: "JudgeHost", dependencyName: host.ServerName, data: model.description, startTime: DateTimeOffset.Now, duration: TimeSpan.Zero, success: false); } else if (kind == "problem") { var probid = toDisable["probid"].Value <int>(); var prob = await DbContext.Problems .Where(p => p.ProblemId == probid) .SingleAsync(); prob.AllowJudge = false; DbContext.Problems.Update(prob); DbContext.AuditLogs.Add(new AuditLog { ContestId = model.cid ?? 0, EntityId = probid, Comment = "internal error created", Resolved = true, Time = DateTimeOffset.Now, Type = AuditLog.TargetType.Problem, UserName = "******", }); Telemetry.TrackDependency( dependencyTypeName: "Problem", dependencyName: $"p{probid} - {prob.Title}", data: model.description, startTime: DateTimeOffset.Now, duration: TimeSpan.Zero, success: false); } else { Telemetry.TrackDependency( dependencyTypeName: "Unresolved", dependencyName: kind, data: model.description, startTime: DateTimeOffset.Now, duration: TimeSpan.Zero, success: false); } var ie = new InternalError { JudgehostLog = model.judgehostlog, JudgingId = model.judgingid, ContestId = model.cid, Description = model.description, Disabled = model.disabled, Status = InternalErrorStatus.Open, Time = DateTimeOffset.Now, }; if (model.judgingid.HasValue) { await submissionManager.RejudgeForErrorAsync(model.judgingid.Value); } DbContext.InternalErrors.Add(ie); await DbContext.SaveChangesAsync(); return(ie.ErrorId); }
/// <summary> /// Handle input to API /// </summary> /// <param name="context"></param> private void PerformInput(HttpContext context) { if (!bool.Parse(ConfigurationManager.AppSettings["EnableDataWrites"])) { OutputBadRequestMessage(context, "API is read only. Submissions not currently being accepted."); return; } OCM.API.InputProviders.IInputProvider inputProvider = null; var filter = new APIRequestParams(); //set defaults filter.ParseParameters(context); //override ?v=2 etc if called via /api/v2/ or /api/v1 if (APIBehaviourVersion > 0) { filter.APIVersion = APIBehaviourVersion; } if (APIBehaviourVersion >= 2) { filter.Action = DefaultAction; } if (context.Request.Url.Host.ToLower().StartsWith("api") && filter.APIVersion == null) { //API version is mandatory for api V2 onwards via api.openchargemap.* hostname OutputBadRequestMessage(context, "mandatory API Version not specified in request"); return; } bool performSubmissionCompletedRedirects = false; //Use JSON format submission if explictly specified or by default if API v3 if (context.Request["format"] == "json" || (String.IsNullOrEmpty(context.Request["format"]) && filter.APIVersion >= 3)) { inputProvider = new InputProviders.JSONInputProvider(); } else { inputProvider = new InputProviders.HTMLFormInputProvider(); performSubmissionCompletedRedirects = true; } SubmissionManager submissionManager = new SubmissionManager(); //attempt to determine user from api call User user = inputProvider.GetUserFromAPICall(context); if (user != null && user.IsCurrentSessionTokenValid == false) { //session token provided didn't match latest in user details, reject user details. context.Response.StatusCode = 401; } else { //allow contact us input whether use is authenticated or not if (context.Request["action"] == "contactus_submission" || filter.Action == "contact") { ContactSubmission contactSubmission = new ContactSubmission(); bool processedOK = inputProvider.ProcessContactUsSubmission(context, ref contactSubmission); bool resultOK = submissionManager.SendContactUsMessage(contactSubmission.Name, contactSubmission.Email, contactSubmission.Comment); if (resultOK == true) { context.Response.Write("OK"); } else { context.Response.Write("Error"); } } //if user not authenticated reject any other input if (user == null) { context.Response.StatusCode = 401; return; } //gather input variables if (context.Request["action"] == "cp_submission" || filter.Action == "poi") { //gather/process data for submission OCM.API.Common.Model.ChargePoint cp = new Common.Model.ChargePoint(); bool processedOK = inputProvider.ProcessEquipmentSubmission(context, ref cp); bool submittedOK = false; if (processedOK == true) { //perform submission int submissionId = submissionManager.PerformPOISubmission(cp, user); if (submissionId > -1) { submittedOK = true; } } if (processedOK && submittedOK) { if (performSubmissionCompletedRedirects) { if (submittedOK) { context.Response.Redirect("http://openchargemap.org/submissions/complete.aspx", true); } else { context.Response.Redirect("http://openchargemap.org/submissions/error.aspx", true); } } else { context.Response.StatusCode = 202; } } else { if (performSubmissionCompletedRedirects) { context.Response.Redirect("http://openchargemap.org/submissions/error.aspx", true); } else { context.Response.StatusCode = 500; } } } if (context.Request["action"] == "comment_submission" || filter.Action == "comment") { UserComment comment = new UserComment(); bool processedOK = inputProvider.ProcessUserCommentSubmission(context, ref comment); if (processedOK == true) { //perform submission int result = submissionManager.PerformSubmission(comment, user); if (filter.APIVersion >= 3) { if (result > 0) { OutputSubmissionReceivedMessage(context, "OK", true); } else { OutputBadRequestMessage(context, "Failed"); } } else { if (result >= 0) { context.Response.Write("OK:" + result); } else { context.Response.Write("Error:" + result); } } } else { context.Response.Write("Error: Validation Failed"); } } if (context.Request["action"] == "mediaitem_submission" || filter.Action == "mediaitem") { var p = inputProvider;// as OCM.API.InputProviders.HTMLFormInputProvider; MediaItem m = new MediaItem(); bool accepted = false; string msg = ""; try { accepted = p.ProcessMediaItemSubmission(context, ref m, user.ID); } catch (Exception exp) { msg += exp.ToString(); } if (accepted) { submissionManager.PerformSubmission(m, user); //OutputSubmissionReceivedMessage(context, "OK :" + m.ID, true); if (filter.APIVersion >= 3) { OutputSubmissionReceivedMessage(context, "OK", true); } else { context.Response.Write("OK"); } } else { if (filter.APIVersion >= 3) { OutputBadRequestMessage(context, "Failed"); } else { context.Response.Write("Error"); } } } } }
//ToDO -> David <- do not store the files on the server public string Convert(long datasetVersionId) { string datarepo = _dataRepo.Name; SubmissionManager publishingManager = new SubmissionManager(); using (DatasetManager datasetManager = new DatasetManager()) using (DataStructureManager dataStructureManager = new DataStructureManager()) using (PublicationManager publicationManager = new PublicationManager()) using (ZipFile zip = new ZipFile()) { DatasetVersion datasetVersion = datasetManager.GetDatasetVersion(datasetVersionId); long datasetId = datasetVersion.Dataset.Id; Publication publication = publicationManager.GetPublication() .Where( p => p.DatasetVersion.Id.Equals(datasetVersion.Id) && p.Broker.Name.ToLower().Equals(_broker.Name)) .FirstOrDefault(); // if(broker exist) if (publication == null && _broker != null) { Broker broker = _broker; if (broker != null) { OutputMetadataManager.GetConvertedMetadata(datasetId, TransmissionType.mappingFileExport, broker.MetadataFormat); // get primary data // check the data sturcture type ... if (datasetVersion.Dataset.DataStructure.Self is StructuredDataStructure) { OutputDataManager odm = new OutputDataManager(); // apply selection and projection odm.GenerateAsciiFile(datasetId, datasetVersion.Id, broker.PrimaryDataFormat, false); } int versionNr = datasetManager.GetDatasetVersionNr(datasetVersion); string zipName = publishingManager.GetZipFileName(datasetId, versionNr); string zipPath = publishingManager.GetDirectoryPath(datasetId, broker.Name); string dynamicZipPath = publishingManager.GetDynamicDirectoryPath(datasetId, broker.Name); string zipFilePath = Path.Combine(zipPath, zipName); string dynamicFilePath = Path.Combine(dynamicZipPath, zipName); FileHelper.CreateDicrectoriesIfNotExist(Path.GetDirectoryName(zipFilePath)); if (FileHelper.FileExist(zipFilePath)) { if (FileHelper.WaitForFile(zipFilePath)) { FileHelper.Delete(zipFilePath); } } // add datastructure //ToDo put that functiom to the outputDatatructureManager #region datatructure long dataStructureId = datasetVersion.Dataset.DataStructure.Id; DataStructure dataStructure = dataStructureManager.StructuredDataStructureRepo.Get(dataStructureId); if (dataStructure != null) { try { string dynamicPathOfDS = ""; dynamicPathOfDS = storeGeneratedFilePathToContentDiscriptor(datasetId, datasetVersion, "datastructure", ".txt"); string datastructureFilePath = AsciiWriter.CreateFile(dynamicPathOfDS); string json = OutputDataStructureManager.GetVariableListAsJson(dataStructureId); AsciiWriter.AllTextToFile(datastructureFilePath, json); } catch (Exception ex) { throw ex; } } #endregion datatructure foreach (ContentDescriptor cd in datasetVersion.ContentDescriptors) { string path = Path.Combine(AppConfiguration.DataPath, cd.URI); string name = cd.URI.Split('\\').Last(); if (FileHelper.FileExist(path)) { zip.AddFile(path, ""); } } // add xsd of the metadata schema string xsdDirectoryPath = OutputMetadataManager.GetSchemaDirectoryPath(datasetId); if (Directory.Exists(xsdDirectoryPath)) { zip.AddDirectory(xsdDirectoryPath, "Schema"); } XmlDocument manifest = OutputDatasetManager.GenerateManifest(datasetId, datasetVersion.Id); if (manifest != null) { string dynamicManifestFilePath = OutputDatasetManager.GetDynamicDatasetStorePath(datasetId, versionNr, "manifest", ".xml"); string fullFilePath = Path.Combine(AppConfiguration.DataPath, dynamicManifestFilePath); manifest.Save(fullFilePath); zip.AddFile(fullFilePath, ""); } string message = string.Format("dataset {0} version {1} was published for repository {2}", datasetId, datasetVersion.Id, broker.Name); LoggerFactory.LogCustom(message); //Session["ZipFilePath"] = dynamicFilePath; zip.Save(zipFilePath); return(zipFilePath); } } return(""); } }