예제 #1
0
            public void ShouldReturnResultValueFromDictionaryWhenTypeIsInCache()
            {
                // Given
                var cache = new TypeCache<Exception>();
                var initialValue = cache.Get<ArgumentNullException>(() => new ArgumentNullException());

                // When
                var value = cache.Get<ArgumentNullException>(() => new ArgumentNullException());

                // Then
                value.Should().BeSameAs(initialValue);
            }
        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);
        }
예제 #3
0
        public async Task <LangCulture[]> Execute(string domain)
        {
            var langCultures = _typeCache.Get(domain);

            if (langCultures != null)
            {
                return(langCultures);
            }

            langCultures = await _dbContext
                           .Set <LangCulture>()
                           .Include(lc => lc.Language)
                           .Where(lc => lc.Countryes.Any(c => c.HttpDomains.Any(d => d.Name == domain)))
                           .ToArrayAsync();

            if (!langCultures.Any())
            {
                langCultures = await _dbContext
                               .Set <LangCulture>()
                               .Include(lc => lc.Language)
                               .Where(lc => lc.Countryes.Any(c => c.HttpDomains.Any(d => d.Name == null)))
                               .ToArrayAsync();
            }

            foreach (var langCulture in langCultures)
            {
                await LocalizeItem(langCulture);
            }

            _typeCache.Set(domain, langCultures);
            return(langCultures);
        }
예제 #4
0
        public static TypeOnStack Get(Type type)
        {
            if (TypeHelpers.ContainsGenericParameters(type))
            {
                throw new InvalidOperationException("Sigil does not currently support generic types; found " + type);
            }

            if (type == typeof(char))
            {
                type = typeof(ushort);
            }

            var ret = TypeCache.Get(type);

            return
                (new TypeOnStack
            {
                CallingConvention = ret.CallingConvention,
                HasAttachedMethodInfo = ret.HasAttachedMethodInfo,
                InstanceType = ret.InstanceType,
                ParameterTypes = ret.ParameterTypes,
                ReturnType = ret.ReturnType,
                Type = ret.Type,
                UsedBy = new LinqHashSet <SigilTuple <InstructionAndTransitions, int> >()
            });
        }
        private ChannelService Arrange(ServiceChannelTypeEnum channelType, List <ServiceChannelVersioned> list = null)
        {
            var channelList      = list ?? _channelList;
            var publishedChannel = channelList.Where(o => o.PublishingStatusId == PublishedId).FirstOrDefault();

            publishedChannel.TypeId = TypeCache.Get <ServiceChannelType>(channelType.ToString());
            var id = publishedChannel.Id;

            unitOfWorkMockSetup.Setup(uw => uw.ApplyIncludes(
                                          It.IsAny <IQueryable <ServiceChannelVersioned> >(),
                                          It.IsAny <Func <IQueryable <ServiceChannelVersioned>, IQueryable <ServiceChannelVersioned> > >(),
                                          It.IsAny <bool>()
                                          )).Returns((IQueryable <ServiceChannelVersioned> channelServices, Func <IQueryable <ServiceChannelVersioned>, IQueryable <ServiceChannelVersioned> > func, bool applyFilters) =>
            {
                return(channelServices);
            }
                                                     );
            var unitOfWork     = unitOfWorkMockSetup.Object;
            var contextManager = new TestContextManager(unitOfWork, unitOfWork);

            var serviceUtilities = new ServiceUtilities(UserIdentification, LockingManager, contextManager, UserOrganizationService,
                                                        VersioningManager, UserInfoService, UserOrganizationChecker);

            ArrangeTranslationManager(channelType);

            VersioningManagerMock.Setup(s => s.GetVersionId <ServiceChannelVersioned>(unitOfWork, _publishedChannelRootId, PublishingStatus.Published, true)).Returns(id);

            // repositories
            ChannelRepoMock.Setup(g => g.All()).Returns(channelList.AsQueryable());

            return(new ChannelService(contextManager, UserIdentification, translationManagerMockSetup.Object, TranslationManagerVModel,
                                      Logger, ServiceChannelLogic, serviceUtilities, CommonService, new VmListItemLogic(), DataUtils, new VmOwnerReferenceLogic(),
                                      AddressService, CacheManager, PublishingStatusCache, VersioningManager, UserOrganizationChecker, UrlService));
        }
        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);
        }
예제 #7
0
        public static void AddTypeToCache <T>(IDbConnection connection) where T : new()
        {
            if (VerifiedTypesCache.Contains(typeof(T)))
            {
                return;
            }

            var sqlConnection = connection as SqlConnection;

            if (sqlConnection == null)
            {
                return;
            }

            VerifiedTypesCache.Add(typeof(T));

            var tableName = HopBase.GetTypeToTableNameService(typeof(T));

            var columns =
                connection
                .Hop()
                .ReadTuples <Tuple <string, int>, T>("column_name, ordinal_position", string.Format("table_name = '{0}'", tableName), "information_schema.columns")
                .ToList();

            var unMatchedProperties = TypeCache.Get <T>().Properties.Where(x => columns.All(y => y.Item1 != x.Name)).ToList();

            if (!unMatchedProperties.Any())
            {
                return;
            }

            var sb = new StringBuilder();

            //create table if no column found
            if (!columns.Any())
            {
                var propertyInfo = TypeCache.Get <T>().IdProperty;
                unMatchedProperties = unMatchedProperties.Where(x => x != TypeCache.Get <T>().IdProperty).ToList();
                sb.AppendLine(string.Format("CREATE TABLE {0}({1} {2} PRIMARY KEY {3});", tableName, propertyInfo.Name, GetSqlString(GetSqlType(propertyInfo.PropertyType)), propertyInfo.PropertyType == typeof(int) ? "IDENTITY" : string.Empty));
            }

            foreach (var source in unMatchedProperties)
            {
                sb.Append(string.Format("ALTER TABLE  {0} ", tableName));
                var sqlDbType = GetSqlType(source.PropertyType);
                sb.AppendLine(string.Format(" ADD {0} {1}", source.Name, GetSqlString(sqlDbType)));
            }

            using (var dbCommand = connection.CreateCommand())
            {
                dbCommand.CommandText = sb.ToString();

                connection.Open();
                dbCommand.ExecuteNonQuery();
                connection.Close();
            }
        }
예제 #8
0
        static HopBase()
        {
            GetGeneratorService    = () => new MsilGeneratorService();
            GetIdExtractorService  = () => new ReflectionBasedIdExtractorService();
            GetMaterializerService = () => new IlBasedMaterializerService();

            //define default services
            GetTypeToTableNameService = type => TypeCache.Get(type).TableName;
            GetIdPropertyService      = type => TypeCache.Get(type).IdProperty;
        }
예제 #9
0
            public void ShouldReturnResultOfValueFactoryWhenTypeIsNotInCache()
            {
                // Given
                var cache = new TypeCache<object>();

                // When
                var value = cache.Get<string>(() => "value");

                // Then
                value.Should().Be("value");
            }
예제 #10
0
        public static void Update <T>(this IHop hopper, IEnumerable <T> instances) where T : new()
        {
            SchemaVerifierService.AddTypeToCache <T>(hopper.Connection);

            IIdExtractorService idExtractorService = HopBase.GetIdExtractorService();
            List <T>            instanceList       = instances as List <T> ?? instances.ToList();

            var sb           = new StringBuilder();
            int paramCounter = 0;

            using (var dbCommand = new SqlCommand())
            {
                dbCommand.Connection = (SqlConnection)hopper.Connection;

                foreach (T inst in instanceList)
                {
                    sb.AppendLine(string.Format("UPDATE {0} SET ", HopBase.GetTypeToTableNameService(typeof(T))));

                    sb.AppendLine(
                        TypeCache.Get <T>().PropertiesWithoutId
                        .Select((x, i) =>
                    {
                        string paramName = string.Format("@param{0}{1}", paramCounter, i);
                        object value     = x.GetValue(inst, null);
                        if (value == null)
                        {
                            return(string.Empty);
                        }
                        dbCommand.Parameters.Add(new SqlParameter(paramName, value));
                        return(string.Format("{0} = {1}", x.Name, paramName));
                    })
                        .Where(x => x != string.Empty)
                        .Aggregate((set1, set2) => set1 + ", " + set2));

                    object instanceId = idExtractorService.GetId(inst);

                    if (instanceId == null || HopBase.GetDefault(instanceId.GetType()).Equals(instanceId))
                    {
                        throw new HopUpdateWithoutKeyException(inst);
                    }

                    sb.AppendLine(string.Format(" WHERE {0} = {1}", idExtractorService.GetIdField <T>(), instanceId));
                    paramCounter++;
                }

                dbCommand.CommandText = sb.ToString();
                dbCommand.Connection.Open();
                dbCommand.ExecuteNonQuery();
                dbCommand.Connection.Close();
            }
        }
예제 #11
0
        static IEnumerable <(string name, string value)> GetProperties(object obj)
        {
            var(fields, properties) = TypeCache.Get(obj.GetType());

            foreach (var x in fields)
            {
                yield return(name : x.Name.Camelize(), value : x.GetValue(obj)?.ToString() ?? "[null]");
            }

            foreach (var x in properties)
            {
                yield return(name : x.Name.Camelize(), value : x.GetValue(obj)?.ToString() ?? "[null]");
            }
        }
예제 #12
0
        private static void CollectFromInterfacesByValueType(HashSet <Type> drawers, Type targetType)
        {
            var interfaces = TypeCache.Get(targetType).MostDerivedInterfaces;

            foreach (var i in interfaces)
            {
                var drawer = GetByValueTypeImpl(i);
                if (drawer != null)
                {
                    drawers.Add(drawer);
                }
                CollectFromInterfacesByValueType(drawers, i);
            }
        }
예제 #13
0
        private object ReadObject(Stream input, ValueTag tag, Type objectType)
        {
            if (objectType == null)
            {
                throw new ArgumentNullException("objectType");
            }

            if (objectType == typeof(object) || objectType == typeof(Dictionary <string, object>))
            {
                throw new ArgumentException("objectType");
            }

            var length       = input.ReadPackedValueUInt32();
            var basePosition = input.Position;
            var endPosition  = basePosition + length;

            if (endPosition > input.Length)
            {
                throw new EndOfStreamException();
            }

            var typeInfo = TypeCache.Get(objectType);
            var instance = Activator.CreateInstance(objectType);

            var propertyTag = new ValueTag(input.ReadValueU8());

            while (propertyTag.Type != ValueType.Invalid)
            {
                var          propertyName = input.ReadStringZ(Encoding.UTF8);
                PropertyInfo propertyInfo;
                if (typeInfo.Properties.TryGetValue(propertyName, out propertyInfo) == false)
                {
                    throw new InvalidOperationException(
                              string.Format("Property '{0}' not found on '{1}'",
                                            propertyName,
                                            objectType.FullName));
                }
                var propertyValue = this.ReadValue(input, propertyTag, propertyInfo.PropertyType);
                propertyInfo.SetValue(instance, propertyValue, null);
                propertyTag = new ValueTag(input.ReadValueU8());
            }

            if (input.Position != endPosition)
            {
                throw new FormatException();
            }

            return(instance);
        }
        private DataAccess.Services.OrganizationService ArrangeAndGetService(IList <OrganizationVersioned> organizations, bool isAland = false)
        {
            var publishedOrganization = organizations.Where(o => o.PublishingStatusId == PublishedId).FirstOrDefault();

            if (isAland)
            {
                _areaRepoMock.Setup(g => g.All()).Returns(new List <Area>()
                {
                    new Area
                    {
                        Id         = _areaId,
                        AreaTypeId = TypeCache.Get <AreaType>(AreaTypeEnum.Province.ToString()),
                        Code       = "20"
                    }
                }.AsQueryable());
            }
            else
            {
                _areaRepoMock.Setup(g => g.All()).Returns(new List <Area>().AsQueryable());
            }

            unitOfWorkMockSetup.Setup(uw => uw.ApplyIncludes(
                                          It.IsAny <IQueryable <OrganizationVersioned> >(),
                                          It.IsAny <Func <IQueryable <OrganizationVersioned>, IQueryable <OrganizationVersioned> > >(),
                                          It.IsAny <bool>()
                                          )).Returns((IQueryable <OrganizationVersioned> list, Func <IQueryable <OrganizationVersioned>, IQueryable <OrganizationVersioned> > func, bool applyFilters) =>
            {
                return(list);
            });

            var organizationMock = new Mock <IOrganizationVersionedRepository>();

            organizationMock.Setup(o => o.All()).Returns(organizations.AsQueryable());
            unitOfWorkMockSetup.Setup(uw => uw.CreateRepository <IRepository <OrganizationVersioned> >()).Returns(organizationMock.Object);

            var unitOfWorkMock = unitOfWorkMockSetup.Object;

            var contextManager = new TestContextManager(unitOfWorkMock, unitOfWorkMock);

            var serviceUtilities = new ServiceUtilities(UserIdentification, LockingManager, contextManager, UserOrganizationService,
                                                        VersioningManager, UserInfoService, UserOrganizationChecker);

            // service
            return(new DataAccess.Services.OrganizationService(contextManager, translationManagerMockSetup.Object, TranslationManagerVModel, Logger, OrganizationLogic,
                                                               serviceUtilities, DataUtils, CommonService, AddressService, PublishingStatusCache, LanguageCache,
                                                               VersioningManager, UserOrganizationChecker, CacheManager.TypesCache));
        }
예제 #15
0
        public Materializer <T> CreateMaterializer <T>()
        {
            var baseType       = typeof(Materializer <T>);
            var localType      = TypeCache.Get <T>();
            var emptyArgsArray = new Type[] {};

            var typeBuilderHelper = AssemblyBuilder.DefineType(localType.Type.Name + "Materializer", baseType);

            //constructor
            typeBuilderHelper.DefaultConstructor.Emitter.ldarg_0.call(baseType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, emptyArgsArray, null)).ret();

            //getobject impl
            var defineMethod = typeBuilderHelper.DefineMethod(baseType.GetMethod("GetObject"));

            var emitter   = defineMethod.Emitter;
            var returnVar = emitter.DeclareLocal(localType.Type);

            //create new T
            emitter
            .newobj(localType.Type.GetConstructor(emptyArgsArray))
            .stloc(returnVar);

            foreach (var propertyInfo in localType.Properties)
            {
                emitter =
                    emitter
                    .ldloc_0
                    .ldarg_0
                    .ldarg_1
                    .ldstr(propertyInfo.Name)
                    .ldloc_0
                    .callvirt(propertyInfo.GetGetMethod())
                    .call(baseType.GetMethod("GetValue").MakeGenericMethod(propertyInfo.PropertyType))
                    .callvirt(propertyInfo.GetSetMethod())
                    .nop;
            }

            emitter
            .ldloc_0
            .ret();

            var type = typeBuilderHelper.Create();

            AssemblyBuilder.Save();

            return((Materializer <T>)Activator.CreateInstance(type));
        }
예제 #16
0
        private ChannelService Arrange(IVmOpenApiServiceChannelIn vm, ServiceChannelTypeEnum channelType)
        {
            var userName = "******";

            publishedEntity.TypeId = TypeCache.Get <ServiceChannelType>(channelType.ToString());

            unitOfWorkMockSetup.Setup(uw => uw.ApplyIncludes(
                                          It.IsAny <IQueryable <ServiceChannelVersioned> >(),
                                          It.IsAny <Func <IQueryable <ServiceChannelVersioned>, IQueryable <ServiceChannelVersioned> > >(),
                                          It.IsAny <bool>()
                                          )).Returns(new List <ServiceChannelVersioned> {
                publishedEntity
            }.AsQueryable());
            var unitOfWork = unitOfWorkMockSetup.Object;

            var contextManager = new TestContextManager(unitOfWork, unitOfWork);

            UserIdentificationMock.Setup(s => s.UserName).Returns(userName);
            ExternalSourceRepoMock.Setup(s => s.All())
            .Returns(new List <ExternalSource>()
            {
                new ExternalSource {
                    SourceId = sourceId + "2", RelationId = userName, ObjectType = typeof(Model.Models.ServiceChannel).Name
                }
            }.AsQueryable());     // does not return same source id

            var serviceUtilities = new ServiceUtilities(UserIdentificationMock.Object, LockingManager, contextManager, UserOrganizationService,
                                                        VersioningManager, UserInfoService, UserOrganizationChecker);

            translationManagerVModelMockSetup.Setup(t => t.Translate <IVmOpenApiServiceChannelIn, ServiceChannelVersioned>(vm, unitOfWork))
            .Returns(publishedEntity);
            translationManagerVModelMockSetup.Setup(t => t.TranslateAll <VmOpenApiConnection, ServiceServiceChannel>(It.IsAny <List <VmOpenApiConnection> >(), unitOfWork))
            .Returns(new List <ServiceServiceChannel>());

            ArrangeTranslationManager(channelType);

            CommonServiceMock.Setup(s => s.PublishAllAvailableLanguageVersions <ServiceChannelVersioned, ServiceChannelLanguageAvailability>(publishedEntity.Id, It.IsAny <Expression <Func <ServiceChannelLanguageAvailability, bool> > >()))
            .Returns(new PublishingResult());

            return(new ChannelService(contextManager, UserIdentification, translationManagerMockSetup.Object, TranslationManagerVModel,
                                      Logger, ServiceChannelLogic, serviceUtilities, CommonService, new VmListItemLogic(), DataUtils, new VmOwnerReferenceLogic(),
                                      AddressService, CacheManager, PublishingStatusCache, VersioningManager, UserOrganizationChecker, UrlService));
        }
예제 #17
0
        /// <summary>
        /// Inserts a collection of entities to the database
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="hopper"></param>
        /// <param name="instances">Collection to insert</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void Insert <T>(this IHop hopper, ICollection <T> instances) where T : new()
        {
            if (instances == null)
            {
                throw new ArgumentNullException("instances", "Please provide a non null value to parameter instances");
            }

            if (!instances.Any())
            {
                return;
            }

            SchemaVerifierService.AddTypeToCache <T>(hopper.Connection);

            var propertyInfos = TypeCache.Get <T>().PropertiesWithoutId;
            var objects       =
                instances
                .Select(objToInsert =>
                        propertyInfos
                        .Select(prop => prop.GetValue(objToInsert, null).ToSqlString())
                        .Aggregate((field1, field2) => field1 + ", " + field2)
                        );

            var tableName  = HopBase.GetTypeToTableNameService(typeof(T));
            var columnList =
                propertyInfos
                .Select(x => x.Name)
                .Aggregate((field1, field2) => field1 + ", " + field2);

            var intoClause   = string.Format("{0} ({1})", tableName, columnList);
            var valuesClause =
                objects
                .Select(x => "(" + x + ")")
                .Aggregate((obj1, obj2) => obj1 + ", " + obj2);

            var lastId = hopper.Insert <T>(intoClause, valuesClause);

            foreach (T source in instances.Reverse())
            {
                HopBase.GetIdExtractorService().SetId(source, lastId--);
            }
        }
        public void ServicesFound_WholeCountryExceptAland_MunicipalityInAland()
        {
            // Arrange
            var services         = EntityGenerator.GetServiceEntityList(1, PublishingStatusCache);
            var publishedService = services.Where(o => o.PublishingStatusId == PublishedId).FirstOrDefault();

            publishedService.AreaInformationTypeId = TypeCache.Get <AreaInformationType>(AreaInformationTypeEnum.WholeCountryExceptAlandIslands.ToString());

            // service
            var service = ArrangeAndGetService(services, true);

            // Act
            var result = service.GetServicesByMunicipality(_municipalityId, null, 1, 1);

            // Assert
            result.Should().NotBeNull();
            result.PageCount.Should().Be(0);
            var vmResult = Assert.IsType <V3VmOpenApiGuidPage>(result);

            vmResult.ItemList.Should().BeNullOrEmpty();
        }
        public void GetLatestActiveServiceChannel(PublishingStatus publishingStatus)
        {
            // Arrange
            var channelType = ServiceChannelTypeEnum.ServiceLocation;
            var item        = _channelList.Where(i => i.PublishingStatusId == PublishingStatusCache.Get(publishingStatus)).FirstOrDefault();

            item.TypeId = TypeCache.Get <ServiceChannelType>(channelType.ToString());
            var rootId = item.UnificRootId;
            var id     = item.Id;

            VersioningManagerMock.Setup(s => s.GetVersionId <ServiceChannelVersioned>(unitOfWorkMockSetup.Object, rootId, null, true))
            .Returns(() =>
            {
                if (publishingStatus == PublishingStatus.Deleted || publishingStatus == PublishingStatus.OldPublished)
                {
                    return(null);
                }

                return(id);
            });

            var service = Arrange(channelType);

            // Act
            var result = service.GetServiceChannelById(rootId, 7, VersionStatusEnum.LatestActive);

            // Assert
            // Method should only return draft, modified or published versions.
            VersioningManagerMock.Verify(x => x.GetVersionId <ServiceChannelVersioned>(unitOfWorkMockSetup.Object, rootId, null, true), Times.Once);
            if (publishingStatus == PublishingStatus.Draft || publishingStatus == PublishingStatus.Modified || publishingStatus == PublishingStatus.Published)
            {
                result.Should().NotBeNull();
                var vmResult = Assert.IsType <V7VmOpenApiServiceLocationChannel>(result);
                vmResult.PublishingStatus.Should().Be(publishingStatus.ToString());
            }
            else
            {
                result.Should().BeNull();
            }
        }
        public void OrganizationsFound_TypeIsMunicipality()
        {
            // Arrange
            var organizations         = EntityGenerator.GetOrganizationEntityList(1, PublishingStatusCache);
            var publishedOrganization = organizations.Where(o => o.PublishingStatusId == PublishedId).FirstOrDefault();

            publishedOrganization.MunicipalityId = _municipalityId;
            publishedOrganization.TypeId         = TypeCache.Get <OrganizationType>(OrganizationTypeEnum.Municipality.ToString());

            // 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);
        }
        public void GetLatestServiceChannel(PublishingStatus publishingStatus)
        {
            // Arrange
            var channelType = ServiceChannelTypeEnum.WebPage;
            var item        = _channelList.Where(i => i.PublishingStatusId == PublishingStatusCache.Get(publishingStatus)).FirstOrDefault();

            item.TypeId = TypeCache.Get <ServiceChannelType>(channelType.ToString());
            var rootId = item.UnificRootId;
            var id     = item.Id;

            VersioningManagerMock.Setup(s => s.GetVersionId <ServiceChannelVersioned>(unitOfWorkMockSetup.Object, rootId, null, false)).Returns(id);
            var service = Arrange(channelType);

            // Act
            var result = service.GetServiceChannelById(rootId, 7, VersionStatusEnum.Latest);

            // Assert
            result.Should().NotBeNull();
            var vmResult = Assert.IsType <V7VmOpenApiWebPageChannel>(result);

            vmResult.PublishingStatus.Should().Be(publishingStatus.ToString());
            VersioningManagerMock.Verify(x => x.GetVersionId <ServiceChannelVersioned>(unitOfWorkMockSetup.Object, rootId, null, false), Times.Once);
        }
예제 #22
0
 private PropertyInfo GetKeyProperty()
 {
     return(TypeCache.Get <T>().IdProperty);
 }
예제 #23
0
        public AddServiceTests()
        {
            _serviceId          = Guid.NewGuid();
            _serviceVersionedId = Guid.NewGuid();
            _channelId          = Guid.NewGuid();
            _channelVersionedId = Guid.NewGuid();

            SetupTypesCacheMock <ServiceType>();
            SetupTypesCacheMock <ServiceChargeType>();

            var serviceVersioned = new ServiceVersioned
            {
                Id           = _serviceVersionedId,
                UnificRootId = _serviceId,
                UnificRoot   = new Model.Models.Service()
                {
                    Id = _serviceId,
                    ServiceServiceChannels = new List <ServiceServiceChannel>()
                },
                Organization = new Model.Models.Organization()
            };

            var channelVersioned = EntityGenerator.CreateEntity <ServiceChannelVersioned, ServiceChannel, ServiceChannelLanguageAvailability>(PublishedId, _channelId, _channelVersionedId);

            channelVersioned.UnificRoot = new ServiceChannel {
                Id = _channelId, Versions = new List <ServiceChannelVersioned> {
                    channelVersioned
                }
            };

            var connectionList = new List <ServiceServiceChannel>
            {
                new ServiceServiceChannel {
                    Service          = serviceVersioned.UnificRoot,
                    ServiceId        = serviceVersioned.UnificRootId,
                    ServiceChannel   = channelVersioned.UnificRoot,
                    ServiceChannelId = channelVersioned.UnificRootId
                }
            };

            translationManagerVModelMockSetup.Setup(t => t.Translate <IVmOpenApiServiceInVersionBase, ServiceVersioned>(It.IsAny <IVmOpenApiServiceInVersionBase>(), It.IsAny <IUnitOfWorkWritable>()))
            .Returns((IVmOpenApiServiceInVersionBase x, IUnitOfWorkWritable y) =>
            {
                if (!string.IsNullOrEmpty(x.StatutoryServiceGeneralDescriptionId))
                {
                    serviceVersioned.StatutoryServiceGeneralDescriptionId = x.StatutoryServiceGeneralDescriptionId.ParseToGuid();
                }
                serviceVersioned.PublishingStatusId = PublishingStatusCache.Get(x.PublishingStatus);
                if (x.ServiceNames?.Count > 0)
                {
                    serviceVersioned.ServiceNames = new List <ServiceName>();
                    x.ServiceNames.ForEach(n => serviceVersioned.ServiceNames.Add(new ServiceName {
                        Name = n.Value
                    }));
                }
                if (!string.IsNullOrEmpty(x.Type))
                {
                    serviceVersioned.TypeId = TypeCache.Get <ServiceType>(x.Type);
                }
                if (!string.IsNullOrEmpty(x.ServiceChargeType))
                {
                    serviceVersioned.ChargeTypeId = TypeCache.Get <ServiceChargeType>(x.ServiceChargeType);
                }

                return(serviceVersioned);
            });

            translationManagerVModelMockSetup.Setup(t => t.TranslateAll <VmOpenApiServiceServiceChannelInVersionBase, ServiceServiceChannel>(It.IsAny <List <V7VmOpenApiServiceServiceChannelAstiInBase> >(), It.IsAny <IUnitOfWorkWritable>()))
            .Returns((List <V7VmOpenApiServiceServiceChannelAstiInBase> x, IUnitOfWorkWritable y) =>
            {
                var connections = new List <ServiceServiceChannel>();
                x.ForEach(c =>
                {
                    var cv        = EntityGenerator.CreateEntity <ServiceChannelVersioned, ServiceChannel, ServiceChannelLanguageAvailability>(PublishedId, c.ChannelGuid, _channelVersionedId);
                    cv.UnificRoot = new ServiceChannel {
                        Id = c.ChannelGuid, Versions = new List <ServiceChannelVersioned> {
                            cv
                        }
                    };
                    var connection = new ServiceServiceChannel
                    {
                        ServiceChannelId = c.ChannelGuid,
                        ServiceChannel   = cv.UnificRoot
                    };
                    if (c.Description?.Count > 0)
                    {
                        connection.ServiceServiceChannelDescriptions = new List <ServiceServiceChannelDescription>();
                        c.Description.ForEach(d =>
                        {
                            var description = new ServiceServiceChannelDescription {
                                Description = d.Value
                            };
                            connection.ServiceServiceChannelDescriptions.Add(description);
                        });
                        connections.Add(connection);
                    }
                });
                return(connections);
            });

            ServiceRepoMock.Setup(g => g.All()).Returns((new List <ServiceVersioned> {
                serviceVersioned
            }).AsQueryable());
            ConnectionRepoMock.Setup(g => g.All()).Returns(connectionList.AsQueryable());

            //ServiceChannelRepoMock.Setup(g => g.All()).Returns((new List<ServiceChannelVersioned> { channelVersioned }).AsQueryable());
            unitOfWorkMockSetup.Setup(uw => uw.ApplyIncludes(
                                          It.IsAny <IQueryable <ServiceVersioned> >(),
                                          It.IsAny <Func <IQueryable <ServiceVersioned>, IQueryable <ServiceVersioned> > >(),
                                          It.IsAny <bool>()
                                          )).Returns(new List <ServiceVersioned> {
                serviceVersioned
            }.AsQueryable());

            unitOfWorkMockSetup.Setup(uw => uw.ApplyIncludes(
                                          It.IsAny <IQueryable <ServiceServiceChannel> >(),
                                          It.IsAny <Func <IQueryable <ServiceServiceChannel>, IQueryable <ServiceServiceChannel> > >(),
                                          It.IsAny <bool>()
                                          )).Returns(connectionList.AsQueryable());

            VersioningManagerMock.Setup(s => s.GetVersionId <ServiceVersioned>(unitOfWorkMockSetup.Object, _serviceId, PublishingStatus.Published, true)).Returns(_serviceVersionedId);

            translationManagerMockSetup.Setup(t => t.Translate <ServiceVersioned, VmOpenApiServiceVersionBase>(It.IsAny <ServiceVersioned>()))
            .Returns((ServiceVersioned sv) =>
            {
                var vm = new VmOpenApiServiceVersionBase()
                {
                    Id = sv.UnificRootId,
                    StatutoryServiceGeneralDescriptionId = sv.StatutoryServiceGeneralDescriptionId,
                    PublishingStatus = PublishingStatusCache.GetByValue(sv.PublishingStatusId)
                };
                if (sv.ServiceNames?.Count > 0)
                {
                    vm.ServiceNames = new List <VmOpenApiLocalizedListItem>();
                    sv.ServiceNames.ForEach(n => vm.ServiceNames.Add(new VmOpenApiLocalizedListItem {
                        Value = n.Name
                    }));
                }
                if (sv.UnificRoot?.ServiceServiceChannels?.Count > 0)
                {
                    vm.ServiceChannels = new List <V7VmOpenApiServiceServiceChannel>();
                    sv.UnificRoot.ServiceServiceChannels.ForEach(c =>
                    {
                        var channel = new V7VmOpenApiServiceServiceChannel
                        {
                            ServiceChannel = new VmOpenApiItem {
                                Id = c.ServiceChannelId
                            }
                        };
                        vm.ServiceChannels.Add(channel);
                    });
                }

                return(vm);
            });
        }
예제 #24
0
        static void ISO8601 <T>(T data, TextWriter output, Options options)
        {
            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint && options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <ISO8601PrettyPrintExcludeNullsJSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint && options.IsJSONP)
            {
                TypeCache <ISO8601PrettyPrintExcludeNullsJSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <ISO8601ExcludeNullsJSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint && options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <ISO8601PrettyPrintJSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint && options.ShouldIncludeInherited)
            {
                TypeCache <ISO8601PrettyPrintExcludeNullsInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldIncludeInherited)
            {
                TypeCache <ISO8601ExcludeNullsInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.IsJSONP)
            {
                TypeCache <ISO8601ExcludeNullsJSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint && options.IsJSONP)
            {
                TypeCache <ISO8601PrettyPrintJSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint)
            {
                TypeCache <ISO8601PrettyPrintExcludeNulls, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint && options.ShouldIncludeInherited)
            {
                TypeCache <ISO8601PrettyPrintInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <ISO8601JSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls)
            {
                TypeCache <ISO8601ExcludeNulls, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint)
            {
                TypeCache <ISO8601PrettyPrint, T> .Get()(output, data, 0);

                return;
            }

            if (options.IsJSONP)
            {
                TypeCache <ISO8601JSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldIncludeInherited)
            {
                TypeCache <ISO8601Inherited, T> .Get()(output, data, 0);

                return;
            }

            TypeCache <ISO8601, T> .Get()(output, data, 0);
        }
예제 #25
0
        static void Milliseconds <T>(T data, TextWriter output, Options options)
        {
            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint && options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <MillisecondsPrettyPrintExcludeNullsJSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint && options.IsJSONP)
            {
                TypeCache <MillisecondsPrettyPrintExcludeNullsJSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <MillisecondsExcludeNullsJSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint && options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <MillisecondsPrettyPrintJSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint && options.ShouldIncludeInherited)
            {
                TypeCache <MillisecondsPrettyPrintExcludeNullsInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldIncludeInherited)
            {
                TypeCache <MillisecondsExcludeNullsInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.IsJSONP)
            {
                TypeCache <MillisecondsExcludeNullsJSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint && options.IsJSONP)
            {
                TypeCache <MillisecondsPrettyPrintJSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint)
            {
                TypeCache <MillisecondsPrettyPrintExcludeNulls, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint && options.ShouldIncludeInherited)
            {
                TypeCache <MillisecondsPrettyPrintInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <MillisecondsJSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls)
            {
                TypeCache <MillisecondsExcludeNulls, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint)
            {
                TypeCache <MillisecondsPrettyPrint, T> .Get()(output, data, 0);

                return;
            }

            if (options.IsJSONP)
            {
                TypeCache <MillisecondsJSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldIncludeInherited)
            {
                TypeCache <MillisecondsInherited, T> .Get()(output, data, 0);

                return;
            }

            TypeCache <Milliseconds, T> .Get()(output, data, 0);
        }
예제 #26
0
        static void NewtonsoftStyle <T>(T data, TextWriter output, Options options)
        {
            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint && options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <NewtonsoftStylePrettyPrintExcludeNullsJSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint && options.IsJSONP)
            {
                TypeCache <NewtonsoftStylePrettyPrintExcludeNullsJSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <NewtonsoftStyleExcludeNullsJSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint && options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <NewtonsoftStylePrettyPrintJSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint && options.ShouldIncludeInherited)
            {
                TypeCache <NewtonsoftStylePrettyPrintExcludeNullsInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldIncludeInherited)
            {
                TypeCache <NewtonsoftStyleExcludeNullsInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.IsJSONP)
            {
                TypeCache <NewtonsoftStyleExcludeNullsJSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint && options.IsJSONP)
            {
                TypeCache <NewtonsoftStylePrettyPrintJSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls && options.ShouldPrettyPrint)
            {
                TypeCache <NewtonsoftStylePrettyPrintExcludeNulls, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint && options.ShouldIncludeInherited)
            {
                TypeCache <NewtonsoftStylePrettyPrintInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.IsJSONP && options.ShouldIncludeInherited)
            {
                TypeCache <NewtonsoftStyleJSONPInherited, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldExcludeNulls)
            {
                TypeCache <NewtonsoftStyleExcludeNulls, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldPrettyPrint)
            {
                TypeCache <NewtonsoftStylePrettyPrint, T> .Get()(output, data, 0);

                return;
            }

            if (options.IsJSONP)
            {
                TypeCache <NewtonsoftStyleJSONP, T> .Get()(output, data, 0);

                return;
            }

            if (options.ShouldIncludeInherited)
            {
                TypeCache <NewtonsoftStyleInherited, T> .Get()(output, data, 0);

                return;
            }

            TypeCache <NewtonsoftStyle, T> .Get()(output, data, 0);
        }
예제 #27
0
        public IEnumerable <T> ReadObjects <T>(IDataReader dataReader, Task <Materializer <T> > emitterTask) where T : new()
        {
            var selectedColumnNamesInOrder = Enumerable
                                             .Range(0, dataReader.FieldCount)
                                             .Select(x => new { ColumnName = dataReader.GetName(x), OrdinalIndex = x })
                                             .Select(x => new { ColumName = x.ColumnName, PropertyInfo = TypeCache.Get <T>().Properties.FirstOrDefault(prop => prop.Name.ToLower() == x.ColumnName.ToLower()), OrindalIndex = x.OrdinalIndex })
                                             .ToList();

            while (dataReader.Read())
            {
                var newObject = new T();

                foreach (var filler in selectedColumnNamesInOrder)
                {
                    var value = dataReader.GetValue(filler.OrindalIndex);
                    filler.PropertyInfo.SetValue(newObject, value is DBNull ? HopBase.GetDefault(filler.PropertyInfo.PropertyType) : value, null);
                }

                yield return(newObject);
            }
        }