public async Task <IActionResult> Put(string id, [FromBody] StorageDrive request) { try { Guid?entityId = Guid.Parse(id); if (request.Id == null || request.Id == Guid.Empty || request.Id != entityId) { request.Id = entityId; } if (request.OrganizationId == null || request.OrganizationId == Guid.Empty) { request.OrganizationId = _organizationManager.GetDefaultOrganization().Id; } if (string.IsNullOrEmpty(request.StoragePath)) { request.StoragePath = request.Name; } _manager.UpdateDrive(id, request, request.OrganizationId.ToString()); await _webhookPublisher.PublishAsync("Files.DriveUpdated", id, request.Name).ConfigureAwait(false); return(await base.PutEntity(id, request)); } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> Post([FromBody] QueueModel request) { if (request == null) { ModelState.AddModelError("Save", "No data passed"); return(BadRequest(ModelState)); } var queue = repository.Find(null, d => d.Name.ToLower(null) == request.Name.ToLower(null))?.Items?.FirstOrDefault(); if (queue != null) { ModelState.AddModelError("Queue", "Queue Name Already Exists"); return(BadRequest(ModelState)); } try { var result = await base.PostEntity(request); await webhookPublisher.PublishAsync("Queues.NewQueueCreated", request.Id.ToString(), request.Name).ConfigureAwait(false); return(result); } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> Post([FromBody] QueueModel request) { try { if (request == null) { throw new EntityDoesNotExistException("No data passed"); } var queue = repository.Find(null, d => d.Name.ToLower(null) == request.Name.ToLower(null))?.Items?.FirstOrDefault(); if (queue != null) { throw new EntityAlreadyExistsException("Queue name already exists"); } var result = await base.PostEntity(request); await _webhookPublisher.PublishAsync("Queues.NewQueueCreated", request.Id.ToString(), request.Name).ConfigureAwait(false); return(result); } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> Post([FromBody] CreateJobViewModel request) { if (request == null) { ModelState.AddModelError("Save", "No data passed"); return(BadRequest(ModelState)); } Guid entityId = Guid.NewGuid(); if (request.Id == null || !request.Id.HasValue || request.Id.Equals(Guid.Empty)) { request.Id = entityId; } try { Job job = request.Map(request); //assign request to job entity Automation automation = automationRepo.GetOne(job.AutomationId ?? Guid.Empty); if (automation == null) //no automation was found { ModelState.AddModelError("Save", "No automation was found for the specified automation id"); return(NotFound(ModelState)); } AutomationVersion automationVersion = automationVersionRepo.Find(null, q => q.AutomationId == automation.Id).Items?.FirstOrDefault(); job.AutomationVersion = automationVersion.VersionNumber; job.AutomationVersionId = automationVersion.Id; foreach (var parameter in request.JobParameters ?? Enumerable.Empty <JobParameter>()) { parameter.JobId = entityId; parameter.CreatedBy = applicationUser?.UserName; parameter.CreatedOn = DateTime.UtcNow; parameter.Id = Guid.NewGuid(); jobParameterRepo.Add(parameter); } //send SignalR notification to all connected clients await _hub.Clients.All.SendAsync("botnewjobnotification", request.AgentId.ToString()); await _hub.Clients.All.SendAsync("sendjobnotification", "New Job added."); await _hub.Clients.All.SendAsync("broadcastnewjobs", Tuple.Create(request.Id, request.AgentId, request.AutomationId)); await webhookPublisher.PublishAsync("Jobs.NewJobCreated", job.Id.ToString()).ConfigureAwait(false); return(await base.PostEntity(job)); } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> Post(string queueItemId, [FromBody] string[] requests) { try { var entityId = new Guid(queueItemId); var queueItem = queueItemRepository.Find(0, 1).Items?.Where(q => q.Id.ToString() == queueItemId).FirstOrDefault(); long?payload = 0; if (requests.Length == 0 || requests == null) { ModelState.AddModelError("Attach", "No files uploaded to attach"); return(BadRequest(ModelState)); } foreach (var request in requests) { var binaryObject = binaryObjectRepository.Find(null, q => q.Id == Guid.Parse(request))?.Items?.FirstOrDefault(); if (binaryObject == null) { ModelState.AddModelError("Save", "No file attached"); return(BadRequest(ModelState)); } long?size = binaryObject.SizeInBytes; if (size <= 0) { ModelState.AddModelError("File attachment", $"File size of file {binaryObject.Name} cannot be 0"); return(BadRequest(ModelState)); } //create queue item attachment QueueItemAttachment queueItemAttachment = new QueueItemAttachment() { BinaryObjectId = (Guid)binaryObject.Id, QueueItemId = Guid.Parse(queueItemId), CreatedBy = applicationUser?.UserName, CreatedOn = DateTime.UtcNow, SizeInBytes = (long)binaryObject.SizeInBytes }; repository.Add(queueItemAttachment); payload += queueItemAttachment.SizeInBytes; } //update queue item payload queueItem.PayloadSizeInBytes += (long)payload; queueItemRepository.Update(queueItem); await webhookPublisher.PublishAsync("QueueItems.QueueItemUpdated", queueItem.Id.ToString(), queueItem.Name).ConfigureAwait(false); var queueItemAttachments = repository.Find(null).Items?.Where(q => q.QueueItemId == entityId); return(Ok(queueItemAttachments)); } catch (Exception ex) { ModelState.AddModelError("Attach", ex.Message); return(BadRequest(ModelState)); } }
public async Task <IActionResult> Post([FromBody] AutomationViewModel request) { try { Guid versionId = Guid.NewGuid(); var automation = new Automation() { Name = request.Name, AutomationEngine = request.AutomationEngine, Id = request.Id }; var response = await base.PostEntity(automation); manager.AddAutomationVersion(request); await webhookPublisher.PublishAsync("Automations.NewAutomationCreated", automation.Id.ToString(), automation.Name).ConfigureAwait(false); return(response); } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> Post([FromBody] AgentGroup request) { try { var result = await base.PostEntity(request); await _webhookPublisher.PublishAsync("AgentGroups.NewAgentGroupCreated", request.Id.ToString(), request.Name).ConfigureAwait(false); return(result); } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> Post(string queueItemId, [FromBody] string[] requests, string driveName = null) { try { var queueItem = _queueItemRepository.GetOne(Guid.Parse(queueItemId)); var queueItemAttachments = _manager.AddFileAttachments(queueItem, requests, driveName); await _webhookPublisher.PublishAsync("QueueItems.QueueItemUpdated", queueItemId, queueItem.Name).ConfigureAwait(false); return(Ok(queueItemAttachments)); } catch (Exception ex) { return(ex.GetActionResult()); } }
/// <summary> /// Creates a new Heartbeat entity for the specified Agent id /// </summary> /// <param name="request"></param> /// <param name="agentId"></param> /// <returns>Newly created Heartbeat</returns> public AgentHeartbeat PerformAgentHeartbeat(HeartbeatViewModel request, string agentId) { Agent agent = _agentRepo.GetOne(new Guid(agentId)); if (agent == null) { throw new EntityDoesNotExistException("The Agent ID provided does not match any existing Agents"); } if (agent.IsConnected == false) { throw new EntityOperationException("Agent is not connected. Please connect the agent and try again"); } if (request.IsHealthy == false) { _webhookPublisher.PublishAsync("Agents.UnhealthyReported", agent.Id.ToString(), agent.Name).ConfigureAwait(false); } AgentHeartbeat agentHeartbeat = request.Map(request); //Add HeartBeat Values agentHeartbeat.AgentId = new Guid(agentId); agentHeartbeat.CreatedBy = _caller?.Identity.Name; agentHeartbeat.CreatedOn = DateTime.UtcNow; agentHeartbeat.LastReportedOn = request.LastReportedOn ?? DateTime.UtcNow; _agentHeartbeatRepo.Add(agentHeartbeat); return(agentHeartbeat); }
/// <summary> /// Updates the AgentGroupMembers of the specified AgentGroup id /// </summary> /// <param name="agentGroupId"></param> /// <param name="agentId"></param> /// <returns></returns> public IEnumerable <AgentGroupMember> UpdateGroupMembers(string agentGroupId, IEnumerable <AgentGroupMember> groupMembers) { var agentGroupGuid = Guid.Parse(agentGroupId); AgentGroup agentGroup = _agentGroupRepository.GetOne(agentGroupGuid); if (agentGroup == null) { throw new EntityDoesNotExistException("No agent group was found with the specified id"); } List <AgentGroupMember> memberList = new List <AgentGroupMember>(); DeleteGroupMembers(agentGroupId);//delete existing members foreach (var member in groupMembers ?? Enumerable.Empty <AgentGroupMember>()) { member.AgentGroupId = agentGroupGuid; member.CreatedBy = _caller.Identity.Name; member.CreatedOn = DateTime.UtcNow; _agentGroupMemberRepository.Add(member); memberList.Add(member); } _webhookPublisher.PublishAsync("AgentGroups.AgentGroupMemberUpdated", agentGroupId, agentGroup.Name).ConfigureAwait(false); return(memberList.AsEnumerable()); }
public async Task <IActionResult> Post([FromForm] AutomationViewModel request) { try { var automation = _manager.AddAutomation(request); var response = await base.PostEntity(automation); await _webhookPublisher.PublishAsync("Automations.NewAutomationCreated", automation.Id.ToString(), automation.Name).ConfigureAwait(false); return(response); } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> Post([FromBody] CreateAgentViewModel request) { try { _agentManager.CreateAgentUserAccount(request); //post agent entity Agent newAgent = request.Map(request); await _webhookPublisher.PublishAsync("Agents.NewAgentCreated", newAgent.Id.ToString(), newAgent.Name).ConfigureAwait(false); return(await base.PostEntity(newAgent)); } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> Post([FromBody] GlobalCredentialViewModel request) { try { Credential credential = _credentialManager.CreateGlobalCredential(request); var result = await base.PostEntity(credential); await _webhookPublisher.PublishAsync("Credentials.NewCredentialCreated", credential.Id.ToString(), credential.Name).ConfigureAwait(false); return(result); } catch (Exception ex) { return(ex.GetActionResult()); } }
public void RaiseBusinessEvent(string id, RaiseBusinessEventViewModel request) { Guid entityId = new Guid(id); var existingEvent = _integrationEventRepository.GetOne(entityId); VerifyBusinessEvent(existingEvent); _webhookPublisher.PublishAsync(existingEvent.Name, request.EntityId.ToString(), request.EntityName, request.Message, request.PayloadJSON).ConfigureAwait(false); }
public async Task PublishTestWebhook() { var separator = DateTime.Now.Millisecond; await _webHookPublisher.PublishAsync(AppWebHookNames.TestWebhook, new { UserName = "******" + separator, EmailAddress = "Test Email " + separator } ); }
public async Task <IActionResult> Post([FromBody] Credential request) { if (request == null) { ModelState.AddModelError("Save", "No data passed"); return(BadRequest(ModelState)); } try { applicationUser = userManager.GetUserAsync(httpContextAccessor.HttpContext.User).Result; if (request.PasswordSecret != null && applicationUser != null) { request.PasswordHash = userManager.PasswordHasher.HashPassword(applicationUser, request.PasswordSecret); } var credential = repository.Find(null, d => d.Name.ToLower(null) == request.Name.ToLower(null))?.Items?.FirstOrDefault(); if (credential != null) { ModelState.AddModelError("Credential", "Credential Name Already Exists"); return(BadRequest(ModelState)); } if (!credentialManager.ValidateStartAndEndDates(request)) { ModelState.AddModelError("Credential", "Start and End Date are not valid"); return(BadRequest(ModelState)); } var result = await base.PostEntity(request); await webhookPublisher.PublishAsync("Credentials.NewCredentialCreated", request.Id.ToString(), request.Name).ConfigureAwait(false); return(result); } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> Delete(string id, string driveName = null) { try { var existingQueueItem = repository.GetOne(Guid.Parse(id)); _manager.DeleteQueueItem(existingQueueItem, driveName); var response = await base.DeleteEntity(id); await _webhookPublisher.PublishAsync("QueueItems.QueueItemDeleted", existingQueueItem.Id.ToString(), existingQueueItem.Name).ConfigureAwait(false); _hub.Clients.All.SendAsync("sendnotification", "QueueItem deleted."); return(response); } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> Post([FromBody] BinaryObject request) { try { var response = await base.PostEntity(request); await webhookPublisher.PublishAsync("Files.NewFileCreated", request.Id.ToString(), request.Name).ConfigureAwait(false); return(response); } catch (Exception ex) { return(ex.GetActionResult()); } }
public object LocalFileStorageOperation(FileManagerDirectoryContent args) { if (args.Action == "delete" || args.Action == "rename") { if ((args.TargetPath == null) && (args.Path == "")) { FileManagerResponse response = new FileManagerResponse(); response.Error = new ErrorDetails { Code = "401", Message = "Restricted to modify the root folder." }; return(this.operation.ToCamelCase(response)); } } var serverDrive = GetDrive(); var entityId = Guid.Parse(args.Id); ServerFile serverFile = new ServerFile(); ServerFolder serverFolder = new ServerFolder(); if (args.IsFile) { serverFile = serverFileRepository.GetOne(entityId); } else { serverFolder = serverFolderRepository.GetOne(entityId); } switch (args.Action) { case "read": //reads the file(s) or folder(s) from the given path //update FileAttribute (retrieval) var fileAttribute = fileAttributeRepository.Find(null).Items?.Where(q => q.Name == FileAttributes.RetrievalCount.ToString() && q.ServerFileId == entityId).FirstOrDefault(); fileAttribute.AttributeValue += 1; fileAttributeRepository.Update(fileAttribute); return(this.operation.ToCamelCase(this.operation.GetFiles(args.Path, args.ShowHiddenItems))); case "delete": //deletes the selected file(s) or folder(s) from the given path if (args.IsFile.Equals(true)) { DeleteFile(args.Path); serverDrive.StorageSizeInBytes -= args.Size; } else { //removes the size of folder and any files from server drive property var files = serverFileRepository.Find(null).Items?.Where(q => q.StorageFolderId == entityId); long fileSize = 0; foreach (var file in files) { fileSize += file.SizeInBytes; } serverDrive.StorageSizeInBytes -= args.Size - fileSize; DeleteFolder(args.Path); } serverDriveRepository.Update(serverDrive); webhookPublisher.PublishAsync("Files.DriveUpdated", serverDrive.Id.ToString(), serverDrive.Name); return(this.operation.ToCamelCase(this.operation.Delete(args.Path, args.Names))); case "copy": //copies the selected file(s) or folder(s) from a path and then pastes them into a given target path if (args.IsFile.Equals(true)) { foreach (var file in args.UploadFiles) { var folderId = GetFolderId(args.Path); //add serverFile entity SaveServerFileViewModel viewModel = new SaveServerFileViewModel() { Id = Guid.Parse(args.Id), ContentType = file.ContentType, CorrelationEntity = "", //TODO: update or remove CorrelationEntityId = Guid.Empty, //TODO: update or remove HashCode = null, SizeInBytes = file.Length, StorageFolderId = folderId, StoragePath = args.Path, StorageProvider = "LocalFileStorage", File = file }; SaveFile(viewModel); } } else { //add serverFolder entity AddFolder(args); } AddBytesToServerDrive(serverDrive, args.Size); return(this.operation.ToCamelCase(this.operation.Copy(args.Path, args.TargetPath, args.Names, args.RenameFiles, args.TargetData))); case "move": //cuts the selected file(s) or folder(s) from a path and then pastes them into a given target path if (args.IsFile.Equals(true)) { foreach (var file in args.UploadFiles) { var folderId = GetFolderId(args.Path); UpdateServerFileViewModel viewModel = new UpdateServerFileViewModel() { ContentType = file.ContentType, CorrelationEntity = "", //TODO: remove or update CorrelationEntityId = Guid.Empty, //TODO: remove or update HashCode = null, File = file, SizeInBytes = file.Length, StorageFolderId = folderId, StoragePath = Path.Combine(args.Path, file.FileName), StorageProvider = "LocalFileStorage" }; UpdateFile(viewModel); } } else { //update ServerFolder entity serverFolder.ParentFolderId = Guid.Parse(args.ParentId); serverFolder.StoragePath = args.Path; serverFolderRepository.Update(serverFolder); webhookPublisher.PublishAsync("Files.FolderUpdated", serverFolder.Id.ToString(), serverFolder.Name); } return(this.operation.ToCamelCase(this.operation.Move(args.Path, args.TargetPath, args.Names, args.RenameFiles, args.TargetData))); case "details": //gets the details of the selected file(s) or folder(s) return(this.operation.ToCamelCase(this.operation.Details(args.Path, args.Names, args.Data))); case "create": //creates a new folder in a given path //add ServerFolder entity AddFolder(args); AddBytesToServerDrive(serverDrive, args.Size); return(this.operation.ToCamelCase(this.operation.Create(args.Path, args.Name))); case "search": //gets the list of file(s) or folder(s) from a given path based on the searched key string //add to retrieval count value to file attribute entity for each file //update FileAttribute (retrieval) foreach (var file in args.UploadFiles) { fileAttribute = fileAttributeRepository.Find(null).Items?.Where(q => q.Name == FileAttributes.RetrievalCount.ToString() && q.ServerFileId == entityId).FirstOrDefault(); fileAttribute.AttributeValue += 1; fileAttributeRepository.Update(fileAttribute); } return(this.operation.ToCamelCase(this.operation.Search(args.Path, args.SearchString, args.ShowHiddenItems, args.CaseSensitive))); case "rename": //renames a file or folder if (args.IsFile.Equals(true)) { //update ServerFile entity foreach (var file in args.UploadFiles) { var folderId = GetFolderId(args.Path); UpdateServerFileViewModel viewModel = new UpdateServerFileViewModel() { ContentType = file.ContentType, CorrelationEntity = "", //TODO: remove or update CorrelationEntityId = Guid.Empty, //TODO: remove or update HashCode = null, File = file, SizeInBytes = file.Length, StorageFolderId = folderId, StoragePath = Path.Combine(args.Path, file.FileName), StorageProvider = "LocalFileStorage" }; UpdateFile(viewModel); } } else { //update ServerFolder entity serverFolder.ParentFolderId = Guid.Parse(args.ParentId); serverFolder.StoragePath = args.Path; serverFolderRepository.Update(serverFolder); webhookPublisher.PublishAsync("Files.FolderUpdated", serverFolder.Id.ToString(), serverFolder.Name); } return(this.operation.ToCamelCase(this.operation.Rename(args.Path, args.Name, args.NewName))); } return(null); }
public async Task Should_Not_Send_Webhook_If_There_Is_No_Subscription_Async() { CreateTenantAndSubscribeToWebhook( AppWebhookDefinitionNames.Users.Created, AppFeatures.WebhookFeature, "true" ); AbpSession.TenantId = GetDefaultTenant().Id; await _webhookPublisher.PublishAsync(AppWebhookDefinitionNames.Test, new { Name = "Musa", Surname = "Demir" }); await _backgroundJobManagerSubstitute.DidNotReceive() .EnqueueAsync <WebhookSenderJob, WebhookSenderArgs>(Arg.Any <WebhookSenderArgs>()); }
public async Task <IActionResult> Delete(string id) { Guid queueItemId = new Guid(id); QueueItem existingQueueItem = repository.GetOne(queueItemId); if (existingQueueItem == null) { ModelState.AddModelError("QueueItem", "QueueItem cannot be found or does not exist."); return(NotFound(ModelState)); } if (existingQueueItem.IsLocked) { ModelState.AddModelError("Delete", "Queue Item is locked at this time and cannot be deleted"); return(BadRequest(ModelState)); } await webhookPublisher.PublishAsync("QueueItems.QueueItemDeleted", existingQueueItem.Id.ToString(), existingQueueItem.Name).ConfigureAwait(false); var response = await base.DeleteEntity(id); _hub.Clients.All.SendAsync("sendnotification", "QueueItem deleted."); //soft delete each queue item attachment entity and binary object entity that correlates to the queue item var attachmentsList = queueItemAttachmentRepository.Find(null, q => q.QueueItemId == existingQueueItem.Id)?.Items; foreach (var attachment in attachmentsList) { queueItemAttachmentRepository.SoftDelete((Guid)attachment.Id); var existingBinary = binaryObjectRepository.GetOne(attachment.BinaryObjectId); if (existingBinary != null) { await webhookPublisher.PublishAsync("Files.FileDeleted", existingBinary.Id.ToString(), existingBinary.Name).ConfigureAwait(false); } binaryObjectRepository.SoftDelete(attachment.BinaryObjectId); } return(response); }
public string CreateJob(string scheduleSerializeObject, IEnumerable <ParametersViewModel>?parameters) { var schedule = JsonSerializer.Deserialize <Schedule>(scheduleSerializeObject); if (organizationSettingManager.HasDisallowedExecution()) { return("DisallowedExecution"); } var automationVersion = automationVersionRepository.Find(null, a => a.AutomationId == schedule.AutomationId).Items?.FirstOrDefault(); //if this is a scheduled job get the schedule parameters if (schedule.StartingType.Equals("RunNow") == false) { List <ParametersViewModel> parametersList = new List <ParametersViewModel>(); var scheduleParameters = scheduleParameterRepository.Find(null, p => p.ScheduleId == schedule.Id).Items; foreach (var scheduleParameter in scheduleParameters) { ParametersViewModel parametersViewModel = new ParametersViewModel { Name = scheduleParameter.Name, DataType = scheduleParameter.DataType, Value = scheduleParameter.Value, CreatedBy = scheduleParameter.CreatedBy, CreatedOn = DateTime.UtcNow }; parametersList.Add(parametersViewModel); } parameters = parametersList.AsEnumerable(); } Job job = new Job(); job.AgentId = schedule.AgentId == null ? Guid.Empty : schedule.AgentId.Value; job.CreatedBy = schedule.CreatedBy; job.CreatedOn = DateTime.UtcNow; job.EnqueueTime = DateTime.UtcNow; job.JobStatus = JobStatusType.New; job.AutomationId = schedule.AutomationId == null ? Guid.Empty : schedule.AutomationId.Value; job.AutomationVersion = automationVersion != null ? automationVersion.VersionNumber : 0; job.AutomationVersionId = automationVersion != null ? automationVersion.Id : Guid.Empty; job.Message = "Job is created through internal system logic."; foreach (var parameter in parameters ?? Enumerable.Empty <ParametersViewModel>()) { JobParameter jobParameter = new JobParameter { Name = parameter.Name, DataType = parameter.DataType, Value = parameter.Value, JobId = job.Id ?? Guid.Empty, CreatedBy = schedule.CreatedBy, CreatedOn = DateTime.UtcNow, Id = Guid.NewGuid() }; jobParameterRepository.Add(jobParameter); } jobRepository.Add(job); _hub.Clients.All.SendAsync("botnewjobnotification", job.AgentId.ToString()); webhookPublisher.PublishAsync("Jobs.NewJobCreated", job.Id.ToString()).ConfigureAwait(false); return("Success"); }
public async Task <IActionResult> Post([FromBody] Asset request) { try { var asset = repository.Find(null, d => d.Name.ToLower(null) == request.Name.ToLower(null))?.Items?.FirstOrDefault(); if (asset != null) { ModelState.AddModelError("Asset", "Asset Name Already Exists"); return(BadRequest(ModelState)); } request = manager.GetSizeInBytes(request); var response = await base.PostEntity(request); await webhookPublisher.PublishAsync("Assets.NewAssetCreated", request.Id.ToString(), request.Name).ConfigureAwait(false); return(response); } catch (Exception ex) { return(ex.GetActionResult()); } }
public StorageDrive AddStorageDrive(StorageDrive drive) { Guid?organizationId = _organizationManager.GetDefaultOrganization().Id; var existingDrive = _storageDriveRepository.Find(null).Items?.Where(q => q.OrganizationId == organizationId && q.Name.ToLower() == drive.Name.ToLower()).FirstOrDefault(); if (existingDrive != null) { throw new EntityAlreadyExistsException($"Drive {drive.Name} already exists within this organization"); } CheckDefaultDrive(drive, organizationId); var adapterType = drive.FileStorageAdapterType; if (string.IsNullOrEmpty(adapterType)) { adapterType = AdapterType.LocalFileStorage.ToString(); } //check if a new drive can be created for the current organization long?maxSizeInBytes = drive.MaxStorageAllowedInBytes; //size of new drive long?organizationStorage = GetTotalOrganizationStorage(organizationId); //sum of all drives for the current organization long?orgMaxSizeInBytes = _organizationManager.GetMaxStorageInBytes(organizationId); //max allowed storage for the current organization long?updatedOrgStorage = maxSizeInBytes + organizationStorage; //sum of new drive and all existing drives if (orgMaxSizeInBytes != null && maxSizeInBytes > orgMaxSizeInBytes) { throw new EntityOperationException("Drive size would exceed the allowed storage space for this organization"); } if (string.IsNullOrEmpty(drive.StoragePath)) { drive.StoragePath = drive.Name; } if (drive.MaxStorageAllowedInBytes == null) { drive.MaxStorageAllowedInBytes = orgMaxSizeInBytes; } if (string.IsNullOrEmpty(drive.FileStorageAdapterType)) { drive.FileStorageAdapterType = AdapterType.LocalFileStorage.ToString(); } if (drive.IsDefault == null) { drive.IsDefault = false; } var storageDrive = new StorageDrive() { Name = drive.Name, FileStorageAdapterType = drive.FileStorageAdapterType, OrganizationId = organizationId, StoragePath = drive.StoragePath, CreatedBy = _httpContextAccessor.HttpContext.User.Identity.Name, CreatedOn = DateTime.UtcNow, StorageSizeInBytes = drive.StorageSizeInBytes ?? 0, MaxStorageAllowedInBytes = drive.MaxStorageAllowedInBytes, IsDefault = drive.IsDefault }; _storageDriveRepository.Add(storageDrive); _webhookPublisher.PublishAsync("Files.NewDriveCreated", storageDrive.Id.ToString(), storageDrive.Name); return(storageDrive); }
public async Task <IActionResult> Post([FromBody] CreateAgentViewModel request) { try { //name must be unique Agent namedAgent = repository.Find(null, d => d.Name.ToLower(null) == request.Name.ToLower(null))?.Items?.FirstOrDefault(); if (namedAgent != null) { ModelState.AddModelError("Agent", "Agent Name Already Exists"); return(BadRequest(ModelState)); } Guid entityId = Guid.NewGuid(); if (request.Id == null || !request.Id.HasValue || request.Id.Equals(Guid.Empty)) { request.Id = entityId; } //create agent app user var user = new ApplicationUser() { Name = request.Name, UserName = request.UserName }; var loginResult = await userManager.CreateAsync(user, request.Password).ConfigureAwait(false); var errors = loginResult.Errors; if (errors.Any()) { foreach (var error in errors) { if (error.Code == "DuplicateUserName") { ModelState.AddModelError("Agent", "Username Already Exists"); return(BadRequest(ModelState)); } } ModelState.AddModelError("Agent", "Failed to Create Agent User"); return(BadRequest(ModelState)); } else { Person newPerson = new Person() { Name = request.Name, IsAgent = true }; var person = personRepo.Add(newPerson); if (person == null) { ModelState.AddModelError("Agent", "Failed to Create Agent User"); return(BadRequest(ModelState)); } //update the user var registeredUser = userManager.FindByNameAsync(user.UserName).Result; registeredUser.PersonId = (Guid)person.Id; await userManager.UpdateAsync(registeredUser).ConfigureAwait(false); //post agent entity Agent newAgent = request.Map(request); await webhookPublisher.PublishAsync("Agents.NewAgentCreated", newAgent.Id.ToString(), newAgent.Name).ConfigureAwait(false); return(await base.PostEntity(newAgent)); } } catch (Exception ex) { return(ex.GetActionResult()); } }
public string CreateJob(string scheduleSerializeObject, IEnumerable<ParametersViewModel>? parameters) { var schedule = JsonSerializer.Deserialize<Schedule>(scheduleSerializeObject); //if schedule has expired if (DateTime.UtcNow > schedule.ExpiryDate) { _recurringJobManager.RemoveIfExists(schedule.Id.Value.ToString());//removes an existing recurring job return "ScheduleExpired"; } if (_organizationSettingManager.HasDisallowedExecution()) { return "DisallowedExecution"; } //if this is not a "RunNow" job, then use the schedule parameters if (schedule.StartingType.Equals("RunNow") == false) { if (schedule.MaxRunningJobs != null) { if (ActiveJobLimitReached(schedule.Id, schedule.MaxRunningJobs)) { return "ActiveJobLimitReached"; } } List<ParametersViewModel> parametersList = new List<ParametersViewModel>(); var scheduleParameters = _scheduleParameterRepository.Find(null, p => p.ScheduleId == schedule.Id).Items; foreach (var scheduleParameter in scheduleParameters) { ParametersViewModel parametersViewModel = new ParametersViewModel { Name = scheduleParameter.Name, DataType = scheduleParameter.DataType, Value = scheduleParameter.Value, CreatedBy = scheduleParameter.CreatedBy, CreatedOn = DateTime.UtcNow }; parametersList.Add(parametersViewModel); } parameters = parametersList.AsEnumerable(); } var automationVersion = _automationVersionRepository.Find(null, a => a.AutomationId == schedule.AutomationId).Items?.FirstOrDefault(); Job job = new Job(); job.AgentId = schedule.AgentId == null ? Guid.Empty : schedule.AgentId.Value; job.AgentGroupId = schedule.AgentGroupId == null ? Guid.Empty : schedule.AgentGroupId.Value; job.CreatedBy = schedule.CreatedBy; job.CreatedOn = DateTime.UtcNow; job.EnqueueTime = DateTime.UtcNow; job.JobStatus = JobStatusType.New; job.AutomationId = schedule.AutomationId == null ? Guid.Empty : schedule.AutomationId.Value; job.AutomationVersion = automationVersion != null ? automationVersion.VersionNumber : 0; job.AutomationVersionId = automationVersion != null ? automationVersion.Id : Guid.Empty; job.Message = "Job is created through internal system logic."; job.ScheduleId = schedule.Id; foreach (var parameter in parameters ?? Enumerable.Empty<ParametersViewModel>()) { JobParameter jobParameter = new JobParameter { Name = parameter.Name, DataType = parameter.DataType, Value = parameter.Value, JobId = job.Id ?? Guid.Empty, CreatedBy = schedule.CreatedBy, CreatedOn = DateTime.UtcNow, Id = Guid.NewGuid() }; _jobParameterRepository.Add(jobParameter); } _jobRepository.Add(job); if (job.AgentGroupId == null || job.AgentGroupId == Guid.Empty) { _hub.Clients.All.SendAsync("botnewjobnotification", job.AgentId.ToString()); } else //notify all group members { var agentsInGroup = _agentGroupManager.GetAllMembersInGroup(job.AgentGroupId.ToString()); foreach (var groupMember in agentsInGroup ?? Enumerable.Empty<AgentGroupMember>()) { _hub.Clients.All.SendAsync("botnewjobnotification", groupMember.AgentId.ToString()); } } _webhookPublisher.PublishAsync("Jobs.NewJobCreated", job.Id.ToString()).ConfigureAwait(false); return "Success"; }
public async Task <IActionResult> Post([FromForm] GlobalAssetViewModel request) { try { Asset asset = new Asset(); asset = request.Map(request); asset = _manager.CreateAsset(asset, request.File, request.DriveName); var response = await base.PostEntity(asset); await _webhookPublisher.PublishAsync("Assets.NewAssetCreated", asset.Id.ToString(), asset.Name).ConfigureAwait(false); return(response); } catch (Exception ex) { return(ex.GetActionResult()); } }