示例#1
0
        public void MapTo_WhenCalled_EntityIsMapped()
        {
            var reader = Substitute.For<IDataReader>();

            var values = new[]
            {
                new {Name = "MY_PROPERTY", Value = (object) "SomeValue"},
                new {Name = "MY_NULLABLE_INT1", Value = (object) DBNull.Value},
                new {Name = "MY_NULLABLE_INT2", Value = (object) 1},
                new {Name = "MY_INT1", Value = (object) 2}
            };

            reader.FieldCount.Returns(values.Length);
            for (int i = 0; i < values.Length; i++)
            {
                reader.GetName(i).Returns(values[i].Name);
                reader.GetValue(i).Returns(values[i].Value);
            }

            var config = new DbConfig(c => { }, MappingConvention.OracleStyle, string.Empty);
            var map = reader.GetSetterMap<MyEntity>(config);
            var entity = reader.MapTo(map);
            
            Assert.AreEqual("SomeValue", entity.MyProperty);
            Assert.IsNull(entity.MyNullableInt1);
            Assert.AreEqual(1, entity.MyNullableInt2);
            Assert.AreEqual(2, entity.MyInt1);
        }
示例#2
0
        public void MapTo_WhenCalled_MissingProperty_IsIgnored()
        {
            var values = new[]
            {
                new {Name = "UNMAPPED_PROPERTY", Value = (object) "SomeValue"},
            };

            var record = Substitute.For<IDataReader>();
            record.FieldCount.Returns(2);
            for (int i = 0; i < values.Length; i++)
            {
                record.GetName(i).Returns(values[i].Name);
                record.GetValue(i).Returns(values[i].Value);
            }

            var config = new DbConfig(c => { }, MappingConvention.OracleStyle, string.Empty);
            var map = record.GetSetterMap<SomeEntity>(config);

            var entity = record.MapTo(map);

            Assert.IsNull(entity.MyProperty);
            Assert.IsNull(entity.MyNullableInt1);
            Assert.IsNull(entity.MyNullableInt2);
            Assert.AreEqual(default(int), entity.MyInt1);
        }
示例#3
0
文件: DbAccess.cs 项目: mind0n/hive
		public override void GetReady(DbConfig cfg)
		{
			if (!string.IsNullOrEmpty(cfg.Url))
			{
				this.ConnStr = string.Format(cfg.Connector, cfg.Url.MapPath());
			}
		}
示例#4
0
		internal XmlDataRecord(XDocument baseElement, Type target, DbConfig config = null)
			: this(baseElement,
				  config != null 
					? config.GetOrCreateClassInfoCache(target) 
					: new DbConfig().GetOrCreateClassInfoCache(target))
		{

		}
示例#5
0
		public ObjectDataRecord(object poco, DbConfig config, int depth)
		{
			_poco = poco;
			_config = config;
			Depth = depth;
			_classTypeCache = config.GetOrCreateClassInfoCache(poco.GetType());
			RecordsAffected = -1;
			FieldCount = _classTypeCache.Propertys.Count;
		}
示例#6
0
文件: DbConfig.cs 项目: mfz888/xcore
        public static void CreateDbConfig() {
            DbConfig config=new DbConfig();
            string[] ddlfiles = System.IO.Directory.GetFiles(PathHelper.Map("~/"), "*.dll");
            if (ddlfiles.Length == 0)
            {
                ddlfiles = System.IO.Directory.GetFiles(PathHelper.Map("~/bin"), "*.dll");
            }
            foreach (string dll in ddlfiles)
            {
                config.AssemblyList.Add(System.IO.Path.GetFileName(dll).Replace(".dll", ""));
            }
            //this.AssemblyList.Add("XCore");
            config.DbType.Add("default", "access");
            config.ConnectionStringTable.Add("default", DatabaseBuilder.ConnectionStringPrefix + DatabaseBuilder.BuildAccessDb4o());

            String cfgPath = getConfigPath();
            file.Write(cfgPath, JsonString.ConvertObject(config, true));
            loadMappingInfo(config);
            checkConnectionString(config);
            DbConfig.Instance = config;
            MappingClass.loadByReflection();
            MappingClass.checkMultiDB(MappingClass.Instance);
        }
示例#7
0
文件: DbConfig.cs 项目: mfz888/xcore
        private static DatabaseType getDbType(String dbname, String connectionString, DbConfig result)
        {

            foreach (KeyValuePair<String, Object> kv in result.DbType)
            {
                if (kv.Key == dbname) return DbTypeChecker.GetFromString(kv.Value.ToString());
            }

            DatabaseType dbtype = DbTypeChecker.GetDatabaseType(connectionString);
            return dbtype;
        }
示例#8
0
文件: DbConfig.cs 项目: mfz888/xcore
        private static void checkConnectionString( DbConfig result ) {

            logger.Info( "检查数据库连接设置..." );

            if (result.ConnectionStringTable == null) return;

            Dictionary<String, ConnectionString> connStringMap = new Dictionary<String, ConnectionString>();

            Dictionary<String, String> newString = new Dictionary<string, string>();
            foreach (KeyValuePair<String, object> kv in result.ConnectionStringTable) {

                String connectionString = kv.Value.ToString();
                DatabaseType dbtype = getDbType( kv.Key, connectionString, result );

				ConnectionString objConnString = new ConnectionString ();
				objConnString.Name = kv.Key;
				objConnString.StringContent = connectionString;
				objConnString.DbType = dbtype;

                connStringMap.Add( kv.Key, objConnString );

                logger.Info( "链接字符串:" + connectionString );

                IDatabaseDialect dialect = DataFactory.GetDialect( dbtype );

                if ((dbtype == DatabaseType.Access)) {
                    String connectionItem = dialect.GetConnectionItem( connectionString, ConnectionItemType.Database );
                    logger.Info( "database path original:" + connectionItem );

                    if (IsRelativePath( connectionItem )) {
                        connectionItem = strUtil.Join(SystemInfo.ApplicationPath, connectionItem);
                        //connectionItem = PathHelper.Map( strUtil.Join( SystemInfo.ApplicationPath, connectionItem ) );
                    }
                    logger.Info("database path now:" + connectionItem);
                    String newConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", connectionItem);
                    newString.Add(kv.Key, newConnString);
                    if (!file.Exists(connectionItem))
                    {
                        try
                        {
                            object catobj = null;
                            try
                            {
                                catobj = rft.GetInstance("Interop.ADOX", "ADOX.CatalogClass");
                            }
                            catch
                            {
                                logger.Error("Interop.ADOX.dll文件不存在,请检查bin目录!");
                            }
                            object connstr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + connectionItem + ";" +
                                             "Jet OLEDB:Engine Type=5";
                            rft.CallMethod(catobj, "Create", new[] {connstr});
                            //ADOX.CatalogClass cat = new ADOX.CatalogClass();
                            //cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + connectionItem + ";" + "Jet OLEDB:Engine Type=5");
                            //Console.WriteLine("Database Created Successfully");
                            //logger.Info("Access数据库已创建:" + connectionItem);
                            //cat = null;
                        }
                        catch
                        {
                            logger.Info("Access数据库创建失败:" + connectionItem);
                        }
                    }
                }
            }

            foreach (KeyValuePair<String, String> kv in newString) {
                result.ConnectionStringTable[kv.Key] = kv.Value;
                connStringMap[kv.Key].StringContent = kv.Value;
            }

            result.SetConnectionStringMap( connStringMap );
        }
示例#9
0
文件: DbConfig.cs 项目: mfz888/xcore
        private static void loadMappingInfo( DbConfig dbc ) {
            if (dbc.Mapping.Count == 0) return;
            foreach (Dictionary<String, object> dic in dbc.Mapping) {

                MappingInfo mi = new MappingInfo();

                if (dic.ContainsKey( "name" )) mi.TypeName = dic["name"].ToString();
                if (dic.ContainsKey( "database" )) mi.Database = dic["database"].ToString();
                if (dic.ContainsKey( "table" )) mi.Table = dic["table"].ToString();

                dbc.addMapping( mi );
            }
        }
示例#10
0
 protected DatabaseTest()
 {
     test = new DbTest(GetType().Name);
     config = DbConfig.FromProviderName(test.ProviderName);
 }
示例#11
0
		/// <summary>
		///     Create a DbAccessLAyer with exernal Strategy
		/// </summary>
		/// <exception cref="ArgumentNullException"></exception>
		public DbAccessLayer(string fullTypeNameToIDatabaseStrategy, string connection, ILogger logger = null,
			DbConfig config = null)
			: this(logger, config)
		{
			if (string.IsNullOrEmpty(fullTypeNameToIDatabaseStrategy))
				throw new ArgumentNullException("fullTypeNameToIDatabaseStrategy");

			ResolveDbType(fullTypeNameToIDatabaseStrategy);

			var database = GenerateStrategy(fullTypeNameToIDatabaseStrategy, String.Concat((object) connection));

			Database = new DefaultDatabaseAccess();
			Database.Attach(database);
			DatabaseStrategy = database;
		}
示例#12
0
		public static void Config(DbConfig configBase)
		{
			configBase.SetConfig<ConfigLessUserInplaceConfig>(f =>
			{
				f.SetClassAttribute(new ForModelAttribute(UsersMeta.TableName));
				f.SetPrimaryKey(e => e.PropertyA);
				f.SetForModelKey(e => e.PropertyA, UsersMeta.PrimaryKeyName);
				f.SetForModelKey(e => e.PropertyB, UsersMeta.ContentName);
			});
		}
示例#13
0
        private static DatabaseType getDbType(String dbname, String connectionString, DbConfig result)
        {
            foreach (KeyValuePair <String, Object> kv in result.DbType)
            {
                if (kv.Key == dbname)
                {
                    return(DbTypeChecker.GetFromString(kv.Value.ToString()));
                }
            }

            DatabaseType dbtype = DbTypeChecker.GetDatabaseType(connectionString);

            return(dbtype);
        }
示例#14
0
		public override void GetReady(DbConfig cfg)
		{
			
		}
示例#15
0
文件: DbConfig.cs 项目: nust03/xcore
        //----------------------------------------------------------------------
        private static DbConfig loadConfig( String cfgPath )
        {
            String str = string.Empty;
            DbConfig dbc = null;
            try
            {
                str = file.Read(cfgPath, true);
                dbc = JSON.ToObject<DbConfig>(str);
                Dictionary<string, object>.Enumerator en = dbc.ConnectionStringTable.GetEnumerator();
                List<System.Data.KeyValue> kvlist = new List<KeyValue>();
                while (en.MoveNext())
                {
                    string connstr = en.Current.Value.ToString();
                    if (connstr.IndexOf(':') <= 0 && dbc.DbType[en.Current.Key].ToString() == "access")
                    {
                        connstr = connstr.Replace(DatabaseBuilder.ConnectionStringPrefix, DatabaseBuilder.ConnectionStringPrefix + PathHelper.Map("/")).Replace('/', '\\');
                        kvlist.Add(new System.Data.KeyValue(en.Current.Key, connstr.Replace("\\\\", "\\")));
                    }
                }
                foreach (System.Data.KeyValue kv in kvlist)
                {
                    dbc.ConnectionStringTable[kv.Key] = kv.Value;
                }
            }
            catch (FileNotFoundException ex)
            {
                dbc = new DbConfig();
                file.Write(cfgPath, Json.ToStringEx(dbc));
                dbc = loadConfig(cfgPath);
                //file.Write(cfgPath, Json.ToStringEx(dbc).Replace("\n", "").Replace("\r", "").Replace("\t", "").Replace("\b", "").Replace(" ", ""));
            }

            loadMappingInfo( dbc );
            checkConnectionString( dbc );

            return dbc;
        }
示例#16
0
		/// <summary>
		///     Create a DbAccessLayer that uses a Predefined type and Connection string
		/// </summary>
		public DbAccessLayer(DbAccessType dbAccessType, string connection, ILogger logger = null, DbConfig config = null)
			: this(logger, config)
		{
			if (dbAccessType == DbAccessType.Unknown)
			{
				throw new InvalidEnumArgumentException("dbAccessType", (int) DbAccessType.Unknown, typeof(DbAccessType));
			}

			DbAccessType = dbAccessType;
			Database = new DefaultDatabaseAccess();
			var database =
				GenerateStrategy(ProviderCollection.FirstOrDefault(s => s.Key == dbAccessType).Value, connection);
			Database.Attach(database);
			DatabaseStrategy = database;
		}
示例#17
0
		internal XmlDataRecord(string xmlStream, Type target, DbConfig config)
			: this(xmlStream, config.GetOrCreateClassInfoCache(target))
		{

		}
示例#18
0
		/// <summary>
		///     This is our standart solution for Seriliation
		///     takes care of the loader strategy
		/// </summary>
		/// <returns></returns>
		public static XmlDataRecord TryParse(string xmlStream, Type target, bool single, DbConfig accessLayer = null)
		{
			if (string.IsNullOrEmpty(xmlStream) || string.IsNullOrWhiteSpace(xmlStream))
				return null;
			try
			{
				var xDocument = XDocument.Parse(xmlStream, LoadOptions.None);
				var record = new XmlDataRecord(xDocument, target, accessLayer);

				if (single)
				{
					return record.CreateListOfItems().FirstOrDefault();
				}

				return record;
			}
			catch (Exception)
			{
				return null;
			}
		}
示例#19
0
		/// <summary>
		///     Create a DbAccessLayer with a new Database
		/// </summary>
		/// <exception cref="ArgumentNullException"></exception>
		public DbAccessLayer(IDatabaseStrategy database, ILogger logger = null, DbConfig config = null)
			: this(logger, config)
		{
			if (database == null)
				throw new ArgumentNullException("database");
			DbAccessType = database.SourceDatabase;
			//ResolveDbType(database.GetType().FullName);

			Database = new DefaultDatabaseAccess();
			Database.Attach(database);
			DatabaseStrategy = database;
		}
示例#20
0
		/// <summary>
		///     Creates a DbAccessLayer with a new Database
		///     dbAccessType will be Guessed
		/// </summary>
		public DbAccessLayer(IDatabase database, ILogger logger = null, DbConfig config = null)
			: this(logger, config)
		{
			if (database == null)
				throw new ArgumentNullException("database");

			DbAccessType = DbAccessType.Unknown;
			Database = database;
		}
示例#21
0
		public static object ReflectionPropertySet(
			DbConfig config,
			object instance,
			DbClassInfoCache info,
			IDataRecord reader,
			Dictionary<int, DbPropertyInfoCache> cache,
			DbAccessType? dbAccessType)
		{
			if (instance == null) throw new ArgumentNullException("instance");
			if (info == null) throw new ArgumentNullException("info");
			if (reader == null)
				return instance;

			//Left c# property name and right the object to read from the reader
			//var listofpropertys = new Dictionary<string, object>();

			var propertys = info.Propertys.ToArray();
			var instanceOfFallbackList = new Dictionary<string, object>();

			if (cache == null)
			{
				cache = new Dictionary<int, DbPropertyInfoCache>();
				for (var i = 0; i < reader.FieldCount; i++)
				{
					DbPropertyInfoCache val = null;
					info.Propertys.TryGetValue(info.SchemaMappingDatabaseToLocal(reader.GetName(i)), out val);
					cache.Add(i, val);
				}
			}

			for (var i = 0; i < reader.FieldCount; i++)
			{
				var property = cache[i];
				var value = reader.GetValue(i);

				if (property != null)
				{
					var attributes = property.Attributes;
					var valueConverterAttributeModel =
						attributes.FirstOrDefault(s => s.Attribute is ValueConverterAttribute);

					//Should the SQL value be converted
					if (valueConverterAttributeModel != null)
					{
						var converter = valueConverterAttributeModel.Attribute as ValueConverterAttribute;
						//Create the converter and then convert the value before everything else
						var valueConverter = converter.CreateConverter();
						value = valueConverter.Convert(value, property.PropertyInfo.PropertyType, converter.Parameter,
							CultureInfo.CurrentCulture);
					}

					var xmlAttributeModel =
						attributes.FirstOrDefault(s => s.Attribute is FromXmlAttribute);

					//should the Content be considerd as XML text?
					if (xmlAttributeModel != null)
					{
						//Get the XML text and check if its null or empty
						var xmlStream = value.ToString();
						if (string.IsNullOrEmpty(xmlStream))
						{
							continue;
						}

						//Check for List
						//if this is a list we are expecting other entrys inside
						if (property.CheckForListInterface())
						{
							//target Property is of type list
							//so expect a xml valid list Take the first element and expect the propertys inside this first element
							var record = XmlDataRecord.TryParse(xmlStream,
								property.PropertyInfo.PropertyType.GetGenericArguments().FirstOrDefault(), false, config);
							var xmlDataRecords = record.CreateListOfItems();

							var genericArguments =
								config.GetOrCreateClassInfoCache(property.PropertyInfo.PropertyType.GetGenericArguments().FirstOrDefault());
							var enumerableOfItems =
								xmlDataRecords.Select(
									s => DbAccessLayerHelper.SetPropertysViaReflection(genericArguments, s, dbAccessType, config)).ToList();
							object castedList;

							if (genericArguments.Type.IsClass && genericArguments.Type.GetInterface("INotifyPropertyChanged") != null)
							{
								var caster =
									typeof(DbCollection<>).MakeGenericType(genericArguments.Type).GetConstructor(new[] {typeof(IEnumerable)});

								Debug.Assert(caster != null, "caster != null");

								castedList = caster.Invoke(new object[] {enumerableOfItems});
							}
							else
							{
								var caster =
									typeof(NonObservableDbCollection<>).MakeGenericType(genericArguments.Type)
										.GetConstructor(new[] {typeof(IEnumerable)});

								Debug.Assert(caster != null, "caster != null");

								castedList = caster.Invoke(new object[] {enumerableOfItems});
							}

							property.Setter.Invoke(instance, castedList);
						}
						else
						{
							var classInfo = config.GetOrCreateClassInfoCache(property
								.PropertyInfo
								.PropertyType);

							var xmlDataRecord = XmlDataRecord.TryParse(xmlStream, property.PropertyInfo.PropertyType, true, config);

							//the t
							var xmlSerilizedProperty = DbAccessLayerHelper.SetPropertysViaReflection(classInfo, xmlDataRecord, dbAccessType,
								config);
							property.Setter.Invoke(instance, xmlSerilizedProperty);
						}
					}
					else if (value is DBNull || value == null)
					{
						property.Setter.Invoke(instance, new object[] {null});
					}
					else
					{
						object changedType;
						if (value.GetType() != property.PropertyInfo.PropertyType)
						{
							changedType = DataConverterExtensions.ChangeType(value, property.PropertyInfo.PropertyType);
						}
						else
						{
							changedType = value;
						}

						property.Setter.Invoke(instance, changedType);
					}
				}
				//This variable is null if we tried to find a property with the LoadNotImplimentedDynamicAttribute but did not found it
				else if (instanceOfFallbackList != null)
				{
					//no property found Look for LoadNotImplimentedDynamicAttribute property to include it

					if (instanceOfFallbackList.Any())
					{
						instanceOfFallbackList.Add(reader.GetName(i), value);
					}
					else
					{
						var maybeFallbackProperty =
							propertys.FirstOrDefault(
								s => s.Value.Attributes.Any(e => e.Attribute is LoadNotImplimentedDynamicAttribute));
						if (maybeFallbackProperty.Value != null)
						{
							instanceOfFallbackList = (Dictionary<string, object>) maybeFallbackProperty.Value.Getter.Invoke(instance);
							if (instanceOfFallbackList == null)
							{
								instanceOfFallbackList = new Dictionary<string, object>();
								maybeFallbackProperty.Value.Setter.Invoke(instance, instanceOfFallbackList);
							}
							instanceOfFallbackList.Add(reader.GetName(i), value);
						}
						else
						{
							instanceOfFallbackList = null;
						}
					}
				}
			}


			//foreach (var item in listofpropertys)
			//{
			//	var property = propertys.FirstOrDefault(s => s.PropertyName == item.Key);

			//}

			if (reader is EgarDataRecord)
			{
				(reader as IDisposable).Dispose();
			}

			return instance;
		}
示例#22
0
文件: DbConfig.cs 项目: nust03/xcore
        private static void checkConnectionString( DbConfig result )
        {
            logger.Info( "checkConnectionString..." );

            if (result.ConnectionStringTable == null) return;

            Dictionary<String, ConnectionString> connStringMap = new Dictionary<String, ConnectionString>();

            Dictionary<String, String> newString = new Dictionary<string, string>();
            foreach (KeyValuePair<String, object> kv in result.ConnectionStringTable) {

                String connectionString = kv.Value.ToString();
                DatabaseType dbtype = getDbType( kv.Key, connectionString, result );

                ConnectionString objConnString = new ConnectionString ();
                objConnString.Name = kv.Key;
                objConnString.StringContent = connectionString;
                objConnString.DbType = dbtype;

                connStringMap.Add( kv.Key, objConnString );

                logger.Info( "connectionString:" + connectionString );

                IDatabaseDialect dialect = DataFactory.GetDialect( dbtype );

                if ((dbtype == DatabaseType.Access)) {
                    String connectionItem = dialect.GetConnectionItem( connectionString, ConnectionItemType.Database );
                    logger.Info( "database path original:" + connectionItem );

                    if (IsRelativePath( connectionItem )) {
                        connectionItem = strUtil.Join(SystemInfo.ApplicationPath, connectionItem);
                        //connectionItem = PathHelper.Map( strUtil.Join( SystemInfo.ApplicationPath, connectionItem ) );
                        logger.Info( "database path now:" + connectionItem );
                        String newConnString = String.Format( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", connectionItem );

                        newString.Add( kv.Key, newConnString );
                    }
                }
            }

            foreach (KeyValuePair<String, String> kv in newString) {
                result.ConnectionStringTable[kv.Key] = kv.Value;
                connStringMap[kv.Key].StringContent = kv.Value;
            }

            result.SetConnectionStringMap( connStringMap );
        }
示例#23
0
		internal DbAccessLayer(ILogger logger = null, DbConfig config = null)
		{
			if (config == null)
			{
				_config = new DbConfig();
			}
			else
			{
				_config = config;
			}
			DefaultLookupPath = AppDomain.CurrentDomain.BaseDirectory;
			_logger = logger;
			Debugger = false;
			LoadCompleteResultBeforeMapping = true;
			CheckFactoryArguments = true;
			SelectDbAccessLayer();
			UpdateDbAccessLayer();
		}