Пример #1
0
        public IActionResult DeleteReturnsPost(long id, int year, AdminDeleteReturnViewModel viewModel)
        {
            var  organisation = dataRepository.Get <Organisation>(id);
            User currentUser  = ControllerHelper.GetGpgUserFromAspNetUser(User, dataRepository);

            viewModel.ParseAndValidateParameters(Request, m => m.Reason);
            if (viewModel.HasAnyErrors())
            {
                viewModel.Organisation = organisation;
                viewModel.Year         = year;
                return(View("DeleteReturns", viewModel));
            }

            foreach (long returnId in viewModel.ReturnIds)
            {
                if (!organisation.Returns.Select(r => r.ReturnId).Contains(returnId))
                {
                    throw new Exception("The ReturnID that the user requested to be deleted does not belong to this Organisation");
                }
            }
            foreach (long returnId in viewModel.ReturnIds)
            {
                dataRepository.Get <Return>(returnId).SetStatus(ReturnStatuses.Deleted, currentUser.UserId, viewModel.Reason);
            }

            // Audit log
            auditLogger.AuditChangeToOrganisation(
                AuditedAction.AdminDeleteReturn,
                organisation,
                new
            {
                ReportingYear = year,
                ReturnIds     = string.Join(", ", viewModel.ReturnIds),
                Reason        = viewModel.Reason
            },
                User);

            return(RedirectToAction("ViewReturns", "AdminOrganisationReturn", new { id }));
        }
Пример #2
0
        public void DeleteDealItem_InvalidInput_ShouldNotFound()
        {
            //init
            var deals    = dealController.Deals(1, int.MaxValue).GetObject <PagedResult <Deal> >().Queryable.ToArray();
            var dealsGen = ControllerHelper.ChooseFrom(deals);

            var dealItems = new List <int>();

            foreach (var item in deals)
            {
                var dealitemofdeal = sut.GetDealItemsOfDeal(item.Id).GetObject <IEnumerable <DealItem> >().ToList().Select(x => x.Id);
                dealItems.AddRange(dealitemofdeal);
            }

            var invalidDealItemArb = Arb.Generate <int>().Where(i => !dealItems.Contains(i)).ToArbitrary();

            Prop.ForAll(invalidDealItemArb, (i) =>
            {
                var result = sut.DeleteDealItem(i).Result;
                Assert.IsInstanceOf <NotFoundResult>(result);
            }).QuickCheckThrowOnFailure();
        }
        /// <summary>
        /// Initializes the ListView bag.
        /// </summary>
        /// <param name="redirectPageUrl">The redirect page URL.</param>
        protected virtual void InitializeListViewBag(string redirectPageUrl)
        {
            var timezoneInfo = UserManager.GetManager().GetUserTimeZone();

            this.ViewBag.IsRtl = EventSchedulerHelper.IsRtl();

            if (this.HttpContext != null && this.HttpContext.Items.Contains("versionpreview") && this.HttpContext.Items["versionpreview"].ToString().ToLowerInvariant() == "true")
            {
                this.ViewBag.WidgetId = ControllerHelper.GetWidgetId(this);
            }
            else
            {
                this.ViewBag.WidgetId = this.ViewData["controlDataId"];
            }

            this.ViewBag.CurrentPageId = this.GetPageId();

            this.ViewBag.DetailsPageId  = this.DetailsPageId == Guid.Empty ? (SiteMapBase.GetActualCurrentNode() == null ? Guid.Empty : SiteMapBase.GetActualCurrentNode().Id) : this.DetailsPageId;
            this.ViewBag.UiCulture      = SystemManager.CurrentContext.AppSettings.Multilingual ? Telerik.Sitefinity.Services.SystemManager.CurrentContext.Culture.ToString() : string.Empty;
            this.ViewBag.TimeZoneOffset = timezoneInfo.BaseUtcOffset.TotalMilliseconds.ToString();
            this.ViewBag.TimeZoneId     = timezoneInfo.Id;
        }
Пример #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            Util.InitSecurityContext(this.notice);

            this.Page.Response.CacheControl = "no-cache";

            if (Page.IsPostBack == false)
            {
                ControllerHelper.ExecuteMethodByRequest(this);

                this.DeluxeSearch.UserCustomSearchConditions = DbUtil.LoadSearchCondition(ThisPageSearchResourceKey, "Default");
                this.CurrentAdvancedSearchCondition          = new PageAdvancedSearchCondition();

                this.gridMain.PageSize     = this.grid2.PageSize = ProfileUtil.PageSize;
                this.views.ActiveViewIndex = ProfileUtil.GeneralViewModeIndex;
            }

            this.binding1.Data      = this.UserObject;
            this.searchBinding.Data = this.CurrentAdvancedSearchCondition;
        }
Пример #5
0
        public async Task <JsonResult> Post(int id, [FromBody] Answer answer)
        {
            var result = await quizAttemptManager.InsertAnswerAsync(Token.UserId, id, answer);

            switch (result)
            {
            case UpdateQuizAttemptStatusResult.DateError:
                return(ControllerHelper.CreateErrorResponse(HttpStatusCode.NotAcceptable, "DateError"));

            case UpdateQuizAttemptStatusResult.NotAuthorized:
                return(ControllerHelper.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized"));

            case UpdateQuizAttemptStatusResult.StatusError:
                return(ControllerHelper.CreateErrorResponse(HttpStatusCode.Conflict, "StatusError"));

            case UpdateQuizAttemptStatusResult.TimeUp:
                return(ControllerHelper.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "TimeUp"));

            default:
                return(ControllerHelper.CreateResponse(result));
            }
        }
Пример #6
0
        // [Route("update")]
        public async Task <IActionResult> Put([FromBody] Applicant applicant)
        {
            if (ModelState.IsValid)
            {
                var result = await _service.UpdateApplicant(applicant);

                if (result.Success)
                {
                    return(Ok(result));
                }
                else
                {
                    _logger.LogError($"Err: {result.Message}. ErrCode: {(int)result.MessageCode}");
                    return(BadRequest(result));
                }
            }
            else
            {
                _logger.LogError($"Err: Validation Error. ErrCode: {(int)MessageCode.ValidationFailed}");
                return(BadRequest(ControllerHelper.GetModelStateErrors(ModelState)));
            }
        }
Пример #7
0
        public ApiResponse UpdateJsFile([FromQuery] string project, [FromRoute] string name, [FromQuery] string oldName, [FromQuery] string newName)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, name, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                //!if (!newName.ToLower().EndsWith(".js")) newName += ".js";

                // TODO: All validation needs to be move OM API
                var existing = app.JsFiles.FirstOrDefault(js => js.Filename.Equals(oldName, StringComparison.OrdinalIgnoreCase));

                if (existing == null)
                {
                    return(ApiResponse.ExclamationModal($"The output file \"{oldName}\" does not exist in \"{project}/{name}\""));
                }

                var existingNewName = app.JsFiles.FirstOrDefault(js => js.Filename.Equals(newName, StringComparison.OrdinalIgnoreCase));

                if (existingNewName != null)
                {
                    return(ApiResponse.ExclamationModal($"The output file \"{newName}\" already exists in \"{project}/{name}\""));
                }

                existing.Filename = newName;
                SettingsInstance.SaveSettingsToFile();

                //!GeneratorThreadDispatcher.SetOutputFilesDirty(cs);

                return(ApiResponse.Success());
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
Пример #8
0
        public IEnumerable <IFavorite> GetFavoritesContainedOnList(int listId)
        {
            var uid       = ControllerHelper.GetCurrentUserId();
            var favorites = sqlDataAccess.GetFavoritesContainedOnList(uid, listId).ToList();

            var veIds  = favorites.OfType <VeFavorite>().Select(f => f.VeId).ToList();
            var access = GetUserAccess(WebHelper.GetClientLanguage(Request));

            var found = elasticService
                        .QueryForIds <ElasticArchiveRecord>(veIds, access, new Paging {
                Take = ElasticService.ELASTIC_SEARCH_HIT_LIMIT, Skip = 0
            }).Entries;

            foreach (var f in favorites)
            {
                if (f is VeFavorite veFavorite)
                {
                    var elasticHit = found.FirstOrDefault(e => e?.Data?.ArchiveRecordId == veFavorite.VeId.ToString());
                    if (elasticHit == null)
                    {
                        continue;
                    }

                    veFavorite.Title           = elasticHit.Data?.Title;
                    veFavorite.Level           = elasticHit.Data?.Level;
                    veFavorite.CreationPeriod  = elasticHit.Data?.CreationPeriod?.Text;
                    veFavorite.ReferenceCode   = elasticHit.Data?.ReferenceCode;
                    veFavorite.CanBeOrdered    = elasticHit.Data?.CanBeOrdered ?? false;
                    veFavorite.CanBeDownloaded = !string.IsNullOrWhiteSpace(elasticHit.Data?.PrimaryDataLink) &&
                                                 access.HasAnyTokenFor(elasticHit.Data.PrimaryDataDownloadAccessTokens);
                    yield return(veFavorite);
                }
                else
                {
                    yield return(f);
                }
            }
        }
Пример #9
0
        public ApiResponse UpdateWhitelist([FromQuery] string project, [FromRoute] string name, [FromQuery] string whitelist, [FromQuery] bool allowAllPrivate)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, name, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                app.WhitelistAllowAllPrivateIPs = allowAllPrivate;

                if (whitelist != null)
                {
                    var ar = whitelist.Split('\n').Select(w => w.Trim()).Where(w => !string.IsNullOrEmpty(w));

                    if (ar.Count() > 0)
                    {
                        app.WhitelistedDomainsCsv = string.Join(",", ar);
                    }
                    else
                    {
                        app.WhitelistedDomainsCsv = null;
                    }
                }
                else
                {
                    app.WhitelistedDomainsCsv = null;
                }

                SettingsInstance.SaveSettingsToFile();

                return(ApiResponse.Success());
            }
            catch (Exception e)
            {
                return(ApiResponse.Exception(e));
            }
        }
Пример #10
0
        public void Add_ProjectReport_PreviousReport()
        {
            // Arrange
            var      helper   = new TestHelper();
            var      user     = PrincipalHelper.CreateForPermission(Permissions.ReportsSpl);
            DateTime fromDate = DateTime.UtcNow;

            var init = helper.InitializeDatabase(user);

            init.CreateDefaultWorkflowsWithStatus();
            init.SaveChanges();

            var project  = init.CreateProject(1);
            var report   = init.CreateProjectReport(1, agency: project.Agency);
            var snapshot = init.CreateProjectSnapshot(1, agency: project.Agency);

            init.SetStatus(project, "SPL", "AP-SPL");
            report.IsFinal       = true;
            report.To            = DateTime.UtcNow;
            snapshot.SnapshotOn  = report.To.Value;
            snapshot.NetProceeds = 100;
            snapshot.Project     = project;

            init.SaveChanges();
            var projectReport = EntityHelper.CreateProjectReport(2, agency: project.Agency);

            var options = ControllerHelper.CreateDefaultPimsOptions();
            var service = helper.CreateService <ProjectReportService>(user, options);

            // Act
            var result    = service.Add(projectReport);
            var snapshots = service.GetSnapshots(result.Id);

            // Assert
            Assert.NotNull(result);
            Assert.True(result.Id > 0);
            Assert.Equal(snapshots.First().BaselineIntegrity, -100);
        }
        public void ProcessRequest(HttpContext context)
        {
            WebUtility.CheckHttpContext();


            if (!CheckBeforeRequest(context))
            {
                ResponseException(new ApplicationException("无用户身份信息!请重新登录系统。"), context, GetErrorDetail);
            }
            try
            {
                DateTime s = DateTime.Now;
                ControllerHelper.ExecuteProcess(context);
                DateTime e    = DateTime.Now;
                TimeSpan span = e - s;
                context.Response.Headers.Add("All-Time", span.TotalMilliseconds.ToString());
            }
            catch (Exception ex)
            {
                Exception innerEx = ex.InnerException;
                if (innerEx == null)
                {
                    ResponseException(ex, context, GetErrorDetail);
                }
                else
                {
                    if (innerEx is ApplicationException)
                    {
                        ResponseException(innerEx, context, GetErrorMsg);
                    }
                    else
                    {
                        ResponseException(innerEx, context, GetErrorDetail);
                    }
                }
            }
            AfterProcess(context);
        }
Пример #12
0
        public IActionResult GetFileChanges([FromQuery] string project, [FromQuery] string app, [FromQuery] string endpoint, [FromQuery] string file, [FromQuery] int from = 0, [FromQuery] int to = 0)
        {
            try
            {
                if (SettingsInstance.Instance.ProjectList == null)
                {
                    return(NotFound());
                }

                if (!ControllerHelper.GetProjectAndAppAndEndpoint(project, app, endpoint, out var proj, out var application, out var ep, out var resp))
                {
                    return(NotFound());
                }

                var jsFile = application.GetJsFile(file);

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

                var jsFileDescriptor = $"{project}/{app}/{endpoint}/{file}";

                if (to == -1)
                {
                    to = jsFile.Version;
                }

                var changes = JsFileChangesTracker.Instance.BuildChangeList(ep, jsFile, from, to);

                return(Ok(changes));
            }
            catch (Exception ex)
            {
                SessionLog.Exception(ex);
                return(BadRequest(ex.Message));
            }
        }
        private IActionResult FoundPostWithId(AddOrganisationFoundViewModel viewModel)
        {
            Organisation organisation = dataRepository.Get <Organisation>(viewModel.DeObfuscatedId);

            // IsUkAddress can be set by a hidden input (in which case it will be bound automatically)
            // Or it can be set by a GovUk_Radio button (in which case we need to use ParseAndValidate to get the value)
            // So, if the value hasn't already been bound, ParseAndValidate it
            if (!viewModel.IsUkAddress.HasValue)
            {
                viewModel.ParseAndValidateParameters(Request, m => m.IsUkAddress);
            }

            // If IsUkAddress still doesn't has a value on, then show an error
            if (!viewModel.IsUkAddress.HasValue)
            {
                PopulateViewModelBasedOnOrganisation(viewModel, organisation);
                return(View("Found", viewModel));
            }

            organisationService.UpdateIsUkAddressIfItIsNotAlreadySet(organisation.OrganisationId, viewModel.GetIsUkAddressAsBoolean());

            User user = ControllerHelper.GetGpgUserFromAspNetUser(User, dataRepository);

            UserOrganisation existingUserOrganisation = organisation.UserOrganisations
                                                        .Where(uo => uo.UserId == user.UserId)
                                                        .FirstOrDefault();

            if (existingUserOrganisation != null)
            {
                AddOrganisationAlreadyRegisteringViewModel alreadyRegisteringViewModel =
                    CreateAlreadyRegisteringViewModel(viewModel, existingUserOrganisation);
                return(View("AlreadyRegistering", alreadyRegisteringViewModel));
            }

            UserOrganisation userOrganisation = registrationRepository.CreateRegistration(organisation, user, Url);

            return(RedirectToConfirmationPage(userOrganisation));
        }
Пример #14
0
        public FileController(IRequestClient <DownloadAssetRequest, DownloadAssetResult> downloadClient,
                              IRequestClient <GetAssetStatusRequest, GetAssetStatusResult> statusClient,
                              IRequestClient <PrepareAssetRequest, PrepareAssetResult> prepareClient,
                              IDownloadTokenDataAccess downloadTokenDataAccess,
                              IDownloadLogDataAccess downloadLogDataAccess,
                              IElasticService elasticService,
                              IUsageAnalyzer usageAnalyzer,
                              IUserAccessProvider userAccessProvider,
                              ITranslator translator,
                              ICacheHelper cacheHelper,
                              IUserDataAccess userDataAccess,
                              IOrderDataAccess orderDataAccess,
                              IFileDownloadHelper downloadHelper,
                              IKontrollstellenInformer kontrollstellenInformer)
        {
            this.usageAnalyzer           = usageAnalyzer;
            this.translator              = translator;
            this.cacheHelper             = cacheHelper;
            this.downloadClient          = downloadClient;
            this.statusClient            = statusClient;
            this.prepareClient           = prepareClient;
            this.downloadTokenDataAccess = downloadTokenDataAccess;
            this.downloadLogDataAccess   = downloadLogDataAccess;
            this.elasticService          = elasticService;
            this.userDataAccess          = userDataAccess;
            this.orderDataAccess         = orderDataAccess;
            this.downloadHelper          = downloadHelper;
            this.kontrollstellenInformer = kontrollstellenInformer;

            // Workaround für Unit-Test
            GetUserAccessFunc = userId =>
            {
                userId = string.IsNullOrWhiteSpace(userId) ? ControllerHelper.GetCurrentUserId() : userId;
                var language = WebHelper.GetClientLanguage(Request);

                return(userAccessProvider.GetUserAccess(language, userId));
            };
        }
Пример #15
0
        //页面:角色权限设置页面 SaveRoleMenuButton
        // GET: /Sys/Base_Role/RoleRights?rolecode=000
        public ActionResult RoleRights(string rolecode)
        {
            var expando = (IDictionary <string, object>) new ExpandoObject();

            expando["menulist"]               = string.Format("/{0}/{1}/GetList_Meuns", "Sys", "Base_Role");
            expando["saverolemenus"]          = string.Format("/{0}/{1}/SaveRoleMenus", "Sys", "Base_Role");
            expando["saverolemenubutton"]     = string.Format("/{0}/{1}/SaveRoleMenuButton", "Sys", "Base_Role");
            expando["saverolemenubutton_all"] = string.Format("/{0}/{1}/SaveRoleMenuButton_All", "Sys", "Base_Role");
            ParamQuery pq = ParamQuery.Instance().From("V_Base_MenuButton").OrderBy("order by MenuCode asc,ButtonSort asc");
            var        listMenuButtons     = Base_MenuService.Instance.GetMenuButtons();
            var        listRoleMenus       = Base_RoleService.Instance.GetRoleMenus(rolecode);
            var        listRoleMenuButtons = Base_RoleService.Instance.GetRoleMenuButtons(rolecode);
            var        model = new
            {
                urls = ControllerHelper.GetIndexUrls("Sys", "Base_Role", expando),
                data = new { rolecode = rolecode },
                list_menu_buttons      = listMenuButtons,
                list_role_menus        = listRoleMenus,
                list_role_menu_buttons = listRoleMenuButtons
            };

            return(View("RoleMenuButton", model));
        }
Пример #16
0
        public void GetWeeklyTwoWeeklyPurchaseAndSalePrice_ShouldBeIntegrated()
        {
            var dealersResult = dealerController.Dealers();
            var givenDealers  = dealersResult.GetObject <PagedResult <Dealer> >().Queryable.Select(i => i.Id).ToArray();
            var dealersArb    = ControllerHelper.ChooseFrom(givenDealers).ToArbitrary();

            Prop.ForAll(dealersArb, (dealerId) =>
            {
                var weekly = sut.GetWeeklyPurchaseAndSalePrice(dealerId).Result.GetObject <IEnumerable <DatePurchaseAndSalePriceModel> >();

                var twoWeekPurchasePrice = sut.GetTwoWeeksPurchasesPrice(dealerId).Result.GetObject <IEnumerable <AmountOverDateModel> >();
                var twoWeekSalesPrice    = sut.GetTwoWeeksSalesPrice(dealerId).Result.GetObject <IEnumerable <AmountOverDateModel> >();

                foreach (var daily in weekly)
                {
                    var dayPurchase = twoWeekPurchasePrice.Where(p => ((DateTime)p.Date).Date == ((DateTime)daily.Date).Date).Single();
                    var daySale     = twoWeekSalesPrice.Where(s => ((DateTime)s.Date).Date == ((DateTime)daily.Date).Date).Single();

                    Assert.AreEqual(daily.PurchasesAmount, dayPurchase.Amount);
                    Assert.AreEqual(daily.SalesAmount, daySale.Amount);
                }
            }).QuickCheckThrowOnFailure();
        }
Пример #17
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            var context = filterContext.HttpContext;
            var code    = context.Request.Params["code"];
            var user    = ControllerHelper.GetUserInfoByCodeOrCookie(context, code);

            if (user == null)
            {
                filterContext.Result = new EmptyResult();
                filterContext.HttpContext.Response.Write("<h1>第一次使用请进行简单的注册,点击订阅号下面两个按钮\"我的故事\",\"写点什么\"中的任意一个,添加用户.</h1>");
            }
            else if (user.ID == Guid.Empty)
            {
                filterContext.Result = new EmptyResult();
                filterContext.HttpContext.Response.Redirect("~/Home/AddUser?openId=" + user.OpenId);
            }
            else
            {
                HttpContext.Current.Items["USER"] = user;
            }
        }
Пример #18
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/xml";

            try
            {
                ControllerHelper.ExecuteMethodByRequest(this);

                if (this._XmlResponse == null)
                {
                    throw new ApplicationException("不支持的调用格式");
                }
            }
            catch (System.Exception ex)
            {
                this._XmlResponse = BuildExceptionXml(ex);
            }

            if (this._XmlResponse != null)
            {
                this._XmlResponse.Save(context.Response.OutputStream);
            }
        }
        public IActionResult ReportLinkToWebsitePost(string encryptedOrganisationId, int reportingYear, ReportLinkToWebsiteViewModel viewModel)
        {
            long organisationId = ControllerHelper.DecryptOrganisationIdOrThrow404(encryptedOrganisationId);

            ControllerHelper.ThrowIfUserAccountRetiredOrEmailNotVerified(User, dataRepository);
            ControllerHelper.ThrowIfUserDoesNotHavePermissionsForGivenOrganisation(User, dataRepository, organisationId);
            ControllerHelper.ThrowIfReportingYearIsOutsideOfRange(reportingYear);

            ValidateUserInput(viewModel);

            if (viewModel.HasAnyErrors())
            {
                PopulateViewModel(viewModel, organisationId, reportingYear);
                return(View("ReportLinkToWebsite", viewModel));
            }

            SaveChangesToDraftReturn(viewModel, organisationId, reportingYear);

            string nextPageUrl = Url.Action("ReportOverview", "ReportOverview", new { encryptedOrganisationId, reportingYear });

            StatusMessageHelper.SetStatusMessage(Response, "Saved changes to draft", nextPageUrl);
            return(LocalRedirect(nextPageUrl));
        }
        public IActionResult ConfirmInScopeAnswers(string encryptedOrganisationId, int reportingYear, ScopeViewModel viewModel)
        {
            long organisationId = DecryptOrganisationId(encryptedOrganisationId);

            // Check user has permissions to access this page
            ControllerHelper.ThrowIfUserAccountRetiredOrEmailNotVerified(User, dataRepository);
            ControllerHelper.ThrowIfUserDoesNotHavePermissionsForGivenOrganisation(User, dataRepository, organisationId);

            // Get Organisation and OrganisationScope for reporting year
            Organisation organisation = dataRepository.Get <Organisation>(organisationId);

            DateTime currentSnapshotDate = organisation.SectorType.GetAccountingStartDate();

            RetireOldScopes(organisation, reportingYear);

            UpdateScopes(organisation, ScopeStatuses.InScope, reportingYear, null, null);

            dataRepository.SaveChanges();

            SendScopeChangeEmails(organisation, viewModel.ReportingYear, currentSnapshotDate, ScopeStatuses.InScope);

            return(RedirectToAction("ScopeDeclared", "Organisation", new { id = encryptedOrganisationId }));
        }
Пример #21
0
        private void Init(int time = 300)
        {
            CtrlWaiting waiting = new CtrlWaiting(() =>
            {
                try
                {
                    List <Maticsoft.Model.SMT_CONTROLLER_INFO> ctrls = ControllerHelper.GetList("1=1", true); //获取所有控制器
                    List <Maticsoft.Model.SMT_CONTROLLER_ZONE> areas = AreaDataHelper.GetAreas(true);         //获取所有区域
                    this.Invoke(new Action(() =>
                    {
                        ShowAreas(areas);
                        ShowCtrls(ctrls);
                    }));
                }
                catch (System.Exception ex)
                {
                    WinInfoHelper.ShowInfoWindow(this, "加载异常:" + ex.Message);
                    log.Error("加载异常:", ex);
                }
            });

            waiting.Show(this, time);
        }
Пример #22
0
        // [Route("add")]
        public async Task <IActionResult> Post([FromBody] Applicant applicant)
        {
            if (ModelState.IsValid)
            {
                var result = await _service.AddApplicant(applicant);

                if (result.Success)
                {
                    return(Created($"{Url.Action()}/{result.Data}", result));
                }
                else
                {
                    _logger.LogError($"Err: {result.Message}. ErrCode: {(int)result.MessageCode}");
                    return(BadRequest(result));
                }
            }
            else
            {
                //invalid model state
                _logger.LogError($"Err: Validation Error. ErrCode: {(int)MessageCode.ValidationFailed}");
                return(BadRequest(ControllerHelper.GetModelStateErrors(ModelState)));
            }
        }
Пример #23
0
        public IHttpActionResult Update(int id, CompanyRequest companyRequest)
        {
            if (companyRequest == null)
            {
                return(BadRequest("Empty request body!"));
            }

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

            var company = _companyService.GetById(id);

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

            var result = _companyService.Update(id, companyRequest);

            return(Ok(result));
        }
Пример #24
0
        public static MethodInfo GetMethod(
            string requestMethod, Controller controller, string actionName)
        {
            foreach (var methodInfo in GetSuitableMethods(controller, actionName))
            {
                var attributes = ControllerHelper.GetHttpMethodAttributes(methodInfo);

                if (!attributes.Any() && requestMethod.ToUpper() == Constants.GetMethodUpper)
                {
                    return(methodInfo);
                }

                foreach (var attribute in attributes)
                {
                    if (attribute.IsValid(requestMethod))
                    {
                        return(methodInfo);
                    }
                }
            }

            return(null);
        }
Пример #25
0
        public void ShowForm(WinMenu menu)
        {
            Form form = null;
            if (string.IsNullOrEmpty(menu.PluginName) == false && string.IsNullOrEmpty(menu.ControllerName) == false)
            {
                string controllername = menu.ControllerName.Split(new char[] { '|' })[0];
                string viewname = menu.ControllerName.Split(new char[] { '|' }).Length > 1 ? menu.ControllerName.Split(new char[] { '|' })[1] : null;
                if (controllername.Trim() == "") throw new Exception("配置的菜单不存在!");

                WinformController basec = ControllerHelper.CreateController(controllername);
                if(basec==null)
                    throw new Exception("配置的菜单不存在!");
                if (string.IsNullOrEmpty(viewname))
                    form = (Form)basec.DefaultView;
                else {
                    if (basec.iBaseView.ContainsKey(viewname) == false)
                        throw new Exception("配置的菜单不存在!");
                    form = (Form)basec.iBaseView[viewname];
                }
            }
            string tabId = "view" + form.GetHashCode();
            ShowForm(form, menu.Name, tabId);
        }
Пример #26
0
        public IActionResult UpdateStock([FromBody] ProductListViewModel input)
        {
            try
            {
                foreach (var product in input.Products)
                {
                    var inDb = _context.Products.Where(p => p.Id == product.Id).SingleOrDefault();

                    inDb.Price = product.Price;
                    inDb.Stock = product.Stock;

                    _context.Update(inDb);
                }

                _context.SaveChanges();

                return(ControllerHelper.ReturnResult(UpdateResult.Success));
            }
            catch (System.Exception ex)
            {
                return(ControllerHelper.ReturnResult(UpdateResult.Error, ex.Message));
            }
        }
Пример #27
0
        public IHttpActionResult Update(int id, ExperimentRequest experimentRequest)
        {
            if (experimentRequest == null)
            {
                return(BadRequest("Empty request body!"));
            }

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

            var experiment = _experimentService.GetById(id);

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

            var result = _experimentService.Update(id, experimentRequest, HttpContext.Current);

            return(Ok(result));
        }
Пример #28
0
        public IHttpActionResult Create([FromBody] CompanyRequest companyToCreate)
        {
            if (companyToCreate == null)
            {
                return(BadRequest("Empty request body!"));
            }

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

            var temp = _companyService.GetByName(companyToCreate.Name);

            if (temp != null)
            {
                return(BadRequest("A company with that name already exists!"));
            }

            var result = _companyService.Create(companyToCreate);

            return(Ok(result));
        }
Пример #29
0
        public ApiResponse DeleteApplication([FromQuery] string project, string name)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, name, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                if (proj.DeleteApplication(app))
                {
                    SettingsInstance.SaveSettingsToFile();

                    //!WorkSpawner.RemoveApplication(cs); TODO: Move to endpoint
                }

                return(ApiResponse.Success());
            }
            catch (Exception e)
            {
                return(ApiResponse.Exception(e));
            }
        }
        public IActionResult Size(SizeViewModel model)
        {
            string failureMessage = null;
            string successMessage = null;
            var    redirectUrl    = "/ManageSite/Size";

            if (ModelState.IsValid)
            {
                var result = ManageSiteHelper.AddSize(model, _context);


                if (result == UpdateResult.Error)
                {
                    failureMessage = "Size couldn't be updated.";
                }
                else if (result == UpdateResult.Success)
                {
                    successMessage = "Size updated.";
                }
                else if (result == UpdateResult.Duplicate)
                {
                    failureMessage = "Size already exists.";
                }
            }


            if (!string.IsNullOrWhiteSpace(failureMessage))
            {
                redirectUrl += string.Format("?failureMessage={0}", failureMessage);
            }
            if (!string.IsNullOrWhiteSpace(successMessage))
            {
                redirectUrl += string.Format("?successMessage={0}", successMessage);
            }

            return(ControllerHelper.RedirectToLocal(this, redirectUrl));
        }
Пример #31
0
 public CustomerController(ICustomerRepo iCustomerRepo)
 {
     svc = new CustomerSvc(iCustomerRepo);
     cHelper = new ControllerHelper(this, iCustomerRepo);
 }
Пример #32
0
 public ExpenseController(IExpenseRepo iExpenseRepo)
 {
     svc = new ExpenseSvc(iExpenseRepo);
     cHelper = new ControllerHelper(this, iExpenseRepo);
 }
Пример #33
0
 public InvoiceController(ICustomerRepo iCustomerRepo, ISalesmanRepo iSalesmanRepo)
 {
     cHelper = new ControllerHelper(this, iCustomerRepo);
     customerSvc = new CustomerSvc(iCustomerRepo);
     salesmanSvc = new SalesmanSvc(iSalesmanRepo);
 }
Пример #34
0
 public QuotationController(ICustomerRepo iCustomerRepo)
 {
     cHelper = new ControllerHelper(this, iCustomerRepo);
     customerSvc = new CustomerSvc(iCustomerRepo); 
 }