Пример #1
0
 protected DefaultEntityStore(IStoreMapping storeMapping, StorageDialectSettings dialectSettings)
 {
     _storeMapping    = storeMapping ?? throw new ArgumentNullException(nameof(storeMapping));
     _dialectSettings = dialectSettings ?? throw new ArgumentNullException(nameof(dialectSettings));
     //_classMap = ClassMapCached.Fetch<TKey, TEntity>();
     this._classMap = ClassMapCached <TKey, TEntity> .ClassMap;
 }
Пример #2
0
        public IObjectClone CloneObject(object obj)
        {
            IObjectManager om    = this.Context.ObjectManager;
            IObjectClone   clone = new ObjectClone();

            IClassMap classMap = this.Context.DomainMap.MustGetClassMap(obj.GetType());

            foreach (IPropertyMap propertyMap in classMap.GetAllPropertyMaps())
            {
                if (propertyMap.IsCollection)
                {
                }
                else
                {
                    if (om.HasOriginalValues(obj, propertyMap.Name))
                    {
                        clone.SetPropertyValue(propertyMap.Name, om.GetPropertyValue(obj, propertyMap.Name));
                        clone.SetOriginalPropertyValue(propertyMap.Name, om.GetOriginalPropertyValue(obj, propertyMap.Name));
                        clone.SetNullValueStatus(propertyMap.Name, om.GetNullValueStatus(obj, propertyMap.Name));
                        clone.SetUpdatedStatus(propertyMap.Name, om.GetUpdatedStatus(obj, propertyMap.Name));
                    }
                }
            }

            clone.SetObjectStatus(om.GetObjectStatus(obj));

            this.clonedObjects.Add(obj);

            return(clone);
        }
Пример #3
0
 /// <summary>
 /// Generates the private fields of the entity.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <param name="classMap">The class map.</param>
 private static void GeneratePrivateFields(StreamWriter file, IClassMap classMap)
 {
     foreach (IPropertyMap property in classMap.PropertyMaps)
     {
         ClassUtility.GenerateField(file, property);
     }
 }
		/// <summary>
		/// Generates the DAO interface file.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <param name="classMap">The class map.</param>
		private static void GenerateDai(string path, IClassMap classMap)
		{
			
			using (StreamWriter file = new StreamWriter(path + GetInterfaceName(classMap) + ".cs", false))
			{
				ClassUtility.AppendHeader(file);
				
				file.WriteLine("using System.Collections.Generic;");
				file.WriteLine("using DOL.Database.DataTransferObjects;");
				file.WriteLine();

				file.WriteLine("namespace DOL.Database.DataAccessInterfaces");
				file.WriteLine("{");
				file.WriteLine("	public interface " + GetInterfaceName(classMap) + " : IGenericDao<" + EntityGenerator.GetTypeName(classMap) + ">");
				file.WriteLine("	{");

				// generate 'find' methods
				GenerateFindMethods(classMap, file);

				// generate 'find by' methods
				GenerateFindByMethods(classMap, file);
				
				// generate 'cout by' methods
				GenerateCountByMethods(classMap, file);

				file.WriteLine("	}");
				file.WriteLine("}");
			}
		}
Пример #5
0
        public static IDbCommand BuildJoin <T, T1>(IDbConnection connection, IClassMap <T> classMap, IClassMap <T1> joinMap, Expression <Func <T, T1, bool> > predicate)
        {
            if (classMap == null)
            {
                throw new ArgumentNullException("classMap");
            }
            if (joinMap == null)
            {
                throw new ArgumentNullException("joinMap");
            }
            if (predicate == null)
            {
                throw new ArgumentNullException("predicate");
            }

            var ctx        = new QueryContext(classMap, joinMap);
            var columnList = classMap.Properties.Aggregate(string.Empty, GetColumnListAggregator(ctx.AliasForTable(classMap)));
            var command    = DbCommandDecorator.Create(connection);
            var visitor    = new PredicateVisitor(ctx);

            visitor.Visit(predicate.Body);
            foreach (var pair in visitor.Parameters)
            {
                command.AddParam(pair.Key, pair.Value);
            }
            command.CommandText = String.Format(SELECTJOIN, columnList, classMap.TableName, ctx.AliasForTable(classMap), joinMap.TableName, ctx.AliasForTable(joinMap), visitor.ToString());
            return(command);
        }
Пример #6
0
 /// <summary>
 /// Generates the public access properties.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <param name="classMap">The class map.</param>
 private static void GenerateProperties(StreamWriter file, IClassMap classMap)
 {
     foreach (IPropertyMap property in classMap.PropertyMaps)
     {
         ClassUtility.GenerateProperty(file, property, false);
     }
 }
Пример #7
0
		/// <summary>
		/// Generates the public access properties.
		/// </summary>
		/// <param name="file">The file.</param>
		/// <param name="classMap">The class map.</param>
		private static void GenerateProperties(StreamWriter file, IClassMap classMap)
		{
			foreach (IPropertyMap property in classMap.PropertyMaps)
			{
				ClassUtility.GenerateProperty(file, property, false);
			}
		}
		/// <summary>
		/// Generates all the 'find by' methods of this interface.
		/// </summary>
		/// <param name="classMap">The class map.</param>
		/// <param name="file">The file.</param>
		private static void GenerateFindByMethods(IClassMap classMap, StreamWriter file)
		{
			foreach (KeyValuePair<int, IList<IPropertyMap>> pair in classMap.DOLGetFindByGroups())
			{
				IList<IPropertyMap> paramProps = pair.Value;
				
				string findBy = StringUtility.CombineObjects(paramProps, MapToStringConverters.PropertyAnd)
					.ToString();
				
				// method name
				file.Write("		IList<" + EntityGenerator.GetTypeName(classMap) + "> FindBy" + findBy);
				
				// method's params
				file.Write("(");
				bool first = true;
				foreach (IPropertyMap propertyMap in paramProps)
				{
					if (!first)
					{
						file.Write(", ");
					}
						
					// param type and name
					string paramName = ClassUtility.GetParamName(propertyMap);
					string paramType = ClassUtility.ConvertColumnTypeToCsType(propertyMap.GetColumnMap().DataType);
					file.Write(paramType + " " + paramName);
					first = false;
				}
				file.Write(");");
					
				file.WriteLine();

			}
		}
        private static IList GetRequiredPropertyMaps(IClassMap classMap)
        {
            IList requiredPropertyMaps = new ArrayList();

            foreach (IPropertyMap propertyMap in classMap.GetAllPropertyMaps())
            {
                if (propertyMap.IsIdentity)
                {
                    if (!propertyMap.GetIsAssignedBySource())
                    {
                        requiredPropertyMaps.Add(propertyMap);
                    }
                }
                else
                {
                    if (!propertyMap.IsCollection)
                    {
                        if (!propertyMap.GetIsNullable())
                        {
                            requiredPropertyMaps.Add(propertyMap);
                        }
                    }
                }
            }

            return(requiredPropertyMaps);
        }
Пример #10
0
		/// <summary>
		/// Generates the private fields of the entity.
		/// </summary>
		/// <param name="file">The file.</param>
		/// <param name="classMap">The class map.</param>
		private static void GeneratePrivateFields(StreamWriter file, IClassMap classMap)
		{
			foreach (IPropertyMap property in classMap.PropertyMaps)
			{
				ClassUtility.GenerateField(file, property);
			}
		}
        public virtual string GetObjectKey(object obj)
        {
            string    key      = "";
            IClassMap classMap = m_ObjectManager.Context.DomainMap.MustGetClassMap(obj.GetType());
            string    sep      = classMap.KeySeparator;

            if (sep == "")
            {
                sep = " ";
            }
            object value;

            foreach (IPropertyMap propertyMap in classMap.GetKeyPropertyMaps())
            {
                value = m_ObjectManager.GetPropertyValue(obj, propertyMap.Name);
                if (value == null || m_ObjectManager.GetNullValueStatus(obj, propertyMap.Name))
                {
                    return("");
                }
                if (!(propertyMap.ReferenceType == ReferenceType.None))
                {
                    value = m_ObjectManager.GetObjectKey(value);
                    if (((string)value).Length < 1)
                    {
                        return("");
                    }
                }
                key += Convert.ToString(value) + sep;
            }
            if (key.Length > sep.Length)
            {
                key = key.Substring(0, key.Length - sep.Length);
            }
            return(key);
        }
        public virtual void SetObjectIdentity(object obj, string identity)
        {
            IClassMap classMap = m_ObjectManager.Context.DomainMap.MustGetClassMap(obj.GetType());
            string    sep      = classMap.IdentitySeparator;

            if (sep == "")
            {
                sep = "|";
            }
            string[] arrId = identity.Split(sep.ToCharArray());
            long     i     = 0;
            Type     refType;
            object   refObj;
            object   val;

            foreach (IPropertyMap propertyMap in classMap.GetIdentityPropertyMaps())
            {
                if (propertyMap.ReferenceType != ReferenceType.None)
                {
                    refType = obj.GetType().GetProperty(propertyMap.Name).PropertyType;
                    refObj  = m_ObjectManager.Context.GetObjectById(Convert.ToString(arrId[i]), refType, true);
                    m_ObjectManager.SetPropertyValue(obj, propertyMap.Name, refObj);
                    m_ObjectManager.SetOriginalPropertyValue(obj, propertyMap.Name, refObj);
                    m_ObjectManager.SetNullValueStatus(obj, propertyMap.Name, false);
                }
                else
                {
                    val = ConvertValueToType(obj, propertyMap, arrId[i]);
                    m_ObjectManager.SetPropertyValue(obj, propertyMap.Name, val);
                    m_ObjectManager.SetOriginalPropertyValue(obj, propertyMap.Name, val);
                    m_ObjectManager.SetNullValueStatus(obj, propertyMap.Name, false);
                }
                i += 1;
            }
        }
Пример #13
0
 protected override string GetParameterName(IClassMap classMap, string prefix)
 {
     string name = prefix;
     name = name + classMap.Name;
     name = ":" + name;
     return name;
 }
Пример #14
0
        public virtual SqlTableAlias GetClassTable(string className)
        {
            IClassMap classMap = sqlEmitter.RootClassMap.DomainMap.MustGetClassMap(className);
            ITableMap tableMap = classMap.MustGetTableMap();

            return(sqlEmitter.Select.GetSqlTableAlias(tableMap));
        }
Пример #15
0
        public override Type GetTypeByName(string className)
        {
            IContext  context  = GetContext();
            IClassMap classMap = context.DomainMap.MustGetClassMap(className);

            return(context.AssemblyManager.GetTypeFromClassMap(classMap));
        }
        /// <summary>
        /// Generates the DAO interface file.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="classMap">The class map.</param>
        private static void GenerateDai(string path, IClassMap classMap)
        {
            using (StreamWriter file = new StreamWriter(path + GetInterfaceName(classMap) + ".cs", false))
            {
                ClassUtility.AppendHeader(file);

                file.WriteLine("using System.Collections.Generic;");
                file.WriteLine("using DOL.Database.DataTransferObjects;");
                file.WriteLine();

                file.WriteLine("namespace DOL.Database.DataAccessInterfaces");
                file.WriteLine("{");
                file.WriteLine("	public interface "+ GetInterfaceName(classMap) + " : IGenericDao<" + EntityGenerator.GetTypeName(classMap) + ">");
                file.WriteLine("	{");

                // generate 'find' methods
                GenerateFindMethods(classMap, file);

                // generate 'find by' methods
                GenerateFindByMethods(classMap, file);

                // generate 'cout by' methods
                GenerateCountByMethods(classMap, file);

                file.WriteLine("	}");
                file.WriteLine("}");
            }
        }
        private bool GuidMustBeTemporaryIdentity(Type type, IClassMap classMap)
        {
            IList idPropertyMaps = classMap.GetIdentityPropertyMaps();

            if (idPropertyMaps.Count > 1)
            {
                return(true);
            }

            //should only be one id prop..
            foreach (IPropertyMap propertyMap in idPropertyMaps)
            {
                Type propType = type.GetProperty(propertyMap.Name).PropertyType;
                if (propertyMap.ReferenceType != ReferenceType.None)
                {
                    IClassMap refClassMap = this.Context.DomainMap.MustGetClassMap(propType);
                    return(GuidMustBeTemporaryIdentity(propType, refClassMap));
                }
                else
                {
                    if (!propType.IsAssignableFrom(typeof(Guid)))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
 public virtual void SetObjectIdentity(object obj, KeyStruct keyStruct)
 {
     try
     {
         IClassMap classMap = this.Context.DomainMap.MustGetClassMap(obj.GetType());
         long      i        = 1;
         Type      refType;
         object    refObj;
         object    val;
         foreach (IPropertyMap propertyMap in classMap.GetIdentityPropertyMaps())
         {
             if (propertyMap.ReferenceType != ReferenceType.None)
             {
                 //Bad...only works for referenced objects with non-composite ids...
                 refType = obj.GetType().GetProperty(propertyMap.Name).PropertyType;
                 refObj  = this.Context.GetObjectById(keyStruct.keys[i], refType, true);
                 SetPropertyValue(obj, propertyMap.Name, refObj);
                 SetOriginalPropertyValue(obj, propertyMap.Name, refObj);
                 SetNullValueStatus(obj, propertyMap.Name, false);
             }
             else
             {
                 val = keyStruct.keys[i];
                 SetPropertyValue(false, obj, propertyMap.Name, val);
                 SetOriginalPropertyValue(obj, propertyMap.Name, val);
                 SetNullValueStatus(obj, propertyMap.Name, false);
             }
             i += 1;
         }
     }
     catch (Exception ex)
     {
         throw new NPersistException(string.Format("Could not set Identity '{0}' on object '{1}'", keyStruct.keys[1].ToString(), obj), ex);
     }
 }
Пример #19
0
        private NPathQuery CreateQuery(Type type, IDictionary <string, object> match)
        {
            IDomainMap    domainMap = GetContext().DomainMap;
            IClassMap     classMap  = domainMap.MustGetClassMap(type);
            StringBuilder query     = new StringBuilder();

            query.Append("Select * From " + classMap.Name);
            if (match != null)
            {
                if (match.Keys.Count > 0)
                {
                    query.Append(" Where ");
                    foreach (string propertyName in match.Keys)
                    {
                        query.Append(propertyName + " = ");
                        query.Append("'");
                        query.Append(match[propertyName].ToString());
                        query.Append("'");
                        query.Append(" And ");
                    }
                    query.Length -= 5;
                }
            }

            return(new NPathQuery(query.ToString(), type));
        }
        public virtual IList ParseObjectIdentityKeyParts(IClassMap classMap, IList idPropertyMaps, Type type, string identity)
        {
            string sep = classMap.IdentitySeparator;

            if (sep == "")
            {
                sep = "|";
            }
            string[] arrId      = identity.Split(sep.ToCharArray());
            IList    idKeyParts = new ArrayList(1);
            long     i          = 0;

            foreach (IPropertyMap propertyMap in idPropertyMaps)
            {
                if (propertyMap.ReferenceType != ReferenceType.None)
                {
                    //Bad...only works for referenced objects with non-composite ids...
                    IClassMap refClassMap = propertyMap.MustGetReferencedClassMap();
                    Type      refType     = this.Context.AssemblyManager.MustGetTypeFromClassMap(refClassMap);
                    idKeyParts.Add(ConvertValueToType(refType, (IPropertyMap)refClassMap.GetIdentityPropertyMaps()[0], arrId[i]));
                }
                else
                {
                    idKeyParts.Add(ConvertValueToType(type, propertyMap, arrId[i]));
                }
                i += 1;
            }
            return(idKeyParts);
        }
        /// <summary>
        /// Generates all the 'find' methods of this interface.
        /// </summary>
        /// <param name="classMap">The class map.</param>
        /// <param name="file">The file.</param>
        private static void GenerateFindMethods(IClassMap classMap, StreamWriter file)
        {
            // method name
            file.Write("		"+ EntityGenerator.GetTypeName(classMap) + " Find(");
            ArrayList primaryColumns = classMap.GetTableMap().GetPrimaryKeyColumnMaps();

            // method's params
            bool first = true;

            foreach (IColumnMap columnMap in primaryColumns)
            {
                IPropertyMap propertyMap = classMap.GetPropertyMapForColumnMap(columnMap);

                if (!first)
                {
                    file.Write(", ");
                }

                // param type and name
                string paramName = ClassUtility.GetParamName(propertyMap);
                string paramType = ClassUtility.ConvertColumnTypeToCsType(columnMap.DataType);
                file.Write(paramType + " " + paramName);
                first = false;
            }
            file.Write(");");

            file.WriteLine();
        }
        public virtual MarshalReference FromObjectAsReference(object sourceObject)
        {
            IClassMap        classMap = Context.DomainMap.MustGetClassMap(sourceObject.GetType());
            MarshalReference mr       = new MarshalReference();

            mr.Type = classMap.GetName();
            foreach (IPropertyMap propertyMap in classMap.GetIdentityPropertyMaps())
            {
                if (propertyMap.ReferenceType == ReferenceType.None)
                {
                    if (propertyMap.IsCollection)
                    {
                    }
                    else
                    {
                        mr.Value.ReferenceProperties.Add(FromProperty(sourceObject, propertyMap));
                    }
                }
                else
                {
                    if (propertyMap.IsCollection)
                    {
                    }
                    else
                    {
                        mr.Value.ReferenceProperties.Add(FromReference(sourceObject, propertyMap));
                    }
                }
            }

            return(mr);
        }
        private void InitProperties()
        {
            Type baseType = target.GetType().BaseType;

            PropertyInfo[] propertyArray = baseType.GetProperties();
            properties.Clear();

            IProxy   proxy   = (IProxy)target;
            IContext context = proxy.GetInterceptor().Context;

            foreach (PropertyInfo property in propertyArray)
            {
                if (property.PropertyType.IsInterface)
                {
                    continue;
                }

                if (!property.CanWrite)
                {
                    continue;
                }

                IClassMap classmap = context.DomainMap.GetClassMap(property.PropertyType);
                if (classmap != null)
                {
                    continue;
                }

                properties[property.Name] = property;
            }
        }
        public bool HasIdentity(object obj)
        {
            IClassMap classMap = this.Context.DomainMap.MustGetClassMap(obj.GetType());

            object value;

            foreach (IPropertyMap propertyMap in classMap.GetIdentityPropertyMaps())
            {
                value = GetPropertyValue(obj, propertyMap.Name);
                if (value == null || GetNullValueStatus(obj, propertyMap.Name) == true)
                {
                    return(false);
                }
                else if (propertyMap.ReferenceType != ReferenceType.None)
                {
                    //this ensures that a complete id can be created ahead in case of auto-in
                    //m_ObjectManager.GetPropertyValue(obj, propertyMap.Name);
                    if (!HasIdentity(value))
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
        public virtual MarshalQuery FromQuery(IQuery query)
        {
            MarshalQuery mq = new MarshalQuery();

            if (query is NPathQuery)
            {
                mq.QueryType = "NPathQuery";
            }
            if (query is SqlQuery)
            {
                mq.QueryType = "SqlQuery";
            }
            IClassMap classMap = Context.DomainMap.MustGetClassMap(query.PrimaryType);

            mq.PrimitiveType = classMap.GetName();
            mq.QueryString   = query.Query.ToString();
            foreach (IQueryParameter p in query.Parameters)
            {
                MarshalParameter mp = new MarshalParameter();
                mp.DbType = p.DbType;
                mp.Name   = p.Name;
                mp.Value  = FromParameterValue(p);
                mq.Parameters.Add(mp);
            }
            return(mq);
        }
Пример #26
0
        public static void GenerateRepositoryDeleteObjectMethod(IClassMap classMap, CodeTypeDeclaration classDecl)
        {
            CodeMemberMethod methodMember = new CodeMemberMethod();

            methodMember.Name = GetRepositoryDeleteObjectMethodName(classMap);

            CodeTypeReference typeReference = new CodeTypeReference(classMap.GetName());

            methodMember.Attributes = MemberAttributes.Public;

            CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(typeReference, MakeCamelCase(classMap.GetName()));

            methodMember.Parameters.Add(parameter);

            CodeArgumentReferenceExpression argExp = new CodeArgumentReferenceExpression(MakeCamelCase(classMap.GetName()));

            CodeThisReferenceExpression  thisExp    = new CodeThisReferenceExpression();
            CodeFieldReferenceExpression contextVar = new CodeFieldReferenceExpression(thisExp, "context");

            CodeMethodInvokeExpression deleteCall = new CodeMethodInvokeExpression(contextVar, "DeleteObject", new CodeExpression[] { argExp });

            methodMember.Statements.Add(deleteCall);

            CodeMethodInvokeExpression commitCtx = new CodeMethodInvokeExpression(contextVar, "Commit", new CodeExpression[] {});

            methodMember.Statements.Add(commitCtx);

            classDecl.Members.Add(methodMember);
        }
        public string GetIdentity(MarshalReference marshalReference, MarshalReferenceValue marshalReferenceValue)
        {
            IClassMap     classMap = Context.DomainMap.MustGetClassMap(marshalReference.Type);
            StringBuilder id       = new StringBuilder();
            string        sep      = classMap.IdentitySeparator;

            if (sep == "")
            {
                sep = "|";
            }
            foreach (IPropertyMap propertyMap in classMap.GetIdentityPropertyMaps())
            {
                if (propertyMap.ReferenceType == ReferenceType.None)
                {
                    MarshalProperty mp = marshalReferenceValue.GetReferenceProperty(propertyMap.Name);
                    id.Append(mp.Value + sep);
                }
                else
                {
                    MarshalReference mr = marshalReferenceValue.GetReferenceReference(propertyMap.Name);
                    id.Append(GetIdentity(mr, marshalReferenceValue) + sep);
                }
            }
            if (id.Length > 0)
            {
                id.Length -= sep.Length;
            }
            return(id.ToString());
        }
Пример #28
0
 private void CustomValidateObject(object obj, IClassMap classMap, IList exceptions)
 {
     if (classMap.ValidateMethod.Length > 0)
     {
         MethodInfo methodInfo = GetMethod(obj, classMap.ValidateMethod);
         if (methodInfo != null)
         {
             if (exceptions == null)
             {
                 methodInfo.Invoke(obj, null);
             }
             else
             {
                 try
                 {
                     methodInfo.Invoke(obj, null);
                 }
                 catch (Exception ex)
                 {
                     HandleException(obj, "", exceptions, ex.InnerException);
                 }
             }
         }
     }
 }
Пример #29
0
        public static void GenerateRepositoryGetAllObjectsMethod(IClassMap classMap, CodeTypeDeclaration classDecl)
        {
            CodeMemberMethod methodMember = new CodeMemberMethod();

            methodMember.Name = GetRepositoryGetAllObjectsMethodName(classMap);

            CodeTypeReference typeReference     = new CodeTypeReference(classMap.GetName());
            CodeTypeReference listTypeReference = new CodeTypeReference(typeof(IList));

            methodMember.ReturnType = listTypeReference;

            methodMember.Attributes = MemberAttributes.Public;

            CodeThisReferenceExpression  thisExp    = new CodeThisReferenceExpression();
            CodeFieldReferenceExpression contextVar = new CodeFieldReferenceExpression(thisExp, "context");

            CodeTypeOfExpression typeOfExp = new CodeTypeOfExpression(typeReference);

            CodeMethodInvokeExpression listInit = new CodeMethodInvokeExpression(contextVar, "GetObjects", new CodeExpression[] { typeOfExp });

            CodeVariableDeclarationStatement listVarDecl = new CodeVariableDeclarationStatement(typeof(IList), "list", listInit);
            CodeVariableReferenceExpression  listVar     = new CodeVariableReferenceExpression("list");

            methodMember.Statements.Add(listVarDecl);

            CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement(listVar);

            methodMember.Statements.Add(returnStmt);

            classDecl.Members.Add(methodMember);
        }
Пример #30
0
        public void ValidateProperty(object obj, string propertyName, IList exceptions)
        {
            IClassMap    classMap    = this.Context.DomainMap.MustGetClassMap(obj.GetType());
            IPropertyMap propertyMap = classMap.MustGetPropertyMap(propertyName);

            DoValidateProperty(obj, propertyMap, exceptions);
        }
        //pass 0 = get all properties (for ToObject overload) , pass 1 = get only primitive props, pass 2 = get only ref props
        public virtual void ToObject(MarshalObject marshalObject, ref object targetObject, int pass, RefreshBehaviorType refreshBehavior)
        {
            IClassMap    classMap = Context.DomainMap.MustGetClassMap(targetObject.GetType());
            IPropertyMap propertyMap;

            //PropertyStatus propStatus;
            if (pass == 0 || pass == 1)
            {
                foreach (MarshalProperty mp in marshalObject.Properties)
                {
                    //propStatus = ctx.GetPropertyStatus(targetObject, mp.Name);
                    propertyMap = classMap.MustGetPropertyMap(mp.Name);
                    ToProperty(targetObject, mp, propertyMap, refreshBehavior);
                }
            }

            if (pass == 0 || pass == 2)
            {
                foreach (MarshalReference mr in marshalObject.References)
                {
                    //propStatus = ctx.GetPropertyStatus(targetObject, mp.Name);
                    propertyMap = classMap.MustGetPropertyMap(mr.Name);
                    ToReference(targetObject, mr, propertyMap, refreshBehavior);
                }
            }

            if (targetObject != null)
            {
                if (pass == 0 || pass == 1)
                {
                    this.Context.IdentityMap.RegisterLoadedObject(targetObject);
                }
            }
        }
        /// <summary>
        /// Generates all the 'find by' methods of this interface.
        /// </summary>
        /// <param name="classMap">The class map.</param>
        /// <param name="file">The file.</param>
        private static void GenerateFindByMethods(IClassMap classMap, StreamWriter file)
        {
            foreach (KeyValuePair <int, IList <IPropertyMap> > pair in classMap.DOLGetFindByGroups())
            {
                IList <IPropertyMap> paramProps = pair.Value;

                string findBy = StringUtility.CombineObjects(paramProps, MapToStringConverters.PropertyAnd)
                                .ToString();

                // method name
                file.Write("		IList<"+ EntityGenerator.GetTypeName(classMap) + "> FindBy" + findBy);

                // method's params
                file.Write("(");
                bool first = true;
                foreach (IPropertyMap propertyMap in paramProps)
                {
                    if (!first)
                    {
                        file.Write(", ");
                    }

                    // param type and name
                    string paramName = ClassUtility.GetParamName(propertyMap);
                    string paramType = ClassUtility.ConvertColumnTypeToCsType(propertyMap.GetColumnMap().DataType);
                    file.Write(paramType + " " + paramName);
                    first = false;
                }
                file.Write(");");

                file.WriteLine();
            }
        }
Пример #33
0
        public virtual TimeToLiveBehavior GetTimeToLiveBehavior(object obj, string propertyName)
        {
            IClassMap    classMap    = this.Context.DomainMap.MustGetClassMap(obj.GetType());
            IPropertyMap propertyMap = classMap.MustGetPropertyMap(propertyName);

            return(GetTimeToLiveBehavior(propertyMap));
        }
Пример #34
0
        /// <summary>
        /// Creates or retrieves the <see cref="IObjectMapping"/> from the classMap.
        /// </summary>
        /// <param name="classMap">The mapping.</param>
        /// <param name="objectCategory">The object category for the object.</param>
        /// <param name="includeObjectCategory">
        /// Indicates if the object category should be included in all queries.
        /// </param>
        /// <param name="namingContext">The location of the objects in the directory.</param>
        /// <param name="objectClasses">The object classes for the object.</param>
        /// <param name="includeObjectClasses">Indicates if the object classes should be included in all queries.</param>
        /// <exception cref="MappingException">
        /// Thrown if the mapping is invalid.
        /// </exception>
        /// <returns></returns>
        public IObjectMapping Map(IClassMap classMap, string namingContext = null, IEnumerable <string> objectClasses = null, bool includeObjectClasses = true, string objectCategory = null, bool includeObjectCategory = true)
        {
            if (classMap == null)
            {
                throw new ArgumentNullException(nameof(classMap));
            }

            return(_mappings.GetOrAdd(classMap.Type, t =>
            {
                var mapped = classMap.PerformMapping(namingContext, objectCategory,
                                                     includeObjectCategory,
                                                     objectClasses, includeObjectClasses);

                mapped.Validate();

                var objectMapping = mapped.ToObjectMapping();

                if (!mapped.WithoutSubTypeMapping)
                {
                    MapSubTypes(objectMapping);
                }

                return objectMapping;
            }));
        }
Пример #35
0
        public static CodeNamespace GenerateRepositoryClass(IClassMap classMap)
        {
            CodeNamespace       domainNamespace = new CodeNamespace(classMap.DomainMap.RootNamespace + ".Repositories");
            CodeTypeDeclaration classDecl       = new CodeTypeDeclaration(GetRepositoryClassName(classMap));

            CodeNamespaceImport import         = new CodeNamespaceImport(classMap.GetFullNamespace());
            CodeNamespaceImport importNPersist = new CodeNamespaceImport("Puzzle.NPersist.Framework");

            domainNamespace.Imports.Add(import);
            domainNamespace.Imports.Add(importNPersist);

            classDecl.IsClass = true;

            GenerateConstructor(classDecl);
            GenerateContextField(classDecl);

            GenerateRepositoryGetByIdentityMethod(classMap, classDecl, false);
            GenerateRepositoryGetByIdentityMethod(classMap, classDecl, true);
            GenerateRepositoryGetAllObjectsMethod(classMap, classDecl);
            //GenerateRepositoryGetByNPathMethod(classMap, classDecl);
            GenerateRepositoryUpdateObjectMethod(classMap, classDecl);
            GenerateRepositoryDeleteObjectMethod(classMap, classDecl);

            domainNamespace.Types.Add(classDecl);

            return(domainNamespace);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DocumentClassMapPropertyDescriptor"/> class.
        /// </summary>
        /// <param name="mappingStore">The mapping store.</param>
        /// <param name="classMap">The class map.</param>
        /// <param name="document">The document.</param>
        public DocumentClassMapPropertyDescriptor(IMappingStore mappingStore, IClassMap classMap, Document document)
            : base(mappingStore, classMap)
        {
            if (document == null)
                throw new ArgumentNullException("document");

            _document = document;
        }
Пример #37
0
		public static CodeCompileUnit GetFactoryClassCompileUnit(IClassMap classMap)
		{			
			CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

			codeCompileUnit.Namespaces.Add(GenerateFactoryClass(classMap));

			return codeCompileUnit ;
		}
Пример #38
0
		public SqlEmitter(INPathEngine npathEngine, NPathSelectQuery query,NPathQueryType queryType, IClassMap rootClassMap, Hashtable propertyColumnMap)
		{
			this.npathEngine = npathEngine;
			this.query = query;
			this.rootClassMap = rootClassMap;
			propertyPathTraverser = new PropertyPathTraverser(this);
			this.propertyColumnMap = propertyColumnMap;
			this.npathQueryType = queryType;
		}
Пример #39
0
        public string AliasForTable(IClassMap classMap)
        {
            if (classMap != null)
                foreach (var pair in _classMaps)
                    if (pair.Value == classMap)
                        return pair.Key;

            return String.Format("t_{0}", _tIndex++);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ExampleClassMapPropertyDescriptor"/> class.
        /// </summary>
        /// <param name="mappingStore">The mapping store.</param>
        /// <param name="classMap">The class map.</param>
        /// <param name="example">The example.</param>
        public ExampleClassMapPropertyDescriptor(IMappingStore mappingStore, IClassMap classMap, object example)
            : base(mappingStore, classMap)
        {
            if (example == null)
                throw new ArgumentNullException("example");

            _example = example;
            _exampleType = _example.GetType();
        }
Пример #41
0
		public virtual Type MustGetTypeFromClassMap(IClassMap classMap)
		{
			Type type = GetTypeFromClassMap(classMap);

			if (type == null)
				throw new MappingException("Could not find the type for the class " + classMap.Name + " (found in the map file) in any loaded Assembly!");
 
			return type;
		}
		/// <summary>
		/// Generates custom fields and methods of the class.
		/// </summary>
		/// <param name="file">The file.</param>
		/// <param name="classMap">The class map.</param>
		public override void GenerateCustomFieldsAndMethods(StreamWriter file, IClassMap classMap)
		{
			ArrayList		allColumns = classMap.GetTableMap().ColumnMaps;
			IColumnMap[]	allColumnsTyped = (IColumnMap[]) allColumns.ToArray(typeof (IColumnMap));
			string			columnNames = StringUtility.CombineObjects(allColumnsTyped, MapToStringConverters.Columns).ToString();

			file.WriteLine("		protected static readonly string c_rowFields = \"" + columnNames + "\";");
			
			base.GenerateCustomFieldsAndMethods(file, classMap);
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="ClassMapPropertyDescriptor"/> class.
        /// </summary>
        /// <param name="mappingStore">The mapping store.</param>
        /// <param name="classMap">The class map.</param>
        /// <param name="instance">The instance.</param>
        public ClassMapPropertyDescriptor(IMappingStore mappingStore, IClassMap classMap, object instance)
            : base(mappingStore, classMap)
        {
            if (instance == null)
                throw new ArgumentNullException("instance");

            _instance = instance;
            if (ClassMap.HasExtendedProperties)
                _extendedProperties = (IDictionary<string, object>)ClassMap.ExtendedPropertiesMap.GetValue(instance);
        }
Пример #44
0
        public static string GetRepositoryClassCsharp(IClassMap classMap)
        {
            CodeCompileUnit compileunit = CodeDomGenerator.GetRepositoryClassCompileUnit(classMap);

            CodeDomProvider provider = new CSharpCodeProvider();

            string code = CodeDomGenerator.ToCode(compileunit, provider);

            return code;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ClassMapPropertyDescriptorBase"/> class.
        /// </summary>
        /// <param name="mappingStore">The mapping store.</param>
        /// <param name="classMap">The class map.</param>
        protected ClassMapPropertyDescriptorBase(IMappingStore mappingStore, IClassMap classMap)
        {
            if (mappingStore == null)
                throw new ArgumentNullException("mappingStore");
            if (classMap == null)
                throw new ArgumentNullException("classMap");

            _mappingStore = mappingStore;
            ClassMap = classMap;
            _codeReplacer = new JavascriptMemberNameReplacer(_mappingStore);
        }
 public static void GenerateDLinqField(IClassMap classMap, IPropertyMap propertyMap, CodeTypeDeclaration classDecl)
 {
     switch (propertyMap.ReferenceType)
     {
         case ReferenceType.None :
             classDecl.Members.Add(GenerateDLinqPrimitiveField(classMap, propertyMap));
         break;
         case ReferenceType.OneToMany :
             GenerateDLinqOneToManyFields(classMap, propertyMap, classDecl);
         break;
     }
 }
Пример #47
0
		public SqlEmitter(INPathEngine npathEngine, NPathSelectQuery query,NPathQueryType queryType, IClassMap rootClassMap,SqlSelectStatement parentQuery,IPropertyMap backReference,int subQueryLevel)
		{
			this.npathEngine = npathEngine;
			this.query = query;
			this.rootClassMap = rootClassMap;
			propertyPathTraverser = new PropertyPathTraverser(this);
			this.propertyColumnMap = new Hashtable() ;
			this.npathQueryType = queryType;
			this.parentQuery = parentQuery;
			this.backReference = backReference;
			this.subQueryLevel = subQueryLevel;
		}
Пример #48
0
 public ObjectTreeNode(IContext context, object obj, object referencedByObj, IPropertyMap referencedByPropertyMap)
 {
     this.context = context;
     this.obj = obj;
     this.ClassMap = context.DomainMap.MustGetClassMap(obj.GetType() );
     this.referencedByObj = referencedByObj;
     this.referencedByClassMap = context.DomainMap.MustGetClassMap(ReferencedByObj.GetType() );
     this.referencedByPropertyMap = referencedByPropertyMap;
     this.Nodes.Add(new TreeNode() );
     SetText();
     this.ImageIndex = 0;
     this.SelectedImageIndex = 0;
 }
 public ObjectListViewItem(IContext context, object obj, Type type, bool isClipBoardItem)
 {
     this.context = context;
     this.obj = obj;
     this.type = type;
     this.isClipBoardItem = isClipBoardItem;
     this.classMap = context.DomainMap.MustGetClassMap(obj.GetType() );
     this.typeClassMap = context.DomainMap.MustGetClassMap(type );
     SetText();
     this.ImageIndex = 0;
     this.StateImageIndex = 0;
     Refresh(true);
 }
 public static PluginOutput GetDataSet(IClassMap classMap)
 {
     Assembly domainAssembly = GetDomain(classMap.DomainMap);
     if (domainAssembly != null)
     {
         List<DataTable> dtList = new List<DataTable>();
         dtList.Add(ClassToTable(classMap.DomainMap, domainAssembly, classMap.Name));
         string res = GetDataSet(dtList, classMap.DomainMap.Name + "DataSet");
         res = res.Replace(domainAssembly.FullName, classMap.DomainMap.AssemblyName);
         return new PluginOutput(res, classMap.DomainMap.Name + "DataSet");
     }
     else
         throw new Exception("Could not compile domain model !");
 }
Пример #51
0
		public static void GenerateFactoryMethods(IClassMap classMap, CodeTypeDeclaration classDecl)
		{
			IList propertyMaps = GetRequiredPropertyMaps(classMap);
			classDecl.Members.Add(GenerateFactoryMethod(classMap, propertyMaps));					

			IList optionalPropertyMaps = GetOptionalPropertyMaps(classMap);
			if (optionalPropertyMaps.Count > 0)
			{
				foreach (IPropertyMap propertyMap in optionalPropertyMaps)
					propertyMaps.Add(propertyMap);

				classDecl.Members.Add(GenerateFactoryMethod(classMap, propertyMaps));					
			}
		}
        public ConcreteClassMapBuilder(IClassMap classMap)
        {
            _classMap = classMap;
            _instance = classMap.CreateInstance();

            if(!_classMap.HasExtendedProperties)
                return;
            
            var extPropType = _classMap.ExtendedPropertiesMap.MemberReturnType;
            if (extPropType == typeof(IDictionary<string, object>))
                extPropType = typeof(Dictionary<string, object>);
            _extendedProperties = (IDictionary<string, object>)Activator.CreateInstance(extPropType);
            _classMap.ExtendedPropertiesMap.SetValue(_instance, _extendedProperties);
        }
		//non-cached
		protected virtual string LoadFile(object obj, IClassMap classMap, string fileName)
		{
			this.Context.LogManager.Debug(this, "Loading object from file", "File: " + fileName + ", Object Type: " + obj.GetType().ToString()); // do not localize

			if (!(File.Exists(fileName)))
				return "";
			else
			{
				StreamReader fileReader = File.OpenText(fileName);
				string xml =  fileReader.ReadToEnd() ;
				fileReader.Close();

				return xml;
			}
		}
        public static CodeMemberMethod GenerateFactoryMethod(IClassMap classMap, IList propertyMaps)
        {
            CodeMemberMethod methodMember = new CodeMemberMethod() ;
            methodMember.Name = GetFactoryMethodName(classMap);

            CodeTypeReference typeReference = new CodeTypeReference(classMap.GetName());
            methodMember.ReturnType = typeReference;

            methodMember.Attributes = MemberAttributes.Public;

            foreach(IPropertyMap propertyMap in propertyMaps)
            {
                CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(new CodeTypeReference(propertyMap.DataType), MakeCamelCase(propertyMap.Name));
                methodMember.Parameters.Add(parameter);
            }

            CodeThisReferenceExpression thisExp = new CodeThisReferenceExpression();
            CodeFieldReferenceExpression contextVar = new CodeFieldReferenceExpression(thisExp, "context");

            CodeTypeOfExpression typeOfExp = new CodeTypeOfExpression(typeReference) ;
            CodeMethodInvokeExpression newObjectInit = new CodeMethodInvokeExpression(contextVar, "CreateObject", new CodeExpression[] { typeOfExp } ) ;

            CodeCastExpression castExp = new CodeCastExpression(typeReference, newObjectInit) ;

            CodeVariableDeclarationStatement newObjectVarDecl = new CodeVariableDeclarationStatement(classMap.GetName(), MakeCamelCase(classMap.GetName()), castExp) ;
            CodeVariableReferenceExpression newObjectVar = new CodeVariableReferenceExpression(MakeCamelCase(classMap.GetName()));

            methodMember.Statements.Add(newObjectVarDecl);

            foreach(IPropertyMap propertyMap in propertyMaps)
            {
                CodeArgumentReferenceExpression argExp = new CodeArgumentReferenceExpression(MakeCamelCase(propertyMap.Name));
                CodeVariableReferenceExpression propExp = new CodeVariableReferenceExpression(MakeCamelCase(classMap.Name) + "." + propertyMap.Name);
                CodeAssignStatement assignStatement = new CodeAssignStatement(propExp, argExp);
                methodMember.Statements.Add(assignStatement);
            }

            CodeMethodInvokeExpression commitCtx = new CodeMethodInvokeExpression(contextVar, "Commit", new CodeExpression[] {} ) ;

            methodMember.Statements.Add(commitCtx);

            CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement(newObjectVar) ;

            methodMember.Statements.Add(returnStmt);

            return methodMember;
        }
Пример #55
0
 public virtual ValidationMode GetValidationMode(IClassMap classMap)
 {
     ValidationMode validationMode = classMap.ValidationMode;
     if (validationMode == ValidationMode.Default)
     {
         validationMode = classMap.DomainMap.ValidationMode;
         if (validationMode == ValidationMode.Default)
         {
             validationMode = this.Context.ValidationMode;
             if (validationMode == ValidationMode.Default)
             {
                 validationMode = ValidationMode.ValidateLoaded;
             }
         }
     }
     return validationMode;
 }
        /*

        private System.Nullable<int> _ReportsTo;

        private EntityRef<Employee> _ReportsToEmployee;

         * */
        public static void GenerateDLinqOneToManyFields(IClassMap classMap, IPropertyMap propertyMap, CodeTypeDeclaration classDecl)
        {
            foreach (IColumnMap columnMap in propertyMap.GetAllColumnMaps())
            {
                string fieldName = propertyMap.GenerateMemberName(columnMap.Name);

                CodeMemberField fieldMember = new CodeMemberField() ;
                fieldMember.Name = fieldName;

                //Add code for adding Nullable generics when OM is ported to .NET 2.0

                CodeTypeReference typeReference = new CodeTypeReference(columnMap.GetSystemType());
                fieldMember.Type = typeReference;

                classDecl.Members.Add(fieldMember);
            }
        }
Пример #57
0
		public virtual Type GetTypeFromClassMap(IClassMap classMap)
		{
			Type type;
			type = Type.GetType(classMap.GetFullName() + ", " + classMap.GetAssemblyName());
			if (type == null)
			{
				foreach (Assembly asm in m_LoadedAssemblies.Values)
				{
					type = asm.GetType(classMap.GetFullName());
					if (type != null)
					{
						break;
					}
				}
			}
			return type;
		}
        public void AddProperty(string name, object value)
        {
            if (_concreteEntityBuilder != null)
                _concreteEntityBuilder.AddProperty(name, value);
            else if (_classMap.DiscriminatorAlias == name)
            {
                //we have found our discriminator and *can* instantiate our type
                _classMap = _classMap.GetClassMapFromDiscriminator(value);
                _concreteEntityBuilder = new ConcreteClassMapBuilder(_classMap);
                foreach (var pair in _properties)
                    _concreteEntityBuilder.AddProperty(pair.Key, pair.Value);

                _properties.Clear();
            }
            else
                _properties.Add(name, value);
        }
        public void Apply(IClassMap classMap)
        {
            string tableName = classMap.EntityType.Name;

            if (classMap.EntityType.IsGenericType)
            {
                // special case for generics: GenericType_GenericParameterType
                tableName = classMap.EntityType.Name.Substring(0, classMap.EntityType.Name.IndexOf('`'));

                foreach (var argument in classMap.EntityType.GetGenericArguments())
                {
                    tableName += "_";
                    tableName += argument.Name;
                }
            }

            classMap.WithTable("`" + tableName + "`");
        }
        public static CodeNamespace GenerateFactoryClass(IClassMap classMap)
        {
            CodeNamespace domainNamespace = new CodeNamespace(classMap.DomainMap.RootNamespace + ".Factories" ) ;
            CodeTypeDeclaration classDecl = new CodeTypeDeclaration(GetFactoryClassName(classMap)) ;

            CodeNamespaceImport import = new CodeNamespaceImport(classMap.GetFullNamespace()) ;
            CodeNamespaceImport importNPersist = new CodeNamespaceImport("Puzzle.NPersist.Framework") ;
            domainNamespace.Imports.Add(import);
            domainNamespace.Imports.Add(importNPersist);

            classDecl.IsClass = true;

            GenerateConstructor(classDecl);
            GenerateContextField(classDecl);
            GenerateFactoryMethods(classMap, classDecl);

            domainNamespace.Types.Add(classDecl);

            return domainNamespace;
        }