public IActionResult Create() { ResourceViewModel resource = new ResourceViewModel(); resource.IsNew = true; return(View(resource)); }
public async Task <IActionResult> Edit(ResourceViewModel resource) { resource.IsValid = ModelState.IsValid || resource == null || string.IsNullOrEmpty(resource.Name) || Guid.Empty == resource.Id; bool isNameUnique = await resourceService.FindIfNameIsUniqueAsync(resource.Id, resource.Name); if (!resource.IsValid.Value && !isNameUnique) { return(View(resource)); } ResourceModel editedResource = new ResourceModel(); editedResource = resourceService.Update(mapper.ResourceViewModelToResource(resource)); if (!ResourceExists(resource.Id)) { return(NotFound()); } if (editedResource == null) { return(NotFound()); } ResourceViewModel newResourceViewModel = mapper.ResourceToResourceViewModel(editedResource); newResourceViewModel.ShowAlert = true; return(View(newResourceViewModel)); }
/// <summary> /// Gets resource entity model from view model. /// </summary> /// <param name="resourceViewModel">Resource view model object.</param> /// <param name="userAadObjectId">Azure Active Directory id of current logged-in user.</param> /// <returns>Returns a resource entity model</returns> public Resource MapToDTO( ResourceViewModel resourceViewModel, Guid userAadObjectId) { resourceViewModel = resourceViewModel ?? throw new ArgumentNullException(nameof(resourceViewModel)); return(new Resource { Id = resourceViewModel.Id, Title = resourceViewModel.Title, Description = resourceViewModel.Description, SubjectId = resourceViewModel.SubjectId, GradeId = resourceViewModel.GradeId, ImageUrl = resourceViewModel.ImageUrl, LinkUrl = resourceViewModel.LinkUrl, AttachmentUrl = resourceViewModel.AttachmentUrl, CreatedOn = DateTimeOffset.Now, UpdatedOn = DateTimeOffset.Now, CreatedBy = userAadObjectId, UpdatedBy = userAadObjectId, ResourceType = resourceViewModel.ResourceType, Grade = resourceViewModel.Grade, Subject = resourceViewModel.Subject, ResourceTag = resourceViewModel.ResourceTag?.ToList(), }); }
public async Task UpdateResource(ResourceViewModel resourceModel, Guid updatetById) { try { string resourceFileString = ""; if (resourceModel.file != null) { using (BinaryReader binaryReader = new BinaryReader(resourceModel.file.OpenReadStream())) { byte[] byteFile = binaryReader.ReadBytes((int)resourceModel.file.Length); resourceFileString = BitConverter.ToString(byteFile); } } Resource resource = _unitOfWork.Repository <Resource>().Get().FirstOrDefault(i => i.Id == resourceModel.id); resource.Name = resourceModel.name; resource.Description = resourceModel.description; resource.Url = resourceModel.url; resource.FileName = resourceModel.fileName; resource.File = resourceFileString; resource.CategoryId = resourceModel.categoryId; resource.UpdatedById = updatetById; _unitOfWork.Repository <Resource>().Update(resource); await _unitOfWork.SaveChangesAsync(); } catch (Exception ex) { throw new Exception($"Error when updating the {nameof(resourceModel)}: {resourceModel.id} ", ex); } }
//public async Task<ActionResult> DisplayResources(Guid id) //{ // try // { // ResourceViewModel model = new ResourceViewModel(); // ViewBag.Skills = await APIHelpers.GetAsync<List<Skills>>("api/Skill/GetSkills"); // var data = await APIHelpers.GetAsync<List<EmployeeUserViewModel>>("api/Resource/GetAvailableResources/" + id); // model.EmployeeUserViewModels = data; // model.Resource = id; // return View("Index", model); // } // catch (Exception ex) // { // throw; // } //} #region Display Resources Method public async Task <ActionResult> DisplayResources(ResourceViewModel model1) { try { ResourceViewModel model = new ResourceViewModel(); ViewBag.Skills = await APIHelpers.GetAsync <List <Skills> >("api/Skill/GetSkills"); var data = await APIHelpers.GetAsync <List <EmployeeUserViewModel> >("api/Resource/GetAvailableResources?id=" + model1.Resource + "&workingid=" + Convert.ToBoolean(model1.IsCurrentlyWorking)); if (Convert.ToBoolean(model1.IsCurrentlyWorking)) { model.EmployeeUserViewModels = data.Where(_ => _.WorkingCount > 0); } else { model.EmployeeUserViewModels = data.Where(_ => _.WorkingCount == 0); } model.Resource = model1.Resource; model.IsCurrentlyWorking = model1.IsCurrentlyWorking; return(View("Index", model)); } catch (Exception ex) { throw; } }
public async Task PatchAsync_ResourceUpdateWithNonAdminUser_ReturnsUnauthorizedResult() { // ARRANGE var resourceTagss = new List <ResourceTag>(); var resourceTag = new ResourceTag() { TagId = Guid.Parse(FakeData.Id), ResourceId = Guid.Parse(FakeData.Id), }; resourceTagss.Add(resourceTag); var resourceModel = new ResourceViewModel { Id = Guid.Parse(FakeData.Id), Title = "Test title", Description = "Test description", ImageUrl = "https://test.jpg", ResourceType = 1, ResourceTag = resourceTagss, }; var resource = FakeData.GetResource(); resource.CreatedBy = Guid.NewGuid(); this.unitOfWork.Setup(uow => uow.ResourceRepository.GetAsync(It.IsAny <Guid>())).ReturnsAsync(resource); this.memberValidationService.Setup(validationService => validationService.ValidateMemberAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(false); this.securityGroupOptions.Value.AdminGroupId = Guid.NewGuid().ToString(); // ACT var result = (ObjectResult)await this.resourceController.PatchAsync(Guid.Parse(FakeData.Id), resourceModel); // ASSERT Assert.AreEqual(result.StatusCode, StatusCodes.Status401Unauthorized); }
/// <summary> /// Gets the tree resources using the Discovery protocol. /// </summary> /// <param name="uri">The URI.</param> /// <param name="depth">The depth.</param> /// <param name="parent">The parent.</param> /// <returns>The message identifier.</returns> public Task <long> GetTreeResources(string uri, int?depth, ResourceViewModel parent = null) { var contentTypes = new string[0]; var result = EtpExtender.GetTreeResources(uri, depth ?? 0, contentTypes); return(Task.FromResult(result)); }
public MainViewModel([NotNull] ResourceManager resourceManager, [NotNull] Configuration configuration, [NotNull] ResourceViewModel resourceViewModel, [NotNull] ITracer tracer, [NotNull] SourceFilesProvider sourceFilesProvider) { ResourceManager = resourceManager; _configuration = configuration; _resourceViewModel = resourceViewModel; _tracer = tracer; SourceFilesProvider = sourceFilesProvider; resourceManager.BeginEditing += ResourceManager_BeginEditing; resourceManager.Reloading += ResourceManager_Reloading; try { var folder = Settings.Default.StartupFolder; if (string.IsNullOrEmpty(folder)) { return; } SourceFilesProvider.Folder = folder; if (Directory.Exists(folder)) { Load(); } } catch (Exception ex) { _tracer.TraceError(ex.ToString()); MessageBox.Show(ex.Message); } }
/// <summary> /// Gets the resources using the Discovery protocol. /// </summary> /// <param name="uri">The URI.</param> /// <param name="parent">The parent.</param> /// <returns>The message identifier.</returns> public Task <long> GetResources(string uri, ResourceViewModel parent = null) { var contentTypes = new string[0]; long messageId; if (Model == null) { messageId = EtpExtender.GetResources(uri); } else if (Model.DiscoveryFunction == Functions.FindResources) { messageId = EtpExtender.FindResources(uri); } else if (Model.DiscoveryFunction == Functions.GetTreeResources) { messageId = EtpExtender.GetTreeResources(uri, Model.DiscoveryDepth, contentTypes); } else if (Model.DiscoveryFunction == Functions.GetGraphResources) { messageId = EtpExtender.GetGraphResources(uri, Model.DiscoveryScope, Model.GroupByType, Model.DiscoveryDepth, contentTypes); } else { messageId = EtpExtender.GetResources(uri); } return(Task.FromResult(messageId)); }
/// <summary> /// Parse and display the new input stream /// </summary> private void CreatePaths(string stream) { GraphicPath path; try { var streamGeometryParser = new StreamGeometryParser(); var graphicPathGeometry = streamGeometryParser.ParseGeometry(stream); path = new GraphicPath(); path.Geometry = graphicPathGeometry; path.FillBrush = new GraphicSolidColorBrush { Color = Color.FromRgb(128, 128, 128) }; ShowError = false; } catch { path = null; ShowError = true; } PreviewViewModel.SetNewGraphicPath(path); ResourceViewModel.SetNewGraphicVisual(path); XamlViewModel.SetNewGraphicVisual(path); CSharpViewModel.SetNewGraphicVisual(path); ExportViewModel.SetNewGraphicVisual(path); }
public static void UpdatedResource() { var model = new ResourceViewModel(); model.Prepare(); ResourceModels = model.ResourceModels; }
public AddNewKeyCommand([NotNull] ResourceViewModel resourceViewModel, [NotNull] IExportProvider exportProvider) { _resourceViewModel = resourceViewModel; _exportProvider = exportProvider; ExecuteCallback = InternalExecute; }
private void Window_Loaded(object sender, RoutedEventArgs e) { try { var db = new MyDbContext(); db.Database.EnsureDeleted(); db.Database.EnsureCreated(); var resourceViewModel = new ResourceViewModel(db); this.DataContext = resourceViewModel; //db.Dispose(); // TEST var customerWindow = new CustomerWindow(db); customerWindow.Show(); // TEST } catch (Exception ex) { Title = ex.Message; } }
public async Task <ActionResult> SaveResource(ResourceViewModel model) { using (ResourceServiceClient client = new ResourceServiceClient()) { Resource obj = new Resource() { Key = new ResourceKey() { Code = model.Code, Type = model.Type }, Data = model.Data, Name = model.Name, Description = model.Description, Editor = User.Identity.Name, EditTime = DateTime.Now, CreateTime = DateTime.Now, Creator = User.Identity.Name }; MethodReturnResult rst = await client.AddAsync(obj); if (rst.Code == 0) { rst.Message = string.Format(StringResource.Resource_SaveResource_Success , model.Type.GetDisplayName() , model.Code); } return(Json(rst)); } }
// GET: Resource/Create public ActionResult Create() { if (IsUserLoggedIn()) { if (IsAdmin()) { var facilities = _facilityService.GetAll(); var model = new ResourceViewModel { ListOfAllFacilities = facilities.ToList() }; return(View("Create", model)); } else { ModelState.AddModelError("", USER_ACCESS_ERR_MSG); return(View("Error")); } } else { ModelState.AddModelError("", USER_LOGIN_ERR_MSG); } return(RedirectToAction("Login", "Standard", new { area = "" })); }
public async Task <IActionResult> Create(ResourceViewModel resource, HttpRequest req, CancellationToken cancellationToken) { _ = req; if (!_identityService.CurrentUserHasRole(AuthJanitorRoles.ResourceAdmin)) { return(new UnauthorizedResult()); } var provider = _providerManager.GetProviderMetadata(resource.ProviderType); if (provider == null) { return(new NotFoundObjectResult("Provider type not found")); } if (!_providerManager.TestProviderConfiguration(provider.ProviderTypeName, resource.SerializedProviderConfiguration)) { return(new BadRequestErrorMessageResult("Invalid Provider configuration!")); } Resource newResource = new Resource() { Name = resource.Name, Description = resource.Description, ProviderType = provider.ProviderTypeName, ProviderConfiguration = resource.SerializedProviderConfiguration }; await _resources.Create(newResource, cancellationToken); await _eventDispatcher.DispatchEvent(AuthJanitorSystemEvents.ResourceCreated, nameof(ResourcesService.Create), newResource); return(new OkObjectResult(_resourceViewModel(newResource))); }
public async Task <(Guid, string)> Add(ResourceViewModel resource) { if (resource.Available.Count > 0) { if (resource.Available.Any(r => r.From == r.To)) { return(Guid.Empty, "Start and end time cannot be the same time"); } if (resource.Available.Any(dayAndTime => resource.HasOverlapping(dayAndTime))) { return(Guid.Empty, "Overlap in available time"); } } HttpResponseMessage result; try { result = await _client.PostAsJsonAsync($"{_mobileBffUrl}/Resource", resource); } catch (Exception e) { return(Guid.Empty, e.Message); } return(result.IsSuccessStatusCode ? (await result.Content.ReadFromJsonAsync <Guid>(), null) : (Guid.Empty, "Failed to create resource")); }
public async Task <ResourceViewModel> GetById(Guid id) { HttpResponseMessage result; try { result = await _client.GetAsync($"{_mobileBffUrl}/Resource/{id}"); } catch (Exception) { return(null); } if (!result.IsSuccessStatusCode) { return(null); } ResourceViewModel resource = null; try { resource = await result.Content.ReadFromJsonAsync <ResourceViewModel>(); } catch (Exception e) { Console.WriteLine("Begin Error"); Console.WriteLine(e); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); Console.WriteLine("End error"); } return(resource ?? null); }
public IActionResult Update(string id, [FromBody] ResourceViewModel resource) { Console.WriteLine("Heroku Controller- Update"); try { if (ModelState.IsValid && !string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(resource.plan)) { //get addon plan based on plan name var addonPlan = Utilities.GetAddonPlanByPlan(resource.plan); if (!addonPlan.IsNull() && addonPlan.is_active) { //update resource _resourcesRepository.UpdatePlan(id, addonPlan.level.ToString()); } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; } } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; } } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); Response.StatusCode = (int)HttpStatusCode.InternalServerError; } return(Json(new { })); }
// GET: Resource/Edit/5 public ActionResult Edit(int id) { if (IsUserLoggedIn()) { if (IsAdmin()) { var resource = _resourceService.GetById(id); if (resource == null) { return(HttpNotFound()); } var model = new ResourceViewModel(resource); model.ListOfAllFacilities = _facilityService.GetAll().ToList(); return(View("Edit", model)); } else { ModelState.AddModelError("", USER_ACCESS_ERR_MSG); return(RedirectToAction("Error")); } } else { ModelState.AddModelError("", USER_LOGIN_ERR_MSG); } return(RedirectToAction("Login", "Standard", new { area = "" })); }
public void TestInitialize() { this.learnNowContext = new LearnNowContext(); this.resourceMapper = new ResourceMapper( this.learnNowContext); this.resourceViewModel = new ResourceViewModel() { Id = Guid.NewGuid(), GradeId = Guid.NewGuid(), Title = "Test subject", Description = "Test description", ImageUrl = "Https://test.jpg", ResourceType = 1, }; this.resourceEntityModel = new Resource() { Id = Guid.NewGuid(), GradeId = Guid.NewGuid(), Title = "Test subject", Description = "Test description", ImageUrl = "Https://test.jpg", ResourceType = 1, UpdatedBy = Guid.NewGuid(), }; }
private void Validate(ResourceViewModel resourceViewModel, ResourceActFilesModel files) { if (resourceViewModel.Resource.ResourceRights == null || resourceViewModel.Resource.ResourceRights.Count < 1) { ModelState.AddModelError(string.Empty, @"Необходимо задать по меньшей мере одно право для ресурса"); } ValidateFiles(files.ResourceAuthorityActs, "Files.ResourceAuthorityActs[{0}]"); ValidateFiles(files.ResourceUsingActs, "Files.ResourceUsingActs[{0}]"); ValidateFiles(files.ResourceOperatorActs, "Files.ResourceOperatorActs[{0}]"); if (files.ResourceOperatorPersons != null) { for (var i = 0; i < files.ResourceOperatorPersons.Count; i++) { ValidateFiles(files.ResourceOperatorPersons[i].Acts, "Files.ResourceOperatorPersons[" + i + "].Acts[{0}]"); } } if (files.ResourceOwnerPersons != null) { for (var i = 0; i < files.ResourceOwnerPersons.Count; i++) { ValidateFiles(files.ResourceOwnerPersons[i].Acts, "Files.ResourceOwnerPersons[" + i + "].Acts[{0}]"); } } }
private void AddSecurityProxy(Project project, ResourceViewModel resource) { try { // 1. Update the content var folder = project.GetRootFolder(); string content = GetSecurityProxyContent(); content = content.Replace("{hash}", resource.Hash); content = content.Replace("{resource_url}", resource.Name); content = content.Replace("{namespace}", project.Name); // 2. Add the security proxy to the project var fileName = string.Format("SecurityProxy_{0}.cs", resource.Hash); var path = Path.Combine(folder, fileName); if (File.Exists(path)) { MessageBox.Show($"The file {fileName} already exists"); return; } using (var writer = new StreamWriter(path)) { writer.Write(content); } project.AddFileToProject(path, _options.Dte2); } catch { MessageBox.Show("Error occured while trying to add the file"); } }
public async Task AddResource(ResourceViewModel resourceModel, Guid userId) { try { string resourceFileString = ""; if (resourceModel.file != null) { using (BinaryReader binaryReader = new BinaryReader(resourceModel.file.OpenReadStream())) { byte[] byteFile = binaryReader.ReadBytes((int)resourceModel.file.Length); resourceFileString = BitConverter.ToString(byteFile); } } Resource resource = new Resource { Name = resourceModel.name, Description = resourceModel.description, Url = resourceModel.url, FileName = resourceModel.fileName, File = resourceFileString, CategoryId = resourceModel.categoryId, CreatedById = userId }; await _unitOfWork.Repository <Resource>().Add(resource); await _unitOfWork.SaveChangesAsync(); } catch (Exception ex) { throw new Exception($"Error when adding the {nameof(resourceModel)}: ", ex); } }
public async Task <ActionResult> SaveModify(ResourceViewModel model) { using (ResourceServiceClient client = new ResourceServiceClient()) { MethodReturnResult <Resource> result = await client.GetAsync(new ResourceKey() { Type = model.Type, Code = model.Code }); if (result.Code == 0) { result.Data.Data = model.Data; result.Data.Name = model.Name; result.Data.Description = model.Description; result.Data.Editor = User.Identity.Name; result.Data.EditTime = DateTime.Now; MethodReturnResult rst = await client.ModifyAsync(result.Data); if (rst.Code == 0) { rst.Message = string.Format(StringResource.Resource_SaveModify_Success , model.Type.GetDisplayName() , model.Code); } return(Json(rst)); } return(Json(result)); } }
/// <summary> /// Prepare all data for the graphic path selection listbox /// </summary> void PrepSelectionList() { if (graphicVisual != null) { var previewIcons = new List <PreviewShapeViewModel>(); int index = 0; CreateShapeSelectionList(graphicVisual, previewIcons, ref index); PreviewShapes = previewIcons; if (previewIcons.Count > 0) { TriggerResetView.Fire(); ResourceViewModel.Reset(); XamlViewModel.Reset(); CSharpViewModel.Reset(); } SelectAllPreviewIcons(true); } else { PreviewShapes = null; PreviewViewModel.SetNewGraphicVisual(null); ResourceViewModel.SetNewGraphicVisual(null); XamlViewModel.SetNewGraphicVisual(null); CSharpViewModel.SetNewGraphicVisual(null); ExportViewModel.SetNewGraphicVisual(null); } }
private ResourceViewModel GetPost(string filePath, string resourceName = null) { var model = new ResourceViewModel(); if (_fileSystem.FileExists(filePath)) { var contents = string.Empty; using (var fileStream = System.IO.File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read)) using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) { contents = streamReader.ReadToEnd(); } model.UrlPath = GetPostMetadataValue("Url", contents); if (string.IsNullOrEmpty(model.UrlPath)) { model.UrlPath = GetUrl(filePath, resourceName); } model.Published = DateTime.ParseExact(GetPostMetadataValue("Published", contents), "yyyyMMdd", CultureInfo.InvariantCulture); model.Title = GetPostMetadataValue("Title", contents); model.Type = GetPostMetadataValue("Type", contents); model.Name = GetPostMetadataValue("Name", contents); model.Company = GetPostMetadataValue("Company", contents); model.Position = GetPostMetadataValue("Position", contents); model.Video = GetPostMetadataValue("Video", contents); model.Tags = GetPostMetadataValue("Tags", contents); model.Image = Markdown.ToHtml(GetPostMetadataValue("Image", contents), MarkdownPipeline); model.Quote = GetPostMetadataValue("Quote", contents); model.Summary = GetPostMetadataValue("Summary", contents); model.Post = Markdown.ToHtml(contents.Remove(0, contents.IndexOf("---") + 3), MarkdownPipeline); model.InternalVideo = GetPostMetadataValue("InternalVideo", contents); } return(model); }
public IActionResult AddResource() { var model = new ResourceViewModel(); model.Action = Action.Add; return(View("AddOrEditResource", model)); }
/// <summary> /// Gets the resources using the Discovery protocol. /// </summary> /// <param name="uri">The URI.</param> /// <param name="parent">The parent.</param> /// <returns>The message identifier.</returns> public Task <long> GetResources(string uri, ResourceViewModel parent = null) { var result = Client.Handler <IDiscoveryCustomer>() .GetResources(uri); return(Task.FromResult(result)); }
public override async Task Load(ResourceViewModel resource) { await base.Load(resource); SelectedReference = Resource.References.OrderBy(r => r.DisplayName).FirstOrDefault(); SelectedTarget = SelectedReference?.Targets.FirstOrDefault(); }
public DesktopViewModel() { this.ResourceViewModeCollection = new ObservableCollection<ResourceViewModel>(); this.OperationsViewModel = new OperationsViewModel(); this.resourceInfoList = new List<ResourceSettingInfo>(Settings.ResourceInfos); Service.Hosting.FetchAll(false); IEnumerable<VirtualMachine> virtualMachineList = Service.Hosting.VirtualMachines; for (int i = 0; i < virtualMachineList.Count(); i++) { VirtualMachine virtualMachine = virtualMachineList.ElementAt(i); ResourceViewModel resourceViewModel = new ResourceViewModel(new VirtualMachineResource(virtualMachine)) { Left = (i * 58) + 8, Top = 10 }; resourceViewModel.DetailAction += OnDetailAction; this.ApplySettings(resourceViewModel); this.ResourceViewModeCollection.Add(resourceViewModel); } IEnumerable<Disk> detachedDisks = Service.Hosting.Disks.Where(d => d.VirtualMachineIds.Length == 0); for (int i = 0; i < detachedDisks.Count(); i++) { Disk disk = detachedDisks.ElementAt(i); ResourceViewModel resourceViewModel = new ResourceViewModel(new DiskResource(disk)) { Left = (i * 58) + 8, Top = 80 }; resourceViewModel.DetailAction += OnDetailAction; this.ApplySettings(resourceViewModel); this.ResourceViewModeCollection.Add(resourceViewModel); } IEnumerable<Interface> detachedInterfaces = Service.Hosting.Interfaces.Where(i => i.VirtualMachineId == null); for (int i = 0; i < detachedInterfaces.Count(); i++) { Interface iface = detachedInterfaces.ElementAt(i); ResourceViewModel resourceViewModel = new ResourceViewModel(new InterfaceResource(iface)) { Left = (i * 58) + 8, Top = 150 }; resourceViewModel.DetailAction += OnDetailAction; this.ApplySettings(resourceViewModel); this.ResourceViewModeCollection.Add(resourceViewModel); } }
public ActionResult Edit(int id, ResourceViewModel resource) { if (resource.Save(ModelState, true)) { return RedirectToAction("Index", new { id = resource.ModelObject.Id }); } else { ViewData.Model = resource; return View(); } }
public ActionResult Edit(ResourceViewModel viewModel) { if (ModelState.IsValid) { this.WorkerService.UpdateEntity(viewModel); return RedirectToAction("Index"); } else { viewModel = this.WorkerService.GetViewModelForEdit(viewModel); return View(viewModel); } }
private void AssertUnchangedFields(Resource resource, ResourceViewModel resourceViewModel) { Assert.Equal(resource.Author, resourceViewModel.Author); Assert.Equal(resource.SubmitUser, resourceViewModel.SubmitUser); }
private void AddResource(IResource resource, double left, double top) { ResourceViewModel resourceViewModel = new ResourceViewModel(resource) { Left = left, Top = top, ZIndex = (this.GetMaxResourceZIndex() + 1) }; resourceViewModel.DetailAction += OnDetailAction; this.ResourceViewModeCollection.Add(resourceViewModel); }
private void ApplySettings(ResourceViewModel resourceViewModel) { ResourceSettingInfo resourceInfo = this.resourceInfoList.SingleOrDefault(r => r.Name == resourceViewModel.Name); if (resourceInfo != null) { resourceViewModel.Left = resourceInfo.Location.X; resourceViewModel.Top = resourceInfo.Location.Y; resourceViewModel.ZIndex = resourceInfo.ZIndex; } }
public ActionResult Show(Guid id, string token, string timeStamp) { AuthenticateToken(id, token, timeStamp); SetAddonCookie(); var headerClient = new RestClient("http://appharbor.com/"); var headerRequest = new RestRequest("header", Method.GET); var headerResponse = headerClient.Execute(headerRequest); // TODO: Fetch the resource from persistance store var resource = new Resource(); // TODO: Populate the view model with the resource data var viewModel = new ResourceViewModel { Header = headerResponse.Content, }; return View(viewModel); }
private void OnOperationCompleted(OperationViewModel operationViewModel, ResourceViewModel resourceViewModel) { if ((operationViewModel.Type & OperationType.Detach) == OperationType.Detach || (operationViewModel.Type & OperationType.Start) == OperationType.Start || (operationViewModel.Type & OperationType.Stop) == OperationType.Stop || (operationViewModel.Type & OperationType.Reboot) == OperationType.Reboot || (operationViewModel.Type & OperationType.Update) == OperationType.Update) { this.UpdateResource(resourceViewModel, operationViewModel); } if ((operationViewModel.Type & OperationType.Detach) == OperationType.Detach || (operationViewModel.Type & OperationType.Create) == OperationType.Create) { dynamic operation = operationViewModel.Operation; if ((operationViewModel.Type & OperationType.Create) == OperationType.Create) { if (operation is DiskOperation) { Disk disk = Service.Hosting.Fetch<Disk>(operation.DiskId); this.AddResource(new DiskResource(disk), 20, 20); } else if (operation is InterfaceOperation) { Interface iface = Service.Hosting.Fetch<Interface>(operation.InterfaceId); this.AddResource(new InterfaceResource(iface), 20, 20); } else if (operation is IpAddressOperation) { } else if (operation is VirtualMachineOperation) { VirtualMachine virtualMachine = Service.Hosting.Fetch<VirtualMachine>(operation.VirtualMachineId.Value); this.AddResource(new VirtualMachineResource(virtualMachine), 20, 20); } } else if ((operationViewModel.Type & OperationType.Detach) == OperationType.Detach) { if ((operationViewModel.Type & OperationType.Disk) == OperationType.Disk) { this.AddResource(new DiskResource(operation.Disk), 20, 20); } else if ((operationViewModel.Type & OperationType.Interface) == OperationType.Interface) { this.AddResource(new DiskResource(operation.Interface), 20, 20); } } } else if ((operationViewModel.Type & OperationType.Attach) == OperationType.Attach || (operationViewModel.Type & OperationType.Delete) == OperationType.Delete) { this.RemoveResource(resourceViewModel); } }
private void RemoveResource(ResourceViewModel resourceViewModel) { Service.Hosting.Remove(resourceViewModel.HostingResource); this.ResourceViewModeCollection.Remove(resourceViewModel); }
private void UpdateResource(ResourceViewModel resourceViewModel, OperationViewModel operationViewModel) { if (resourceViewModel.Type == ResourceType.Disk) { Disk disk = Service.Hosting.Fetch<Disk>(resourceViewModel.Id); resourceViewModel.Update(new DiskResource(disk)); } else if (resourceViewModel.Type == ResourceType.Interface) { Interface iface = Service.Hosting.Fetch<Interface>(resourceViewModel.Id); resourceViewModel.Update(new InterfaceResource(iface)); } else if (resourceViewModel.Type == ResourceType.VirtualMachine) { VirtualMachine virtualMachine = Service.Hosting.Fetch<VirtualMachine>(resourceViewModel.Id); resourceViewModel.Update(new VirtualMachineResource(virtualMachine)); } }
public ActionResult Show(string id, string token, string timeStamp) { string requestBody = Request.GetBody(); Emailer.SendEmail("Addon Action", "Show - " + requestBody); AuthenticateToken(Guid.Parse(id), token, timeStamp); SetAddonCookie(); var headerClient = new RestClient("http://appharbor.com/"); var headerRequest = new RestRequest("header", Method.GET); var headerResponse = headerClient.Execute(headerRequest); // TODO: Fetch the resource from persistance store var resource = new Resource(); // TODO: Populate the view model with the resource data var viewModel = new ResourceViewModel { Header = headerResponse.Content, }; return View(viewModel); }
private void MoveResourceInBounds(ResourceViewModel resourceViewModel) { Storyboard storyboard = new Storyboard(); var view = (FrameworkElement)(desktopView.ItemContainerGenerator.ContainerFromItem(resourceViewModel)); const double offset = 4; double left = resourceViewModel.Left; double right = left + view.ActualWidth; double top = resourceViewModel.Top; double bottom = top + view.ActualHeight; bool leftOutBound = left < 0; bool rightOutBound = right > desktopView.ActualWidth; bool topOutBound = top < 0; bool bottomOutBound = bottom > desktopView.ActualHeight; if (leftOutBound || rightOutBound) { double from = left; double to = (leftOutBound ? offset : (desktopView.ActualWidth - view.ActualWidth - offset)); DoubleAnimationUsingKeyFrames animation = new DoubleAnimationUsingKeyFrames() { Duration = TimeSpan.FromMilliseconds(125) }; animation.KeyFrames.Add(new SplineDoubleKeyFrame(from, KeyTime.FromTimeSpan(TimeSpan.Zero))); animation.KeyFrames.Add(new SplineDoubleKeyFrame(to + ((leftOutBound ? offset : offset * -1) * 2), KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(80)))); animation.KeyFrames.Add(new SplineDoubleKeyFrame(to, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(125)))); AnimationClock clock = animation.CreateClock(); clock.CurrentTimeInvalidated += (sender, e) => { double current = animation.GetCurrentValue(from, to, clock); resourceViewModel.Left = current; }; storyboard.Children.Add(animation); Storyboard.SetTargetProperty(animation, new PropertyPath(ResourceView.DummyLeftProperty)); } if (topOutBound || bottomOutBound) { double from = top; double to = (topOutBound ? offset : (desktopView.ActualHeight - view.ActualHeight - offset)); DoubleAnimationUsingKeyFrames animation = new DoubleAnimationUsingKeyFrames() { Duration = TimeSpan.FromMilliseconds(125) }; animation.KeyFrames.Add(new SplineDoubleKeyFrame(from, KeyTime.FromTimeSpan(TimeSpan.Zero))); animation.KeyFrames.Add(new SplineDoubleKeyFrame(to + ((topOutBound ? offset : offset * -1) * 2), KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(80)))); animation.KeyFrames.Add(new SplineDoubleKeyFrame(to, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(125)))); AnimationClock clock = animation.CreateClock(); clock.CurrentTimeInvalidated += (sender, e) => { double current = animation.GetCurrentValue(from, to, clock); resourceViewModel.Top = current; }; storyboard.Children.Add(animation); Storyboard.SetTargetProperty(animation, new PropertyPath(ResourceView.DummyTopProperty)); } this.BeginStoryboard(storyboard); }