public static BadRequestException ColumnCapacityExceededException(string columnName, int maxCapacity) { var errorMessage = I18NHelper.FormatInvariant( ErrorMessages.ArtifactList.ColumnCapacityExceeded, columnName, maxCapacity); return(new BadRequestException(errorMessage, ErrorCodes.BadRequest)); }
public static BadRequestException InvalidColumnsException(IReadOnlyList <ProfileColumn> invalidColumns) { if (invalidColumns.IsEmpty()) { throw new ArgumentException(nameof(invalidColumns)); } string message; if (invalidColumns.Count == 1) { message = I18NHelper.FormatInvariant( ErrorMessages.ArtifactList.ColumnsSettings.SingleInvalidColumn, invalidColumns.First().PropertyName); } else { const int maxPropertiesToShow = 3; message = I18NHelper.FormatInvariant( invalidColumns.Count > maxPropertiesToShow ? ErrorMessages.ArtifactList.ColumnsSettings.MultipleInvalidColumns : ErrorMessages.ArtifactList.ColumnsSettings.SomeInvalidColumns, string.Join(", ", invalidColumns.Take(maxPropertiesToShow).Select(column => column.PropertyName))); } return(new BadRequestException(message, ErrorCodes.InvalidColumns)); }
/// <summary> /// Throws an exception if the argumentValue is less than lowerValue. /// </summary> /// <typeparam name="T">A type that implements <see cref="IComparable"/>.</typeparam> /// <param name="lowerValue">The lower value accepted as valid.</param> /// <param name="argumentValue">The argument value to test.</param> /// <param name="argumentName">Name of the argument.</param> /// <exception cref="System.ArgumentOutOfRangeException">Validation error.</exception> public static void ArgumentGreaterOrEqualThan <T>(T lowerValue, T argumentValue, string argumentName) where T : struct, IComparable { if (argumentValue.CompareTo((T)lowerValue) < 0) { throw new ArgumentOutOfRangeException(argumentName, argumentValue, I18NHelper.FormatInvariant("The size of '{0}' should be greater or equal to '{1}'.", argumentName, lowerValue)); } }
private static bool Compare <T>(T obj1, T obj2, out string message) { message = null; if (obj1 == null && obj2 == null) { return(true); } if (obj1 == null || obj2 == null) { message = "One of the objects is null."; return(false); } var serializer = new XmlSerializer(obj1.GetType()); var serialized1 = new StringWriter(CultureInfo.InvariantCulture); var serialized2 = new StringWriter(CultureInfo.InvariantCulture); serializer.Serialize(serialized1, obj1); serializer.Serialize(serialized2, obj2); var str1 = serialized1.ToString(); var str2 = serialized2.ToString(); var areEqual = str1 == str2; if (!areEqual) { message = I18NHelper.FormatInvariant("object 1:\r\n{0}\r\nobject 2:\r\n{1}", str1, str2); } return(areEqual); }
private async Task ValidateArtifact(VersionControlArtifactInfo artifactInfo) { // Confirm that the artifact is not deleted var isDeleted = await _stateChangeExecutorRepositories.ArtifactVersionsRepository.IsItemDeleted(_input.ArtifactId); if (isDeleted) { throw new ConflictException(I18NHelper.FormatInvariant("Artifact has been deleted and is no longer available for workflow state change. Please refresh your view.")); } if (artifactInfo.IsDeleted) { throw new ConflictException(I18NHelper.FormatInvariant("Artifact has been deleted and is no longer available for workflow state change. Please refresh your view.")); } if (artifactInfo.VersionCount != _input.CurrentVersionId) { throw new ConflictException(I18NHelper.FormatInvariant("Artifact has been updated. The current version of the artifact {0} does not match the specified version {1}. Please refresh your view.", artifactInfo.VersionCount, _input.CurrentVersionId)); } // Lock is obtained by current user inside the stored procedure itself // Check that it is not locked by some other user if (artifactInfo.LockedByUser != null && artifactInfo.LockedByUser.Id != _userId) { throw new ConflictException(I18NHelper.FormatInvariant("Artifact has been updated. Artifact is locked by another user. Please refresh your view.")); } }
public async Task DeleteProject(int userId, int projectId) { ProjectStatus?projectStatus; InstanceItem project = await _instanceRepository.GetInstanceProjectAsync(projectId, userId, fromAdminPortal : true); if (!TryGetProjectStatusIfProjectExist(project, out projectStatus)) { throw new ResourceNotFoundException( I18NHelper.FormatInvariant(ErrorMessages.ProjectWasDeletedByAnotherUser, project.Id, project.Name), ErrorCodes.ResourceNotFound); } if (projectStatus == ProjectStatus.Live) { Func <IDbTransaction, long, Task> action = async(transaction, transactionId) => { var revisionId = await _instanceRepository.RemoveProject(userId, projectId, transaction); await _instanceRepository.DeactivateWorkflowsWithLastAssignmentForDeletedProject(projectId, transaction); var artifactIds = await _instanceRepository.GetProjectArtifactIds(projectId, revisionId - 1, userId, transaction : transaction); await PostOperation(artifactIds, revisionId, userId, transactionId, transaction); }; await _instanceRepository.RunInTransactionAsync(action); } else { await _instanceRepository.PurgeProject(projectId, project); } }
private async Task <int> SaveSettingsAsync(int itemId, int userId, ProfileSettingsParams profileSettings) { if (profileSettings == null) { throw new ArgumentException(I18NHelper.FormatInvariant( ErrorMessages.ArtifactList.SaveProfileSettingsProfileSettingsNull)); } var existingSettings = await _artifactListSettingsRepository.GetSettingsAsync(itemId, userId); var settings = new XmlProfileSettings { Columns = !profileSettings.ColumnsUndefined ? ArtifactListHelper.ConvertProfileColumnsToXmlProfileSettings(profileSettings.Columns) : existingSettings?.Columns, PaginationLimit = !profileSettings.PaginationLimitUndefined ? profileSettings.PaginationLimit : existingSettings?.PaginationLimit, }; if (existingSettings == null) { return(await _artifactListSettingsRepository.CreateSettingsAsync(itemId, userId, settings)); } else { return(await _artifactListSettingsRepository.UpdateSettingsAsync(itemId, userId, settings)); } }
public async Task <ReviewSettings> UpdateReviewSettingsAsync(int reviewId, ReviewSettings updatedReviewSettings, bool autoSave, int userId) { var reviewInfo = await GetReviewInfoAsync(reviewId, userId); if (!await _permissionsRepository.HasEditPermissions(reviewId, userId)) { throw ReviewsExceptionHelper.UserCannotModifyReviewException(reviewId); } var reviewData = await _reviewsRepository.GetReviewAsync(reviewId, userId); if (reviewData.ReviewStatus == ReviewPackageStatus.Closed) { throw new ConflictException(I18NHelper.FormatInvariant(ErrorMessages.ReviewIsClosed, reviewId), ErrorCodes.ReviewClosed); } await LockReviewAsync(reviewId, userId, reviewInfo); UpdateEndDate(updatedReviewSettings, autoSave, reviewData.ReviewPackageRawData); UpdateShowOnlyDescription(updatedReviewSettings, reviewData.ReviewPackageRawData); UpdateCanMarkAsComplete(reviewId, updatedReviewSettings, reviewData.ReviewPackageRawData); UpdateRequireESignature(reviewData.ReviewType, updatedReviewSettings, reviewData.ReviewPackageRawData); await UpdateRequireMeaningOfSignatureAsync(reviewInfo.ItemId, userId, reviewInfo.ProjectId, reviewData.ReviewType, updatedReviewSettings, reviewData.ReviewPackageRawData); await _reviewsRepository.UpdateReviewPackageRawDataAsync(reviewId, reviewData.ReviewPackageRawData, userId); return(await GetReviewSettingsFromReviewData(reviewData, reviewInfo)); }
public async Task <IEnumerable <Reply> > GetReplies(int artifactId, int discussionId, int?subArtifactId = null) { ValidateRequestParameters(artifactId, subArtifactId); if (discussionId < 1) { throw new BadRequestException(I18NHelper.FormatInvariant("Parameter: {0} is out of the range of valid values", nameof(discussionId))); } var userId = Session.UserId; var itemId = subArtifactId.HasValue ? subArtifactId.Value : artifactId; var revisionId = int.MaxValue; var isDeleted = await _artifactVersionsRepository.IsItemDeleted(itemId); var itemInfo = isDeleted ? await _artifactVersionsRepository.GetDeletedItemInfo(itemId) : await _artifactPermissionsRepository.GetItemInfo(itemId, userId, false); if (itemInfo == null || await _discussionsRepository.IsDiscussionDeleted(discussionId)) { throw new ResourceNotFoundException(); } if (subArtifactId.HasValue && itemInfo.ArtifactId != artifactId) { throw new BadRequestException("Please provide a proper subartifact Id"); } if (isDeleted) { revisionId = ((DeletedItemInfo)itemInfo).VersionId; } var permissions = await _artifactPermissionsRepository.GetArtifactPermissions(new[] { artifactId }, Session.UserId, false, revisionId); if (permissions.IsEmpty()) { permissions = await _artifactPermissionsRepository.GetArtifactPermissionDirectly(itemId, Session.UserId, itemInfo.ProjectId); } var projectPermissions = await _artifactPermissionsRepository.GetProjectPermissions(itemInfo.ProjectId); RolePermissions permission = RolePermissions.None; if (!permissions.TryGetValue(artifactId, out permission) || !permission.HasFlag(RolePermissions.Read)) { throw new AuthorizationException("You do not have permission to access the artifact"); } var result = await _discussionsRepository.GetReplies(discussionId, itemInfo.ProjectId); foreach (var reply in result) { reply.CanDelete = !projectPermissions.HasFlag(ProjectPermissions.CommentsDeletionDisabled) && permissions.TryGetValue(artifactId, out permission) && (permission.HasFlag(RolePermissions.DeleteAnyComment) || (permission.HasFlag(RolePermissions.Comment) && reply.UserId == userId)); reply.CanEdit = !projectPermissions.HasFlag(ProjectPermissions.CommentsModificationDisabled) && permissions.TryGetValue(artifactId, out permission) && (permission.HasFlag(RolePermissions.Comment) && reply.UserId == userId); } return(result); }
private bool UserExistsInLdapDirectory(LdapSettings ldapSettings, LoginInfo loginInfo) { var userName = loginInfo.UserName != null?loginInfo.UserName.Trim() : loginInfo.Login; var filter = I18NHelper.FormatInvariant("(&(objectCategory={0})({1}={2}))", ldapSettings.GetEffectiveUserObjectCategoryAttribute(), ldapSettings.GetEffectiveAccountNameAttribute(), LdapHelper.EscapeLdapSearchFilter(userName)); try { var found = _authenticator.SearchLdap(ldapSettings, filter); if (found) { return(true); } _log.LogInformation(LogSourceLdap, I18NHelper.FormatInvariant("User '{0}' is not found in LDAP directory {1}", userName, ldapSettings.LdapAuthenticationUrl)); return(false); } catch (Exception ex) { _log.LogInformation(LogSourceLdap, I18NHelper.FormatInvariant("Error while searching a user in LDAP directory {0}", ldapSettings.LdapAuthenticationUrl)); _log.LogError(LogSourceLdap, ex); return(false); } }
public async Task Search_NotFoundArtifact_ResourceNotFoundException() { // arrange ArtifactBasicDetails artifactBasicDetails = null; _sqlArtifactRepositoryMock.Setup(q => q.GetArtifactBasicDetails(ScopeId, UserId, null)).ReturnsAsync(artifactBasicDetails); _searchEngineRepositoryMock.Setup(q => q.GetCollectionContentSearchArtifactResults(ScopeId, _pagination, true, UserId, null)).ReturnsAsync(_searchArtifactsResult); var errorMessage = I18NHelper.FormatInvariant(ErrorMessages.ArtifactNotFound, ScopeId); var excectedResult = new ResourceNotFoundException(errorMessage, ErrorCodes.ResourceNotFound); ResourceNotFoundException exception = null; // act try { await _searchEngineService.Search(ScopeId, _pagination, ScopeType.Contents, true, UserId); } catch (ResourceNotFoundException ex) { exception = ex; } // assert Assert.IsNotNull(exception); Assert.AreEqual(excectedResult.Message, exception.Message); }
private static XmlPropertyChangeAction ToXmlModel(IePropertyChangeAction ieAction, WorkflowDataMaps dataMaps) { if (ieAction == null) { return(null); } var xmlAction = new XmlPropertyChangeAction { Name = ieAction.Name, PropertyValue = ieAction.PropertyValue, UsersGroups = ToXmlModel(ieAction.UsersGroups, dataMaps) }; int propertyTypeId; if (!dataMaps.PropertyTypeMap.TryGetValue(ieAction.PropertyName, out propertyTypeId) && !WorkflowHelper.TryGetNameOrDescriptionPropertyTypeId(ieAction.PropertyName, out propertyTypeId)) { throw new ExceptionWithErrorCode(I18NHelper.FormatInvariant("Id of Standard Property Type '{0}' is not found.", ieAction.PropertyName), ErrorCodes.UnexpectedError); } xmlAction.PropertyTypeId = propertyTypeId; ToXmlModel(ieAction.ValidValues, propertyTypeId, ieAction.PropertyName, dataMaps, xmlAction); return(xmlAction); }
private static XmlEmailNotificationAction ToXmlModel(IeEmailNotificationAction ieAction, IDictionary <string, int> propertyTypeMap) { if (ieAction == null) { return(null); } var xmlAction = new XmlEmailNotificationAction { Name = ieAction.Name, Emails = ieAction.Emails, Message = ieAction.Message }; if (ieAction.PropertyName != null) { int propertyTypeId; if (!propertyTypeMap.TryGetValue(ieAction.PropertyName, out propertyTypeId)) { throw new ExceptionWithErrorCode( I18NHelper.FormatInvariant("Id of Standard Property Type '{0}' is not found.", ieAction.PropertyName), ErrorCodes.UnexpectedError); } xmlAction.PropertyTypeId = propertyTypeId; } return(xmlAction); }
public static ResourceNotFoundException ReviewNotFoundException(int reviewId, int revisionId = int.MaxValue) { var errorMessage = revisionId != int.MaxValue ? I18NHelper.FormatInvariant("Review (Id:{0}) or its revision (#{1}) is not found.", reviewId, revisionId) : I18NHelper.FormatInvariant("Review (Id:{0}) is not found.", reviewId); return(new ResourceNotFoundException(errorMessage, ErrorCodes.ResourceNotFound)); }
public async Task <AuthenticationUser> AuthenticateSamlUserAsync(string samlResponse) { if (string.IsNullOrEmpty(samlResponse)) { throw new FormatException("Saml response cannot be empty"); } var instanceSettings = await _settingsRepository.GetInstanceSettingsAsync(); if (!instanceSettings.IsSamlEnabled.GetValueOrDefault()) { throw new AuthenticationException("Federated Authentication mechanism must be enabled"); } var fedAuthSettings = await _settingsRepository.GetFederatedAuthenticationSettingsAsync(); if (fedAuthSettings == null) { throw new AuthenticationException("Federated Authentication settings must be provided"); } var principal = _samlRepository.ProcessEncodedResponse(samlResponse, fedAuthSettings); AuthenticationUser user = null; if (fedAuthSettings.IsAllowingNoDomain) { foreach (var allowedDomain in fedAuthSettings.DomainList.OrderBy(l => l.OrderIndex)) { user = await _userRepository.GetUserByLoginAsync($"{allowedDomain.Name}\\{principal.Identity.Name}"); if (user != null) { break; } } } else { user = await _userRepository.GetUserByLoginAsync(principal.Identity.Name); } if (user == null) // cannot find user in the DB { await _log.LogInformation(WebApiConfig.LogSourceSessions, I18NHelper.FormatInvariant("Could not get user with login '{0}'. NameClaimType '{1}'", principal.Identity.Name, fedAuthSettings.NameClaimType)); throw new AuthenticationException("Invalid user name or password", ErrorCodes.InvalidCredentials); } if (!user.IsEnabled) { throw new AuthenticationException(I18NHelper.FormatInvariant("Your account '{0}' has been locked out, please contact your Blueprint Instance Administrator.", user.Login), ErrorCodes.AccountIsLocked); } user.LicenseType = await _userRepository.GetEffectiveUserLicenseAsync(user.Id); return(user); }
public async Task <AuthenticationUser> AuthenticateUserAsync(string login, string password, bool ignoreInvalidLoginAttempts) { if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password)) { throw new AuthenticationException("Username and password cannot be empty", ErrorCodes.EmptyCredentials); } var user = await _userRepository.GetUserByLoginAsync(login); if (user == null) { await _log.LogInformation(WebApiConfig.LogSourceSessions, I18NHelper.FormatInvariant("Could not get user with login '{0}'", login)); throw new AuthenticationException("Invalid username or password", ErrorCodes.InvalidCredentials); } var instanceSettings = await _settingsRepository.GetInstanceSettingsAsync(); if (instanceSettings.IsSamlEnabled.GetValueOrDefault()) { // Fallback is allowed by default (value is null) if (!user.IsFallbackAllowed.GetValueOrDefault(true)) { throw new AuthenticationException("User must be authenticated via Federated Authentication mechanism", ErrorCodes.FallbackIsDisabled); } } AuthenticationStatus authenticationStatus; switch (user.Source) { case UserGroupSource.Database: authenticationStatus = AuthenticateDatabaseUser(user, password, instanceSettings.PasswordExpirationInDays); break; case UserGroupSource.Windows: if (!instanceSettings.IsLdapIntegrationEnabled) { throw new AuthenticationException(string.Format("To authenticate user with login: {0}, ldap integration must be enabled", login), ErrorCodes.LdapIsDisabled); } authenticationStatus = await _ldapRepository.AuthenticateLdapUserAsync(login, password, instanceSettings.UseDefaultConnection); break; default: throw new AuthenticationException(string.Format("Authentication provider could not be found for login: {0}", login)); } await ProcessAuthenticationStatus(authenticationStatus, user, instanceSettings, ignoreInvalidLoginAttempts); user.LicenseType = await _userRepository.GetEffectiveUserLicenseAsync(user.Id); return(user); }
public async Task <WorkflowTriggersContainer> GetWorkflowEventTriggersForTransition(int userId, int artifactId, int workflowId, int fromStateId, int toStateId, int transitionId) { var desiredTransition = await GetTransitionForAssociatedStatesAsync(userId, artifactId, workflowId, fromStateId, toStateId, transitionId); if (desiredTransition == null) { throw new ConflictException(I18NHelper.FormatInvariant("No transitions available. Workflow could have been updated. Please refresh your view.")); } return(GetWorkflowTriggersContainer(desiredTransition.Triggers)); }
public void InvalidColumnsException_AllParamsIsValid_OneProfileColumn_ReturnBadRequestException() { var expectedMessage = I18NHelper.FormatInvariant( ErrorMessages.ArtifactList.ColumnsSettings.SingleInvalidColumn, _profileColumns.First().PropertyName); var result = ArtifactListExceptionHelper.InvalidColumnsException(_profileColumns); Assert.IsNotNull(result); Assert.AreEqual(expectedMessage, result.Message); }
/// <summary> /// Throws an exception if the tested TimeSpam argument is not a valid timeout value. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown if the argument is not null and is not a valid timeout value.</exception> /// <param name="argumentValue">Argument value to check.</param> /// <param name="argumentName">Name of argument being checked.</param> public static void ArgumentIsValidTimeout(TimeSpan?argumentValue, string argumentName) { if (argumentValue.HasValue) { long totalMilliseconds = (long)argumentValue.Value.TotalMilliseconds; if (totalMilliseconds < (long)-1 || totalMilliseconds > (long)2147483647) { throw new ArgumentOutOfRangeException(I18NHelper.FormatInvariant("The valid range for '{0}' is from 0 to 24.20:31:23.647", argumentName)); } } }
public void ToInt32_NonNumericValue_ReturnsDefaultValue() { // Arrange const string s = "foo"; const int defaultValue = 5; // Act int x = I18NHelper.ToInt32(s, defaultValue); // Assert Assert.AreEqual(x, 5, I18NHelper.FormatInvariant("I18NHelper.ToInt32 converted '{0}' into {1} instead of {2}!", s, x, defaultValue)); }
public void Initialize(IFilesRepository fr, Guid fileId) { ThrowIf.ArgumentNull(fr, nameof(fr)); _filesRepository = fr; _file = _filesRepository.GetFileInfo(fileId); if (_file == null) { throw new InvalidOperationException( I18NHelper.FormatInvariant("Fatal. File '{0}' not found in FileStore", fileId)); } }
private async Task <WorkflowState> ValidateCurrentState() { // Get current state and validate current state var currentState = await _stateChangeExecutorRepositories.WorkflowRepository.GetStateForArtifactAsync(_userId, _input.ArtifactId, int.MaxValue, true); if (currentState == null) { throw new ConflictException(I18NHelper.FormatInvariant("Artifact has been updated. There is no workflow state associated with the artifact. Please refresh your view.")); } if (currentState.Id != _input.FromStateId) { throw new ConflictException(I18NHelper.FormatInvariant("Artifact has been updated. The current workflow state id {0} of the artifact does not match the specified state {1}. Please refresh your view.", currentState.Id, _input.FromStateId)); } return(currentState); }
public async Task <IEnumerable <int> > GetExistingProjectsByIdsAsync(IEnumerable <int> projectIds) { var dProjectIds = projectIds.ToList(); if (!dProjectIds.Any()) { throw new ArgumentException(I18NHelper.FormatInvariant("{0} is empty.", nameof(dProjectIds))); } var prm = new DynamicParameters(); prm.Add("@projectIds", SqlConnectionWrapper.ToDataTable(dProjectIds)); return(await _connectionWrapper.QueryAsync <int>("GetExistingProjectsByIds", prm, commandType : CommandType.StoredProcedure)); }
private IHttpActionResult ConstructHttpResponse(int?jobId) { if (!jobId.HasValue) { return(InternalServerError()); } var requestJobUrl = I18NHelper.FormatInvariant("/svc/adminstore/jobs/{0}", jobId.Value); var requestUri = new Uri(requestJobUrl, UriKind.Relative); var result = new AddJobResult() { JobId = jobId.Value }; return(Created(requestUri, result)); }
public async Task <ISet <int> > GetBaselineArtifacts(int baselineId, int userId, bool addDrafts = true, int revisionId = int.MaxValue) { var itemRawData = (await GetItemsRawData(new List <int> { baselineId }, userId, addDrafts, revisionId)).SingleOrDefault(); if (itemRawData != null) { var rawData = itemRawData.RawData; return(BaselineRawDataHelper.ExtractBaselineArtifacts(rawData)); } string errorMessage = I18NHelper.FormatInvariant("Baseline (Id:{0}) is not found.", baselineId); throw new ResourceNotFoundException(errorMessage, ErrorCodes.ResourceNotFound); }
public void Initialize(IFileStreamRepository fsr, IConfigRepository config, Guid fileId) { ThrowIf.ArgumentNull(fsr, nameof(fsr)); ThrowIf.ArgumentNull(config, nameof(config)); _filesRepository = fsr; _configRepository = config; _file = _filesRepository.GetFileHead(fileId); if (_file == null) { throw new InvalidOperationException( I18NHelper.FormatInvariant("Fatal. File '{0}' not found in legacy database", fileId)); } }
public async Task <IEnumerable <int> > DeleteWorkflowEventsAsync(IEnumerable <int> workflowEventIds, int publishRevision, IDbTransaction transaction = null) { if (workflowEventIds == null) { throw new ArgumentNullException(nameof(workflowEventIds)); } var listWorkflowStateIds = workflowEventIds.ToList(); if (!listWorkflowStateIds.Any()) { throw new ArgumentException(I18NHelper.FormatInvariant("{0} is empty.", nameof(workflowEventIds))); } if (publishRevision < 1) { throw new ArgumentException(I18NHelper.FormatInvariant("{0} is less than 1.", nameof(publishRevision))); } var parameters = new DynamicParameters(); parameters.Add("@publishRevision", publishRevision); parameters.Add("@workflowEventIds", SqlConnectionWrapper.ToDataTable(listWorkflowStateIds)); IEnumerable <SqlWorkflowEvent> result; if (transaction == null) { result = await _connectionWrapper.QueryAsync <SqlWorkflowEvent> ( "DeleteWorkflowEvents", parameters, commandType : CommandType.StoredProcedure); } else { result = await transaction.Connection.QueryAsync <SqlWorkflowEvent> ( "DeleteWorkflowEvents", parameters, transaction, commandType : CommandType.StoredProcedure); } return(result.Select(s => s.WorkflowEventId)); }
private void ValidateRequestParameters(int artifactId, int?subArtifactId) { if (artifactId < 1) { throw new BadRequestException(I18NHelper.FormatInvariant("Parameter: {0} is out of the range of valid values", nameof(artifactId))); } if (subArtifactId.HasValue && subArtifactId.Value < 1) { throw new BadRequestException(I18NHelper.FormatInvariant("Parameter: {0} is out of the range of valid values", nameof(subArtifactId))); } if (subArtifactId.HasValue && artifactId == subArtifactId.Value) { throw new BadRequestException("Please provide a proper subartifact Id"); } }
public async Task <IEnumerable <SqlWorkflow> > CreateWorkflowsAsync(IEnumerable <SqlWorkflow> workflows, int publishRevision, IDbTransaction transaction = null) { if (workflows == null) { throw new ArgumentNullException(nameof(workflows)); } var dWorkflows = workflows.ToList(); if (!dWorkflows.Any()) { throw new ArgumentException(I18NHelper.FormatInvariant("{0} is empty.", nameof(workflows))); } if (publishRevision < 1) { throw new ArgumentException(I18NHelper.FormatInvariant("{0} is less than 1.", nameof(publishRevision))); } var parameters = new DynamicParameters(); parameters.Add("@publishRevision", publishRevision); parameters.Add("@workflows", ToWorkflowsCollectionDataTable(dWorkflows)); IEnumerable <SqlWorkflow> result; if (transaction == null) { result = await _connectionWrapper.QueryAsync <SqlWorkflow> ( "CreateWorkflows", parameters, commandType : CommandType.StoredProcedure); } else { result = await transaction.Connection.QueryAsync <SqlWorkflow> ( "CreateWorkflows", parameters, transaction, commandType : CommandType.StoredProcedure); } return(result); }
private static void HandleErrorStates(IList <int> artifactIdsList, ICollection <SqlDiscardPublishState> discardPublishStates) { if (artifactIdsList.Count != discardPublishStates.Count) { throw new ResourceNotFoundException(I18NHelper.FormatInvariant("Not all items could be located."), ErrorCodes.ItemNotFound); } var errorState = discardPublishStates.FirstOrDefault(dps => dps.NotExist); if (errorState != null) { throw new ResourceNotFoundException(I18NHelper.FormatInvariant("Item with ID {0} is not found.", errorState.ItemId), ErrorCodes.ItemNotFound); } errorState = discardPublishStates.FirstOrDefault(dps => dps.NotArtifact); if (errorState != null) { throw new ResourceNotFoundException(I18NHelper.FormatInvariant("Item with ID {0} is not an artifact.", errorState.ItemId), ErrorCodes.ItemNotFound); } errorState = discardPublishStates.FirstOrDefault(dps => dps.Deleted); if (errorState != null) { throw new ResourceNotFoundException(I18NHelper.FormatInvariant("Item with ID {0} is deleted.", errorState.ItemId), ErrorCodes.ItemNotFound); } errorState = discardPublishStates.FirstOrDefault(dps => dps.NoChanges); if (errorState != null) { throw new ConflictException( I18NHelper.FormatInvariant("Artifact with ID {0} has nothing to publish. The artifact will now be refreshed.", errorState.ItemId), ErrorCodes.CannotPublish); } errorState = discardPublishStates.FirstOrDefault(dps => dps.Invalid); if (errorState != null) { throw new ConflictException(I18NHelper.FormatInvariant("Artifact with ID {0} has validation errors.", errorState.ItemId), ErrorCodes.CannotPublishOverValidationErrors); } }