public GetOrganizationsByMunicipalityTests() { _municipalityId = Guid.NewGuid(); _areaId = Guid.NewGuid(); SetupTypesCacheMock <OrganizationType>(); SetupTypesCacheMock <AreaInformationType>(); SetupTypesCacheMock <AreaType>(); // unitOfWork var areaMunicipalityRepoMock = new Mock <IAreaMunicipalityRepository>(); areaMunicipalityRepoMock.Setup(g => g.All()).Returns(EntityGenerator.GetAreaMunicipalityList(_areaId, _municipalityId).AsQueryable()); unitOfWorkMockSetup.Setup(uw => uw.CreateRepository <IAreaMunicipalityRepository>()).Returns(areaMunicipalityRepoMock.Object); _areaRepoMock = new Mock <IAreaRepository>(); unitOfWorkMockSetup.Setup(uw => uw.CreateRepository <IAreaRepository>()).Returns(_areaRepoMock.Object); // Translation manager translationManagerMockSetup.Setup(t => t.TranslateAll <OrganizationVersioned, VmOpenApiOrganizationItem>(It.IsAny <IList <OrganizationVersioned> >())) .Returns((List <OrganizationVersioned> collection) => { var list = new List <VmOpenApiOrganizationItem>(); collection.ForEach(i => list.Add(new VmOpenApiOrganizationItem { Id = i.UnificRootId })); return(list); }); }
public void OrganizationsFound_TypeIsNotMunicipality_AreaType_OrganizationAreaMunicipalityWithinArea() { // Arrange var organizations = EntityGenerator.GetOrganizationEntityList(1, PublishingStatusCache); var publishedOrganization = organizations.Where(o => o.PublishingStatusId == PublishedId).FirstOrDefault(); publishedOrganization.AreaInformationTypeId = TypeCache.Get <AreaInformationType>(AreaInformationTypeEnum.AreaType.ToString()); publishedOrganization.TypeId = TypeCache.Get <OrganizationType>(OrganizationTypeEnum.Company.ToString()); publishedOrganization.OrganizationAreas = new List <OrganizationArea> { new OrganizationArea { Area = new Area { AreaMunicipalities = new List <AreaMunicipality> { new AreaMunicipality { MunicipalityId = _municipalityId } } } } }; // service var service = ArrangeAndGetService(organizations); // Act var result = service.GetOrganizationsByMunicipality(_municipalityId, null, 1, 1); // Assert result.Should().NotBeNull(); result.PageCount.Should().Be(1); var vmResult = Assert.IsType <VmOpenApiOrganizationGuidPage>(result); vmResult.ItemList.Should().NotBeNullOrEmpty(); vmResult.ItemList.Count().Should().Be(1); }
/// <summary> /// Generates the 'select all' method. /// </summary> /// <param name="file">The file.</param> /// <param name="classMap">The class map.</param> public override void GenerateSelectAll(StreamWriter file, IClassMap classMap) { string sqlCommand = "SELECT \" + c_rowFields + \" FROM `" + classMap.GetTableMap().Name + "`"; string entityClassName = EntityGenerator.GetTypeName(classMap); // create an array and store results file.WriteLine(" "+ entityClassName + " entity;"); file.WriteLine(" List<"+ entityClassName + "> results = null;"); file.WriteLine(); file.WriteLine(" m_state.ExecuteQuery("); file.WriteLine(" \""+ sqlCommand + "\","); file.WriteLine(" CommandBehavior.Default,"); file.WriteLine(" delegate(MySqlDataReader reader)"); file.WriteLine(" {"); file.WriteLine(" results = new List<"+ entityClassName + ">();"); file.WriteLine(" while (reader.Read())"); file.WriteLine(" {"); file.WriteLine(" entity = new "+ entityClassName + "();"); file.WriteLine(" FillEntityWithRow(ref entity, reader);"); file.WriteLine(" results.Add(entity);"); file.WriteLine(" }"); file.WriteLine(" }"); file.WriteLine(" );"); file.WriteLine(); file.WriteLine(" return results;"); }
public GetServiceByIdTests() { _list = EntityGenerator.GetServiceEntityList(1, PublishingStatusCache); _publishedItem = _list.Where(o => o.PublishingStatusId == PublishedId).FirstOrDefault(); _publishedItemId = _publishedItem.Id; _publishedRootItemId = _publishedItem.UnificRootId; }
public void NoEntitesFound() { // Arrange // unitOfWork var serviceMock = new Mock <IServiceVersionedRepository>(); serviceMock.Setup(o => o.All()).Returns(EntityGenerator.GetServiceEntityList(0, PublishingStatusCache).AsQueryable()); unitOfWorkMockSetup.Setup(uw => uw.CreateRepository <IServiceVersionedRepository>()).Returns(serviceMock.Object); var channelMock = new Mock <IServiceChannelVersionedRepository>(); channelMock.Setup(o => o.All()).Returns(new List <ServiceChannelVersioned>().AsQueryable()); unitOfWorkMockSetup.Setup(uw => uw.CreateRepository <IServiceChannelVersionedRepository>()).Returns(channelMock.Object); var unitOfWorkMock = unitOfWorkMockSetup.Object; var contextManager = new TestContextManager(unitOfWorkMock, unitOfWorkMock); var serviceUtilities = new ServiceUtilities(UserIdentification, LockingManager, contextManager, UserOrganizationService, VersioningManager, UserInfoService, UserOrganizationChecker); // common service var service = new CommonService(translationManagerMockSetup.Object, TranslationManagerVModel, contextManager, CacheManager.TypesCache, PublishingStatusCache, UserOrganizationChecker, DataServiceFetcherMock, serviceUtilities, VersioningManager, ApplicationConfigurationMock, HttpContextAccessorMock); // Act var result = service.GetServicesAndChannelsByOrganization(Guid.NewGuid(), null, 1, 1); // Assert result.Should().NotBeNull(); result.PageCount.Should().Be(0); result.Should().BeOfType <VmOpenApiEntityGuidPage>(); (result as VmOpenApiEntityGuidPage).ItemList.Should().BeNullOrEmpty(); }
public void AddObject(EntityGenerator e, int closestPoint, Vector3 position, Quaternion rotation, Vector3 scale) { int index = generators.IndexOf(e); if (index == -1) { int staticEntityIndex = staticEntities.Count; generators.Add(e); Debug.Log(staticEntities); List <StaticEntity>[] entities = new List <StaticEntity> [points.Count]; staticEntities.Add(entities); emptyColliders.Add(new List <GameObject[]>()); staticEntities[staticEntityIndex][closestPoint] = new List <StaticEntity>(); staticEntities[staticEntityIndex][closestPoint].Add(new StaticEntity { closestPoint = closestPoint, position = position, rotation = rotation, scale = scale }); } else { if (staticEntities[index][closestPoint] == null) { staticEntities[index][closestPoint] = new List <StaticEntity>(); } staticEntities[index][closestPoint].Add(new StaticEntity { closestPoint = closestPoint, position = position, rotation = rotation, scale = scale }); } }
public void InitLocalMySQL() { if (this.Database.CreateIfNotExists()) { //Setup base datas to load for (int j = 0; j < 20; j++) { Class1 c1 = new Class1(); EntityGenerator <Class1> generatorClass1 = new EntityGenerator <Class1>(); c1 = generatorClass1.GenerateItem(); EntityGenerator <Class2> generatorClass2 = new EntityGenerator <Class2>(); for (int i = 0; i < 10; i++) { c1.Addresses.Add(generatorClass2.GenerateItem()); } MySQLManager <Class1> managerClass1 = new MySQLManager <Class1>(DataConnectionResource.LOCALMYSQL); managerClass1.Insert(c1); ClassD d1 = new ClassD(); EntityGenerator <ClassD> generatorClassD = new EntityGenerator <ClassD>(); d1 = generatorClassD.GenerateItem(); MySQLManager <ClassD> managerClassD = new MySQLManager <ClassD>(DataConnectionResource.LOCALMYSQL); managerClassD.Insert(d1); } } }
public void NoDateDefined(int pageNumber, int pageSize, int count, int expectedPageCount, int expectedItemCountOnPage) { var list = EntityGenerator.GetGeneralDescriptionEntityList(count, PublishingStatusCache) .Where(e => e.PublishingStatusId == PublishedId && e.LanguageAvailabilities.Any(l => l.StatusId == PublishedId)).ToList(); TestBase(null, list, pageNumber, pageSize, count, expectedPageCount, expectedItemCountOnPage); }
public GeneratorCSharp(EntityGenerator generator, Arguments arguments) { _generator = generator; _arguments = arguments; this.Start(); }
public void generator_EmployeeColumns_Test() { var generator = new EntityGenerator(_connection); var table = generator.Tables.FirstOrDefault(t => t.Name == "EMP"); Assert.AreEqual("EMP", table.Name); Assert.AreEqual("dbo", table.Schema); Assert.AreEqual("dbo_EMP", table.SchemaAndName); Assert.AreEqual(false, table.IsView); Assert.AreEqual(8, table.Columns.Count()); Assert.AreEqual(false, table.Columns.First(c => c.ColumnName == "EMPNO").IsNullable); Assert.AreEqual(true, table.Columns.First(c => c.ColumnName == "ENAME").IsNullable); Assert.AreEqual("int", table.Columns.First(c => c.ColumnName == "EMPNO").CSharpType); Assert.AreEqual("string", table.Columns.First(c => c.ColumnName == "ENAME").CSharpType); Assert.AreEqual("string", table.Columns.First(c => c.ColumnName == "JOB").CSharpType); Assert.AreEqual("int", table.Columns.First(c => c.ColumnName == "MGR").CSharpType); Assert.AreEqual("DateTime", table.Columns.First(c => c.ColumnName == "HIREDATE").CSharpType); Assert.AreEqual("decimal", table.Columns.First(c => c.ColumnName == "SAL").CSharpType); Assert.AreEqual("int", table.Columns.First(c => c.ColumnName == "COMM").CSharpType); Assert.AreEqual("int", table.Columns.First(c => c.ColumnName == "DEPTNO").CSharpType); Assert.AreEqual(true, table.Columns.First(c => c.ColumnName == "HIREDATE").IsNullable); Assert.AreEqual(true, table.Columns.First(c => c.ColumnName == "SAL").IsNullable); Assert.AreEqual("Int32", table.Columns.First(c => c.ColumnName == "EMPNO").DotNetType); Assert.AreEqual("String", table.Columns.First(c => c.ColumnName == "ENAME").DotNetType); Assert.AreEqual("String", table.Columns.First(c => c.ColumnName == "JOB").DotNetType); Assert.AreEqual("Int32", table.Columns.First(c => c.ColumnName == "MGR").DotNetType); Assert.AreEqual("int?", table.Columns.First(c => c.ColumnName == "MGR").CSharpTypeNullable); Assert.AreEqual("Int32?", table.Columns.First(c => c.ColumnName == "MGR").DotNetTypeNullable); }
public static int Run(string[] args) { var sw = Stopwatch.StartNew(); int loadResult = LoadOptions(args); if (loadResult != 0) { return(loadResult); } _basePath = AbsolutePath(_options.Source); AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly; // Look in the base path for referenced .dll files instead of the startup path Console.Write("Scanning for DTO objects in {0}... ", _basePath); var apiControllers = GetApiControllers(_basePath); var controllerModels = new HashSet <Type>(apiControllers.SelectMany(GetModelsFromController)); // return and parameter models var allModels = GetAllModelsToGenerate(controllerModels); Console.WriteLine("Found {0}", allModels.Count); var targetPath = AbsolutePath(_options.Destination); // Invoke all generators and pass the results to the index generator var allGeneratedNames = IndexGenerator.Generate(targetPath, EntityGenerator.Generate(targetPath, allModels, _options), DataServiceGenerator.Generate(apiControllers, controllerModels, targetPath, _options) ); RemoveNonGeneratedFiles(targetPath, allGeneratedNames); Console.WriteLine("Done in {0:N3}s", sw.Elapsed.TotalSeconds); return(0); }
public AssociationMetadata(PropertyDescriptor pd) { this.PropertyDescriptor = pd; AttributeCollection propertyAttributes = pd.ExplicitAttributes(); this.AssociationAttribute = (AssociationAttribute)propertyAttributes[typeof(AssociationAttribute)]; this.IsExternal = propertyAttributes[typeof(ExternalReferenceAttribute)] != null; this.IsCollection = EntityGenerator.IsCollectionType(pd.PropertyType); if (!this.IsCollection) { this.PropTypeName = CodeGenUtilities.GetTypeName(pd.PropertyType); this.AssociationTypeName = @"OpenRiaServices.DomainServices.Client.EntityRef<" + this.PropTypeName + ">"; this.Attributes = propertyAttributes.Cast <Attribute>().Where(a => a.GetType() != typeof(DataMemberAttribute)); } else { this.PropTypeName = CodeGenUtilities.GetTypeName(TypeUtility.GetElementType(pd.PropertyType)); this.AssociationTypeName = "OpenRiaServices.DomainServices.Client.EntityCollection<" + this.PropTypeName + ">"; List <Attribute> attributeList = propertyAttributes.Cast <Attribute>().ToList(); ReadOnlyAttribute readOnlyAttr = propertyAttributes.OfType <ReadOnlyAttribute>().SingleOrDefault(); if (readOnlyAttr != null && !propertyAttributes.OfType <EditableAttribute>().Any()) { attributeList.Add(new EditableAttribute(!readOnlyAttr.IsReadOnly)); } this.Attributes = attributeList.Where(a => a.GetType() != typeof(DataMemberAttribute)); } this.PropertyName = CodeGenUtilities.GetSafeName(pd.Name); this.FieldName = CodeGenUtilities.MakeCompliantFieldName(this.PropertyName); }
public async Task <TEntity> SingleOrDefaultAsync(CancellationToken cancellationToken) { return(await Task.Run(() => { cancellationToken.ThrowIfCancellationRequested(); var scan = PrepareScan(); var client = _pool.GetClient(); var scanner = client.scannerOpenWithScan(_tableName, scan, null); var data = client.scannerGetList(scanner, _limit); _pool.ReleaseClient(client); return data; }, cancellationToken) .ContinueWith(x => { cancellationToken.ThrowIfCancellationRequested(); if (x.Result.Count > 1) { throw new CommandException($"Expected 1 result, got {x.Result.Count}"); } if (x.Result.Count == 0) { return default(TEntity); } var generator = new EntityGenerator <TEntity>(_map); return generator.BuildEntity(x.Result.Single()); }, cancellationToken)); }
public void APIStudent_Success() { int testID = 100; string testLastName = "Petrolia"; string testFirstName = "Matoula"; DateTime testEnrollmentDate = DateTime.Now; Enrollment testEnrollment1 = new Enrollment() { EnrollmentID = 1, StudentID = testID, CourseID = 100 }; Enrollment testEnrollment2 = new Enrollment() { EnrollmentID = 2, StudentID = testID, CourseID = 200 }; List <Enrollment> testEnrollments = new List <Enrollment>(); testEnrollments.Add(testEnrollment1); testEnrollments.Add(testEnrollment2); EntityGenerator generator = new EntityGenerator(dbContext); Student studentTest = generator.CreateStudentFull(testID, testLastName, testFirstName, testEnrollmentDate, testEnrollments); //Create a list of enrollments - only Course ID List <EnrollmentApiVM> testEnrollmentsAPI = new List <EnrollmentApiVM>(); foreach (Enrollment enrollment in studentTest.Enrollments) { EnrollmentApiVM enrollmentApiVM = new EnrollmentApiVM(); enrollmentApiVM.courseId = enrollment.CourseID; testEnrollmentsAPI.Add(enrollmentApiVM); } IHttpActionResult okResult = controllerToTest.GetStudent(studentTest.ID); OkNegotiatedContentResult <StudentApiVM> contentResult = okResult as OkNegotiatedContentResult <StudentApiVM>; // string to test the format - not used //string expectedResult = "{\"id\":" + studentTest.ID + ",\"lastname\":" + studentTest.LastName + ",\"firstname\":" + studentTest.FirstMidName + // ",\"enrollmentDate\":" + studentTest.EnrollmentDate.ToString("yyyy-MM-dd") + ",\"enrollments\":[{\"CourseId\":" + testEnrollmentsAPI[0].CourseId + // "},{\"CourseId\":" + testEnrollmentsAPI[1].CourseId + "}]}"; Assert.IsNotNull(contentResult); Assert.AreEqual(studentTest.LastName, contentResult.Content.lastname); Assert.AreEqual(studentTest.FirstMidName, contentResult.Content.firstname); Assert.AreEqual(studentTest.ID, contentResult.Content.id); Assert.AreEqual(studentTest.EnrollmentDate.ToString("yyyy-MM-dd"), contentResult.Content.enrollmentDate); Assert.IsNotNull(contentResult.Content.enrollments); Assert.IsNotEmpty(contentResult.Content.enrollments); Assert.AreEqual(testEnrollmentsAPI[0], contentResult.Content.enrollments[0]); Assert.AreEqual(testEnrollmentsAPI[1], contentResult.Content.enrollments[1]); Assert.AreEqual(testEnrollmentsAPI, contentResult.Content.enrollments); Assert.IsInstanceOf(typeof(OkNegotiatedContentResult <StudentApiVM>), okResult); }
internal void UnpackRevisionDatagram(PoolRevisionPayload payload, long offsetMilliseconds) { Context.Revision = payload.Revision; Context.ConnectionTimestampOffset = offsetMilliseconds; NetBuffer buffer = payload.RevisionData; while (buffer.Remaining >= (sizeof(byte) + sizeof(ushort))) { ushort entityID = buffer.ReadUShort(); ushort typeID = buffer.ReadVWidth(); // This could fail if not enough bytes remaining. while (entityID >= SyncSlots.Length) { ResizeSyncHandleArray(); } bool skipUpdate = false; SyncHandle handle = GetHandle(entityID); if (handle == null) { if (SyncSlots[entityID].Revision > Context.Revision) { // The revision contains content for a deleted entity. skipUpdate = true; } else { // We are talking about an new entity. SpawnEntity(entityID, typeID, Context.Revision); } } else if (handle.Sync.TypeID != typeID) { // We have a type missmatch. if (handle.Sync.Revision < Context.Revision) { // Entity already exists, but is incorrect type and wrong revision // Assume it should have been deleted and recreate it. RemoveHandle(entityID, Context.Revision); SpawnEntity(entityID, typeID, Context.Revision); } else { // Entity is new type, and has a newer revision. Do not disturb it. skipUpdate = true; } } if (skipUpdate) { EntityGenerator.GetEntityFactory(typeID).SkipFromBuffer(buffer); } else { SyncSlots[entityID].Handle.Sync.ReadFromBuffer(buffer, Context); } } }
public async Task <IList <TEntity> > ListAsync(CancellationToken cancellationToken) { return(await Task.Run(() => { cancellationToken.ThrowIfCancellationRequested(); var scan = PrepareScan(); var client = _pool.GetClient(); var scanner = client.scannerOpenWithScan(_tableName, scan, new Dictionary <byte[], byte[]>()); var data = client.scannerGetList(scanner, _limit); _pool.ReleaseClient(client); return data; }, cancellationToken) .ContinueWith(x => { cancellationToken.ThrowIfCancellationRequested(); if (x.Result.Count == 0) { return new List <TEntity>(); } var generator = new EntityGenerator <TEntity>(_map); return generator.BuildEntities(x.Result); }, cancellationToken)); }
public GetOrganizationByIdTests() { _organizationList = EntityGenerator.GetOrganizationEntityList(1, PublishingStatusCache); _publishedOrganization = _organizationList.Where(o => o.PublishingStatusId == PublishedId).FirstOrDefault(); _publishedOrganizationId = _publishedOrganization.Id; _publishedOrganizationRootId = _publishedOrganization.UnificRootId; }
public void Edit_ValidStudentData_Success() { string expectedLastName = "Wood"; string previousLastName = "Dubois"; string previousFirstName = "George"; string previuosEmail = "*****@*****.**"; string previuosPassowrd = "George"; DateTime date = DateTime.Now; EntityGenerator generator = new EntityGenerator(dbContext); Student student = generator.CreateStudent(previousLastName, previousFirstName, previuosEmail, previuosPassowrd, date); student.LastName = expectedLastName; FormDataHelper.PopulateFormData(controllerToTest, student); var result = controllerToTest.EditPost(student.ID, null) as ViewResult; Student savedStudent = dbContext.Students.Find(student.ID); Assert.That(result, Is.Not.Null); Assert.That((result.Model as Student).LastName, Is.EqualTo(expectedLastName)); Assert.That(savedStudent.LastName, Is.EqualTo(expectedLastName)); }
protected Response Generate(string scope, string app) { Response response = new Response(); try { EntityGenerator generator = _kernel.Get <EntityGenerator>(); string compilerVersion = "v4.0"; if (!string.IsNullOrEmpty(_settings["CompilerVersion"])) { compilerVersion = _settings["CompilerVersion"]; } Response genRes = generator.Generate(compilerVersion, _dbDictionary, scope, app); response.Append(genRes); } catch (Exception ex) { _logger.Error(string.Format("Error refreshing dictionary {0}:", ex)); response.Level = StatusLevel.Error; response.Messages.Add(ex.Message); } return(response); }
public void Edit_ValidStudentData_Success() { string expectedLastName = "Wood"; string previousLastName = "Dubois"; string previousFirstName = "George"; EntityGenerator generator = new EntityGenerator(dbContext); Student student = generator.CreateStudent(previousLastName, previousFirstName); student.LastName = expectedLastName; FormDataHelper.PopulateFormData(controllerToTest, student); var stream = new MemoryStream(Encoding.UTF8.GetBytes("whatever")); MyTestPostedFileBase test = new MyTestPostedFileBase(stream, "whatever", "testImage.png"); var result = controllerToTest.EditPost(student.ID, test) as ViewResult; Student savedStudent = dbContext.Students.Find(student.ID); Assert.That(result, Is.Not.Null); Assert.That((result.Model as Student).LastName, Is.EqualTo(expectedLastName)); Assert.That(savedStudent.LastName, Is.EqualTo(expectedLastName)); }
public void Archived_OnlyOnePerRootIdReturned() { var rootId = Guid.NewGuid(); // Let's create two version for same root organization var deletedItem = EntityGenerator.CreateEntity <OrganizationVersioned, Model.Models.Organization, OrganizationLanguageAvailability>(PublishingStatusCache.Get(PublishingStatus.Deleted), rootId); deletedItem.UnificRoot = new Model.Models.Organization { Id = rootId }; var oldPublishedItem = EntityGenerator.CreateEntity <OrganizationVersioned, Model.Models.Organization, OrganizationLanguageAvailability>(PublishingStatusCache.Get(PublishingStatus.OldPublished), rootId); oldPublishedItem.UnificRoot = new Model.Models.Organization { Id = rootId }; var list = new List <OrganizationVersioned> { deletedItem, oldPublishedItem }; var result = ArrangeAndAct(null, list, 1, 1, true); // Assert result.Should().NotBeNull(); result.PageCount.Should().Be(1);// Only one item per root should be found var vmResult = Assert.IsType <VmOpenApiOrganizationGuidPage>(result); vmResult.ItemList.Count.Should().Be(1); }
public void ApplyIncludesReturnsNull() { // Arrange var organizationList = EntityGenerator.GetOrganizationEntityList(1, PublishingStatusCache); var deletedOrganization = organizationList.Where(o => o.PublishingStatusId == DeletedId).FirstOrDefault(); var id = deletedOrganization.Id; var unitOfWork = unitOfWorkMockSetup.Object; var contextManager = new TestContextManager(unitOfWork, unitOfWork); var serviceUtilities = new ServiceUtilities(UserIdentification, LockingManager, contextManager, UserOrganizationService, VersioningManager, UserInfoService, UserOrganizationChecker); translationManagerMockSetup.Setup(t => t.Translate <OrganizationVersioned, VmOpenApiOrganizationSaha>(deletedOrganization)) .Returns(new VmOpenApiOrganizationSaha()); var translationManagerMock = translationManagerMockSetup.Object; VersioningManagerMock.Setup(s => s.GetVersionId <OrganizationVersioned>(unitOfWork, id, PublishingStatus.Published, true)).Returns(Guid.NewGuid()); OrganizationRepoMock.Setup(g => g.All()).Returns(organizationList.AsQueryable()); var service = new DataAccess.Services.OrganizationService(contextManager, translationManagerMock, TranslationManagerVModel, Logger, OrganizationLogic, serviceUtilities, DataUtils, CommonService, AddressService, PublishingStatusCache, LanguageCache, VersioningManager, UserOrganizationChecker, CacheManager.TypesCache); // Act Action act = () => service.GetOrganizationSahaById(id); // Assert act.ShouldThrow <Exception>(); }
public void ServicesFound_AreaType_MunicipalityWithinArea() { // Arrange var services = EntityGenerator.GetServiceEntityList(1, PublishingStatusCache); var publishedService = services.Where(o => o.PublishingStatusId == PublishedId).FirstOrDefault(); publishedService.AreaInformationTypeId = TypeCache.Get <AreaInformationType>(AreaInformationTypeEnum.AreaType.ToString()); publishedService.AreaMunicipalities = new List <ServiceAreaMunicipality> { new ServiceAreaMunicipality { MunicipalityId = _municipalityId } }; // service var service = ArrangeAndGetService(services, true); // Act var result = service.GetServicesByMunicipality(_municipalityId, null, 1, 1); // Assert result.Should().NotBeNull(); result.PageCount.Should().Be(1); var vmResult = Assert.IsType <V3VmOpenApiGuidPage>(result); vmResult.ItemList.Should().NotBeNullOrEmpty(); vmResult.ItemList.Count().Should().Be(1); }
public async Task <TEntity> SingleOrDefaultAsync(CancellationToken cancellationToken) { // Cannot spawn an IO-Bound task because internal thrift limitation (does not expose any IO bound methods) return(await Task.Run(() => { cancellationToken.ThrowIfCancellationRequested(); var cols = ConvertToByteArrays(_columns); var rows = ConvertToByteArrays(_rows); var client = _pool.GetClient(); var data = client.getRowsWithColumns(_tableName, rows.Count > 0 ? rows : null, cols.Count > 0 ? cols : null, null); _pool.ReleaseClient(client); return data; }, cancellationToken) .ContinueWith(x => { cancellationToken.ThrowIfCancellationRequested(); if (x.Result.Count > 1) { throw new CommandException($"Expected 1 result, got {x.Result.Count}"); } if (x.Result.Count == 0) { return default(TEntity); } var generator = new EntityGenerator <TEntity>(_map); return generator.BuildEntity(x.Result.Single()); }, cancellationToken)); }
public async Task <IList <TEntity> > ListAsync(CancellationToken cancellationToken) { return(await Task.Run(() => { cancellationToken.ThrowIfCancellationRequested(); var cols = ConvertToByteArrays(_columns); var rows = ConvertToByteArrays(_rows); var client = _pool.GetClient(); var data = client.getRowsWithColumns(_tableName, rows.Count > 0 ? rows : null, cols.Count > 0 ? cols : null, null); _pool.ReleaseClient(client); return data; }, cancellationToken) .ContinueWith(x => { cancellationToken.ThrowIfCancellationRequested(); if (x.Result.Count == 0) { return new List <TEntity>(); } var generator = new EntityGenerator <TEntity>(_map); return generator.BuildEntities(x.Result); }, cancellationToken)); }
protected InstanceConverter(EntityGenerator <TOutput> factory) { Factory = factory; Instances = new ConcurrentDictionary <int, TOutput>(); NamedInstances = new ConcurrentDictionary <string, TOutput>(); InstancesMap = new ConcurrentDictionary <TInput, IEnumerable <TOutput> >(); }
public void Active_OnlyOnePerRootIdReturned() { var rootId = Guid.NewGuid(); // Let's create two versions for same root channel var publishedItem = EntityGenerator.CreateEntity <ServiceChannelVersioned, ServiceChannel, ServiceChannelLanguageAvailability>(PublishingStatusCache.Get(PublishingStatus.Published), rootId); publishedItem.UnificRoot = new ServiceChannel { Id = rootId }; var modifiedItem = EntityGenerator.CreateEntity <ServiceChannelVersioned, ServiceChannel, ServiceChannelLanguageAvailability>(PublishingStatusCache.Get(PublishingStatus.Modified), rootId); modifiedItem.UnificRoot = new ServiceChannel { Id = rootId }; var list = new List <ServiceChannelVersioned> { publishedItem, modifiedItem }; var result = ArrangeAndAct(null, list, 1, 1, false, true); // Assert result.Should().NotBeNull(); result.PageCount.Should().Be(1);// Only one item per root should be found var vmResult = Assert.IsType <V3VmOpenApiGuidPage>(result); vmResult.ItemList.Count.Should().Be(1); }
public void ReadPrototypes(string pathXml) { if (File.Exists(pathXml)) { XmlReaderSettings settings = new XmlReaderSettings(); XmlReader reader = XmlReader.Create(pathXml, settings); reader.ReadToFollowing("Generators"); int count = 0; while (reader.Read()) { switch (reader.Name) { case "PlanetGenerator": case "ShipGenerator": count++; EntityGenerator pg = new EntityGenerator(reader); generators[reader.Name][pg.Id] = pg; break; } } Debug.LogFormat("Loaded {0} Generators prototypes.", count); } else { Debug.LogErrorFormat("File '{0}' not found.", pathXml); } }
/// <summary> /// Creates an entity generator. /// </summary> /// <returns></returns> // mbr - 21-09-2007 - changed this to also return a context. internal EntityGenerator GetEntityGenerator(Project project, ref EntityGenerationContext context) { if (project == null) { throw new ArgumentNullException("project"); } if (project.Settings == null) { throw new InvalidOperationException("project.Settings is null."); } // mbr - 21-09-2007 - do the context. context = null; // create... EntityGenerator generator = new EntityGenerator(project.Settings.TargetVersion); generator.CompilationOptions.DatabaseName = project.Settings.DatabaseName; generator.DefaultNamespaceName = project.Settings.NamespaceName; generator.EntityBaseTypeName = project.Settings.BaseType; generator.DtoBaseTypeName = project.Settings.DtoBaseType; // setup... context = new EntityGenerationContext(generator, null, null); // return... return(generator); }
public IList <TEntity> List() { var result = ExtractResult(); var generator = new EntityGenerator <TEntity>(_map); return(generator.BuildEntities(result)); }
/// <summary> /// Default constructor for CSharpClientCodeGenerator. It initializes contained generators with their default values. /// </summary> public CSharpClientCodeGenerator() { this._webContextGenerator = new CSharpWebContextGenerator(); this._entityProxyGenerator = new CSharpEntityGenerator(); this._complexObjectGenerator = new CSharpComplexObjectGenerator(); this._domainContextGenerator = new CSharpDomainContextGenerator(); this._enumGenerator = new CSharpEnumGenerator(); }
public void SupplyingStartingValueAndStep() { var generator = new EntityGenerator<SomethingToGenerate>() .Counter(e => e.MyProperty, 5, 2); Assert.Equal(5, generator.One().MyProperty); Assert.Equal(7, generator.One().MyProperty); Assert.Equal(9, generator.One().MyProperty); }
public void SimpleAppend() { var generator = new EntityGenerator<SomethingToGenerate>() .Counter(e => e.MyProperty); Assert.Equal(1, generator.One().MyProperty); Assert.Equal(2, generator.One().MyProperty); Assert.Equal(3, generator.One().MyProperty); }
public void SupplyingFullValue() { var generator = new EntityGenerator<SomethingToGenerate>() .AppendCounter(e => e.MyProperty, () => "SomeString"); Assert.Equal("SomeString1", generator.One().MyProperty); Assert.Equal("SomeString2", generator.One().MyProperty); Assert.Equal("SomeString3", generator.One().MyProperty); }
public void DerivedPropertyIsIgnored() { var something = new EntityGenerator<SomethingDerivedToGenerate>() .With(42) .Ignore(e => e.PropertyToBeIgnored) .One(); Assert.Equal(0, something.PropertyToBeIgnored); }
public void SimpleAppend() { var generator = new EntityGenerator<SomethingToGenerate>() .For(e => e.MyProperty, "SomeString") .AppendCounter(e => e.MyProperty); Assert.Equal("SomeString1", generator.One().MyProperty); Assert.Equal("SomeString2", generator.One().MyProperty); Assert.Equal("SomeString3", generator.One().MyProperty); }
public void CounterOnly() { var generator = new EntityGenerator<SomethingToGenerate>() .AppendCounter(e => e.MyProperty); // the value starts with a random string, and : Assert.True(generator.One().MyProperty.EndsWith("1")); Assert.True(generator.One().MyProperty.EndsWith("2")); Assert.True(generator.One().MyProperty.EndsWith("3")); }
public async Task<IHttpActionResult> Upload() { Repository repo = new Repository(); var users = repo.Users.Any(); var gen = new EntityGenerator<TestModel>(); var model = await gen.FromMultipartFormData(Request.Content, typeof(TestModel)); if (model != null) return Ok(); else return InternalServerError(); }
public void GeneratorIsApplied() { var generator = new EntityGenerator<SomethingToGenerate>() .For(e => e.MyProperty, GetNext); var thing1 = generator.One(); Assert.Equal(1, thing1.MyProperty); var thing2 = generator.One(); Assert.Equal(2, thing2.MyProperty); var thing3 = generator.One(); Assert.Equal(3, thing3.MyProperty); }
public void GeneratorIsApplied() { var generator = new EntityGenerator<Something>() .For(e => e.Value, new IntGenerator(42, 42), new IntGenerator(43, 43)); var is42 = false; var is43 = false; 20.Times( () => { is42 = is42 || generator.One().Value == 42; is43 = is43 || generator.One().Value == 43; }); Assert.True(is42); Assert.True(is43); }
public IgnoreTests() { generator = new EntityGenerator<SomethingToGenerate>() .Ignore(e => e.MyProperty); }
public ManyTests() { generator = new EntityGenerator<SomethingToGenerate>(); }
public DynamicValueConventionTests() { domainGenerator = new EntityGenerator<SomethingToGenerate>() .With(mi => mi.Name == "MyProperty", () => GetNextProductId()); }
private static SyntaxNode GenerateEntity( Language language, Solution solution, Compilation compilation, IImmutableList<INamedTypeSymbol> interfaceSymbols, Func<INamedTypeSymbol, string> entityNamespaceSelector, Func<INamedTypeSymbol, string> entityNameSelector, Func<INamedTypeSymbol, Accessibility> entityAccessibilitySelector, INamedTypeSymbol interfaceSymbol) { var syntaxGenerator = SyntaxGenerator.GetGenerator(solution.Workspace, language.ToSyntaxGeneratorLanguageName()); var generator = new EntityGenerator( language, syntaxGenerator, solution, compilation, interfaceSymbols, entityNamespaceSelector, entityNameSelector, entityAccessibilitySelector, interfaceSymbol); return generator .Generate() .NormalizeWhitespace(); }
private void Generate(string projectName, string applicationname) { if (_databaseDictionary != null && _databaseDictionary.dataObjects != null) { EntityGenerator generator = new EntityGenerator(_settings); string compilerVersion = "v4.0"; if (!String.IsNullOrEmpty(_settings["CompilerVersion"])) { compilerVersion = _settings["CompilerVersion"]; } generator.Generate(compilerVersion, _databaseDictionary, projectName, applicationname); } }
public SpecificValueTests() { domainGenerator = new EntityGenerator<SomethingToGenerate>() .For(e => e.Property, 42); }