private XDocument generateDefaultRevisionInfoXmlMapping() { var document = new XDocument(); var classMapping = MetadataTools.CreateEntity(document, new AuditTableData(null, null, _globalCfg.DefaultSchemaName, _globalCfg.DefaultCatalogName), null, false); classMapping.Add(new XAttribute("name", revisionInfoEntityName), new XAttribute("table", "REVINFO")); MetadataTools.AddNativelyGeneratedId(classMapping, revisionInfoIdData.Name, revisionPropType); var timestampProperty = MetadataTools.AddProperty(classMapping, revisionInfoTimestampData.Name, revisionInfoTimestampType.Name, true, false, null); MetadataTools.AddColumn(timestampProperty, "REVTSTMP", -1, -1, -1, null, false); if (_globalCfg.IsTrackEntitiesChangedInRevisionEnabled) { generateEntityNamesTrackingTableMapping(classMapping, "ModifiedEntityNames", _globalCfg.DefaultSchemaName, _globalCfg.DefaultCatalogName, "REVCHANGES", "REV", "ENTITYNAME", "string"); } return(document); }
private XmlDocument generateDefaultRevisionInfoXmlMapping() { XmlDocument document = new XmlDocument();//ORIG: DocumentHelper.createDocument(); XmlElement class_mapping = MetadataTools.CreateEntity(document, new AuditTableData(null, null, null, null), null); class_mapping.SetAttribute("name", revisionInfoEntityName); class_mapping.SetAttribute("table", "REVINFO"); XmlElement idProperty = MetadataTools.AddNativelyGeneratedId(document, class_mapping, revisionInfoIdData.Name, revisionPropType); //ORIG: MetadataTools.addColumn(idProperty, "REV", -1, 0, 0, null); XmlElement col = idProperty.OwnerDocument.CreateElement("column"); col.SetAttribute("name", "REV"); //idProperty should have a "generator" node otherwise sth. is wrong. idProperty.InsertBefore(col, idProperty.GetElementsByTagName("generator")[0]); XmlElement timestampProperty = MetadataTools.AddProperty(class_mapping, revisionInfoTimestampData.Name, revisionInfoTimestampType.Name, true, false); MetadataTools.AddColumn(timestampProperty, "REVTSTMP", -1, 0, 0, SqlTypeFactory.DateTime.ToString()); return(document); }
/* * private async void LoadDatasets() * { * await Task.Run(() => * { * PbiMetadataTreeBinding.PbiDatasets = new BindableCollection<Dataset>( * from g in PowerBI_Tools.GetDatasets() * orderby g.Name * select g * ); * * // PbiMetadataBinding.PbiDatasets = PbiMetadataTreeBinding.PbiDatasets; * }); * } */ private async void Logout_Click(object sender, RoutedEventArgs e) { await Authentication.LogoutAAD(); AccessToken = null; PowerBI_Tools = null; this.Logout.Visibility = Visibility.Hidden; this.Login.Content = "Sign in"; this.Login.IsEnabled = true; }
public CodeGenerationToolsForK2(object textTransformation) { if (textTransformation == null) { throw new ArgumentNullException("textTransformation"); } _textTransformation = DynamicTextTransformation.Create(textTransformation); _code = new CSharpCodeProvider(); _ef = new MetadataTools(_textTransformation); }
/// <summary> /// Initializes a new CodeGenerationTools object with the TextTransformation (T4 generated class) /// that is currently running /// </summary> public CodeGenerationTools(object textTransformation) { if(textTransformation == null) throw new ArgumentNullException("textTransformation"); _textTransformation = DynamicTextTransformation.Create(textTransformation); _code = new CSharpCodeProvider(); _ef = new MetadataTools(_textTransformation); FullyQualifySystemTypes = false; CamelCaseFields = true; }
private XElement generateRevisionInfoRelationMapping(string revisionAssQName) { var revRelMapping = new XElement(MetadataTools.CreateElementName("key-many-to-one"), new XAttribute("class", revisionAssQName)); if (revisionPropSqlType != null) { // Putting a fake name to make Hibernate happy. It will be replaced later anyway. MetadataTools.AddColumn(revRelMapping, "*", -1, -1, -1, revisionPropSqlType, false); } return(revRelMapping); }
/// <summary> /// Creates a set of FunctionImportParameter objects from the parameters passed in. /// </summary> public static IEnumerable<FunctionImportParameter> Create(IEnumerable<FunctionParameter> parameters, CodeGenerationTools code, MetadataTools ef) { if(parameters == null) throw new ArgumentNullException("parameters"); if(code == null) throw new ArgumentNullException("code"); if(ef == null) throw new ArgumentNullException("ef"); var unique = new UniqueIdentifierService(); var importParameters = new List<FunctionImportParameter>(); foreach(var parameter in parameters) { var importParameter = new FunctionImportParameter(); importParameter.Source = parameter; importParameter.RawFunctionParameterName = unique.AdjustIdentifier(code.CamelCase(parameter.Name)); importParameter.FunctionParameterName = code.Escape(importParameter.RawFunctionParameterName); if(parameter.Mode == ParameterMode.In) { importParameter.NeedsLocalVariable = true; importParameter.FunctionParameterType = code.Escape(parameter.TypeUsage); importParameter.EsqlParameterName = parameter.Name; var clrType = ef.ClrType(parameter.TypeUsage); importParameter.RawClrTypeName = code.Escape(clrType); importParameter.IsNullableOfT = clrType.IsValueType; } else { importParameter.NeedsLocalVariable = false; importParameter.FunctionParameterType = "ObjectParameter"; importParameter.ExecuteParameterName = importParameter.FunctionParameterName; } importParameters.Add(importParameter); } // we save the local parameter uniquification for a second pass to make the visible parameters // as pretty and sensible as possible for(var i = 0; i < importParameters.Count; i++) { var importParameter = importParameters[i]; if(importParameter.NeedsLocalVariable) { importParameter.LocalVariableName = unique.AdjustIdentifier(importParameter.RawFunctionParameterName + "Parameter"); importParameter.ExecuteParameterName = importParameter.LocalVariableName; } } return importParameters; }
/// <summary> /// Adds a <![CDATA[<many-to-one>]]> mapping to the revision entity as an endrevision. /// Also, if <see cref="AuditEntitiesConfiguration.IsRevisionEndTimestampEnabled"/> set, adds a timestamp when the revision is no longer valid. /// </summary> public void AddExtraRevisionMapping(XElement classMapping, XElement revisionInfoRelationMapping) { var verEntCfg = _auditConfiguration.AuditEntCfg; var manyToOne = MetadataTools.AddManyToOne(classMapping, verEntCfg.RevisionEndFieldName, verEntCfg.RevisionInfoEntityAssemblyQualifiedName, true, true); manyToOne.Add(revisionInfoRelationMapping.Elements()); MetadataTools.AddOrModifyColumn(manyToOne, verEntCfg.RevisionEndFieldName); if (verEntCfg.IsRevisionEndTimestampEnabled) { const string revisionInfoTimestampSqlType = "Timestamp"; MetadataTools.AddProperty(classMapping, verEntCfg.RevisionEndTimestampFieldName, revisionInfoTimestampSqlType, true, true, false, null); } }
private async void Login_Click(object sender, RoutedEventArgs e) { var result = await Authentication.LoginAAD(); if (result != null) { AccessToken = result.AccessToken; PowerBI_Tools = new MetadataTools(AccessToken); this.Logout.Visibility = Visibility.Visible; this.Login.Content = result.Account.Username; this.Login.IsEnabled = false; LoadGroups(PreloadDatasets.IsChecked.Value); // LoadDatasets(); // load all datasets from all groups } }
private XmlElement generateRevisionInfoRelationMapping() { XmlDocument document = new XmlDocument(); XmlElement rev_rel_mapping = document.CreateElement("key-many-to-one"); rev_rel_mapping.SetAttribute("type", revisionPropType); rev_rel_mapping.SetAttribute("class", revisionInfoEntityName); if (revisionPropSqlType != null) { // Putting a fake name to make Hibernate happy. It will be replaced later anyway. MetadataTools.AddColumn(rev_rel_mapping, "*", -1, 0, 0, revisionPropSqlType); } return(rev_rel_mapping); }
private void addBidirectionalInfo(IDictionary <System.Type, IEntityMeta> metas) { foreach (var type in metas.Keys) { var persistentClass = _nhibernateConfiguration.GetClassMapping(type); if (persistentClass == null) { continue; } foreach (var property in persistentClass.PropertyIterator) { //is it a collection? var collectionValue = property.Value as Mapping.Collection; if (collectionValue == null) { continue; } //find referenced entity name var referencedEntity = MappingTools.ReferencedEntityName(property.Value); if (referencedEntity == null) { continue; } var refPersistentClass = _nhibernateConfiguration.GetClassMapping(referencedEntity); foreach (var refProperty in refPersistentClass.PropertyClosureIterator) { if (MetadataTools.IsNoneAccess(refProperty.PropertyAccessorName)) { continue; } var attr = createAuditMappedByAttributeIfReferenceImmutable(collectionValue, refProperty); if (attr == null) { continue; } mightAddIndexToAttribute(attr, collectionValue, refPersistentClass.PropertyClosureIterator); var entityMeta = (EntityMeta)metas[type]; var methodInfo = PropertyAndMemberInfo.PersistentInfo(type, new[] { property }).First().Member; addToEntityMeta(attr, entityMeta, methodInfo); } } } }
/// <summary> /// Checks if a property is audited and if yes, fills all of its data. /// </summary> /// <param name="property">Property to check.</param> /// <param name="mappedPropertyName">NH Property name</param> /// <param name="propertyData">Property data, on which to set this property's modification store.</param> /// <param name="accessType">Access type for the property.</param> /// <param name="allClassAudited">Is class fully audited</param> /// <returns>False if this property is not audited.</returns> private bool fillPropertyData(MemberInfo property, string mappedPropertyName, PropertyAuditingData propertyData, string accessType, AuditedAttribute allClassAudited) { // check if a property is declared as not audited to exclude it // useful if a class is audited but some properties should be excluded if ((_metaDataStore.MemberMeta <NotAuditedAttribute>(property) != null && !_overriddenAuditedProperties.Contains(mappedPropertyName)) || _overriddenNotAuditedProperties.Contains(mappedPropertyName)) { return(false); } // if the optimistic locking field has to be unversioned and the current property // is the optimistic locking field, don't audit it if (_globalCfg.DoNotAuditOptimisticLockingField && _persistentPropertiesSource.VersionedProperty != null && _persistentPropertiesSource.VersionedProperty.Name.Equals(mappedPropertyName)) { return(false); } if (!CheckAudited(property, mappedPropertyName, propertyData, allClassAudited)) { return(false); } var propertyName = _propertyNamePrefix + mappedPropertyName; propertyData.Name = propertyName; propertyData.ModifiedFlagName = MetadataTools.ModifiedFlagPropertyName(propertyName, _globalCfg.ModifiedFlagSuffix); propertyData.BeanName = mappedPropertyName; propertyData.AccessType = accessType; addPropertyJoinTables(property, propertyData); addPropertyAuditingOverrides(property, propertyData); if (!processPropertyAuditingOverrides(property, propertyData)) { return(false); // not audited due to AuditOverride annotation } setPropertyAuditMappedBy(property, propertyData); setCustomMapper(property, propertyData); return(true); }
private static void generateEntityNamesTrackingTableMapping(XElement classMapping, string propertyName, string joinTableSchema, string joinTableCatalog, string joinTableName, string joinTablePrimaryKeyColumnName, string joinTableValueColumnName, string joinTableValueColumnType) { var setMapping = new XElement(MetadataTools.CreateElementName("set"), new XAttribute("name", propertyName), new XAttribute("table", joinTableName), new XAttribute("schema", joinTableSchema), new XAttribute("catalog", joinTableCatalog), new XAttribute("fetch", "join"), new XAttribute("lazy", "false"), new XElement(MetadataTools.CreateElementName("key"), new XAttribute("column", joinTablePrimaryKeyColumnName)), new XElement(MetadataTools.CreateElementName("element"), new XAttribute("type", joinTableValueColumnType), new XElement(MetadataTools.CreateElementName("column"), new XAttribute("name", joinTableValueColumnName)))); classMapping.Add(setMapping); }
public static IEnumerable <DeclaredPersistentProperty> PersistentInfo(System.Type @class, IEnumerable <Property> properties, bool includeEmbedded) { // a persistent property can be anything including a noop "property" declared in the mapping // for query only. In this case I will apply some trick to get the MemberInfo. var candidateMembers = @class.GetFields(DefaultBindingFlags).Concat(@class.GetProperties(DefaultBindingFlags).Cast <MemberInfo>()).ToList(); var candidateMembersNames = candidateMembers.Select(m => m.Name).ToList(); foreach (var property in properties) { if (includeEmbedded && property.PropertyAccessorName == "embedded") { yield return(new DeclaredPersistentProperty(property, DeclaredPersistentProperty.NotAvailableMemberInfo)); } if (MetadataTools.IsNoneAccess(property.PropertyAccessorName)) { yield return(new DeclaredPersistentProperty(property, DeclaredPersistentProperty.NotAvailableMemberInfo)); } var exactMemberIdx = candidateMembersNames.IndexOf(property.Name); if (exactMemberIdx >= 0) { // No metter which is the accessor the audit-attribute should be in the property where available and not // to the member used to read-write the value. (This method work even for access="field"). yield return(new DeclaredPersistentProperty(property, candidateMembers[exactMemberIdx])); } else { // try to find the field using field-name-strategy // // This part will run for: // 1) query only property (access="none" or access="noop") // 2) a strange case where the element <property> is declared with a "field.xyz" but only a field is used in the class. (Only God may know way) var exactFieldIdx = getMemberIdxByFieldNamingStrategies(candidateMembersNames, property); if (exactFieldIdx >= 0) { yield return(new DeclaredPersistentProperty(property, candidateMembers[exactFieldIdx])); } } } }
static void Main(string[] args) { Console.WriteLine("Entity Frameworks CodeGenerationTools Demo Program.\n"); //I had problems with accessing Dictionary by [] index, so quickly used these //to check in normal C# usage. //var tc = new TestCollections(); //tc.TestCollections2(); try { //As this program only reads and interprets the XML within the EDMX, //there is no need for a ConnectionString in the App.Config and //no connection is made to a database. //Since this is a test program, let's assume you are executing from .\bin\Debug var currentdirectory = Environment.CurrentDirectory; var inputFile = @"..\..\Model1.edmx"; inputFile = Path.Combine(currentdirectory, inputFile); //Demo 1 //EFFluentUtility is from //http://visualstudiogallery.msdn.microsoft.com/5d663b99-ed3b-481d-b7bc-b947d2457e3c //By opening the VSIX (DbContextFluentTemplate_V50, which is a ZIP) I've taken a //copy of "CSharpDbContextFluent.Mapping.tt" from the ItemTemplate. //Then copied the supporting classes from the template and //entered here in the CodeGenerationToolsLibrary project as a .Net Class here. //I've used the Mapping.tt because it is the most complex, //and shows how to obtain the Mapping info used to //create the EntityConfiguration from the EDMX. // // See PropertyToColumnMapping and ManyToManyMappings from // MetadataLoadResult // EF5FluentUtility efu = new EF5FluentUtility(); MetadataLoadResult mlr = efu.LoadMetadata(inputFile); var a = mlr.EdmItems; var b = mlr.ManyToManyMappings; var c = mlr.PropertyToColumnMapping; var d = mlr.TphMappings; //Obtain the EntityContainer from the ItemsCollection var container = mlr.EdmItems.GetItems <EntityContainer>()[0]; //Iterate all the EntitySets and Properties //EntitySet are as in "People", where the EntityType is "Person" foreach (var entityset in container.BaseEntitySets.OfType <EntitySet>().OrderBy(e => e.Name)) { var entitysetname = entityset.Name; var entityname = entityset.ElementType.Name; var entitytype = entityset.ElementType; var declaringtype = entityset.ElementType.NavigationProperties[0].DeclaringType; //Navigation Properties for a particular Entity var collectionNavigations1 = entityset.ElementType.NavigationProperties.Where(np => np.DeclaringType == entityset.ElementType); // Find m:m relationshipsto configure for a particular Entity var manyManyRelationships = entityset.ElementType.NavigationProperties .Where(np => //np.DeclaringType is EntityType && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many && np.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many // Ensures we only configure from one end. // Convention is to have source on the left, as it would be diagrammatically. && np.RelationshipType.RelationshipEndMembers.First() == np.FromEndMember) .ToArray(); //Now process the M:Ms foreach (var navProperty in manyManyRelationships) { var otherNavProperty = navProperty.ToEndMember.GetEntityType().NavigationProperties.Where(n => n.RelationshipType == navProperty.RelationshipType && n != navProperty).Single(); var association = (AssociationType)navProperty.RelationshipType; //This did not work in the T4 Template. var mapping1 = mlr.ManyToManyMappings[association]; var mapping2 = mlr.ManyToManyMappings.Where(m => m.Key.Name == association.Name).FirstOrDefault().Value; var item1 = mapping1.Item1; //This did not work in the T4 Template. var leftKeyMappings1 = mapping1.Item2[navProperty.ToEndMember]; var leftKeyMappings2 = mapping1.Item2.Where(np => np.Key.Name == navProperty.ToEndMember.Name).FirstOrDefault().Value; // Need to ensure that FKs are declared in the same order as the PK properties on each principal type var leftType = (EntityType)navProperty.DeclaringType; var rightType = (EntityType)otherNavProperty.DeclaringType; //Access using Index [navProperty.FromEndMember] did not work within template. var leftKeyMappings = mapping1.Item2.Where(np => np.Key.Name == navProperty.FromEndMember.Name).FirstOrDefault().Value; //[navProperty.FromEndMember]; var rightKeyMappings = mapping1.Item2.Where(np => np.Key.Name == otherNavProperty.FromEndMember.Name).FirstOrDefault().Value; //[otherNavProperty.FromEndMember]; var left = leftKeyMappings.Where(km => km.Key.Name == "PersonID"); var right = rightType.KeyMembers.Select(m => "\"" + rightKeyMappings.Where(km => km.Key.Name == m.Name).FirstOrDefault().Value + "\"").FirstOrDefault(); } //Dual OrderBy to bring Keys to top of list //Iterate all properties for this particular Entity. var properties = entityset.ElementType.Properties.OrderBy(s => s.Name).OrderBy(p => entityset.ElementType.KeyMembers.Contains(p) == false).ToArray(); foreach (var property in properties) { var propertyname = property.Name; //This did not work in the T4 Template. var mapping1 = mlr.PropertyToColumnMapping[entityset.ElementType]; //PropertyToColumnMapping is a collection for ALL Entities, so here the particular Entity needs to be filtered out. //Mapping returned is a complex generic Dictionary. var mapping2 = mlr.PropertyToColumnMapping.Where(k => k.Key == entityset.ElementType).FirstOrDefault().Value; var mapping3 = mlr.PropertyToColumnMapping.Where(k => k.Key.FullName == entityset.ElementType.FullName).FirstOrDefault().Value; var mapping4 = mapping3.Item2.Where(p => p.Key.Name == property.Name).FirstOrDefault().Value; var i1 = mapping1.Item1; var i2 = mapping1.Item2; var mapright = i2[property]; } } //******************************************************************************** //Demo 2 //This takes EF.Utility.CS.ttinclude and receates as //.net Classes. // MyTextTransformation tt = new MyTextTransformation(); CodeGenerationTools code = new CodeGenerationTools(tt); CodeRegion cregion = new CodeRegion(tt, 1); MetadataTools mtool = new MetadataTools(tt); MetadataLoader mloader = new MetadataLoader(tt); var ItemCollection = mloader.CreateEdmItemCollection(inputFile); var Container = ItemCollection.GetItems <EntityContainer>()[0]; Console.WriteLine(String.Format("Container Name: {0}", Container.Name)); Console.WriteLine(String.Format("Model Namespace: {0}", mloader.GetModelNamespace(inputFile))); Console.WriteLine(String.Format("No Of Items in ItemsCollection: {0}\n", ItemCollection.Count)); Console.WriteLine("Press any key to continue.\n"); Console.ReadKey(); foreach (var i in ItemCollection) { Console.WriteLine(String.Format("Item: {0}, {1}", i.ToString(), i.BuiltInTypeKind.ToString())); } Console.WriteLine("Press any key to continue.\n"); Console.ReadKey(); EdmItemCollection edmItemCollection = null;; var ret = mloader.TryCreateEdmItemCollection(inputFile, out edmItemCollection); StoreItemCollection storeItemCollection = null; ret = mloader.TryCreateStoreItemCollection(inputFile, out storeItemCollection); StorageMappingItemCollection storageMappingItemCollection = null; ret = mloader.TryCreateStorageMappingItemCollection(inputFile, edmItemCollection, storeItemCollection, out storageMappingItemCollection); foreach (var i in storageMappingItemCollection) { Console.WriteLine(String.Format("Item: {0}, {1}", i.ToString(), i.BuiltInTypeKind.ToString())); } DataSpace ds = storageMappingItemCollection.DataSpace; MetadataWorkspace metadataWorkspace = null; ret = mloader.TryLoadAllMetadata(inputFile, out metadataWorkspace); //Get the schema "dbo" from a particular Entity. EntityContainer ec = storeItemCollection.GetItems <EntityContainer>().First(); EntitySet eset = ec.GetEntitySetByName(code.Escape("People"), true); string schemaName1 = eset.MetadataProperties["Schema"].Value.ToString(); //Get the schema "dbo" from any Entity. I guess the schema will be same for all?! EntitySetBase fes = ec.BaseEntitySets.FirstOrDefault(); string schemaName2 = fes.MetadataProperties["Schema"].Value.ToString(); var edmxSchema = EDMXchema.GetSchemaElement(inputFile); Console.WriteLine("Press any key to continue.\n"); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("Press any key to quit."); Console.ReadKey(); // var loadResult = LoadMetadata(inputFile); }
public string Get(AuditConfiguration auditCfg) { return(MetadataTools.ModifiedFlagPropertyName(_propertyNameGetter.Get(auditCfg), auditCfg.GlobalCfg.ModifiedFlagSuffix)); }