public void Setup() { var sources = new IMetadataSource[] { new QueryingMetadataSource() }; var processors = new IMetadataProcessor[] {}; _provider = new MetadataProvider(sources, processors); }
public static IUnityContainer ConfigureUnity(this IUnityContainer container, MockMessageReceiver receiver, MessageProcessingStage[] stages) { var settings = new PerformedOperationsPrimaryFlowProcessorSettings { AppropriatedStages = stages }; var metadataProvider = new MetadataProvider(new IMetadataSource[] { new PerformedOperationsMessageFlowsMetadataSource() }, new IMetadataProcessor[] { new ReferencesEvaluatorProcessor() }); return container .RegisterContexts() .RegisterInstance(Mock.Of<ITelemetryPublisher>()) .RegisterType<ITracer, NullTracer>() .RegisterInstance<IMetadataProvider>(metadataProvider) .RegisterInstance<IPerformedOperationsFlowProcessorSettings>(settings) .RegisterInstance(receiver) .RegisterType<IMessageReceiverFactory, UnityMessageReceiverFactory>(Lifetime.Singleton) .RegisterType<IMessageFlowProcessorResolveStrategy, Mocks.Processor.PrimaryProcessorResolveStrategy>("primary", Lifetime.Singleton) .RegisterType<IMessageFlowReceiverResolveStrategy, MockReceiverResolveStrategy>("primary", Lifetime.Singleton) .RegisterType<IMessageProcessingStagesFactory, UnityMessageProcessingStagesFactory>(Lifetime.Singleton) .RegisterType<IMessageTransformerFactory, UnityMessageTransformerFactory>(Lifetime.Singleton) .RegisterType<IMessageFlowProcessorFactory, UnityMessageFlowProcessorFactory>(Lifetime.Singleton) .RegisterType<IParentContainerUsedRegistrationsContainer, ParentContainerUsedRegistrationsContainer>(Lifetime.Singleton) .RegisterType<IMessageProcessingHandlerFactory, UnityMessageProcessingHandlerFactory>(Lifetime.PerScope) .RegisterType<IMessageProcessingContextAccumulatorFactory, UnityMessageProcessingContextAccumulatorFactory>(Lifetime.PerScope); }
public void NoRegistrationReturnsEmptyMetadata() { var sut = new MetadataProvider(); var metadata = sut.Get(typeof(DummyObject)); Assert.True(Metadata.IsEmpty(metadata)); }
public void when_getting_metadata_then_returns_type_name() { var provider = new MetadataProvider(); var typeName = typeof(given_a_metadata_provider).Name; var metadata = provider.GetMetadata(this); Assert.Contains(typeName, metadata.Values); Assert.Contains("EventType", metadata.Keys); }
//************************************************************************* // Constructor: GraphVertexEdgeBase() // /// <summary> /// Initializes a new instance of the <see cref="GraphVertexEdgeBase" /> /// class. /// </summary> /// /// <param name="id"> /// The object's ID. Must be unique among all objects of the same type. /// </param> //************************************************************************* public GraphVertexEdgeBase( Int32 id ) { m_sName = null; m_iID = id; m_oMetadataProvider = null; // AssertValid(); }
public void RegisterForType() { var medataData = new GenericMetadata<DummyObject>() .WithMemberDependency(o => o.Name, o2 => o2.Name) .WithRuntimeNameProperty(o => o.Name); var sut = new MetadataProvider(); sut.Register(typeof(DummyObject), medataData); var actual = sut.Get(typeof(DummyObject)); Assert.Equal(medataData.AsNonGeneric(), actual); }
public static int Main(string[] args) { var arguments = ParseCommandline(args); using (var container = new UnityContainer()) { var assembly = Assembly.Load(AssemblyName.GetAssemblyName(args[0])); var metadataProvider = new MetadataProvider(assembly.GetExportedTypes() .Where(t => typeof(IMetadataSource).IsAssignableFrom(t)) .Select(x => (IMetadataSource)container.Resolve(x)) .ToArray(), new IMetadataProcessor[0]); container.RegisterInstance<IMetadataProvider>(metadataProvider); container.RegisterType(typeof(ConnectionStringSettingsAspect), assembly.GetExportedTypes().Single(t => typeof(ConnectionStringSettingsAspect).IsAssignableFrom(t))); container.RegisterType<DataConnectionFactory>(); container.RegisterType<SmoConnectionFactory>(); container.RegisterType<ContextEntityTypesProvider>(new ContainerControlledLifetimeManager()); container.RegisterInstance<CommandlineParameters>(arguments); string nunitOutputPath; string isTeamcityString; bool isTeamcity; if (arguments.TryGet("teamcity", out isTeamcityString) && bool.TryParse(isTeamcityString, out isTeamcity) && isTeamcity) { container.RegisterType<ITestStatusObserver, TeamCityTestStatusObserver>(); } else if (arguments.TryGet("nunit25-output", out nunitOutputPath) && !string.IsNullOrWhiteSpace(nunitOutputPath)) { container.RegisterInstance<ITestStatusObserver>(new NUnitTestStatusObserver(nunitOutputPath, assembly)); } else { container.RegisterType<ITestStatusObserver, ConsoleTestStatusObserver>(); } var createDatabases = container.Resolve<CreateDatabasesCommand>(); var dropDatabases = container.Resolve<DropDatabasesCommand>(); var createSchemata = container.Resolve<CreateDatabaseSchemataCommand>(); var runTests = container.Resolve<RunTestsCommand>(); var validateSchemata = container.Resolve<ValidateDatabaseSchemataCommand>(); dropDatabases.Execute(); createDatabases.Execute(); createSchemata.Execute(); validateSchemata.Execute(); runTests.Execute(); dropDatabases.Execute(); return runTests.AnyFailedTest ? -1 : 0; } }
private static bool IsCustomUpdateMethod(MethodInfo method, MetadataProvider metadataProvider) { ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length == 0) { return(false); } if (method.ReturnType != typeof(void)) { return(false); } return(metadataProvider.IsEntityType(parameters[0].ParameterType)); }
/// <inheritdoc /> public ViewDataDictionary([NotNull] ViewDataDictionary source, object model) : base(source, model) { var original = source as ViewDataDictionary <TModel>; if (original != null) { _defaultModelMetadata = original._defaultModelMetadata; } else { _defaultModelMetadata = MetadataProvider.GetMetadataForType(null, typeof(TModel)); } }
public DataService(MappingSchema mappingSchema) { lock (_cache) { if (!_cache.TryGetValue(mappingSchema, out var data)) { data = Tuple.Create(default(T) !, new MetadataInfo(mappingSchema)); } _metadata = new MetadataProvider(data.Item2); _query = new QueryProvider(data.Item2); _update = new UpdateProvider(data.Item2, _metadata, _query); } }
public GenericResponseResult <IDictionary <string, BaseAssociationUpdateResult> > UpdateAssociations(ApplicationMetadata application, AssociationUpdateRequest request, JObject currentData) { var entityMetadata = MetadataProvider.Entity(application.Entity); var cruddata = EntityBuilder.BuildFromJson <CrudOperationData>(typeof(CrudOperationData), entityMetadata, application, currentData, request.Id); if (EagerAssociationTrigger.Equals(request.TriggerFieldName)) { request.AssociationsToFetch = AssociationHelper.AllButSchema; return(new GenericResponseResult <IDictionary <string, BaseAssociationUpdateResult> >(BuildAssociationOptions(cruddata, application, request))); } return(new GenericResponseResult <IDictionary <string, BaseAssociationUpdateResult> >(DoUpdateAssociation(application, request, cruddata))); }
//methods private static void Initialize() { if (_initialized) { if (_initializeException != null) { throw _initializeException; } } else { if (_initializeException != null) { throw _initializeException; } lock (_lock) { if (_initialized) { if (_initializeException != null) { throw _initializeException; } } else { try { DataModelSection section = ConfigurationManager.GetSection(SectionName) as DataModelSection; _providers = new ProviderCollection(); //fill providers collection foreach (ProviderSettings settings in section.Providers) { _providers.Add(InstantiateProvider(settings, typeof(MetadataProvider))); } _provider = (MetadataProvider)_providers[section.DefaultProvider]; _typeMappings = section.TypeMappings; } catch (Exception exception) { _initializeException = exception; throw; } _initialized = true; } } } }
public static void InitializeMetadata(int Timestep, string SpeciesMapFileName, IEnumerable <ISuitabilityParameters> suitabilityParams, ICore mCore) { ScenarioReplicationMetadata scenRep = new ScenarioReplicationMetadata() { RasterOutCellArea = PlugIn.ModelCore.CellArea, TimeMin = PlugIn.ModelCore.StartTime, TimeMax = PlugIn.ModelCore.EndTime //, //ProjectionFilePath = "Projection.?" }; Extension = new ExtensionMetadata(mCore) { Name = PlugIn.PlugInName, TimeInterval = Timestep, ScenarioReplicationMetadata = scenRep }; //--------------------------------------- // table outputs: //--------------------------------------- // NONE //--------------------------------------- // map outputs: //--------------------------------------- foreach (SuitabilityParameters habitatModel in suitabilityParams) { string sppMapPath = MapFileNames.ReplaceTemplateVars(SpeciesMapFileName, habitatModel.HabitatName); OutputMetadata mapOut_LocalHabitat = new OutputMetadata() { Type = OutputType.Map, Name = ("Local Habitat Map: " + habitatModel.HabitatName), //sppModel.Name, FilePath = @sppMapPath, Map_DataType = MapDataType.Continuous, Map_Unit = "Habitat Class", Visualize = true, }; Extension.OutputMetadatas.Add(mapOut_LocalHabitat); } //--------------------------------------- MetadataProvider mp = new MetadataProvider(Extension); mp.WriteMetadataToXMLFile("Metadata", Extension.Name, Extension.Name); }
public static string GetEntitiesInternalPath(bool source = false) { var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var type = source ? "source" : "target"; var propertyname = source ? MetadataProperties.Source : MetadataProperties.Target; var pattern = ApplicationConfiguration.IsUnitTest ? TestInternalMetadataPattern : InternalMetadataPattern; var mapping = MetadataProvider.GlobalProperty(propertyname); if (type == "target" && mapping == null) { //as a fallback, we will look for the same file as the source mapping = MetadataProvider.GlobalProperty("sourcemapping"); } return(baseDirectory + String.Format(pattern, type, mapping)); }
private ApplicationMetadata DetermineSchemaFromAsset(Entity initialValues) { var assetclassstructure = (string)initialValues.GetAttribute("classstructureid"); var completeApplication = MetadataProvider.Application("servicerequest"); if (AssetConstants.PhoneClassStructure.Equals(assetclassstructure)) { return(completeApplication.ApplyPoliciesWeb(new ApplicationMetadataSchemaKey("phone"))); } if (IsPrinterAsset(assetclassstructure)) { return(completeApplication.ApplyPoliciesWeb(new ApplicationMetadataSchemaKey("printer"))); } return(completeApplication.ApplyPoliciesWeb(new ApplicationMetadataSchemaKey("general"))); }
public void TestFrom() { var sliced = SlicedEntityMetadataBuilder.GetInstance(MetadataProvider.Entity("asset"), _schema); Assert.AreEqual(5, sliced.InnerMetadatas.Count); var from = QueryFromBuilder.Build(sliced); Debug.Write(from); Assert.IsTrue(from.Contains("address as location_shipto_")); Assert.IsTrue(from.Contains("address as location_billto_")); Assert.IsTrue(from.Contains("address as location_serv_")); Assert.IsTrue(from.Contains("on (location_.billtoaddresscode")); Assert.IsTrue(from.Contains("on (location_.shiptoaddresscode")); Assert.IsTrue(from.Contains("on (location_.serviceaddresscode")); }
public void TestSelect4() { var schemas = MetadataProvider.Application("imac").Schemas(); var schema = schemas[new ApplicationMetadataSchemaKey("detail", "output", "web")]; var sliced = SlicedEntityMetadataBuilder.GetInstance(MetadataProvider.Entity("imac"), schema); var select = QuerySelectBuilder.BuildSelectAttributesClause(sliced, QueryCacheKey.QueryMode.Detail); Debug.Write(select); Assert.IsFalse(select.Contains("case when imac.serialnum")); Assert.IsTrue(select.Contains("case when asset_.serialnum")); var from = QueryFromBuilder.Build(sliced, null); // Debug.Write(from); Assert.IsTrue(from.Contains("left join person as asset_aucisowner_person_ on (asset_aucisowner_.personid = asset_aucisowner_person_.personid)")); }
public TPoco FirstOrDefault <TPoco>(ISqlCommand command) where TPoco : class { return(RetryPolicy.Execute(() => { OpenConnection(); var reader = CreateTextCommand(command) .ExecuteReader(CommandBehavior.SingleRow); return MetadataProvider .CreateMapper <TPoco>(reader) .MapSingle(); })); }
public IEnumerable <TPoco> Find <TPoco>(ISqlCommand command) where TPoco : class { return(RetryPolicy.Execute(() => { OpenConnection(); var reader = CreateTextCommand(command) .ExecuteReader(); return MetadataProvider .CreateMapper <TPoco>(reader) .MapQuery(); })); }
public void ChangeSRUnionSearch() { var dto = new SearchRequestDto(); dto.BuildUnionDTO(dto, MetadataProvider.FindSchemaDefinition("change.list")); var completeOne = MetadataProvider.Application("change"); var metadata = completeOne.ApplyPolicies(new ApplicationMetadataSchemaKey("list"), InMemoryUser.TestInstance(), ClientPlatform.Web); ApplicationSchemaDefinition schema; var sliced = SlicedEntityMetadataBuilder.GetInstance(MetadataProvider.Entity("wochange"), metadata.Schema, 300); var result = QuerySelectBuilder.BuildSelectAttributesClause(sliced.UnionSchema, QueryCacheKey.QueryMode.Union, dto.unionDTO); Assert.AreEqual("select null, null, null, null, '-666' as zeroedattr, srforchange.description as hlagchangesummary, srforchange.ticketid as ticketid, asset_.description as asset_description, null, null, CASE WHEN srforchange.PLUSPCUSTOMER IS NOT NULL AND srforchange.PLUSPCUSTOMER = 'HLC-00' then 'HLAG' WHEN srforchange.PLUSPCUSTOMER IS NOT NULL AND LENGTH(srforchange.PLUSPCUSTOMER) >= 3 THEN SUBSTR(srforchange.PLUSPCUSTOMER, LENGTH(srforchange.PLUSPCUSTOMER) - 2, 3) ELSE '' END as hlagpluspcustomer, CASE WHEN LOCATE('@',srforchange.REPORTEDBY) > 0 THEN SUBSTR(srforchange.REPORTEDBY,1,LOCATE('@',srforchange.REPORTEDBY)-1) ELSE srforchange.REPORTEDBY END as hlagreportedby, srforchange.status as status ", result); }
private IApplicationResponse Get(string application, [FromUri] DataRequestAdapter request) { var user = SecurityFacade.CurrentUser(); if (null == user) { throw new HttpResponseException(HttpStatusCode.Unauthorized); } var applicationMetadata = MetadataProvider .Application(application) .ApplyPolicies(request.Key, user, ClientPlatform.Web); return(((BaseApplicationDataSet)_dataSetProvider.LookupDataSet(application)).Get(applicationMetadata, user, request)); }
public void HandleEvent(ApplicationStartedEvent eventToDispatch) { var before = new Stopwatch(); var applications = MetadataProvider.Applications(); var completeApplicationMetadataDefinitions = applications as CompleteApplicationMetadataDefinition[] ?? applications.ToArray(); ISet <String> namesToRegister = new HashedSet <string>(); AddAllApplicationsAndUsedEntities(namesToRegister, completeApplicationMetadataDefinitions); foreach (var name in namesToRegister) { _facade.Register(name, "", null, false); } _log.Info(LoggingUtil.BaseDurationMessage("finished registering whereclauses in {0}", before)); }
public string GetValue(string propName) { var entityMetadata = MetadataProvider.Entity(EntityName); var searchRequestDto = SearchRequestDto.GetFromDictionary(new Dictionary <string, string>() { { "propname", propName } }); searchRequestDto.AppendProjectionField(new ProjectionField("propname", "propname")); searchRequestDto.AppendProjectionField(new ProjectionField("propvalue", "propvalue")); var list = EntityRepository.Get(entityMetadata, searchRequestDto); var result = list.FirstOrDefault(); return(result == null ? null : (string)result.GetAttribute("propvalue")); }
private void DeleteItem(string itemId, string itemText, string configId, string metadataType) { if (string.IsNullOrEmpty(itemId) == false && string.IsNullOrEmpty(configId) == false && MessageBox.Show(string.Format(Resources.DocumentDesignerDeleteQuestion, itemText), GetView().GetText(), MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { var dataProvider = new MetadataProvider(metadataType); dataProvider.SetConfigId(configId); dataProvider.DeleteItem(itemId); InvokeUpdateItems(); } }
public DynamicTypeDefinition GetDynamicTypeDefinition(String tableName) { if (_tableNameTypes.TryGetValue(tableName, out Type dynamicTypeType)) { return(GetDynamicTypeDefinition(dynamicTypeType)); } dynamicTypeType = GetDynamicTypeType(); String entityName = MetadataProvider.GetEntityName(tableName); var dynamicTypeDefinition = new DynamicTypeDefinition(dynamicTypeType, entityName, tableName); _tableNameTypes.Add(tableName, dynamicTypeType); _dynamicTypeDefinitions.Add(dynamicTypeType, dynamicTypeDefinition); return(dynamicTypeDefinition); }
public async Task ShouldInclude_NotMappedProperties_Test() { var entityConfigStore = Resolve <IEntityConfigurationStore>(); var metadataProvider = new MetadataProvider(entityConfigStore); var properties = metadataProvider.GetProperties(typeof(EntityWithReadonlyProp)); var includesCalculatedReadonly = properties.Any(p => p.Path == nameof(EntityWithReadonlyProp.CalculatedReadonly)); Assert.True(includesCalculatedReadonly, $"Calculated readonly property '{nameof(EntityWithReadonlyProp.CalculatedReadonly)}' must be included into metadata"); var includesNotMappedReadWrite = properties.Any(p => p.Path == nameof(EntityWithReadonlyProp.NotMappedReadWrite)); Assert.True(includesNotMappedReadWrite, $"Calculated not mapped read/write property '{nameof(EntityWithReadonlyProp.NotMappedReadWrite)}' must be included into metadata"); }
public void MetadataProvider_RetrieveObjectDefinitions_Test() { //arrange MetadataProvider provider = new MetadataProvider(); //act //call using default parameters IEnumerable <IObjectDefinition> entities = provider.RetrieveObjectDefinitions(); //assert: //use linq to pull out the full name and make sure it matches: Assert.AreEqual(2, entities.Count()); Assert.AreEqual("Registrant", entities.FirstOrDefault(entitiy => entitiy.FullName == "Registrant").FullName); Assert.AreEqual("Webinar", entities.FirstOrDefault(entity => entity.FullName == "Webinar").FullName); }
public void MetadataProvider_RetrieveActionDefinitions_Test() { //arrange: MetadataProvider provider = new MetadataProvider(); //act IEnumerable <IActionDefinition> actions = provider.RetrieveActionDefinitions(); //assert: Assert.AreEqual(2, actions.Count()); //Extract by the name, match by the Enum Assert.AreEqual(KnownActions.Create, actions.FirstOrDefault(action => action.FullName == "Create").KnownActionType); Assert.AreEqual(KnownActions.Query, actions.FirstOrDefault(action => action.FullName == "Query").KnownActionType); }
public string BuildWhereClause(string entityName, QueryCacheKey.QueryMode queryMode, SearchRequestDto searchDto = null) { var entity = MetadataProvider.Entity(entityName); if (!entity.Schema.Attributes.Any(a => a.Name.Equals("pluspcustomer"))) { return(null); } var property = MetadataProvider.GlobalProperty("multitenantprefix"); if (property == null) { return(null); } return(String.Format("{0}.pluspcustomer like '{1}'", entityName, property)); }
public String ValidateContraint(softWrench.sW4.Security.Entities.DataConstraint constraint) { try { var entityMetadata = MetadataProvider.Entity(constraint.EntityName); if (entityMetadata == null) { return(String.Format("EntityName {0} not found, unable to apply constraint", constraint.EntityName)); } var query = new EntityQueryBuilder().CountRowsFromConstraint(entityMetadata, constraint); _dao.FindByNativeQuery(query.Sql, query.Parameters); return(null); } catch (Exception e) { return(String.Format("error saving constraint {0}.Cause:{1}", constraint.WhereClause, e.Message)); } }
public void IncidentHardwareReport() { var dto = new SearchRequestDto(); dto.AppendProjectionField(ProjectionField.Default("asset_assetloccomm_commoditiesownedby_.description")); dto.AppendProjectionField(ProjectionField.Default("asset_assetloccomm_.commodity")); var completeOne = MetadataProvider.Application("incident"); var metadata = completeOne.ApplyPolicies(new ApplicationMetadataSchemaKey("hardwarerepair"), InMemoryUser.TestInstance(), ClientPlatform.Web); ApplicationSchemaDefinition schema; var sliced = SlicedEntityMetadataBuilder.GetInstance(MetadataProvider.Entity("incident"), metadata.Schema); var result = QueryFromBuilder.Build(sliced, dto); Assert.AreEqual("from incident as incident left join asset as asset_ on (incident.assetnum = asset_.assetnum and incident.siteid = asset_.siteid)left join assetloccomm as asset_assetloccomm_ on (asset_.assetnum = asset_assetloccomm_.assetnum and asset_.siteid = asset_assetloccomm_.siteid)left join commodities as asset_assetloccomm_commoditiesownedby_ on (asset_assetloccomm_.commodity = asset_assetloccomm_commoditiesownedby_.commodity and asset_assetloccomm_.itemsetid = asset_assetloccomm_commoditiesownedby_.itemsetid and (asset_assetloccomm_commoditiesownedby_.description like 'Asset owened by%'))", result); }
public AttributeHolder ById(string documentId) { var entityMetadata = MetadataProvider.Entity(EntityName); var searchRequestDto = SearchRequestDto.GetFromDictionary(new Dictionary <string, string>() { { "docinfoid", documentId } }); searchRequestDto.AppendProjectionField(new ProjectionField("urlname", "urlname")); searchRequestDto.AppendProjectionField(new ProjectionField("document", "document")); searchRequestDto.AppendProjectionField(new ProjectionField("docinfoid", "docinfoid")); var list = EntityRepository.Get(entityMetadata, searchRequestDto); var result = list.FirstOrDefault(); return(result); }
public ActionResult UploadBlob() { try { MetadataProvider metadataProvider = new MetadataProvider(); var metaData = metadataProvider.RetrieveProjectMetadataViaAPIAsync(Guid.Empty).Result; SaveMetadataToBlob(metaData); TempData["Message"] = "Blob has been uploded sucessfully"; } catch { return(Json("error")); } return(Json("Success")); }
private static IEnumerable <EntityAssociation> FilterByProjectionAndRestrictions(IEnumerable <EntityAssociation> usedAssociations, IEnumerable <string> fieldsToConsider, string prefix = null) { ISet <EntityAssociation> associations = new HashSet <EntityAssociation>(); var entityAssociations = usedAssociations as EntityAssociation[] ?? usedAssociations.ToArray(); foreach (var @alias in fieldsToConsider) { if ([email protected]('.')) { //this won´t impact the relationships, so just continue... continue; } var relName = EntityUtil.GetRelationshipName(@alias); if (relName.IndexOf('_') == relName.LastIndexOf('_')) { var association = entityAssociations.FirstOrDefault(a => a.Qualifier == relName); if (association != null) { associations.Add(association); } } else { var clonedRelName = @alias; var firstIdx = clonedRelName.IndexOf('_'); var before = EntityUtil.GetRelationshipName(clonedRelName.Substring(0, firstIdx)); var after = clonedRelName.Substring(firstIdx + 1); var association = entityAssociations.FirstOrDefault(a => a.Qualifier == before); if (association != null) { var firstEntity = MetadataProvider.Entity(association.To); var innerAssociations = FilterByProjectionAndRestrictions(firstEntity.Associations, new List <string>() { after }); associations.Add(association); foreach (var innerAssociation in innerAssociations) { associations.Add(innerAssociation.CloneWithContext(before)); } } } } return(associations); }
public static ApplicationMetadata GetAssociationApplicationMetadata(ApplicationAssociationDefinition association) { // See if association has a schema defined string optionApplication; string optionSchemaId; association.Schema.RendererParameters.TryGetValue("application", out optionApplication); association.Schema.RendererParameters.TryGetValue("schemaId", out optionSchemaId); if (!String.IsNullOrWhiteSpace(optionApplication) && !String.IsNullOrWhiteSpace(optionSchemaId)) { return(MetadataProvider .Application(optionApplication) .ApplyPolicies(new ApplicationMetadataSchemaKey(optionSchemaId), SecurityFacade.CurrentUser(), ClientPlatform.Web)); } return(null); }
/// <summary> /// Creates and returns the metadata provider for the specified DataController Type. /// </summary> /// <param name="dataControllerType">The DataController Type.</param> /// <returns>The metadata provider.</returns> internal static MetadataProvider CreateMetadataProvider(Type dataControllerType) { // construct a list of all types in the inheritance hierarchy for the controller List <Type> baseTypes = new List <Type>(); Type currType = dataControllerType; while (currType != typeof(DataController)) { baseTypes.Add(currType); currType = currType.BaseType; } // create our base reflection provider List <MetadataProvider> providerList = new List <MetadataProvider>(); ReflectionMetadataProvider reflectionProvider = new ReflectionMetadataProvider(); // Set the IsEntity function which consults the chain of providers. Func <Type, bool> isEntityTypeFunc = (t) => providerList.Any(p => p.LookUpIsEntityType(t)); reflectionProvider.SetIsEntityTypeFunc(isEntityTypeFunc); // Now from most derived to base, create any declared metadata providers, // chaining the instances as we progress. Note that ordering from derived to // base is important - we want to ensure that any providers the user has placed on // their DataController directly come before any DAL providers. MetadataProvider currProvider = reflectionProvider; providerList.Add(currProvider); for (int i = 0; i < baseTypes.Count; i++) { currType = baseTypes[i]; // Reflection rather than TD is used here so we only get explicit // Type attributes. TD inherits attributes by default, even if the // attributes aren't inheritable. foreach (MetadataProviderAttribute providerAttribute in currType.GetCustomAttributes(typeof(MetadataProviderAttribute), false)) { currProvider = providerAttribute.CreateProvider(dataControllerType, currProvider); currProvider.SetIsEntityTypeFunc(isEntityTypeFunc); providerList.Add(currProvider); } } return(currProvider); }
public void TestInverseRelationship() { // var dto = new SearchRequestDto(); // var completeOne = MetadataProvider.Application("change"); // var metadata = completeOne.ApplyPolicies(new ApplicationMetadataSchemaKey("list"), InMemoryUser.TestInstance(), // ClientPlatform.Web); // ApplicationSchemaDefinition schema; // var sliced = SlicedEntityMetadataBuilder.GetInstance(MetadataProvider.Entity("change"), metadata.Schema); // var result = QueryFromBuilder.Build(MetadataProvider.Entity("wochange"), dto); var dto = new SearchRequestDto(); dto.AppendProjectionField(ProjectionField.Default("sr_.description")); var result = QueryFromBuilder.Build(MetadataProvider.Entity("wochange"), dto); Assert.AreEqual("from wochange as wochange left join SR as sr_ on (wochange.origrecordid = sr_.ticketid and wochange.origrecordclass = 'SR' and wochange.woclass = 'CHANGE')", result); }
public void ShouldProcessFactAccordingToPriority() { //arrange var factProcessor = new Mock<IFactProcessor>(); factProcessor.Setup(x => x.ApplyChanges(It.IsAny<IReadOnlyCollection<long>>())) .Returns(new IOperation[0]); var provider = new MetadataProvider(new[] { new FactsReplicationMetadataSource() }, new IMetadataProcessor[0]); var factoryInvocationOrder = new List<Type>(); var factProcessorFactory = new Mock<IFactProcessorFactory>(); factProcessorFactory.Setup(x => x.Create(It.IsAny<IMetadataElement>())) .Callback<IMetadataElement>(element => { var type = element.GetType().GenericTypeArguments[0]; factoryInvocationOrder.Add(type); }) .Returns(factProcessor.Object); var transformation = new FactsReplicator(Mock.Of<ITracer>(), Mock.Of<IReplicationSettings>(), provider, factProcessorFactory.Object, new CustomerIntelligenceFactTypePriorityComparer()); SourceDb.Has(new Erm::Firm { Id = 2 }) .Has(new Erm::FirmAddress { Id = 1, FirmId = 1 }, new Erm::FirmAddress { Id = 2, FirmId = 2 }); TargetDb.Has(new Facts::Firm { Id = 1 }); var inputOperations = new[] { new FactOperation(typeof(Facts::FirmAddress), 1), new FactOperation(typeof(Facts::Firm), 2), new FactOperation(typeof(Facts::FirmAddress), 2), }; //act transformation.Replicate(inputOperations); //assert Assert.That(factoryInvocationOrder.Count, Is.EqualTo(2)); Assert.That(factoryInvocationOrder[0], Is.EqualTo(typeof(Facts::Firm))); Assert.That(factoryInvocationOrder[1], Is.EqualTo(typeof(Facts::FirmAddress))); }
public void RegisterForBaseAndDerived() { var metadataForBase = new GenericMetadata<DummyObject>() .WithRuntimeNameProperty(o => o.Name); var metadataForDerived = new GenericMetadata<DummyClass>() .WithMemberDependency(d => d.Item, d => d.Child); var sut = new MetadataProvider(); sut.Register(typeof(DummyObject), metadataForBase); sut.Register(typeof(DummyClass), metadataForDerived); var expected = new Metadata { RuntimePropertyName = "Name", PropertyDependencies = new DependencyRegistrations { new DependencyRegistration("Item", "Child") } }; var actual = sut.Get(typeof(DummyClass)); Assert.Equal(expected, actual); }
TestSetGetValue5() { // Add N keys for each of N MetadataProvider objects, ask for same keys // in reverse order. // Create an array of keys. const Int32 Keys = 10; String [] asKeys = new String[Keys]; for (Int32 i = 0; i < Keys; i++) { asKeys[i] = Guid.NewGuid().ToString(); } // Create an array of MetadataProvider objects. const Int32 MetadataProviderObjects = 10000; MetadataProvider [] aoMetadataProvider = new MetadataProvider[MetadataProviderObjects]; for (Int32 j = 0; j < MetadataProviderObjects; j++) { aoMetadataProvider[j] = new MetadataProvider(); } // Add a value for each key. The value is just the key with appended // indexes. for (Int32 j = 0; j < MetadataProviderObjects; j++) { MetadataProvider oMetadataProvider = aoMetadataProvider[j]; for (Int32 i = 0; i < Keys; i++) { String sKey = asKeys[i]; oMetadataProvider.SetValue( sKey, sKey + i.ToString() + j.ToString() ); } } // Retrieve the values. Boolean bContainsKey; for (Int32 j = MetadataProviderObjects - 1; j >= 0; j--) { MetadataProvider oMetadataProvider = aoMetadataProvider[j]; for (Int32 i = Keys - 1; i >= 0; i--) { String sKey = asKeys[i]; bContainsKey = oMetadataProvider.ContainsKey(sKey); Assert.IsTrue(bContainsKey); Object oValue; Assert.IsTrue( oMetadataProvider.TryGetValue( sKey, out oValue) ); Assert.IsTrue(oValue is String); Assert.AreEqual(sKey + i.ToString() + j.ToString(), (String)oValue); } // Ask for a non-existent value. bContainsKey = oMetadataProvider.ContainsKey("nHnHn"); Assert.IsFalse(bContainsKey); } // Create another MetadataProvider object and verify that it contains // no keys. MetadataProvider oMetadataProviderNoKeys = new MetadataProvider(); for (Int32 i = 0; i < Keys; i++) { String sKey = asKeys[i]; bContainsKey = oMetadataProviderNoKeys.ContainsKey(sKey); Assert.IsFalse(bContainsKey); Object oValue; Assert.IsFalse( m_oMetadataProvider.TryGetValue( sKey, out oValue) ); } }
//************************************************************************* // Method: SetValue // /// <summary> /// Sets the metadata value associated with a specified key. /// </summary> /// /// <param name="key"> /// The value's key. Can't be null or empty, and can't start with a /// tilde (~). If the key already exists, its value gets overwritten. /// </param> /// /// <param name="value"> /// The value to set. Can be null. /// </param> /// /// <remarks> /// The application can store arbitrary metadata by adding key/value pairs /// via <see cref="SetValue(String, Object)" />. The values can be /// retrieved with <see cref="GetValue(String)" /> or one of its variants. /// The keys are of type <see cref="String" /> and the values are of type /// <see cref="Object" />. /// /// <para> /// If you want to store just a single metadata object, use the <see /// cref="Tag" /> property instead. /// </para> /// /// <para> /// Keys that start with a tilde (~) are reserved by the NodeXL system for /// internal use. /// </para> /// /// </remarks> /// /// <seealso cref="ContainsKey" /> /// <seealso cref="TryGetValue(String, out Object)" /> /// <seealso cref="GetRequiredValue(String, Type)" /> /// <seealso cref="GetValue(String)" /> /// <seealso cref="Tag" /> //************************************************************************* public void SetValue( String key, Object value ) { AssertValid(); const String MethodName = "SetValue"; CheckClientKey(MethodName, key); if (m_oMetadataProvider == null) { m_oMetadataProvider = new MetadataProvider(); } m_oMetadataProvider.SetValue(key, value); }
public MockMetadataProvider() { m_iID = m_iNextID; m_iNextID++; m_sName = null; m_oMetadataProvider = new MetadataProvider(); }
TestRemoveKey5() { // Create N objects, set metadata on each object, remove keys one by // one in backwards order. const Int32 Objects = 10; const Int32 Keys = 5; MetadataProvider [] aoMetadataProvider = new MetadataProvider[Objects]; // Set values on each object. for (Int32 i = 0; i < Objects; i++) { MetadataProvider oMetadataProvider = aoMetadataProvider[i] = new MetadataProvider(); for (Int32 j = 0; j < Keys; j++) { oMetadataProvider.SetValue(j.ToString(), "string"); } } // Remove the keys from each object. for (Int32 i = Objects - 1; i >= 0; i--) { MetadataProvider oMetadataProvider = aoMetadataProvider[i]; for (Int32 j = Keys - 1; j >= 0; j--) { Boolean bRemovedKey = oMetadataProvider.RemoveKey( j.ToString() ); Assert.IsTrue(bRemovedKey); // Check the status of all the keys. for (Int32 I = 0; I < Objects; I++) { MetadataProvider oMetadataProvider2 = aoMetadataProvider[I]; for (Int32 J = 0; J < Keys; J++) { Boolean bContainsKey = oMetadataProvider2.ContainsKey( J.ToString() ); if (I < i) { Assert.IsTrue(bContainsKey); } else if (I == i) { if (J < j) { Assert.IsTrue(bContainsKey); } else { Assert.IsFalse(bContainsKey); } } else { Assert.IsFalse(bContainsKey); } } } } } }
SetUp() { m_oMetadataProvider = new MetadataProvider(); m_oCopy = new MockMetadataProvider(); }
private void comboBoxMeatadataFile_SelectedIndexChanged(object sender, EventArgs e) { _provider = null; _metadataFile = (string)comboBoxMeatadataFile.SelectedItem; RefreshEntityContainers(); }
TestClearMetadata() { // Add tags and N keys for each of N MetadataProvider objects, ask // for same tags and keys, clear metadata for each object. // Create an array of keys. const Int32 Keys = 10; String [] asKeys = new String[Keys]; for (Int32 i = 0; i < Keys; i++) { asKeys[i] = Guid.NewGuid().ToString(); } // Create an array of MetadataProvider objects. const Int32 MetadataProviderObjects = 100; MetadataProvider [] aoMetadataProvider = new MetadataProvider[MetadataProviderObjects]; for (Int32 j = 0; j < MetadataProviderObjects; j++) { aoMetadataProvider[j] = new MetadataProvider(); } // Add a Tag and a value for each key. The value is just the key with // appended indexes. for (Int32 j = 0; j < MetadataProviderObjects; j++) { MetadataProvider oMetadataProvider = aoMetadataProvider[j]; oMetadataProvider.Tag = j.ToString() + "Tag"; for (Int32 i = 0; i < Keys; i++) { String sKey = asKeys[i]; oMetadataProvider.SetValue( sKey, sKey + i.ToString() + j.ToString() ); } } // Retrieve the values. Boolean bContainsKey; for (Int32 j = 0; j < MetadataProviderObjects; j++) { MetadataProvider oMetadataProvider = aoMetadataProvider[j]; Assert.AreEqual( j.ToString() + "Tag", oMetadataProvider.Tag ); for (Int32 i = Keys - 1; i >= 0; i--) { String sKey = asKeys[i]; bContainsKey = oMetadataProvider.ContainsKey(sKey); Assert.IsTrue(bContainsKey); Object oValue; Assert.IsTrue( oMetadataProvider.TryGetValue( sKey, out oValue) ); Assert.IsTrue(oValue is String); Assert.AreEqual(sKey + i.ToString() + j.ToString(), (String)oValue); } // Ask for a non-existent value. bContainsKey = oMetadataProvider.ContainsKey("nHnHn"); Assert.IsFalse(bContainsKey); } // Remove metadata for each object. for (Int32 k = 0; k < MetadataProviderObjects; k++) { aoMetadataProvider[k].ClearMetadata(); // Check all the objects, some of which will have no metadata. for (Int32 j = 0; j < MetadataProviderObjects; j++) { MetadataProvider oMetadataProvider = aoMetadataProvider[j]; if (j > k) { Assert.AreEqual( j.ToString() + "Tag", oMetadataProvider.Tag ); } else { Assert.IsNull(oMetadataProvider.Tag); } for (Int32 i = Keys - 1; i >= 0; i--) { String sKey = asKeys[i]; bContainsKey = oMetadataProvider.ContainsKey(sKey); if (j > k) { Assert.IsTrue(bContainsKey); Object oValue; Assert.IsTrue( oMetadataProvider.TryGetValue( sKey, out oValue) ); Assert.IsTrue(oValue is String); Assert.AreEqual(sKey + i.ToString() + j.ToString(), (String)oValue); } else { Assert.IsFalse(bContainsKey); } } } } }