private async Task EditModuleAsync(Module module) { try { var result = await ModuleService.EditModuleAsync(module); var item = Modules.FirstOrDefault(x => x.Id == result.Id); if (item != null) { item = result; } SnackbarHelper.PrintSuccess(localizer["ModuleUpdated"]); } catch (ApiError e) { if (e.ProblemDetails.Status == 422) { SnackbarHelper.PrintErrorDetails((e.ProblemDetails as UnprocessableEntityProblemDetails).Errors); } } catch (Exception e) { SnackbarHelper.PrintError(e.Message); } StateHasChanged(); }
public ShellViewModel(IWindowManager windowManager, IEventAggregator eventAggregator, ShellService shellService, ModuleService moduleService) { _windowManager = windowManager; _eventAggregator = eventAggregator; _shellService = shellService; _moduleService = moduleService; DisplayName = "EVE Profiteer"; StatusLocked = false; StatusMessage = "Initializing..."; Initialize = InitializeAsync(); _eventAggregator.Subscribe(this); Modules = new BindableCollection <ModuleViewModel>(); OpenKeyManagerCommand = new DelegateCommand(ExecuteOpenKeyManager); OpenSettingsCommand = new DelegateCommand(ExecuteOpenSettings); UpdateTransactionsCommand = new DelegateCommand(ExecuteUpdateTransactions); ProcessAllTransactionsCommand = new DelegateCommand(ExecuteProcessAllTransactions); UpdateAssetsCommand = new DelegateCommand(ExecuteUpdateAssets); UpdateJournalCommand = new DelegateCommand(ExecuteUpdateJournal); UpdateApiCommand = new DelegateCommand(ExecuteUpdateApi); UpdateRefTypesCommand = new DelegateCommand(ExecuteUpdateRefTypes); ProcessUnaccountedTransactionsCommand = new DelegateCommand(ExecuteProcessUnaccountedTransactions); UpdateIndustryJobsCommand = new DelegateCommand(ExecuteUpdateIndystryJobs); UpdateMarketOrdersCommand = new DelegateCommand(ExecuteUpdateMarketOrders); ActivateTabCommand = new DelegateCommand <Type>(ExecuteActivateTab); }
public ActionResult Create(ModuleModel model) { if (ModelState.IsValid) { if (!string.IsNullOrEmpty(model.LinkUrl) && model.LinkUrl.Split('/').Length == 3) { string[] link = model.LinkUrl.Split('/'); model.Area = link[0]; model.Controller = link[1]; model.Action = link[2]; } if (model.ParentId == "0") { model.ParentId = null; model.Action = null; model.Controller = null; model.Area = null; } CreateBaseData(model); OperationResult result = ModuleService.Insert(model); if (result.ResultType == OperationResultType.Success) { return(Json(result)); } else { return(PartialView(model)); } } else { return(PartialView(model)); } }
private async Task DeleteModule(Module module) { try { await PageModuleService.DeletePageModuleAsync(module.PageModuleId); // check if there are any remaining module instances in the site _modules = await ModuleService.GetModulesAsync(PageState.Site.SiteId); if (!_modules.Exists(item => item.ModuleId == module.ModuleId)) { await ModuleService.DeleteModuleAsync(module.ModuleId); } await logger.LogInformation("Module Permanently Deleted {Module}", module); await Load(); StateHasChanged(); } catch (Exception ex) { await logger.LogError(ex, "Error Permanently Deleting Module {Module} {Error}", module, ex.Message); AddModuleMessage("Error Permanently Deleting Module", MessageType.Error); } }
public ActionResult Edit(ModuleModel model) { if (ModelState.IsValid) { this.UpdateBaseData <ModuleModel>(model); if (!string.IsNullOrEmpty(model.LinkUrl) && model.LinkUrl.Split('/').Length == 3) { string[] link = model.LinkUrl.Split('/'); model.Area = link[0]; model.Controller = link[1]; model.Action = link[2]; } OperationResult result = ModuleService.Update(model); if (result.ResultType == OperationResultType.Success) { return(Json(result)); } else { InitParentModule(model); return(PartialView(model)); } } else { InitParentModule(model); return(PartialView(model)); } }
//Create a new training. public ActionResult Create() { TrainingService trainingService = new TrainingService(); TrainingAccess training = new TrainingAccess(); ModuleService moduleService = new ModuleService(); List <ModuleAccess> modules = new List <ModuleAccess>(); modules = moduleService.GetModuleData(); ViewBag.modules = new SelectList(modules, "moduleId", "moduleName"); SelectListItem allStaff = new SelectListItem() { Text = "Open for all", Value = "allStaff" }; SelectListItem manager = new SelectListItem() { Text = "Managers only", Value = "manager" }; SelectListItem newEmployee = new SelectListItem() { Text = "New staff only", Value = "newStaff" }; ViewBag.Type = new SelectList(new SelectListItem[] { allStaff, manager, newEmployee }, "Value", "Text"); return(View(training)); }
public ActionResult ContinueStudy(int id, string type = null) { IQuizService quizService = new QuizService(); ITrainingService trainingService = new TrainingService(); IAccountService accountService = new AccountService(); IModuleService moduleService = new ModuleService(); List <TrainingAccess> trainingListForModule = new List <TrainingAccess>(); List <QuizTransfer> quizListForModule = new List <QuizTransfer>(); AccountModuleAccess accountModule = new AccountModuleAccess(); string userName = User.Identity.Name; //save data in Account_Module table accountModule.AccountId = accountService.GetAccountId(userName); accountModule.ModuleId = id; accountModule.Status = "pass"; if (type == null) { moduleService.TakeModule(accountModule); } //get quiz and training list for the module assigned by customers trainingListForModule = trainingService.GetTrainingDataForModule(id); quizListForModule = quizService.GetQuizForModule(id); Session["trainingListForModule"] = trainingListForModule; Session["quizListForModule"] = quizListForModule; return(View()); }
public object GetVar2() { IModuleService moduleService = new ModuleService(); List <Module> menus = moduleService.GetTreeModules(); // 每页显示记录数 int pageSize = 10; // 记录总数 int rowCount = menus.Count; // 总页数 int pageCount = rowCount % pageSize == 0 ? rowCount / pageSize : rowCount / pageSize + 1; var resultObj = new JQGridDataResult { // 总页数 PageCount = pageCount, // 当前页 PageIndex = 1, // 总记录数 Total = rowCount, // 数据 Data = menus }; return(resultObj); }
public ActionResult GetAllModule(string SName) { //拿到前台发送来的是当前页面和页的大小 int pageSize = Request["rows"] == null ? 15 : int.Parse(Request["rows"]); int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]); int total = 0; short delNormal = (short)Model.Enum.DelFlagEnum.Normal; if (SName == null) { SName = ""; } #region 分页查询 var moduleList = ModuleService.LoadPageEntities(pageSize, pageIndex, out total, d => d.DelFlag == delNormal && d.Name.Contains(SName) && d.TakeEffect, d => d.Code, true); var data = new { total = total, rows = (from u in moduleList select new { u.ID, u.Code, u.Name }).ToList() }; return(Json(data, JsonRequestBehavior.AllowGet)); #endregion }
public async Task Get_Module_With_A_Lesson_And_An_Exercise(Mock <IAuthorizationService> authorizationService, IStateService stateService, Module module, Module invalidModule, User user) { authorizationService.Setup(x => x.HasWriteAccess(user, It.IsAny <Module>(), It.IsAny <CancellationToken>())).ReturnsAsync(false); module.Concepts.First().Exercises.First().Questions.First().Answers.First().Valid = true; invalidModule.Concepts.First().Exercises.First().Questions.First().Answers.ForEach(x => x.Valid = false); invalidModule.Concepts.First().Lessons.Clear(); var context = TestSetup.SetupContext(); var httpContext = TestSetup.SetupHttpContext().SetupSession(user); await context.Modules.AddAsync(module); await context.Modules.AddAsync(invalidModule); await context.SaveChangesAsync(); var service = new ModuleService(context, httpContext, authorizationService.Object, stateService); var result = await service.Get(module.Id); var invalidResult = await service.Get(invalidModule.Id); result.Should().NotBeNull().And.BeEquivalentTo(module); invalidResult.Should().BeNull(); }
/// <summary> /// 权限分配时,生成每个资源对应的权限 /// </summary> public static MvcHtmlString DistributeOptions(this HtmlHelper helper, int moduleId) { //string label = "<form class=\"js-form-permission\" name=\"setPermission\"><input type=\"checkbox\" class=\"js-checkall-permission\" style=\"margin-top:-2px\" data-toggle=\"tooltip\" data-placement=\"top\" data-original-title=\"全选\" /><label class=\"inline mr40 pl20\">{0}</label>"; string label = "<form class=\"js-form-permission\" name=\"setPermission\"><input type=\"checkbox\" class=\"js-checkall-permission\" style=\"margin-top:-2px\" title=\"全选\" /><label class=\"inline mr40 pl20\">{0}</label>"; string checkbox = "<input type=\"checkbox\" name=\"{0}-{1}\" style=\"margin:-2px 8px 0 8px\" />{2}"; StringBuilder opBuilder = new StringBuilder(); ModuleService moduleService = new ModuleService(); IEnumerable<T_Module> modules = moduleService.GetEntities(m => m.ParentId == moduleId); string[] operations = null; int actionId = 0; T_Operation operation = null; OperationService operationService = new OperationService(); foreach (T_Module module in modules) { if (!string.IsNullOrWhiteSpace(module.Operations)) { opBuilder.AppendFormat(label, module.Name); operations = module.Operations.Split(','); foreach (string op in operations) { actionId = Convert.ToInt32(op); operation = operationService.GetEntity(o => o.Id == actionId); opBuilder.AppendFormat(checkbox, module.Id, operation.Id, operation.Name); } opBuilder.Append("</form><p></p>"); } } return MvcHtmlString.Create(opBuilder.ToString()); }
//获取类名 public RoleService(IDbContext context) : base(context) { moduleApp = new ModuleService(context); moduleButtonApp = new ModuleButtonService(context); moduleFieldsApp = new ModuleFieldsService(context); itemsApp = new ItemsDataService(context); }
/// <summary> /// 权限分配时,生成每个资源对应的权限 /// </summary> public static MvcHtmlString DistributeOptions(this HtmlHelper helper, int moduleId) { //string label = "<form class=\"js-form-permission\" name=\"setPermission\"><input type=\"checkbox\" class=\"js-checkall-permission\" style=\"margin-top:-2px\" data-toggle=\"tooltip\" data-placement=\"top\" data-original-title=\"全选\" /><label class=\"inline mr40 pl20\">{0}</label>"; string label = "<form class=\"js-form-permission\" name=\"setPermission\"><input type=\"checkbox\" class=\"js-checkall-permission\" style=\"margin-top:-2px\" title=\"全选\" /><label class=\"inline mr40 pl20\">{0}</label>"; string checkbox = "<input type=\"checkbox\" name=\"{0}-{1}\" style=\"margin:-2px 8px 0 8px\" />{2}"; StringBuilder opBuilder = new StringBuilder(); ModuleService moduleService = new ModuleService(); IEnumerable <T_Module> modules = moduleService.GetEntities(m => m.ParentId == moduleId); string[] operations = null; int actionId = 0; T_Operation operation = null; OperationService operationService = new OperationService(); foreach (T_Module module in modules) { if (!string.IsNullOrWhiteSpace(module.Operations)) { opBuilder.AppendFormat(label, module.Name); operations = module.Operations.Split(','); foreach (string op in operations) { actionId = Convert.ToInt32(op); operation = operationService.GetEntity(o => o.Id == actionId); opBuilder.AppendFormat(checkbox, module.Id, operation.Id, operation.Name); } opBuilder.Append("</form><p></p>"); } } return(MvcHtmlString.Create(opBuilder.ToString())); }
public void GetsInternalAvcCorrectly() { //Arrange var json = new JObject(); json["spec_version"] = 1; json["identifier"] = "DogeCoinFlag"; json["version"] = "1.0.0"; json["download"] = "https://awesomemod.example/AwesomeMod.zip"; var sut = new ModuleService(); // Act var result = sut.GetInternalAvc(CkanModule.FromJson(json.ToString()), TestData.DogeCoinFlagAvcZip()); // Assert Assert.That(result, Is.Not.Null, "ModuleService should get an internal AVC file." ); Assert.That(result.version, Is.EqualTo(new Version("1.1.0")), "ModuleService should get correct version from the internal AVC file." ); Assert.That(result.ksp_version, Is.EqualTo(new KSPVersion("0.24.2")), "ModuleService should get correct ksp_version from the internal AVC file." ); Assert.That(result.ksp_version_min, Is.EqualTo(new KSPVersion("0.24.0")), "ModuleService should get correct ksp_version_min from the internal AVC file." ); Assert.That(result.ksp_version_max, Is.EqualTo(new KSPVersion("0.24.2")), "ModuleService should get correct ksp_version_max from the internal AVC file." ); }
protected override void ExecuteAdd(ModuleService moduleService) { // Here is the place where you can call third party API to add (provision) some service // Usually the result of provisioning is some ID that can be saved in the Atomia service property // in this example we will just randomly create some integer and save it in the "Number" property moduleService["Number"] = (new Random()).Next(0, 10).ToString(); }
public string list_num() { try { UserInfoService us = new UserInfoService(); string quanxian_save1 = us.new_quanxian("sel", "模块单位"); if (quanxian_save1 != null && quanxian_save1.Length > 0 && quanxian_save1 == "是") { } else { return(ResultUtil.error("没有权限!")); } ms = new ModuleService(); return(ResultUtil.success(ms.listByNum(false), "查询成功")); } catch (ErrorUtil err) { return(ResultUtil.fail(401, err.Message)); } catch { return(ResultUtil.error("查询失败")); } }
public string update(module_info moduleInfo) { try { UserInfoService us = new UserInfoService(); string quanxian_save1 = us.new_quanxian("upd", "模块单位"); if (quanxian_save1 != null && quanxian_save1.Length > 0 && quanxian_save1 == "是") { } else { return(ResultUtil.error("没有权限!")); } ms = new ModuleService(); return(ResultUtil.success(ms.update(moduleInfo), "保存成功")); } catch (ErrorUtil err) { return(ResultUtil.fail(401, err.Message)); } catch { return(ResultUtil.error("保存失败")); } }
private async Task ImportModule() { if (_content != string.Empty) { try { bool success = await ModuleService.ImportModuleAsync(ModuleState.ModuleId, _content); if (success) { AddModuleMessage("Content Imported Successfully", MessageType.Success); } else { AddModuleMessage("A Problem Was Encountered Importing Content. Please Ensure The Content Is Formatted Correctly For The Module.", MessageType.Warning); } } catch (Exception ex) { await logger.LogError(ex, "Error Importing Module {ModuleId} {Error}", ModuleState.ModuleId, ex.Message); AddModuleMessage("Error Importing Module", MessageType.Error); } } else { AddModuleMessage("You Must Enter Some Content To Import", MessageType.Warning); } }
public string page(PageUtil <module_info> modulePage, int moduleType) { try { UserInfoService us = new UserInfoService(); string quanxian_save1 = us.new_quanxian("sel", "模块单位"); if (quanxian_save1 != null && quanxian_save1.Length > 0 && quanxian_save1 == "是") { } else { return(ResultUtil.error("没有权限!")); } ms = new ModuleService(); return(ResultUtil.success(ms.page(modulePage, moduleType), "查询成功")); } catch (ErrorUtil err) { return(ResultUtil.fail(401, err.Message)); } catch { return(ResultUtil.error("查询失败")); } }
private string cacheKey = "HaotianCloud_authorizeurldata_";// +权限 public RoleAuthorizeService(IDbContext context) : base(context) { moduleApp = new ModuleService(context); moduleButtonApp = new ModuleButtonService(context); moduleFieldsApp = new ModuleFieldsService(context); userApp = new UserService(context); }
/// <summary> /// /// </summary> /// <param name="cbl"></param> /// <param name="id"></param> public void cbldata(CheckBoxList cbl, int id) { cbl.DataSource = ModuleService.GetChild(id); cbl.DataTextField = "modulename"; cbl.DataValueField = "id"; cbl.DataBind(); }
public static bool HasAccess(string controllerName, string actionName, string customName) { var userService = new UserService(); var user = userService.Get(); var userAuthorizationService = new UserRoleService(); var moduleService = new ModuleService(); int moduleId = 0; var actions = actionName.Split(','); foreach (var action in actions) { var module = moduleService.Get($"{controllerName}.{action}.{customName}"); if (module != null) { moduleId = module.Id; break; } } if (moduleId == 0) { return(false); } if (userAuthorizationService.GetUserRole(moduleId, user.Id)) { return(true); } return(false); }
public void SendCreeerModuleCommand_TestIfPublishAsyncGetsCalled() { // Arrange Mock <ICommandPublisher> mock = new Mock <ICommandPublisher>(MockBehavior.Strict); mock.Setup(publisher => publisher.PublishAsync <CreeerModuleCommandResponse>(It.IsAny <CreeerModuleCommand>())).Returns(Task.FromResult(new CreeerModuleCommandResponse() { Message = "Module toegevoegd", StatusCode = 200 })); IModuleService sut = new ModuleService(mock.Object); Module correctModel = new Module() { Cohort = "2017/2018", Competenties = new Matrix(), Eindeisen = new List <string>() { "Eindeis1", "Eindeis2" }, Moduleleider = new Moduleleider() { Email = "*****@*****.**", Naam = "dirk-jan", Telefoonnummer = "06742136491" }, Studiefase = new Studiefase() { Fase = "Propedeuse", Perioden = new List <int>() { 1, 3 } }, Studiejaar = "Jaar 3", AanbevolenVoor = new List <Specialisatie>() { new Specialisatie() { Code = "SE", Naam = "Software Engineering" } }, AantalEc = 3, ModuleCode = "iad1", ModuleNaam = "Algoritmen en Datastructuren 1", VerplichtVoor = new List <Specialisatie>() { new Specialisatie() { Code = "SE", Naam = "Software Engineering" } } }; // Act var result = sut.SendCreeerModuleCommand(correctModel); // Assert mock.Verify(publisher => publisher.PublishAsync <CreeerModuleCommandResponse>(It.IsAny <CreeerModuleCommand>())); }
public async Task ListModules() => await BuildEmbed(EmojiEnum.Love) .WithTitle("Modules:") .WithDescription($"Use `{BotConfiguration.Prefix}module enable/disable <name>` to change the state of a module!") .AddField("Enabled", ModuleService.GetModules(ConfigurationType.Enabled), true) .AddField("Disabled", ModuleService.GetModules(ConfigurationType.Disabled), true) .AddField("Essential", ModuleService.GetModules(ConfigurationType.Essential), true) .SendEmbed(Context.Channel);
protected override void innerInitContext(IRuleContext context){ IModuleService s = context.modules(); if (null == s && context is IWithServices){ ModuleService service = new ModuleService(); ((IWithServices) context).Services.RegisterService<IModuleService>(service); } base.innerInitContext(context); }
protected void Page_Load(object sender, EventArgs e) { IModuleService moduleService = new ModuleService(); List <Module> menus = moduleService.GetTreeModules(); json = menus.ToJson(); IsMainPage = true; }
public ExampleCommand( ModuleService service, ResourceDescription resource, ModuleService newServiceSettings, ModuleCommandType commandType, int listDepth) : base(service, resource, newServiceSettings, commandType, listDepth) { }
public ActionResult Create() { ModuleService moduleService = new ModuleService(); List <ModuleAccess> moduleList = moduleService.GetModuleData(); ViewBag.moduleId = new SelectList(moduleList, "moduleId", "moduleName"); return(View()); }
public ModuleCommandHandler(ILockService lockService, ModuleService moduleService, PermissionService permissionService, AppSystemService appSystemService) { _lockService = lockService; _moduleService = moduleService; _permissionService = permissionService; _appSystemService = appSystemService; }
private static void InitPrivilegeAndAuthMap() { ModuleService ms = BeanManager.GetInstance <ModuleService>(); AnonymPrivilege = ms.GetAnonymPrivileges(); AnonymAuthMap = ms.GetAnonymAuthMap(); AllPrivilege = ms.GetAllPrivileges(false); }
public ActionResult UpdateModule() { ModuleService moduleService = new ModuleService(); AgreementInfoAccess agreement = new AgreementInfoAccess(); ModuleAccess module = new ModuleAccess(); var moduleName = Request.Form["ModuleName"]; var description = Request.Form["Description"]; var expiryDate = Request.Form["ExpiryDate"]; var userType = Request.Form["userType"]; var content = Request.Form["AgreementContent"]; var moduleId = Convert.ToInt32(Session["moduleId"]); string key = null; var modules = moduleService.GetModuleData(key); foreach (var item in modules) { if (item.ModuleId == moduleId) { module = item; } } agreement = moduleService.ShowAgreement(moduleId); module.Description = description; string oleExpiryDate = module.ExpiryDate.ToShortDateString(); DateTime newExpiryDate = Convert.ToDateTime(expiryDate); if (expiryDate != oleExpiryDate) { if (newExpiryDate.Year > DateTime.Now.Year) { module.ExpiryDate = Convert.ToDateTime(expiryDate); } else if (newExpiryDate.Year == DateTime.Now.Year && newExpiryDate.Month > DateTime.Now.Month) { module.ExpiryDate = Convert.ToDateTime(expiryDate); } else if (newExpiryDate.Year == DateTime.Now.Year && newExpiryDate.Month == DateTime.Now.Month && newExpiryDate.Day > DateTime.Now.Day) { module.ExpiryDate = Convert.ToDateTime(expiryDate); } else { TempData["message"] = "Update failed with Module No." + module.ModuleId + ", Error: Expiry date should be later than today'date."; return(RedirectToAction("Index")); } } agreement.UserType = userType; agreement.Content = content; moduleService.UpdateModule(module, agreement); //if (moduleService.UpdateModule(module, agreement)) //{ // return RedirectToAction("Index"); //} return(RedirectToAction("Index")); }
public override ActionResult Index() { Session.Remove(cacheAllKey); Session.Remove(cacheSearchKey); var result = roleService.GetPagingInfo(base.PageSize); ModuleService moduleService = new ModuleService(); ViewData["ParentModule"] = moduleService.GetParentModules(); return View(result); }
/// <summary> /// Initializes a new instance of the <see cref="InstanceCommand"/> class. /// </summary> /// <param name="service">The service.</param> /// <param name="resource">The resource.</param> /// <param name="newServiceSettings">The new service settings.</param> /// <param name="commandType">Type of the command.</param> /// <param name="listDepth">The list depth.</param> public FoldersCommand(ModuleService service, ResourceDescription resource, ModuleService newServiceSettings, ModuleCommandType commandType, int listDepth) : base(service, resource, newServiceSettings, commandType, listDepth) { this.resource = resource; this.service = service; this.newServiceSettings = newServiceSettings; this.commandType = commandType; this.listDepth = listDepth; }
public ActionResult GetMenu() { JavaScriptSerializer serializer = new JavaScriptSerializer(); var jmenus = serializer.Deserialize <Menu[]>(JsonHelper.getJsonMenu()); var menus = ModuleService.GetUserMenus(User.Identity.Name, this.GetCookieValue("cityid"), this.GetCookieValue("systemid")); return(Json(menus, "text", JsonRequestBehavior.AllowGet)); }
/// <summary> /// Calls the operation. /// </summary> /// <param name="service">The service.</param> /// <param name="operationName">Name of the operation.</param> /// <param name="operationArgument">The operation argument.</param> /// <param name="resource">The resource.</param> /// <returns>Operation result.</returns> public override string CallOperation(ModuleService service, string operationName, string operationArgument, Atomia.Provisioning.Base.ResourceDescription resource) { ModuleCommand command = this.GetModuleCommand(resource, ModuleCommandType.Add, -1, service); if (command is ModuleCommandSimpleBase) { return ((ModuleCommandSimpleBase)command).CallOperation(operationName, operationArgument); } else { throw ExceptionHelper.GetModuleException("ID400018", null, null); } }
protected override void ExecuteAdd(ModuleService moduleService) { Dictionary<string,string> response = this.REST_Execute_POST(this.GetResourceURL(service), this.GetPostData(service)); if (response.ContainsKey("id")) { moduleService["Id"] = response["id"]; } else { throw new Exception("id not found in response, which contained " + string.Join(", ", response.Select(pair => pair.Key + "='" + pair.Value + "'").ToArray())); } }
public override void Update() { ModuleService target = new ModuleService(); Module module = (Module) CreateRecord(); Insert(module); module.Description = "asdf 123"; target.Update(module); Module updated = target.GetByID(module.ID); Assert.AreEqual(module.Description, updated.Description); }
protected virtual Dictionary<string, string> GetPostData(ModuleService service) { var post_data = new Dictionary<string, string>(); foreach (ModuleServiceProperty prop in service.Properties) { if (!string.IsNullOrEmpty(prop.Value)) { post_data[prop.Name.ToLower()] = prop.Value; } } return post_data; }
public override void OnAuthorization(AuthorizationContext filterContext) { //ToTest //int roleID = Convert.ToInt32(HttpContext.Current.Session["RoleID"]); int roleID = 1; string controller = filterContext.GetController(); ModuleService moduleService = new ModuleService(); int controllerID = moduleService.GetModuleIdByName(controller); UserService userService = new UserService(); IEnumerable<string> actions = userService.GetUserOperation(roleID, controllerID); foreach (string action in actions) { filterContext.SetViewData(action, true); } }
public static ModuleService DeserializeService(string serviceSerialized) { ModuleService result = null; //serviceSerialized = serviceSerialized.Replace("_#_#_", " "); JavaScriptSerializer oSerializer = new JavaScriptSerializer(); Dictionary<string, Dictionary<string, string>> serviceFull = (Dictionary<string, Dictionary<string, string>>)oSerializer.Deserialize(serviceSerialized, typeof(Dictionary<string, Dictionary<string, string>>)); string serviceKey = "current"; ModuleService lastService = null; for (int i = 0; i < serviceFull.Count; i++) { Dictionary<string, string> oneServiceDict = serviceFull[serviceKey]; ModuleService tempService = new ModuleService(oneServiceDict["serviceMetaData_Name"], oneServiceDict["serviceMetaData_PhysicalID"]); tempService.InstanceId = oneServiceDict["serviceMetaData_InstanceId"]; //tempService.LogicalID = oneServiceDict["serviceMetaData_LogicalID"]; readonly //tempService.Name = oneServiceDict["serviceMetaData_Name"]; readonly //tempService.PhysicalID = oneServiceDict["serviceMetaData_PhysicalID"]; set in constructor tempService.ProvisioningId = oneServiceDict["serviceMetaData_ProvisioningId"]; foreach (KeyValuePair<String, String> entry in oneServiceDict) { if (entry.Key.IndexOf("serviceMetaData_") < 0) { tempService.Properties.Add(new ModuleServiceProperty(entry.Key, entry.Value)); } } if (serviceKey == "current") { lastService = tempService; result = lastService; } else { lastService.Parent = tempService; lastService = lastService.Parent; } serviceKey = serviceKey + ".parent"; } return result; }
public void GetByProject() { for (int i = 0; i < 10; i++) { Insert(CreateRecord()); } ModuleService target = new ModuleService(); Collection<Module> collection = target.GetByProject(_project.ID); Assert.IsTrue(collection.Count >= 10); foreach (Module module in collection) { Assert.AreEqual(_project.ID, module.ProjectID); } }
//TODO: use and test ~/Controls/Report.ascx /// <summary> /// Fills the form with the given item. /// </summary> /// <param name="item">The item.</param> public void FillForm(ProjectItem item) { if (item != null) { lblType.Text = item.Type.ToString(); lblName.Text = item.Name; lblDescription.Text = item.Description; lblStartDate.Text = Utility.MaskNull(item.StartDate); lblExpEndDate.Text = Utility.MaskNull(item.ExpEndDate); lblActEndDate.Text = Utility.MaskNull(item.ActEndDate); double percentComplete; switch (item.Type) { case ProjectItemType.Project: { ModuleService service = new ModuleService(); List<Module> modules = new List<Module>(service.GetByProject(item.ID)); List<ProjectItem> moduleItems = modules.ConvertAll(i => (ProjectItem) i); percentComplete = GetPercentComplete(moduleItems); break; } case ProjectItemType.Module: { TaskService taskService = new TaskService(); List<Task> tasks = new List<Task>(taskService.GetByModule(item.ID)); List<ProjectItem> taskItems = tasks.ConvertAll(i => (ProjectItem) i); percentComplete = GetPercentComplete(taskItems); break; } case ProjectItemType.Task: { percentComplete = item.IsComplete ? 1 : 0; break; } default: { throw new ArgumentOutOfRangeException(); } } lblItemStatus.Text = percentComplete.ToString("p"); } }
/// <summary> /// 生成用户功能菜单 /// </summary> public static MvcHtmlString CreateMenu(this HtmlHelper helper) { //HttpSessionState session = new HttpSessionState(); //session.Get("RoleId"); //ToTest int roleID = 1; string parentMenu = "<a href=\"#{0}\" class=\"nav-header\" data-toggle=\"collapse\"><i class=\"ico-menu ico-{1}\"></i>{2}</a>"; string childMenu = "<ul id=\"{0}\" class=\"nav nav-list collapse in pl20\">{1}</ul>"; string childContent = "<li><a target=\"content\" href=\"/{0}\"><i class=\"ico-menu ico-{1}\"></i>{2}</a></li>"; UserService userService = new UserService(); //获取可以浏览的菜单 IEnumerable<UserBrowseViewModel> modules = userService.GetUserBrowse(roleID); //获取父菜单 IList<UserBrowseViewModel> parentModules = new List<UserBrowseViewModel>(); modules.Enumerate(m => m.ParentId == 0, m => parentModules.Add(m)); //获取子菜单 IEnumerable<T_Module> childModules = null; StringBuilder menuBuilder = new StringBuilder(); StringBuilder childBuilder = new StringBuilder(); ModuleService moduleService = new ModuleService(); foreach (var parent in parentModules) { menuBuilder.AppendFormat(parentMenu, parent.Code + "-menu", parent.Code, parent.Name); childModules = moduleService.GetChildModules(parent.ID); foreach (var child in childModules) { childBuilder.AppendFormat(childContent, child.Url, child.Code, child.Name); } menuBuilder.AppendFormat(childMenu, parent.Code + "-menu", childBuilder.ToString()); childBuilder.Clear(); } return MvcHtmlString.Create(menuBuilder.ToString()); }
/// <summary> /// Removes the service. /// </summary> /// <param name="service">The service.</param> /// <param name="resource">The resource.</param> public override void RemoveService(ModuleService service, Atomia.Provisioning.Base.ResourceDescription resource) { this.PrepareCommandList(service, null, resource, ModuleCommandType.Remove); this.PrepareAndExecuteCommandsFromList(); }
/// <summary> /// Prepares the command list. /// </summary> /// <param name="service">Service to populate.</param> /// <param name="newServiceSettings">New service settings.</param> /// <param name="resource">Server resource.</param> /// <param name="commandType">Type of command.</param> private void PrepareCommandList(ModuleService service, ModuleService newServiceSettings, ResourceDescription resource, ModuleCommandType commandType) { if (commandType != ModuleCommandType.Remove) { this.commands.Add(this.GetModuleCommand(resource, commandType, -1, service, newServiceSettings)); } if (service.Children != null) { for (int i = 0; i < service.Children.Count; i++) { ModuleService childService = service.Children[i]; ModuleService newChildSettings = null; if (newServiceSettings != null && newServiceSettings.Children != null && newServiceSettings.Children.Count > i) { newChildSettings = newServiceSettings.Children[i]; } this.PrepareCommandList(childService, newChildSettings, resource, commandType); } } if (commandType == ModuleCommandType.Remove) { this.commands.Add(this.GetModuleCommand(resource, commandType, -1, service, newServiceSettings)); } }
protected abstract string GetResourceURL(ModuleService moduleService);
protected override void ExecuteModify(ModuleService oldService, ModuleService newService) { string changeFileSufix = "_CopyForRollBack"; switch (transContext) { case "BeginTransaction": { //we copy old file to file with changeFileSufix sufix, and change file string rootFolder = this.resource["RootFolder"].ToString(); if (rootFolder == "") { rootFolder = "c:\\ProvisioningModuleTestFolder\\"; } if (rootFolder.Substring(rootFolder.Length - 1, 1) != "\\") { rootFolder += "\\"; } string newFileName = string.Empty; string oldFileName = string.Empty; newFileName = newService.Properties.Find(p => p.Name == "Name").Value; oldFileName = oldService.Properties.Find(p => p.Name == "Name").Value; string parentFolder = newService.Properties.Find(p => p.Name == "ParentFolder").Value; string newFileFullPath = rootFolder + parentFolder + "\\" + newFileName; string oldFileFullPath = rootFolder + parentFolder + "\\" + oldFileName; string oldFileContent = oldService.Properties.Find(p => p.Name == "Content").Value; string newFileContent = newService.Properties.Find(p => p.Name == "Content").Value; File.Copy(oldFileFullPath, oldFileFullPath + changeFileSufix); if (oldFileContent != newFileContent) { File.WriteAllText(oldFileFullPath, newFileContent); } if (oldFileName != newFileName) { File.Move(oldFileFullPath, newFileFullPath); File.Delete(oldFileFullPath); } } break; case "CommitTransaction": { //change content of file, rename it to new name and delete copy with changeFileSufix string rootFolder = this.resource["RootFolder"].ToString(); if (rootFolder == "") { rootFolder = "c:\\ProvisioningModuleTestFolder\\"; } if (rootFolder.Substring(rootFolder.Length - 1, 1) != "\\") { rootFolder += "\\"; } string newFileName = string.Empty; string oldFileName = string.Empty; newFileName = newService.Properties.Find(p => p.Name == "Name").Value; oldFileName = oldService.Properties.Find(p => p.Name == "Name").Value; string parentFolder = newService.Properties.Find(p => p.Name == "ParentFolder").Value; string newFileFullPath = rootFolder + parentFolder + "\\" + newFileName; string oldFileFullPath = rootFolder + parentFolder + "\\" + oldFileName; File.Delete(oldFileFullPath + changeFileSufix); } break; case "RollBackTransaction": { //we should revert renamed file name, and file content string rootFolder = this.resource["RootFolder"].ToString(); if (rootFolder == "") { rootFolder = "c:\\ProvisioningModuleTestFolder\\"; } if (rootFolder.Substring(rootFolder.Length - 1, 1) != "\\") { rootFolder += "\\"; } string newFileName = string.Empty; string oldFileName = string.Empty; newFileName = newService.Properties.Find(p => p.Name == "Name").Value; oldFileName = oldService.Properties.Find(p => p.Name == "Name").Value; string parentFolder = newService.Properties.Find(p => p.Name == "ParentFolder").Value; string newFileFullPath = rootFolder + parentFolder + "\\" + newFileName; string oldFileFullPath = rootFolder + parentFolder + "\\" + oldFileName; if (oldFileName == newFileName) { File.Delete(oldFileFullPath); } File.Copy(oldFileFullPath + changeFileSufix, oldFileFullPath); } break; } }
protected override void ExecuteRemove(ModuleService moduleService) { this.REST_Execute_DELETE(this.GetResourceURL(moduleService)); }
public void DeleteWithTasks() { ProjectService service = new ProjectService(); Project project = (Project) CreateRecord(); Insert(project); ModuleService moduleService = new ModuleService(); Module module = new Module(project.ID, "Name", "Description"); moduleService.Insert(module); TaskService taskService = new TaskService(); for (int i = 0; i < 5; i++) { taskService.Insert(new Task(module.ID, "Task", "Description", TaskComplexity.Medium)); } service.Delete(project.ID); Assert.AreEqual(0, moduleService.GetByProject(project.ID).Count); Assert.AreEqual(0, taskService.GetByModule(module.ID).Count); }
public HaproxyCommandBase(ModuleService service, ResourceDescription resource, ModuleService newServiceSettings, ModuleCommandType commandType, int listDepth) : base(service, resource, newServiceSettings, commandType, listDepth) { this.jsonSerializer = new JavaScriptSerializer(); }
protected override void ValidateService(ModuleService moduleService) { }
public ListenerSettingCommand(ModuleService service, ResourceDescription resource, ModuleService newServiceSettings, ModuleCommandType commandType, int listDepth) : base(service, resource, newServiceSettings, commandType, listDepth) { }
protected override string GetResourceURL(ModuleService moduleService) { string id = moduleService.Properties.Single(p => p.Name == "Id").Value; string parent_url = "listener/" + moduleService.Parent.Properties.Single(p => p.Name == "Id").Value; return parent_url + "/" + (string.IsNullOrEmpty(id) ? "setting" : ("setting/" + id)); }
public override void TestFixtureTearDown() { base.TestFixtureTearDown(); ModuleService moduleService = new ModuleService(); moduleService.Delete(_module.ID); ProjectService projectService = new ProjectService(); projectService.Delete(_project.ID); UserService userService = new UserService(); userService.Delete(_developer.ID); }
public override void TestFixtureSetUp() { ProjectService projectService = new ProjectService(); _project = new Project("Name", "Description"); projectService.Insert(_project); ModuleService moduleService = new ModuleService(); _module = new Module(_project.ID, "Name", "Description"); moduleService.Insert(_module); UserService userService = new UserService(); _developer = new User(UserRole.Developer, Guid.NewGuid().ToString(), "asdf"); userService.Insert(_developer); base.TestFixtureSetUp(); }
public void DeleteWithModules() { ProjectService service = new ProjectService(); Project project = (Project) CreateRecord(); Insert(project); ModuleService moduleService = new ModuleService(); for (int i = 0; i < 5; i++) { moduleService.Insert(new Module(project.ID, "Module", "Description")); } service.Delete(project.ID); Assert.AreEqual(0, moduleService.GetByProject(project.ID).Count); }
void IModule.Install(ModuleManager manager) { _manager = manager; _client = manager.Client; _service = manager.Client.Modules(true); manager.CreateCommands("modules", group => { group.MinPermissions((int)PermissionLevel.BotOwner); group.CreateCommand("list") .Description("Gives a list of all available modules.") .Do(async e => { string text = "Available Modules: " + string.Join(", ", _service.Modules.Select(x => x.Id)); await _client.Reply(e, text); }); group.CreateCommand("enable") .Description("Enables a module for this server.") .Parameter("module") .PublicOnly() .Do(e => { var module = GetModule(e.Args[0]); if (module == null) { _client.ReplyError(e, "Unknown module"); return; } if (module.FilterType == ModuleFilter.None || module.FilterType == ModuleFilter.AlwaysAllowPrivate) { _client.ReplyError(e, "This module is global and cannot be enabled/disabled."); return; } if (!module.FilterType.HasFlag(ModuleFilter.ServerWhitelist)) { _client.ReplyError(e, "This module doesn't support being enabled for servers."); return; } var server = e.Server; if (!module.EnableServer(server)) { _client.ReplyError(e, $"Module {module.Id} was already enabled for server {server.Name}."); return; } _client.Reply(e, $"Module {module.Id} was enabled for server {server.Name}."); }); group.CreateCommand("disable") .Description("Disables a module for this server.") .Parameter("module") .PublicOnly() .Do(e => { var module = GetModule(e.Args[0]); if (module == null) { _client.ReplyError(e, "Unknown module"); return; } if (module.FilterType == ModuleFilter.None || module.FilterType == ModuleFilter.AlwaysAllowPrivate) { _client.ReplyError(e, "This module is global and cannot be enabled/disabled."); return; } if (!module.FilterType.HasFlag(ModuleFilter.ServerWhitelist)) { _client.ReplyError(e, "This module doesn't support being enabled for servers."); return; } var server = e.Server; if (!module.DisableServer(server)) { _client.ReplyError(e, $"Module {module.Id} was not enabled for server {server.Name}."); return; } _client.Reply(e, $"Module {module.Id} was disabled for server {server.Name}."); }); }); }
public FileCommand(ModuleService service, ResourceDescription resource, ModuleService newServiceSettings, ModuleCommandType commandType, int listDepth, string transContext) : base(service, resource, newServiceSettings, commandType, listDepth) { this.transContext = transContext; }
protected override void ExecuteModify(ModuleService oldService, Base.Module.ModuleService service) { this.REST_Execute_PUT(this.GetResourceURL(service), this.GetPostData(service)); }
void IModule.Install(ModuleManager manager) { _client = manager.Client; _moduleService = _client.GetService<ModuleService>(); manager.CreateDynCommands("module", PermissionLevel.ServerAdmin, group => { group.AddCheck((cmd, usr, chnl) => !chnl.IsPrivate); group.CreateCommand("channel enable") .Description("Enables a module on the current channel.") .Parameter("module", ParameterType.Unparsed) .Do(async e => { ModuleManager module = await VerifyFindModule(e.GetArg("module"), e.Channel); if (module == null) return; if (!await CanChangeModuleStateInServer(module, ModuleFilter.ChannelWhitelist, e)) return; Channel channel = e.Channel; if (!module.EnableChannel(channel)) { await e.Channel.SafeSendMessage( $"Module `{module.Id}` was already enabled for channel `{channel.Name}`."); return; } _channelModulesDictionary.AddModuleToSave(module.Id, e.Channel.Id); await e.Channel.SafeSendMessage($"Module `{module.Id}` was enabled for channel `{channel.Name}`."); }); group.CreateCommand("channel disable") .Description("Disable a module on the current channel.") .Parameter("module", ParameterType.Unparsed) .Do(async e => { ModuleManager module = await VerifyFindModule(e.GetArg("module"), e.Channel); if (module == null) return; if (!await CanChangeModuleStateInServer(module, ModuleFilter.ChannelWhitelist, e, false)) return; Channel channel = e.Channel; if (!module.DisableChannel(channel)) { await e.Channel.SafeSendMessage( $"Module `{module.Id}` was not enabled for channel `{channel.Name}`."); return; } _channelModulesDictionary.DeleteModuleFromSave(module.Id, e.Channel.Id); await e.Channel.SafeSendMessage($"Module `{module.Id}` was disabled for channel `{channel.Name}`."); }); group.CreateCommand("server enable") .Description("Enables a module on the current server.") .Parameter("module", ParameterType.Unparsed) .Do(async e => { ModuleManager module = await VerifyFindModule(e.GetArg("module"), e.Channel); if (module == null) return; if (!await CanChangeModuleStateInServer(module, ModuleFilter.ServerWhitelist, e)) return; Server server = e.Server; if (!module.EnableServer(server)) { await e.Channel.SafeSendMessage( $"Module `{module.Id}` was already enabled for server `{server.Name}`."); return; } _serverModulesDictionary.AddModuleToSave(module.Id, e.Server.Id); await e.Channel.SafeSendMessage($"Module `{module.Id}` was enabled for server `{server.Name}`."); }); group.CreateCommand("server disable") .Description("Disables a module for the current server.") .Parameter("module", ParameterType.Unparsed) .Do(async e => { ModuleManager module = await VerifyFindModule(e.GetArg("module"), e.Channel); if (module == null) return; if (!await CanChangeModuleStateInServer(module, ModuleFilter.ServerWhitelist, e, false)) return; Server server = e.Server; if (!module.DisableServer(server)) { await e.Channel.SafeSendMessage( $"Module `{module.Id}` was not enabled for server `{server.Name}`."); return; } _serverModulesDictionary.DeleteModuleFromSave(module.Id, e.Server.Id); await e.Channel.SafeSendMessage($"Module `{module.Id}` was disabled for server `{server.Name}`."); }); group.CreateCommand("list") .Description("Lists all available modules.") .Do(async e => { StringBuilder builder = new StringBuilder("**Available modules:**\r\n"); foreach (ModuleManager module in _moduleService.Modules) { builder.Append($"`* {module.Id,-20} "); if (e.Channel.IsPrivate) { if (module.FilterType.HasFlag(ModuleFilter.AlwaysAllowPrivate)) builder.Append($"Always available on prviate."); } else { if (module.FilterType.HasFlag(ModuleFilter.ServerWhitelist)) builder.Append($"Globally server: {module.EnabledServers.Contains(e.Server),-5} "); if (module.FilterType.HasFlag(ModuleFilter.ChannelWhitelist)) builder.Append($"Channel: {module.EnabledChannels.Contains(e.Channel),-5}"); } builder.AppendLine("`"); } await e.Channel.SafeSendMessage(builder.ToString()); }); }); _client.JoinedServer += async (s, e) => { foreach (string moduleName in DefaultModules) { ModuleManager module = await VerifyFindModule(moduleName, null, false); if (module == null) return; if (!module.FilterType.HasFlag(ModuleFilter.ServerWhitelist)) throw new InvalidOperationException(); Server server = e.Server; module.EnableServer(server); _serverModulesDictionary.AddModuleToSave(module.Id, server.Id); } }; }