Ejemplo n.º 1
0
        /// <summary>
        /// Creates properties for the given <see cref="JsonContract"/>.
        /// </summary>
        /// <param name="type">The type to create properties for.</param>
        /// /// <param name="memberSerialization">The member serialization mode for the type.</param>
        /// <returns>Properties for the given <see cref="JsonContract"/>.</returns>
        protected override IList <JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var members = GetSerializableMembers(type);

            if (members == null)
            {
                throw new JsonSerializationException("Null collection of seralizable members returned.");
            }

            var properties         = new JsonPropertyCollection(type);
            var modelConfiguration = _breezeConfigurator.GetModelConfiguration(type);

            foreach (var member in members)
            {
                var property = CreateProperty(type, member, memberSerialization, modelConfiguration);

                if (property != null)
                {
                    var nameTable = DefaultContractResolverStateNameTableField.GetValue(this);
                    // nametable is not thread-safe for multiple writers
                    lock (nameTable)
                    {
                        property.PropertyName = (string)PropertyNameTableAddMethod
                                                .Invoke(nameTable, new object[] { property.PropertyName });
                    }

                    properties.AddProperty(property);
                }
            }

            var syntheticPoperties = _getMetadataFunc(type).GetSyntheticProperties();

            if (syntheticPoperties != null && syntheticPoperties.Any())
            {
                foreach (var syntheticProp in syntheticPoperties)
                {
                    var propertyName = ResolvePropertyName(syntheticProp.Name);

                    // Skip manually added syntetic properties
                    if (!properties.Any(x => x.PropertyName == propertyName))
                    {
                        properties.Add(new JsonProperty
                        {
                            Readable      = true,
                            Writable      = true,
                            PropertyName  = propertyName,
                            PropertyType  = syntheticProp.PkType.ReturnedClass,
                            ValueProvider = new NHSyntheticPropertyValueProvider(syntheticProp)
                        });
                    }
                }
            }

            IList <JsonProperty> orderedProperties = properties.OrderBy(p => p.Order ?? -1).ToList();

            ApplySerializationRules(type, orderedProperties, memberSerialization);
            return(orderedProperties);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Refresh the entities from the database.  This picks up changes due to triggers, etc.
 /// </summary>
 /// <param name="saveMap"></param>
 protected void RefreshFromSession(Dictionary <Type, List <EntityInfo> > saveMap)
 {
     //using (var tx = session.BeginTransaction()) {
     foreach (var kvp in saveMap)
     {
         var config = breezeConfigurator.GetModelConfiguration(kvp.Key);
         if (!config.RefreshAfterSave && !config.RefreshAfterUpdate)
         {
             continue;
         }
         foreach (var entityInfo in kvp.Value)
         {
             if ((entityInfo.EntityState == EntityState.Added && config.RefreshAfterSave) || (entityInfo.EntityState == EntityState.Modified && config.RefreshAfterUpdate))
             {
                 session.Refresh(entityInfo.Entity);
             }
         }
     }
     //tx.Commit();
     //}
 }
        private void AddEntityType(
            EntityMetadata entityMetadata,
            BreezeMetadata metadata)
        {
            var type = entityMetadata.Type;
            var modelConfiguration = _breezeConfigurator.GetModelConfiguration(type);
            var entityType         = new EntityType(type)
            {
                BaseTypeName = entityMetadata.BaseType != null
                    ? GetBreezeTypeFullName(entityMetadata.BaseType)
                    : null,
                AutoGeneratedKeyType = modelConfiguration.AutoGeneratedKeyType ?? entityMetadata.AutoGeneratedKeyType,
                DefaultResourceName  = modelConfiguration.ResourceName ?? Pluralize(type.Name),
                Custom = modelConfiguration.Custom
            };

            metadata.ResourceEntityTypeMap.Add(entityType.DefaultResourceName, GetBreezeTypeFullName(type));

            AddProperties(entityMetadata, entityType, modelConfiguration, metadata);

            metadata.StructuralTypes.Add(entityType);
        }
Ejemplo n.º 4
0
        private bool SetupEntityInfoForSaving(Type entityType, EntityInfo entityInfo, IClassMetadata meta)
        {
            var    id          = meta.GetIdentifier(entityInfo.Entity);
            var    sessionImpl = _session.GetSessionImplementation();
            object dbEntity;

            string[] propNames;

            if (entityInfo.EntityState == EntityState.Added)
            {
                //meta.Instantiate(id) -> Instantiate method can create a proxy when formulas are present. Saving non persistent proxies will throw an exception
                dbEntity = Activator.CreateInstance(entityType, true);
                meta.SetIdentifier(dbEntity, id);
            }
            else
            {
                //dbEntity = session.Get(entityType, id); Get is not good as it can return a proxy
                if (meta.IdentifierType.IsComponentType)
                {
                    // for entities with composite key the identifier is the entity itself
                    // we need to create a copy as ImmediateLoad will fill the given entity
                    var componentType = (ComponentType)meta.IdentifierType;
                    dbEntity = Activator.CreateInstance(entityType, true);

                    // We need to check if the primary key was changed
                    var oldKeyValues = new object[componentType.PropertyNames.Length];
                    var keyModified  = false;
                    for (var i = 0; i < componentType.PropertyNames.Length; i++)
                    {
                        var propName = componentType.PropertyNames[i];
                        if (entityInfo.OriginalValuesMap.ContainsKey(propName))
                        {
                            oldKeyValues[i] = entityInfo.OriginalValuesMap[propName];
                            keyModified     = true;
                        }
                        else
                        {
                            oldKeyValues[i] = componentType.GetPropertyValue(entityInfo.Entity, i);
                        }
                    }

                    componentType.SetPropertyValues(dbEntity, oldKeyValues);
                    dbEntity = sessionImpl.ImmediateLoad(entityType.FullName, dbEntity);

                    // As NHibernate does not support updating the primary key we need to do it manually using hql
                    if (keyModified)
                    {
                        var newKeyValues   = componentType.GetPropertyValues(entityInfo.Entity);
                        var parameters     = new Dictionary <string, KeyValuePair <object, IType> >();
                        var setStatement   = "set ";
                        var whereStatement = "where ";
                        for (var i = 0; i < componentType.PropertyNames.Length; i++)
                        {
                            if (i > 0)
                            {
                                setStatement   += ", ";
                                whereStatement += " and ";
                            }
                            var propName  = componentType.PropertyNames[i];
                            var paramName = string.Format("new{0}", propName);
                            setStatement += string.Format("{0}=:{1}", propName, paramName);
                            parameters.Add(paramName, new KeyValuePair <object, IType>(newKeyValues[i], componentType.Subtypes[i]));

                            paramName       = string.Format("old{0}", propName);
                            whereStatement += string.Format("{0}=:{1}", propName, paramName);
                            parameters.Add(paramName, new KeyValuePair <object, IType>(oldKeyValues[i], componentType.Subtypes[i]));
                        }
                        var updateQuery = sessionImpl.CreateQuery(new StringQueryExpression(string.Format("update {0} {1} {2}", entityType.Name, setStatement, whereStatement)));
                        foreach (var pair in parameters)
                        {
                            updateQuery.SetParameter(pair.Key, pair.Value.Key, pair.Value.Value);
                        }
                        var count = updateQuery.ExecuteUpdate();
                        if (count != 1)
                        {
                            throw new InvalidOperationException(string.Format("Query for updating composite key updated '{0}' rows instead of '1'", count));
                        }
                        componentType.SetPropertyValues(dbEntity, componentType.GetPropertyValues(entityInfo.Entity));
                    }
                }
                else
                {
                    dbEntity = sessionImpl.ImmediateLoad(entityType.FullName, id);
                }

                //dbEntity = session.Get(entityType, id, LockMode.None);
            }


            if (dbEntity == null)
            {
                throw new NullReferenceException(string.Format("Entity of type '{0}' with id '{1}' does not exists in database",
                                                               entityType.FullName, id));
            }

            //var modelConfig = BreezeModelConfigurator.GetModelConfiguration(entityType);

            //Save the original client object
            _clientEntityObjects[entityInfo] = entityInfo.Entity;

            //We have to set the properties from the client object
            propNames = meta.PropertyNames;
            var propTypes = meta.PropertyTypes;

            var config = _breezeConfigurator.GetModelConfiguration(entityType);

            // TODO: set only modified properties
            for (var i = 0; i < propNames.Length; i++)
            {
                var propType = propTypes[i];
                var propName = propNames[i];

                var memberConfig = config.MemberConfigurations.ContainsKey(propName)
                    ? config.MemberConfigurations[propName]
                    : null;
                if (memberConfig != null && (
                        (memberConfig.Ignored.HasValue && memberConfig.Ignored.Value) ||
                        (memberConfig.Writable.HasValue && !memberConfig.Writable.Value) ||
                        (memberConfig.ShouldDeserializePredicate != null && memberConfig.ShouldDeserializePredicate.Invoke(entityInfo.Entity) == false)
                        ))
                {
                    continue;
                }

                if (propType.IsAssociationType)
                {
                    continue;
                }

                if (propType.IsComponentType)
                {
                    var compType       = (ComponentType)propType;
                    var componentVal   = GetPropertyValue(meta, entityInfo.Entity, propName);
                    var dbComponentVal = GetPropertyValue(meta, dbEntity, propName);
                    var compPropsVal   = compType.GetPropertyValues(componentVal);
                    compType.SetPropertyValues(dbComponentVal, compPropsVal);
                }
                else
                {
                    var val = meta.GetPropertyValue(entityInfo.Entity, propName);
                    meta.SetPropertyValue(dbEntity, propName, val);
                }
            }
            typeof(EntityInfo).GetProperty("Entity").SetValue(entityInfo, dbEntity);
            return(true);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Add the metadata for an entity.
        /// </summary>
        /// <param name="meta"></param>
        void AddClass(IClassMetadata meta)
        {
            var type = meta.MappedClass;

            // "Customer:#Breeze.Nhibernate.NorthwindIBModel": {
            var classKey = type.Name + ":#" + type.Namespace;
            var cmap     = new Dictionary <string, object>();

            _typeList.Add(cmap);

            cmap.Add("shortName", type.Name);
            cmap.Add("namespace", type.Namespace);

            var entityPersister = meta as IEntityPersister;
            var metaModel       = entityPersister.EntityMetamodel;
            var superType       = metaModel.SuperclassType;

            if (superType != null)
            {
                var baseTypeName = superType.Name + ":#" + superType.Namespace;
                cmap.Add("baseTypeName", baseTypeName);
            }

            var generator = entityPersister != null ? entityPersister.IdentifierGenerator : null;

            if (generator != null)
            {
                string genType = null;
                if (generator is IdentityGenerator)
                {
                    genType = "Identity";
                }
                else if (generator is Assigned || generator is ForeignGenerator)
                {
                    genType = "None";
                }
                else
                {
                    genType = "KeyGenerator";
                }
                cmap.Add("autoGeneratedKeyType", genType); // TODO find the real generator
            }

            var resourceName = _pluralizationService.Pluralize(type.Name);

            //We add custom resource name if defined
            var modelConfiguration = _breezeConfigurator.GetModelConfiguration(type);

            if (!string.IsNullOrEmpty(modelConfiguration.ResourceName))
            {
                resourceName = modelConfiguration.ResourceName;
            }

            cmap.Add("defaultResourceName", resourceName);
            _resourceMap.Add(resourceName, classKey);

            var dataList = new List <Dictionary <string, object> >();

            cmap.Add("dataProperties", dataList);
            var navList = new List <Dictionary <string, object> >();

            cmap.Add("navigationProperties", navList);

            AddClassProperties(meta, dataList, navList);
        }
Ejemplo n.º 6
0
 /// <inheritdoc />
 protected sealed override List <MemberInfo> GetSerializableMembers(Type objectType)
 {
     return(_breezeConfigurator.GetModelConfiguration(objectType).Members.Values.Select(o => o.MemberInfo).ToList());
 }