public EntityFieldsMapper(Type entityType, PersistentStorage ps) { _ps = ps; ObjectDescription od = ClassFactory.GetObjectDescription(entityType, ps); foreach (PropertyDescription prop in od.Properties) { string dbPropName = ""; FieldNameAttribute attr = prop.GetAttribute <FieldNameAttribute>(); if (attr == null) { dbPropName = prop.Name; } else if (prop.ReflectedObject.GetAttribute <IdFieldNameAttribute>() != null && prop.ReflectedObject.GetAttribute <IdFieldNameAttribute>().Name == prop.Name) { dbPropName = prop.ReflectedObject.GetAttribute <IdFieldNameAttribute>().Name; } else { dbPropName = attr.FieldName; } _entityFieldsMapping.Add(prop.Name, dbPropName); _entityFieldsMappingInverse.Add(dbPropName, prop.Name); } }
public IEntity LoadEntityById(object Id) { ObjectDescription od = ClassFactory.GetObjectDescription(ReflectedType); string sqlQuery = SqlQueryBuilder.BuildSelectSingleRow(od, Id); SqlCommand command = new SqlCommand(sqlQuery, _connection); SqlDataReader reader = command.ExecuteReader(); if (!reader.HasRows) { return(null); } IEntity e = (IEntity)od.CreateObject(); foreach (PropertyDescription prop in od.Properties) { if (prop.IsRelation) { continue; } prop.SetValue(e, reader[Mapper[prop.Name]]); } foreach (PropertyDescription prop in od.Relations) { if (prop.IsOneToOneRelation) { object oid = reader[Mapper[prop.Name]]; Type t = prop.RelatedType; IEntity ent = _ps.GetEntityById(t, oid); prop.SetValue(e, ent); } } return(e); }
private string GetValueList(EntityBase e) { string list = ""; ObjectDescription od = ClassFactory.GetObjectDescription(_mapper.EntityType, _ps); foreach (PropertyDescription pd in od.Properties) { if (pd == od.IdField || pd.IsNonPersistent || pd.IsOneToManyRelation || pd.IsManyToManyRelation) { continue; } if (list != "") { list += ", "; } if (pd.IsOneToOneRelation) { list += (e[pd.Name] as EntityBase)[pd.RelationAttribute.RelatedColumn]; } else { list += ValueToString(e[pd.Name]); } } return(list); }
/// <summary> /// /// </summary> /// <param name="entity"></param> /// <returns>If there is now row corresponding to the entity (because it has been recently created) /// then a new row is created</returns> private DataRow GetUnderlyingRow(IEntity entity) { ObjectDescription od = ClassFactory.GetObjectDescription(ReflectedType, _ps); DataView dv = new DataView(UnderlyngDataSet.Tables[Mapper.TableName]); DataRow row; if (entity.State == EntityState.New) { row = dv.Table.NewRow(); if (row[Mapper[od.IdField.Name]] == null || row[Mapper[od.IdField.Name]] == DBNull.Value) { entity.ID = row[Mapper[od.IdField.Name]] = Guid.NewGuid(); } else { entity.ID = row[Mapper[od.IdField.Name]]; } } else { object id = od.IdField.GetValue(entity); //dv.RowFilter = CreateFilterString(Mapper[od.IdField.Name], id); row = dv.Table.Rows.Find(id); } return(row); }
public static string BuildSelectSingleRow(ObjectDescription od, object id) { Mapper m = new Mapper(od.ObjectType); string sqlQuery = "SELECT "; foreach (PropertyDescription prop in od.Properties) { sqlQuery += m[prop.Name] + ","; } if (sqlQuery[sqlQuery.Length - 1] == ',') { sqlQuery = sqlQuery.Remove(sqlQuery.Length - 1); } else { throw new Exception("There is no data to load from Database"); } sqlQuery += " FROM "; sqlQuery += m.TableName + " "; sqlQuery += "WHERE "; sqlQuery += m[od.IdField.Name] + " = "; if (id is int) { sqlQuery += id.ToString(); } else { sqlQuery += "'" + id.ToString() + "'"; } return(sqlQuery); }
private IEntity ProcessProperties(ref EntityBase entity, DataRow row) { ObjectDescription od = ClassFactory.GetObjectDescription(ReflectedType, _ps); List <PropertyDescription> l = new List <PropertyDescription>(); foreach (PropertyDescription prop in od.Properties) { if (prop.GetAttribute <NonPersistentAttribute>() != null) { continue; } if (prop.IsId) { continue; } RelationAttribute relAttr = prop.GetAttribute <RelationAttribute>(); if (relAttr != null) { if (relAttr.RelationType == RelationType.ManyToMany) { l.Add(prop); continue; } else if (relAttr.RelationType == RelationType.OneToOne) { SetOtoRelationValue(ref entity, row, relAttr, prop); continue; } else if (relAttr.RelationType == RelationType.OneToMany) { l.Add(prop); continue; } } object val = prop.GetValue(entity); if (val != null) { row[Mapper[prop.Name]] = val; } else { row[Mapper[prop.Name]] = DBNull.Value; } } entity.AcceptChanges(); foreach (PropertyDescription prop in l) { RelationAttribute relAttr = prop.GetAttribute <RelationAttribute>(); if (relAttr.RelationType == RelationType.ManyToMany) { SetMtmRelationValues(ref entity, row, relAttr, prop); } else if (relAttr.RelationType == RelationType.OneToMany) { SetOtmRelationValues(ref entity, row, relAttr, prop); } } return(entity); }
public virtual DependencyProvider[] CreateDependencyProviders(Kernel kernel, ObjectDescription description, bool strongTyped) { var depProvider = DependencyProvider.CreatePropertyProvider(description, _property, strongTyped); depProvider.InjectObjectBuilders(kernel); return(new DependencyProvider[] { depProvider }); }
static DependencyProvider[] DoCreateParameterProviders(ObjectDescription description, MethodBase methodBase, bool strongTyped) { var paramInfos = methodBase.GetParameters(); var methodParameterCount = paramInfos.Length; if (methodParameterCount == 0) { return(null); } var dependencies = new DependencyProvider[methodParameterCount]; for (var i = 0; i < methodParameterCount; i++) { var paramInfo = paramInfos[i]; if (paramInfo.ParameterType.IsAutowirable()) { dependencies[i] = CreateAutowiredDependencyProvider(new ParameterInjectionTargetInfo(paramInfo, description), strongTyped); } else { throw ParameterException.RequiredParameterNotProvided(methodBase, paramInfo); } } return(dependencies); }
public void Save(List <IEntity> entities) { ObjectDescription ObjectType = null; if (entities.Count > 0) { ObjectType = new ObjectDescription(entities[0].GetType()); } else { return; } XmlDocument doc = new XmlDocument(); doc.Load(Source); XPathNavigator nav = doc.CreateNavigator(); nav.MoveToFollowing(ObjectType.TableName, ""); foreach (IEntity entity in entities) { if (entity.Id != 0) { Update(entity, nav); } else { Insert(entity, nav); } } doc.Save(Source); }
private object GetValueInternal(string key, bool oldValue, bool fromGetValue) { ObjectDescription d = ClassFactory.GetObjectDescription(GetType(), CreatorPs); //ClassFactory.GetThreadDefaultPs(System.Threading.Thread.CurrentThread)); object val = null; if (_values.IsUnassignedValue(key) && !fromGetValue) { val = d.Properties[key].GetValue(this); _values[key] = val; return(val); } if (oldValue) { //return GetValueFromDic(_oldValues, key); //return _row[key, DataRowVersion.Original]; val = _values[key, true]; } else { val = _values[key]; //GetValueFromDic(_values, key); if (PropertyValueGet != null) { PropertyValueGet(this, d.Properties[key], val); } } if ((d.Properties[key].IsManyToManyRelation || d.Properties[key].IsOneToManyRelation) && val == null) { val = _values[key] = Activator.CreateInstance(d.Properties[key].PropertyType, this, d.Properties[key]); } return(val); }
public void SetOtmRelations(EntityBase entity) { foreach (PropertyDescription p in ClassFactory.GetObjectDescription(ReflectedType, _ps).Relations) { if (p.IsOneToManyRelation && !p.IsNonPersistent && !p.IsInternal) { ObjectDescription od = ClassFactory.GetObjectDescription(p.RelatedType, _ps); PropertyDescription pd = od.Properties[p.RelationAttribute.RelatedColumn]; Mapper m = new Mapper(pd.ReflectedObject.ObjectType, _ps); string select = "SELECT " + m[pd.ReflectedObject.IdField.Name, true] + " FROM " + m.FullTableName + " AS t" + " WHERE " + m[pd.Name, true] + " = " + IdToString(entity.ID); List <object[]> list = new List <object[]>(); GetReader(select, list); foreach (object[] val in list) { object id = val[0]; EntityBase e = _ps.GetEntityById(p.RelatedType, id); if (e != null) { (p.GetValue(entity) as IList).Add(e); } } } } }
public List <EntityBase> LoadAll() { ObjectDescription od = new ObjectDescription(ReflectedType, _ps); string select = null; if (_selectAll == null) { _selectAll = select = BuildSqlSelect(ReflectedType); } else { select = _selectAll; } //DateTime t1 = _dt = DateTime.Now; List <EntityBase> list = FillEntityList(select); if (list.Count > 0) { SetOtoRelations(list); SetOtmRelations(list); SetMtmRelations(list); } //} foreach (EntityBase entity in list) { entity.EndLoad(); } return(list); }
/// <summary> /// Create a Table from an Object /// </summary> void CreateTable(string name, ObjectDescription description, DataColumnCollection newColumns = null) { if (newColumns != null) { _db.ExecuteSQL("drop table [" + _schemaObjects + "].[" + name + "]"); } string query = "create table [" + _schemaObjects + "].[{0}] ("; List <string> columns = new List <string>(); foreach (var item in description.fields.OrderBy(F => F.name)) { columns.Add("[" + item.name + "] " + DataType(item)); } query = query + string.Join(",", columns) + ")"; _db.ExecuteSQL(query.Replace("{0}", name)); if (description.fields.Any(F => F.name.ToLower() == "SystemModstamp".ToLower())) { _db.ExecuteSQL("CREATE INDEX [I_" + name + "_SM] ON [" + name + "] ([SystemModstamp])"); } }
public List <EntityBase> LoadAll() { List <EntityBase> list = new List <EntityBase>(); ObjectDescription od = ClassFactory.GetObjectDescription(ReflectedType, _ps); XmlReader reader = NavigateToNode(Mapper.TableName, _sourceReader); string entNodeName = "entity"; reader.ReadToDescendant(od.ObjectType.Name); // Now we are at the first record of the needed table while (!reader.EOF) { XmlReader rdr = reader.ReadSubtree(); // get the subtree of the entity instance rdr.Read(); // Get the root node of the entity instance EntityBase entity = ReadObject(rdr, od); //SkipWhiteSpace(reader); _ps.Caches[ReflectedType].Add(entity); reader.ReadToFollowing(od.ObjectType.Name); list.Add(entity); } SetOtoRelations(list); SetOtmRelations(list); SetMtmRelations(list); return(list); }
public string CreateUpdateStatement(EntityBase e) { ObjectDescription od = ClassFactory.GetObjectDescription(_mapper.EntityType, _ps); string nameValuePairs = ""; foreach (PropertyDescription pd in od.Properties) { if (pd == od.IdField || pd.IsNonPersistent || pd.IsOneToManyRelation || pd.IsManyToManyRelation) { continue; } if (nameValuePairs != "") { nameValuePairs += ", "; } if (pd.IsOneToOneRelation) { nameValuePairs += SqlMapper[pd.Name] + " = " + (e[pd.Name] as EntityBase)[pd.RelationAttribute.RelatedColumn]; } else { nameValuePairs += SqlMapper[pd.Name] + " = " + ValueToString(e[pd.Name]); } } nameValuePairs += ", " + ValueToString(e.ID) + " AS " + _mapper[od.IdField.Name]; return(_updateTemplate.Replace("@@NameValuePairs", nameValuePairs).Replace("@@ID", ValueToString(e.ID))); }
private void WriteEntity(IEntity entity, XPathNavigator nav) { ObjectDescription ObjectType = new ObjectDescription(entity.GetType()); foreach (PropertyInfo prop in ObjectType.Properties) { nav.MoveToFollowing(prop.Name, ""); bool write = true; foreach (object o in prop.GetCustomAttributes(true)) { if (o is NonPersistentAttribute) { write = false; } } if (write) { try { object value = ObjectType.GetPropertyValueForSave(prop.Name, entity); nav.SetTypedValue(value); } catch { throw new ApplicationException(string.Format("Unable to write attribute: {0}", prop.Name)); } } nav.MoveToParent(); } }
private void SearchTextBox_KeyDown(object sender, KeyEventArgs e) { if (ResultsListBox.SelectedIndex == -1) { if (ResultsListBox.Items.Count > 0) { ResultsListBox.SelectedIndex = 0; } else { return; } } if (e.Key == Key.Down) { ResultsListBox.SelectedIndex = (ResultsListBox.SelectedIndex + 1) % ResultsListBox.Items.Count; } else if (e.Key == Key.Up) { ResultsListBox.SelectedIndex = (ResultsListBox.SelectedIndex - 1) % ResultsListBox.Items.Count; } else if (e.Key == Key.Enter || e.Key == Key.Return) { ObjectDescription o = ResultsListBox.SelectedItem as ObjectDescription; if (o != null) { GearsetResources.Console.Inspect(o.Name, o.Object); } } }
/// <summary> /// Extract information for a class. /// </summary> /// <param name="assembly"></param> /// <param name="className"></param> /// <param name="defaultLang"></param> /// <param name="element"></param> private static void ProcessClass(Assembly resources, string assembly, string className, string defaultLang, XElement element) { MasterObjectTable mot = Locator.Current.GetService <MasterObjectTable>(); // Get the descriptions IEnumerable <XElement> nodes = from node in element.Descendants(DescriptionTag) select node; if (nodes.Count() > 0) { // Process the description LogHost.Default.Debug("Loading description definition for class '{0}'", className); ObjectDescription description = ProcessDescription(defaultLang, nodes.First()); if ((description.Icon != null) && (description.Icon.Length > 0)) { description.Icon = CopyIconImage(resources, assembly, description.Icon); } mot.AddDescription(className, description); } // Get the configurations nodes = from node in element.Descendants(ConfigurationTag) select node; if (nodes.Count() > 0) { // Process the configuration LogHost.Default.Debug("Loading configuration definition for class '{0}'", className); IConfigurationDescription config = ProcessConfiguration(defaultLang, nodes.First()); if (config != null) { mot.AddConfigurationDescription(className, config); } } }
private void GetOtmRealationValues(ref EntityBase entity, DataRow row, RelationAttribute relAttr, PropertyDescription property) { ObjectDescription od = ClassFactory.GetObjectDescription(ReflectedType, _ps); Cryptany.Core.DPO.Mapper m = new Mapper(relAttr.RelatedType, _ps); DataRelation rel = ForeignKeys[property]; //foreach ( DataRelation r in UnderlyngDataSet.Tables[Mapper.TableName].ChildRelations ) //{ // if ( r.ChildTable == UnderlyngDataSet.Tables[m.TableName] ) // rel = r; //} //if ( rel == null ) // throw new Exception("The child relation was not found"); (property.GetValue(entity) as IList).Clear(); string relatedTypeIdField = ClassFactory.GetObjectDescription(relAttr.RelatedType, _ps).IdField.Name; foreach (DataRow childrow in entity.SourceRow.GetChildRows(rel)) { object childid = childrow[m[relatedTypeIdField]]; if (childid == null || childid == DBNull.Value) { continue; } EntityBase e = _ps.GetEntityById(relAttr.RelatedType, childid); (property.GetValue(entity) as IList).Add(e); } }
public void Save(EntityBase entity) { if (entity.State == EntityState.Unchanged || entity.State == EntityState.NewDeleted) { return; } if (!_compiled) { Compile(); } ObjectDescription od = ClassFactory.GetObjectDescription(entity.GetType(), _ps); EntityBase ent; if (od.IsWrapped) { ent = (entity as IWrapObject).WrappedObject; _ps.SaveInner(ent); return; } else { ent = entity; } DataRow row = GetUnderlyingRow(ent); bool isNew = ent.State == EntityState.New; //ent.State = EntityState.Unchanged; if (isNew && !_ps.Caches[ent.GetType()].Contains(ent.ID)) { _ps.Caches[ent.GetType()].Add(ent); } if (ent.State == EntityState.Deleted || ent.State == EntityState.NewDeleted) { if (_ps.Caches[ent.GetType()].Contains(ent.ID)) { _ps.Caches[ent.GetType()].Delete(ent); } } //else { ProcessProperties(ref ent, row); if (isNew) { UnderlyngDataSet.Tables[Mapper.TableName].Rows.Add(row); //UpdateParentEntities(ent); } } if (ent.State == EntityState.Deleted) { row.Delete(); } ent.AcceptChanges(); }
public static DependencyProvider CreatePropertyProvider(ObjectDescription description, PropertyInfo property, bool strongTyped) { Requires.NotNull(description, "description"); Requires.NotNull(property, "property"); IInjectionTargetInfo injectionTargetInfo = new PropertyInjectionTargetInfo(property, description); return(CreateAutowiredDependencyProvider(injectionTargetInfo, strongTyped)); }
public static DependencyProvider[] CreateParameterProviders(ObjectDescription description, MethodBase methodBase, ParameterSet configuredParameters, bool strongTyped) { Requires.NotNull(description, "description"); Requires.NotNull(methodBase, "methodBase"); return(configuredParameters == null ? DoCreateParameterProviders(description, methodBase, strongTyped) : DoCreateParameterProviders(description, methodBase, configuredParameters, strongTyped)); }
static void AppendObjectDescriptionDetail(StringBuilder sb, ObjectDescription description) { sb.Append("ContractType = "); sb.Append(description.ContractType.ToTypeName()); sb.AppendLine(); sb.Append("ConcreteType = "); sb.Append(description.ConcreteType.ToTypeName()); }
public List <T> GetEntities <T>() where T : EntityBase { Type type = typeof(T); ObjectDescription objDescr = ClassFactory.GetObjectDescription(type, this); if (!objDescr.IsAggregated) { ILoader loader = GetLoader(type); List <T> list = Caches.GetEntities <T>(); if ((list == null || list.Count == 0) && !_loadedTypes.Contains(type)) { { if (objDescr.IsVirtual) { List <EntityBase> l = (List <EntityBase>) type.GetMethod(objDescr.GetAllMethodName, BindingFlags.Static).Invoke(null, new object[] { this }); list = l.ConvertAll <T>( delegate(EntityBase e) { return(e as T); } ); } else { list = loader.LoadAll <T>(); } _loadedTypes.Add(type); } } if (list == null || list.Count == 0) { list = new List <T>(); } return(list); } else { AgregatedClassAttribute aggr = objDescr.GetAttribute <AgregatedClassAttribute>(); List <T> l = new List <T>(); foreach (Type t in aggr.ChildTypes) { List <EntityBase> templist = GetEntities(t); if (templist != null && templist.Count > 0) { foreach (T ee in templist) { l.Add(ee); } } } return(l); } }
public void CreateNew() { ObjectDescription od = ClassFactory.GetObjectDescription(this.GetType(), this.CreatorPs); if (od.IdFiledType == typeof(Guid)) { this[od.IdField.Name] = Guid.NewGuid(); } State = EntityState.New; }
public TypedInjectionConfigurationGroup(ObjectDescription description, IConstructorInjectionConfigurationItem ctorConfigItem) : base(description) { Requires.NotNull(ctorConfigItem, "ctorConfigItem"); if (!ctorConfigItem.MatchInjectionConfigurationGroup(this)) { throw new InvalidOperationException(); } _ctorConfigItem = ctorConfigItem; }
internal void DoSetInstance(ObjectDescription description, LifetimeScopeWithParent currentScope, object instance) { if (_cachedInstances == null) { _cachedInstances = new Dictionary <ScopedInstanceKey, object>(); } var key = new ScopedInstanceKey(description, currentScope); _cachedInstances.Add(key, instance); }
protected void Results_DoubleClick(object sender, MouseButtonEventArgs e) { if (e.OriginalSource != null) { ObjectDescription o = ((FrameworkElement)e.OriginalSource).DataContext as ObjectDescription; if (o != null) { GearsetResources.Console.Inspect(o.Name, o.Object); } } }
internal object DoGetInstance(ObjectDescription description, LifetimeScopeWithParent currentScope) { if (_cachedInstances == null) { return(null); } var key = new ScopedInstanceKey(description, currentScope); object instance; return(_cachedInstances.TryGetValue(key, out instance) ? instance : null); }
public InjectionConfigurationSet(ObjectDescription description, ObjectRelation admin, InjectionConfigurationGroup defaultGroup) { if (!defaultGroup.MatchInjectionConfigurationSet(this)) { throw new InvalidOperationException(); } _description = description; _admin = admin; _defaultGroup = defaultGroup; }
/// <summary> /// Extract a description from the given element. /// /// This is used for the object description as well as individual item descriptions. /// </summary> /// <param name="defaultLang"></param> /// <param name="parent"></param> /// <returns></returns> private static ObjectDescription ProcessDescription(string defaultLang, XElement parent) { ObjectDescription description = new ObjectDescription(); // Get the text first description.DisplayName = GetLocalisedText(defaultLang, parent, DisplayNameTag); description.Description = GetLocalisedText(defaultLang, parent, ShortDescriptionTag); description.DetailedDescription = GetLocalisedText(defaultLang, parent, LongDescriptionTag); // Handle the icon differently IEnumerable<XElement> nodes = from node in parent.Descendants(IconTag) where node.Attribute(ImageAttribute) != null select node; if (nodes.Count() > 0) { description.Icon = nodes.First().Attribute(ImageAttribute).Value.Trim(); } // Done return description; }