public IndustryModule(IPublishStorableCommands publisher, IRepository<Industry> repository) { this.RequiresAnyClaim(new[] { RoleType.Admin.ToString(), RoleType.ProductManager.ToString() }); const string industriesRoute = "/Industries"; Get[industriesRoute + "/{industryIds?}"] = parameters => { var allIndustryDtos = Mapper.Map<IEnumerable<IIndustry>, IEnumerable<IndustryDto>>(repository); if (!parameters.industryIds.HasValue) return Response.AsJson(allIndustryDtos); var filteredIndustries = Enumerable.Empty<Industry>(); if (parameters.industryIds.HasValue) { var industryString = (string)parameters.industryIds.Value; var industryIds = industryString.Split(',').Select(x => new Guid(x)); filteredIndustries = repository.Where(x => industryIds.Contains(x.Id)); } var industries = filteredIndustries as IList<Industry> ?? filteredIndustries.ToList(); var filteredIndustryDtos = Mapper.Map<IEnumerable<IIndustry>, IEnumerable<IndustryDto>>(industries).ToList(); foreach (var industry in filteredIndustryDtos) industry.IsSelected = true; var industryDtos = allIndustryDtos as IList<IndustryDto> ?? allIndustryDtos.ToList(); var response = industries.Any() ? filteredIndustryDtos.Concat(industryDtos).DistinctBy(c => c.Id) : industryDtos; return Response.AsJson(response); }; Post[industriesRoute] = parameters => { var model = Request.Body<dynamic>(); if (model.name.Value == null) throw new LightstoneAutoException("Could not bind 'Name' value"); publisher.Publish(new CreateIndustry(Guid.NewGuid(), model.name.Value, false)); return Response.AsJson(new { response = "Success!" }); }; Put[industriesRoute] = parameters => { var model = Request.Body<dynamic>(); if (model.id.Value == null && model.name.Value == null) throw new LightstoneAutoException("Could not bind 'id' or 'Name' value"); publisher.Publish(new RenameIndustry(new Guid(model.id.Value), model.name.Value, false)); return Response.AsJson(new { response = "Success!" }); }; }
private static void RepositoryTests(IRepository<Person> personRepo, Action commitChanges) { Console.WriteLine("Testing with '{0}' ", personRepo); var id = Guid.NewGuid(); var person = new Person { Id = id, Name = id.ToString() }; personRepo.Add(person); // Commit the changes depending on the provider commitChanges(); var found = personRepo.Where(p => p.Id == id) .FirstOrDefault(); Console.Write(found.Name); }
/// <summary> /// Gets the tags associated with media objects the user has permission to view. /// </summary> /// <param name="repo">The metadata tag repository.</param> /// <returns>A collection of <see cref="Entity.Tag" /> instances.</returns> /// <remarks>This function is similar to <see cref="GetTagsForAlbums(IRepository{MetadataTagDto})" />, so if a developer /// modifies it, be sure to check that function to see if it needs a similar change.</remarks> private IEnumerable<Entity.Tag> GetTagsForMediaObjects(IRepository<MetadataTagDto> repo) { var qry = repo.Where( m => m.FKGalleryId == SearchOptions.GalleryId && m.Metadata.MetaName == TagName); if (!String.IsNullOrEmpty(SearchOptions.SearchTerm)) { qry = qry.Where(m => m.FKTagName.Contains(SearchOptions.SearchTerm)); } if (SearchOptions.IsUserAuthenticated) { if (!UserCanViewRootAlbum) { // User can't view the root album, so get a list of the albums she *can* see and make sure our // results only include albums that are viewable. var albumIds = SearchOptions.Roles.GetViewableAlbumIdsForGallery(SearchOptions.GalleryId); qry = qry.Where(a => albumIds.Contains(a.Metadata.MediaObject.FKAlbumId)); } } else if (UserCanViewRootAlbum) { // Anonymous user, so don't include any private albums in results. qry = qry.Where(a => !a.Metadata.MediaObject.Album.IsPrivate); } else { // User is anonymous and does not have permission to view the root album, meaning they // can't see anything. Return empty collection. return new List<Entity.Tag>(); } return qry.GroupBy(t => t.FKTagName).Select(t => new Entity.Tag { Value = t.Key, Count = t.Count() }); }
public PackageModule(IPublishStorableCommands publisher, IRepository<Domain.Entities.Packages.Read.Package> readRepo, INEventStoreRepository<Package> writeRepo, IRepository<State> stateRepo, IEntryPoint entryPoint, IAdvancedBus eBus, IUserManagementApiClient userManagementApi, IBillingApiClient billingApiClient, IPublishIntegrationMessages integration) { Get[PackageBuilderApi.PackageRoutes.RequestIndex.ApiRoute] = _ => { return _.showAll ? Response.AsJson( from p1 in readRepo where p1.Version == (from p2 in readRepo where p2.PackageId == p1.PackageId && !p2.IsDeleted select p2.Version).Max() select p1) : Response.AsJson(readRepo.Where(x => !x.IsDeleted)); }; Get[PackageBuilderApi.PackageRoutes.RequestLookup.ApiRoute] = parameters => { var filter = ((string)Context.Request.Query["q_word[]"].Value + "").Replace(",", " "); var pageIndex = 0; var pageSize = 0; int.TryParse(Context.Request.Query["page_num"].Value, out pageIndex); int.TryParse(Context.Request.Query["per_page"].Value, out pageSize); var industries = ((string)parameters.industryIds.Value + "").Split(',').Select(x => !string.IsNullOrEmpty(x) ? new Guid(x) : new Guid()); var publishedPackages = from p1 in readRepo where p1.Version == (from p2 in readRepo where p2.PackageId == p1.PackageId select p2.Version).Max() && p1.State.Name == StateName.Published && p1.Industries.Any(ind => industries.Contains(ind.Id)) && (p1.Name + "").Trim().ToLower().StartsWith(filter) select p1; var packages = new PagedList<Domain.Entities.Packages.Read.Package>(publishedPackages, pageIndex - 1, pageSize, x => !x.IsDeleted); return Response.AsJson( new { result = packages, cnt_whole = packages.RecordsFiltered }); }; Get[PackageBuilderApi.PackageRoutes.RequestUpdate.ApiRoute] = parameters => Response.AsJson( new { Response = new[] { Mapper.Map<IPackage, PackageDto>(writeRepo.GetById(parameters.id)) } }); Post[PackageBuilderApi.PackageRoutes.Execute.ApiRoute] = parameters => { var apiRequest = this.Bind<ApiRequestDto>(); this.Info(() => StringExtensions.FormatWith("Package Execute Initialized for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); this.Info(() => StringExtensions.FormatWith("Package Read Initialized, TimeStamp: {0}", DateTime.UtcNow)); var package = writeRepo.GetById(apiRequest.PackageId, true); this.Info(() => StringExtensions.FormatWith("Package Read Completed, TimeStamp: {0}", DateTime.UtcNow)); if (package == null) { this.Error(() => StringExtensions.FormatWith("Package not found:", apiRequest.PackageId)); throw new LightstoneAutoException("Package could not be found"); } this.Info(() => StringExtensions.FormatWith("PackageBuilder Auth to UserManagement Initialized for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); var token = Context.Request.Headers.Authorization.Split(' ')[1]; var accountNumber = userManagementApi.Get(token, "/CustomerClient/{id}", new[] { new KeyValuePair<string, string>("id", apiRequest.CustomerClientId.ToString()) }, null); this.Info(() => StringExtensions.FormatWith("PackageBuilder Auth to UserManagement Completed for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); var responses = ((Package)package).Execute(entryPoint, apiRequest.UserId, Context.CurrentUser.UserName, Context.CurrentUser.UserName, apiRequest.RequestId, accountNumber, apiRequest.ContractId, apiRequest.ContractVersion, apiRequest.DeviceType, apiRequest.FromIpAddress, "", apiRequest.SystemType, apiRequest.RequestFields, (double)package.CostOfSale, (double)package.RecommendedSalePrice, apiRequest.HasConsent); // Filter responses for cleaner api payload this.Info(() => StringExtensions.FormatWith("Package Response Filter Cleanup Initialized for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); var filteredResponse = new List<IProvideResponseDataProvider> { new ResponseMeta(apiRequest.RequestId, responses.ResponseState()) }; filteredResponse.AddRange(Mapper.Map<IEnumerable<IDataProvider>, IEnumerable<IProvideResponseDataProvider>>(responses)); this.Info(() => StringExtensions.FormatWith("Package Response Filter Cleanup Completed for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); integration.SendToBus(new PackageResponseMessage(package.Id, apiRequest.UserId, apiRequest.ContractId, accountNumber, filteredResponse.Any() ? filteredResponse.AsJsonString() : string.Empty, apiRequest.RequestId, Context != null ? Context.CurrentUser.UserName : "unavailable")); this.Info(() => StringExtensions.FormatWith("Package Execute Completed for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); return filteredResponse; }; Post[PackageBuilderApi.PackageRoutes.CommitRequest.ApiRoute] = _ => { var apiRequest = this.Bind<ApiCommitRequestDto>(); var token = Context.Request.Headers.Authorization.Split(' ')[1]; var request = billingApiClient.Get(token, "/Transactions/Request/{requestId}", new[] { new KeyValuePair<string, string>("requestId", apiRequest.RequestId.ToString()) } ,null); if (request.Contains("error")) return request; // RabbitMQ new TransactionBus(eBus).SendDynamic(Mapper.Map(apiRequest, new TransactionRequestMessage())); this.Info(() => StringExtensions.FormatWith("Updated TransactionRequest UserState: {0}", apiRequest.UserState)); if (apiRequest.UserState == ApiCommitRequestUserState.Cancelled) return Response.AsJson(new { Success = "Request successfully cancelled by user" }); if (apiRequest.UserState == ApiCommitRequestUserState.VehicleNotProvided) return Response.AsJson(new { Success = "Request successfully marked as VehicleNotProvided by user" }); this.Info(() => StringExtensions.FormatWith("Package ExecuteWithCarId Initialized for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); this.Info(() => StringExtensions.FormatWith("Package Read Initialized, TimeStamp: {0}", DateTime.UtcNow)); var package = writeRepo.GetById(apiRequest.PackageId, true); this.Info(() => StringExtensions.FormatWith("Package Read Completed, TimeStamp: {0}", DateTime.UtcNow)); if (package == null) { this.Error(() => StringExtensions.FormatWith("Package not found:", apiRequest.PackageId)); throw new LightstoneAutoException("Package could not be found"); } this.Info(() => StringExtensions.FormatWith("PackageBuilder Auth to UserManagement Initialized for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); var accountNumber = userManagementApi.Get(token, "/CustomerClient/{id}", new[] { new KeyValuePair<string, string>("id", apiRequest.CustomerClientId.ToString()) }, null); this.Info(() => StringExtensions.FormatWith("PackageBuilder Auth to UserManagement Completed for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); var responses = ((Package)package).ExecuteWithCarId(entryPoint, apiRequest.UserId, Context.CurrentUser.UserName, Context.CurrentUser.UserName, apiRequest.RequestId, accountNumber, apiRequest.ContractId, apiRequest.ContractVersion, apiRequest.DeviceType, apiRequest.FromIpAddress, "", apiRequest.SystemType, apiRequest.RequestFields, (double)package.CostOfSale, (double)package.RecommendedSalePrice, apiRequest.HasConsent); // Filter responses for cleaner api payload this.Info(() => StringExtensions.FormatWith("Package Response Filter Cleanup Initialized for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); var filteredResponse = new List<IProvideResponseDataProvider> { new ResponseMeta(apiRequest.RequestId, responses.ResponseState()) }; filteredResponse.AddRange(Mapper.Map<IEnumerable<IDataProvider>, IEnumerable<IProvideResponseDataProvider>>(responses)); this.Info(() => StringExtensions.FormatWith("Package Response Filter Cleanup Completed for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); integration.SendToBus(new PackageResponseMessage(package.Id, apiRequest.UserId, apiRequest.ContractId, accountNumber, filteredResponse.Any() ? filteredResponse.AsJsonString() : string.Empty, apiRequest.RequestId, Context != null ? Context.CurrentUser.UserName : "unavailable")); this.Info(() => StringExtensions.FormatWith("Package ExecuteWithCarId Completed for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow)); return filteredResponse; }; Post[PackageBuilderApi.PackageRoutes.ProcessCreate.ApiRoute] = parameters => { var dto = this.Bind<PackageDto>(); dto.Id = dto.Id == new Guid() ? Guid.NewGuid() : dto.Id; // Required for acceptance tests where we specify the Id var dProviders = Mapper.Map<IEnumerable<DataProviderDto>, IEnumerable<DataProviderOverride>>(dto.DataProviders); publisher.Publish(new CreatePackage(dto.Id, dto.Name, dto.Description, dto.CostOfSale, dto.RecommendedSalePrice, dto.Notes, dto.PackageEventType, Mapper.Map<PackageDto, IEnumerable<Industry>>(dto), dto.State, dto.Owner, DateTime.UtcNow, null, dProviders)); ////RabbitMQ var metaEntity = Mapper.Map(dto, new PackageMessage()); var advancedBus = new TransactionBus(eBus); advancedBus.SendDynamic(metaEntity); return Response.AsJson(new { msg = "Success" }); }; Put[PackageBuilderApi.PackageRoutes.ProcessUpdate.ApiRoute] = parameters => { var dto = this.Bind<PackageDto>(); var dProviders = Mapper.Map<IEnumerable<DataProviderDto>, IEnumerable<DataProviderOverride>>(dto.DataProviders); publisher.Publish(new UpdatePackage(parameters.id, dto.Name, dto.Description, dto.CostOfSale, dto.RecommendedSalePrice, dto.Notes, dto.PackageEventType, Mapper.Map<PackageDto, IEnumerable<Industry>>(dto), dto.State, dto.Version, dto.Owner, dto.CreatedDate, DateTime.UtcNow, dProviders)); ////RabbitMQ var metaEntity = Mapper.Map(dto, new PackageMessage()); var advancedBus = new TransactionBus(eBus); advancedBus.SendDynamic(metaEntity); return Response.AsJson(new { msg = "Success, " + parameters.id + " edited" }); }; Put["/Packages/Clone/{id}/{cloneName}"] = parameters => { var packageToClone = Mapper.Map<IPackage, PackageDto>(writeRepo.GetById(parameters.id)); var dataProvidersToClone = Mapper.Map<IEnumerable<DataProviderDto>, IEnumerable<DataProviderOverride>>( packageToClone.DataProviders); var stateResolve = stateRepo.Where(x => x.Alias == "Draft") .Select(y => new State(y.Id, y.Name, y.Alias)); publisher.Publish(new CreatePackage(Guid.NewGuid(), parameters.cloneName, packageToClone.Description, packageToClone.CostOfSale, packageToClone.RecommendedSalePrice, packageToClone.Notes, packageToClone.PackageEventType, packageToClone.Industries, stateResolve.FirstOrDefault(), packageToClone.Owner, DateTime.UtcNow, null, dataProvidersToClone)); return Response.AsJson( new { msg = "Success, Package with ID: " + parameters.id + " has been cloned to package '" + parameters.cloneName + "'" }); }; Delete[PackageBuilderApi.PackageRoutes.ProcessDelete.ApiRoute] = parameters => { this.RequiresAnyClaim(new[] { RoleType.Admin.ToString(), RoleType.ProductManager.ToString(), RoleType.Support.ToString() }); publisher.Publish(new DeletePackage(new Guid(parameters.id))); return Response.AsJson(new { msg = "Success, " + parameters.id + " deleted" }); }; }
public UserAliasModule(IBus bus, IRepository<ClientUserAlias> userAliasRepository, IRepository<User> usereRepository) { Get["/UserAliases/{clientId:guid}"] = _ => { var clientId = (Guid)_.clientId; var aliases = userAliasRepository.Where(x => x.Client.Id == clientId); return Response.AsJson(Mapper.Map<IEnumerable<ClientUserAlias>, IEnumerable<UserAliasDto>>(aliases)); }; //TODO: Error checking for file type. Allow csv only Post["/UserAliases/ImportUsers/FilesUpload/{clientId:guid}"] = _ => { var clientId = (Guid)_.clientId; var filesUploaded = Request.Files; var files = new List<FileUploadDto>(); var clientImportUsers = new List<UserAliasDto>(); foreach (var httpFile in filesUploaded) { //if (httpFile.ContentType != "text/csv") //{ // // Response for file upload component // files.Add(new FileUploadDto // { // name = httpFile.Name, // size = Convert.ToInt32(httpFile.Value.Length), // error = "File type not allowed" // }); // break; //}; // CSV to object using (var reader = new StreamReader(httpFile.Value)) { var contents = reader.ReadToEnd().Split('\n'); var csv = from line in contents select line.Split(',').ToArray(); clientImportUsers.AddRange(csv.Skip(1).TakeWhile(r => r.Length > 1 && r.Last().Trim().Length > 0) .Select(row => new UserAliasDto { UuId = row[0], FirstName = row[1], LastName = row[2], UserName = row[3].Replace("\r", ""), ClientId = clientId })); foreach (var clientImportUser in clientImportUsers) { var exists = userAliasRepository.Any(x => x.Client.Id == clientId && x.UserName.Trim().ToLower() == clientImportUser.UserName.Trim().ToLower()); if (exists) throw new LightstoneAutoException("{0} already exists".FormatWith(clientImportUser.UserName)); var entity = Mapper.Map(clientImportUser, new ClientUserAlias()); bus.Publish(new CreateUpdateEntity(entity, "Create")); } } // Response for file upload component files.Add(new FileUploadDto { name = httpFile.Name, size = Convert.ToInt32(httpFile.Value.Length), thumbnailUrl = "http://icons.iconarchive.com/icons/custom-icon-design/pretty-office-2/72/success-icon.png", deleteType = "DELETE" }); } var fileResponseJsonObject = new JObject(new JProperty("files", JsonConvert.SerializeObject(files))); return Response.AsJson(fileResponseJsonObject); }; Post["/UserAliases/LinkAlias"] = _ => { var dto = this.Bind<AliasDto>(); var command = new LinkUserAliasCommand(dto.AliasId, dto.CustomerId, dto.UserId); bus.Publish(command); return Response.AsJson("Saved!"); }; }