Пример #1
0
        public   void Test_Initialization()
        {


            var dbConfig = new DbConfig()
            {
                ConnectionString =
                    string.Format("Data Source= " +
                                  "(DESCRIPTION =" +
                                  "(ADDRESS = (PROTOCOL = TCP)(HOST = {0} )(PORT = {1}))" +
                                  "(CONNECT_DATA = (SID = {2})));User Id={3};Password={4};",
                                  "localhost", "1521", "xe", "easylink", "1197344"),
                DatabaseType = DatabaseType.Oracle,
                SchemaName = "EASYLINK",
                AuditRecordType = typeof(AuditRecord)
            };

            DatabaseFactory.Initialize(dbConfig);
 

            database = DatabaseFactory.Create();


            Mapping.SetNextId<Employee>(NextIdOption.Sequence,"EMPLOYEE_ID_SEQ");
            Mapping.SetNextId<Program>(NextIdOption.Sequence, "PROGRAM_ID_SEQ");
            Mapping.SetNextId<EmployeeProgram>(NextIdOption.Sequence, "EMPLOYEE_PROGRAM_ID_SEQ");
            Mapping.SetNextId<Address>(NextIdOption.Sequence, "ADDRESS_ID_SEQ");
            Mapping.SetNextId<FinancialInfo>(NextIdOption.Sequence, "FINANCIAL_INFO_ID_SEQ");
            Mapping.SetNextId<AdditionalInfo>(NextIdOption.Sequence, "ADDITIONAL_INFO_ID_SEQ");
            Mapping.SetNextId<Lookup>(NextIdOption.Sequence, "LOOKUP_ID_SEQ");
            Mapping.SetNextId<AuditRecord>(NextIdOption.Sequence, "AUDIT_ID_SEQ");
 
        }
        public  void Test_Initialization()
        {


            var dbConfig = new DbConfig()
            {
                ConnectionString = @"Server=meng;Database=easylink;User Id=sa; Password=1197344;",
                DatabaseType = DatabaseType.SqlServer,
                SchemaName = "dbo",
                AuditRecordType = typeof(AuditRecord)
            };

            DatabaseFactory.Initialize(dbConfig);

            database = DatabaseFactory.Create();


            Mapping.SetNextId<Employee>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<Program>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<EmployeeProgram>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<Address>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<FinancialInfo>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<AdditionalInfo>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<Lookup>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<AuditRecord>(NextIdOption.AutoIncrement);

 
        }
Пример #3
0
        // TODO: only works with string datatypes
        public static void Insert( object obj )
        {
            DbConfig config = new DbConfig();
            string tableName = obj.GetType().Name;
            string schemaName = config.Schema;
            string fields = SqlUtil.BuildFieldNames( obj );
            string values = SqlUtil.BuildFieldValues( obj );

            /*
            PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties( obj );
            for( int i = 0; i < descriptors.Count; i++ ) {
                Console.WriteLine( descriptors[ i ].Name + ": " + descriptors[i].GetValue( obj ).ToString() );
                fields += "[" + descriptors[i].Name + "]";
                values += "'" + descriptors[ i ].GetValue( obj ) + "'";
                if( i < descriptors.Count - 1 ) {
                    fields += ",";
                    values += ",";
                }
            }
            */
            string qualifiedTableName = SqlUtil.WriteQualifiedName( schemaName, tableName );
            string sqlString = "insert into " + qualifiedTableName +
                " ( " + fields +
                " ) values ( " + values + " ) ";
            Console.WriteLine( sqlString );

            IDbConnection conn = ConnectionFactory.GetConnection( new DbConfig() );
            using( conn ) {
                IDataReader rdr = DbUtil.ExecuteReader( conn, sqlString );
                rdr.Close();
            }
        }
Пример #4
0
		public void FakeClassStructProperty()
		{
			var cache = new DbConfig(true);
			Assert.That(() =>
			{
				var fakeType = cache.GetFake("FakeType");

				fakeType.Propertys.Add("Test", new DbAutoStaticPropertyInfoCache<long>("Test", fakeType.Type));

				Assert.That(fakeType.Propertys.Count, Is.EqualTo(1));
				Assert.That(fakeType.Mehtods.Count, Is.EqualTo(6));
				Assert.That(fakeType.Attributes, Is.Empty);

				var refElement = fakeType.DefaultFactory();
				var originalValue = 12L;

				Assert.That(refElement, Is.Not.Null.And.TypeOf(fakeType.Type));

				var propTest = fakeType.Propertys["Test"];
				Assert.That(propTest, Is.Not.Null);
				propTest.Setter.Invoke(refElement, originalValue);
				var propValue = propTest.Getter.Invoke(refElement);
				Assert.That(propValue, Is.Not.Null.And.EqualTo(originalValue));
			}, Throws.Nothing);
		}
Пример #5
0
        public  void Test_Initialization()
        {

 
            var dbConfig = new DbConfig()
            {
                ConnectionString = "Server=127.0.0.1;Port=3306; Uid=root; Pwd=1197344; Database=test;",
                DatabaseType =  DatabaseType.MySql, 
                SchemaName = "test",
                AuditRecordType = typeof(AuditRecord)
            };

            DatabaseFactory.Initialize(dbConfig);



            database = DatabaseFactory.Create();


            Mapping.SetNextId<Employee>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<Program>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<EmployeeProgram>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<Address>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<FinancialInfo>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<AdditionalInfo>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<Lookup>(NextIdOption.AutoIncrement);
            Mapping.SetNextId<AuditRecord>(NextIdOption.AutoIncrement);
 
        }
Пример #6
0
Файл: Db.cs Проект: jhgbrt/yadal
 /// <summary>
 /// Instantiate Db with connectionString and a custom IConnectionFactory
 /// </summary>
 /// <param name="connectionString">the connection string</param>
 /// <param name="config"></param>
 /// <param name="connectionFactory">the connection factory</param>
 internal Db(string connectionString, DbConfig config, IConnectionFactory connectionFactory = null)
 {
     _connectionString = connectionString;
     _connectionFactory = connectionFactory ?? new AdoNetProviderFactory(config.ProviderName);
     _connection = new Lazy<IDbConnection>(CreateConnection);
     Config = config;
 }
        public  void Test_Initialization()
        {

            

            var dbConfig = new DbConfig()
            {
                ConnectionString = "Server=localhost;Port=5432;Database=Easylink;Pooling =false; User Id=postgres;Password=1197344;",
                DatabaseType = DatabaseType.PostgreSql,
                SchemaName = "public",
                AuditRecordType = typeof(AuditRecord)
            };

            DatabaseFactory.Initialize(dbConfig);


            database = DatabaseFactory.Create();

            Mapping.SetNextId<Employee>(NextIdOption.Sequence,"employee_seq");
            Mapping.SetNextId<Program>(NextIdOption.Sequence, "program_seq");
            Mapping.SetNextId<EmployeeProgram>(NextIdOption.Sequence, "employee_program_seq");
            Mapping.SetNextId<Address>(NextIdOption.Sequence, "address_seq");
            Mapping.SetNextId<FinancialInfo>(NextIdOption.Sequence, "financial_info_seq");
            Mapping.SetNextId<AdditionalInfo>(NextIdOption.Sequence, "additional_info_seq");
            Mapping.SetNextId<Lookup>(NextIdOption.Sequence, "lookup_seq");
            Mapping.SetNextId<AuditRecord>(NextIdOption.Sequence, "audit_seq");
 
        }
Пример #8
0
        public void Test_Initialization()
        {
            var dbConfig = new DbConfig()
            {
                ConnectionString =
                    string.Format("Data Source= " +
                                  "(DESCRIPTION =" +
                                  "(ADDRESS = (PROTOCOL = TCP)(HOST = {0} )(PORT = {1}))" +
                                  "(CONNECT_DATA = (SID = {2})));User Id={3};Password={4};",
                                  "localhost", "1521", "xe", "easylink", "1197344"),
                DatabaseType = DatabaseType.Oracle,
                SchemaName = "EASYLINK",
                AuditRecordType = typeof(AuditRecord)
            };

            DatabaseFactory.Initialize(dbConfig);


            database = DatabaseFactory.Create();


 
            Mapping.SetNextId<Lookup>(NextIdOption.Sequence,"LOOKUP_ID_SEQ");
       



        }
Пример #9
0
 public void ChangeDdl()
 {
     DbConfig config = new DbConfig();
     //config.DriverList = _Drives;
     config.AmonHandler = new AmonHandler<Rdbms>(ChangeDdl);
     config.ShowDialog(this);
 }
Пример #10
0
 public static void Create( string in_schemaname, DbConfig in_config )
 {
     IDbConnection conn = ConnectionFactory.GetConnection( in_config );
     using( conn ) {
         if( !Exists( in_schemaname, in_config ) ) {
             IDataReader reader = DbUtil.ExecuteReader( conn, "create schema " + in_schemaname );
         }
     }
 }
Пример #11
0
        private PgDb(DbConfig config)
        {
            Config = config;

            this.user = config.User;
            this.password = config.Password;
            this.server = config.ServerName;
            this.database = config.DatabaseName;
            this.port = config.Port;
        }
Пример #12
0
 /**
 * Drops a database table given the table name and schema
 */
 public static void Drop( string in_schema, string in_table, DbConfig in_config )
 {
     using( IDbConnection dbConnection = ConnectionFactory.GetConnection( in_config ) )
     {
         dbConnection.Open();
         IDataReader reader;
         reader = DbUtil.ExecuteReader( dbConnection, "drop table [" + in_schema + "].[" + in_table + "]" );
         reader.Close();
     }
 }
Пример #13
0
 /**
  * Return a database connection according to mapper config
  * could be oracle or sql server
  *
  * @in_mapperConfig - mapper configuration object
  */
 public static IDbConnection GetConnection( DbConfig in_mapperConfig )
 {
     IDbConnection returnValue;
     if( in_mapperConfig.DatabaseType == DatabaseType.MSSql ) {
         returnValue = new SqlConnection( in_mapperConfig.ConnectionString );
     }
     else if( in_mapperConfig.DatabaseType == DatabaseType.Oracle ) {
         returnValue = new OracleConnection( in_mapperConfig.ConnectionString );
     }
     else { throw new Exception( "Unsupported database type" ); }
     return returnValue;
 }
Пример #14
0
		public void FakeCreation()
		{
			var cache = new DbConfig(true);
			Assert.That(() =>
			{
				var fakeType = cache.GetFake("FakeType");
				Assert.That(fakeType.Name, Is.Not.Null.And.EqualTo("FakeType"));
				Assert.That(fakeType.Propertys, Is.Empty);
				Assert.That(fakeType.Mehtods.Count, Is.EqualTo(6));
				Assert.That(fakeType.Attributes, Is.Empty);
			}, Throws.Nothing);
		}
Пример #15
0
 public static bool Exists( string in_schemaname, DbConfig in_config )
 {
     IDbConnection conn = ConnectionFactory.GetConnection( in_config );
     using( conn ) {
         IDataReader reader = DbUtil.ExecuteReader( conn, "IF EXISTS (SELECT * FROM sys.schemas WHERE name = '" + in_schemaname + "') select 1" );
         if( reader.Read() ) {
             return true;
         }
         else {
             return false;
         }
     }
 }
Пример #16
0
        // retrieve objects by single field comparison
        // TODO: should this be a generic method? Then we can return List<T> directly
        public static List<object> GetByField( Type in_type, string in_field, string in_value )
        {
            DbConfig config = new DbConfig();
            string qualifiedTableName = SqlUtil.WriteQualifiedName( config.Schema, in_type.Name );
            string qualifiedFieldName = SqlUtil.WriteQualifiedName( in_field );
            string sqlString = "select * from " + qualifiedTableName + " where " + qualifiedFieldName + " = '" + in_value + "'";
            IDataReader rdr = DbUtil.ExecuteReader( ConnectionFactory.GetConnection( new DbConfig() ), sqlString );

            List<object> retval = new List<object>();
            while( rdr.Read() ) {
                object obj = Activator.CreateInstance( in_type );
                PopulateObjectFromReader( obj, rdr );
                retval.Add( obj );
            }
            return retval;
        }
Пример #17
0
        /**
        * Create a table in the database given a list of fields and the
        * table name. We use a Field collection as a conveneint way of specifying all
        * field info including data type.
        */
        public static void CreateTable( string in_tableName, List<Field> in_fields, DbConfig in_config )
        {
            // sqlColumns is the portion of the create script that defines the columns
            string sqlColumns = "";

            for( int i = 0; i < in_fields.Count; i++ )
            {
                // this is sort of a hack .. but sql won't let you have duplicate column names
                // anyway, so we exclude the id column from our list, we hard code it into the query
                // since we want it to autonumber
                if( in_fields[ i ].Name != "ID" )
                {
                    // map .net types to sql datatypes as strings for use in the create script
                    string sqlType;
                    if( in_fields[ i ].Type == typeof( String ) ) {
                        sqlType = "varchar(20)";
                    }
                    else if( in_fields[ i ].Type == typeof( int ) ) {
                        sqlType = "int";
                    }
                    else {
                        throw new Exception( "Unsupported datatype: " + in_fields[ i ].Type.ToString() );
                    }

                    sqlColumns += in_fields[ i ].Name + " " + sqlType + " not null";
                    if( i != in_fields.Count - 1 ) {
                        sqlColumns += ", ";
                    }
                }
            }

            // hack for special case where we don't have any properties
            string firstSeparator = ", ";
            if( in_fields.Count == 0 ) {
                firstSeparator = " ";
            }

            using( IDbConnection dbConnection = ConnectionFactory.GetConnection( in_config ) ) {
                IDataReader reader = DbUtil.ExecuteReader(
                    dbConnection,
                    "create table [" + in_config.Schema + "].[" + in_tableName + "] ( ID int identity(0,1) not null" + firstSeparator + sqlColumns + " )" );
                reader.Close();
            }
        }
        public  void Test_Initialization()
        {
            var dbConfig = new DbConfig()
            {
                ConnectionString = @"Server=meng;Database=easylink;User Id=sa; Password=1197344;",
                DatabaseType = DatabaseType.SqlServer,
                SchemaName = "dbo",
                AuditRecordType = typeof(AuditRecord)
            };

            DatabaseFactory.Initialize(dbConfig);


            database = DatabaseFactory.Create();


            Mapping.SetNextId<AspNetRole>(NextIdOption.None);
          
 
        }
Пример #19
0
        public void Test_Initialization()
        {
 

            var dbConfig = new DbConfig()
            {
                ConnectionString = "Server=localhost;Port=5432;Database=Easylink;Pooling =false; User Id=postgres;Password=1197344;",
                DatabaseType = DatabaseType.PostgreSql,
                SchemaName = "public",
                AuditRecordType = typeof(AuditRecord)
            };

            DatabaseFactory.Initialize(dbConfig);
			

            database = DatabaseFactory.Create();

            Mapping.SetNextId<Lookup>(NextIdOption.Sequence, "lookup_seq");
  
        }
Пример #20
0
        public  void Test_Initialization()
        {
           
            var dbConfig = new DbConfig()
            {
                ConnectionString = @"Server=meng;Database=easylink;User Id=sa; Password=1197344;",
                DatabaseType = DatabaseType.SqlServer,
                SchemaName = "dbo",
                AuditRecordType = typeof(AuditRecord)
            };

            DatabaseFactory.Initialize(dbConfig);


            database = DatabaseFactory.Create();

            Mapping.SetNextId<Invoice>(NextIdOption.Sequence, "Invoice_Id_Seq");
            Mapping.SetNextId<AuditRecord>(NextIdOption.AutoIncrement);


        }
Пример #21
0
		public void TestStructCreating()
		{
			var cache = new DbConfig(true);
			cache.Include<StructCreating>();
			Assert.That(() => cache.SClassInfoCaches.First().DefaultFactory(), Is.Not.Null);
		}
Пример #22
0
 public SqlServerProxyDbContext(DbConfig dbConfig) : base(dbConfig)
 {
 }
Пример #23
0
 /// <summary>
 /// Creates the <see cref="PgDb"/> from config file in file path.
 /// </summary>
 /// <param name="configPath">The config file path.</param>
 /// <returns>The initialized <see cref="PgDb"/> instance.</returns>
 public static PgDb Create(string configPath)
 {
     DbConfig config = new DbConfig(configPath);
     return new PgDb(config);
 }
Пример #24
0
 public DbHelper(DbConfig config)
 {
     this.config = config;
 }
Пример #25
0
        public static object ReflectionPropertySet(
            DbConfig config,
            object instance,
            DbClassInfoCache info,
            EagarDataRecord reader,
            ReflectionSetCacheModel cacheModel,
            DbAccessType?dbAccessType)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            if (info == null)
            {
                throw new ArgumentNullException(nameof(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>();
            IDictionary <int, DbPropertyInfoCache> cache = new Dictionary <int, DbPropertyInfoCache>();

            for (var i = 0; i < reader.FieldCount; i++)
            {
                info.Propertys.TryGetValue(info.SchemaMappingDatabaseToLocal(reader.GetName(i)), out var val);
                cache.Add(i, val);
            }

            //var containsKey = cacheModel?.Cache.ContainsKey(info.Type);
            //if (containsKey != true)
            //{
            //	for (var i = 0; i < reader.FieldCount; i++)
            //	{
            //		info.Propertys.TryGetValue(info.SchemaMappingDatabaseToLocal(reader.GetName(i)), out var val);
            //		cache.Add(i, val);
            //	}

            //	if (containsKey == false)
            //	{
            //		cacheModel.Cache[info.Type] = cache;
            //	}
            //}
            //if (containsKey == true)
            //{
            //	cache = cacheModel.Cache[info.Type];
            //}

            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 => genericArguments
                                    .SetPropertiesViaReflection(EagarDataRecord.WithExcludedFields(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) });
                                castedList = caster.Invoke(new object[] { enumerableOfItems });
                            }
                            else
                            {
                                var caster =
                                    typeof(NonObservableDbCollection <>).MakeGenericType(genericArguments.Type)
                                    .GetConstructor(new[] { typeof(IEnumerable) });
                                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 = classInfo.SetPropertiesViaReflection(
                                EagarDataRecord.WithExcludedFields(xmlDataRecord), dbAccessType,
                                config);
                            property.Setter.Invoke(instance, xmlSerilizedProperty);
                        }
                    }
                    else if (value is DBNull || value == null)
                    {
                        //property.Setter.Invoke(instance, new object[] {null});
                    }
                    else if (value is IEnumerable <EagarDataRecord> navigationValue)
                    {
                        Type targetType;
                        if (property.CheckForListInterface())
                        {
                            targetType = property.PropertyType.GetElementType();
                            if (targetType == null)
                            {
                                targetType = property.PropertyType.GetGenericArguments().FirstOrDefault();
                            }
                        }
                        else
                        {
                            targetType = property.PropertyType;
                        }

                        var classInfo   = config.GetOrCreateClassInfoCache(targetType);
                        var enumeration = navigationValue.Select(subReader =>
                        {
                            bool created;
                            var source = CreateInstance(classInfo, subReader, out created);
                            if (created)
                            {
                                return(source);
                            }
                            return(ReflectionPropertySet(config, source, classInfo, subReader, cacheModel, dbAccessType));
                        }).ToArray();

                        if (property.CheckForListInterface())
                        {
                            var caster =
                                typeof(DbCollection <>).MakeGenericType(targetType)
                                .GetConstructor(new[] { typeof(IEnumerable) });
                            var castedList = caster.Invoke(new object[] { enumeration });
                            property.Setter.Invoke(instance, castedList);
                        }
                        else
                        {
                            property.Setter.Invoke(instance, enumeration.FirstOrDefault());
                        }
                    }
                    else
                    {
                        object changedType = value;
                        if (property.PropertyType.IsInstanceOfType(value))
                        {
                            changedType = value;
                        }
                        else
                        {
                            if (!DataConverterExtensions.ChangeType(ref changedType, property.PropertyInfo.PropertyType))
                            {
                                continue;
                            }
                        }

                        //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);

            //}
            return(instance);
        }
Пример #26
0
 protected virtual void OnConfigure(DbConfig config)
 {
     if (storageType == StorageType.File) {
         config.SetValue(ConfigKeys.StorageSystem, ConfigDefaultValues.FileStorageSystem);
     } else if (storageType == StorageType.Memory) {
         config.SetValue(ConfigKeys.StorageSystem, ConfigDefaultValues.HeapStorageSystem);
     }
 }
 public AdoPaymentRepository(DbConfig dbConfig)
 {
     connectionString = dbConfig.ConnectionString;
 }
Пример #28
0
 public RegionController(IOptions <DbConfig> config)
 {
     // Or to temporarily use legacy PostGIS on a single connection only:
     dbcofig = config.Value;
     mySpatialRepo.connectionString = dbcofig.PostgresqlConnection;
 }
Пример #29
0
 public DatabaseService(IOptions <DbConfig> config, ILogger <DatabaseService> log)
 {
     _log    = log;
     _config = config.Value;
 }
Пример #30
0
        private static string GetDisplayFields()
        {
            List <string> displayFields = new List <string>();

            ScrudHelper.AddDisplayField(displayFields, "core.cash_flow_headings.cash_flow_heading_id", DbConfig.GetDbParameter(AppUsers.GetCurrentUserDB(), "CashFlowHeadingDisplayField"));
            ScrudHelper.AddDisplayField(displayFields, "core.account_masters.account_master_id", DbConfig.GetDbParameter(AppUsers.GetCurrentUserDB(), "AccountMasterDisplayField"));
            return(string.Join(",", displayFields));
        }
Пример #31
0
        private void 数据库配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _sysCfg = new SysConfigManager().Get();
            var form = new DbConfig();
            form.InitConfig(_sysCfg.DbConfig);
            var result = form.ShowDialog();

            if (result != DialogResult.OK) return;

            form.SetConfig(_sysCfg.DbConfig);
            var sh = new SqlHelper(_sysCfg.DbConfig.GetConnectionString());
            try
            {
                sh.Open();
                new SysConfigManager().Set(_sysCfg);
                try
                {
                    sh.Execute(_sysCfg.Excel2TplusHistorySql);
                }
                catch { }
            }
            catch
            {
                MessageBox.Show("数据库无法连接");
            }
            finally
            {
                sh.Close();
            }
        }
Пример #32
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "ChuckProtoParser", Version = "v1"
                });
            });

            services.AddDbContextFactory <DeviceControllerContext>(options =>
                                                                   options.UseMySql(DbConfig.ToString(), ServerVersion.AutoDetect(DbConfig.ToString())), ServiceLifetime.Singleton);
            services.AddDbContext <DeviceControllerContext>(options =>
                                                            //options.UseMySQL(DbConfig.ToString()));
                                                            options.UseMySql(DbConfig.ToString(), ServerVersion.AutoDetect(DbConfig.ToString())), ServiceLifetime.Scoped);
            services.AddScoped(typeof(IAsyncRepository <>), typeof(EfCoreRepository <,>));

            var options = new ConfigurationOptions
            {
                EndPoints =
                {
                    { $"{Config.Redis.Host}:{Config.Redis.Port}" }
                },
                Password = Config.Redis.Password,
            };

            services.AddSingleton <IConnectionMultiplexer>(ConnectionMultiplexer.Connect(options));
        }
Пример #33
0
        private static void InsertData()
        {
            using (var context = new DbConfig())
            {
                if (context.Database.EnsureCreated())
                {
                    context.RoleUsers.Add(new RoleUsers
                    {
                        NameRole = "Chef de projet"
                    });

                    context.RoleUsers.Add(new RoleUsers
                    {
                        NameRole = "Responsable de projet"
                    });

                    context.TypeExigences.Add(new TypeExigence
                    {
                        NameExigence = "Données"
                    });

                    context.TypeExigences.Add(new TypeExigence
                    {
                        NameExigence = "Performances"
                    });

                    context.TypeExigences.Add(new TypeExigence
                    {
                        NameExigence = "Interface utilisateurs"
                    });

                    context.TypeExigences.Add(new TypeExigence
                    {
                        NameExigence = "Qualités"
                    });

                    context.TypeExigences.Add(new TypeExigence
                    {
                        NameExigence = "Services"
                    });


                    context.User.Add(new User
                    {
                        Trigramme  = "TSp",
                        Firstname  = "Tristan",
                        Lastname   = "Spinnewyn",
                        Email      = "*****@*****.**",
                        RoleUserId = 1,
                        Password   = new PasswordHasher <object?>().HashPassword(null, "admin")
                    });
                    context.User.Add(new User
                    {
                        Trigramme  = "TS2",
                        Firstname  = "Tristan",
                        Lastname   = "Spinnewyn",
                        Email      = "*****@*****.**",
                        RoleUserId = 2,
                        Password   = new PasswordHasher <object?>().HashPassword(null, "admin")
                    });

                    context.User.Add(new User
                    {
                        Trigramme  = "TS3",
                        Firstname  = "Tristan",
                        Lastname   = "Spinnewyn",
                        Email      = "*****@*****.**",
                        RoleUserId = 2,
                        Password   = new PasswordHasher <object?>().HashPassword(null, "admin")
                    });

                    context.SaveChanges();
                }
            }
        }
 public ActionResult Add(tb_mqpath_partition_model model)
 {
     try
     {
         using (DbConn conn = DbConfig.CreateConn(DataConfig.MqManage))
         {
             try
             {
                 conn.Open();
                 conn.BeginTransaction();
                 model.state          = (byte)XXF.BaseService.MessageQuque.BusinessMQ.SystemRuntime.EnumMqPathPartitionState.Running;
                 model.partitionindex = new tb_mqpath_partition_dal().GetMaxPartitionIndexOfMqPath(conn, model.mqpathid) + 1;
                 if (new tb_mqpath_dal().Get(conn, model.mqpathid) == null)
                 {
                     throw new Exception("无法找到队列");
                 }
                 if (new tb_mqpath_partition_dal().GetByPartitionId(conn, model.partitionid) != null)
                 {
                     throw new Exception("分区已被使用");
                 }
                 if (new tb_mqpath_partition_dal().CheckMaxPartitionIndexOfMqPathIsRunning(conn, model.mqpathid) == false)
                 {
                     throw new Exception("最后的分区未处于正常使用状态,若分区正在待删状态,请删除完毕后新增分区。");
                 }
                 if (new tb_mqpath_partition_dal().Add2(conn, model))
                 {
                     new tb_partition_dal().UpdateIsUsed(conn, 1, model.partitionid);
                     var partitioninfo = XXF.BaseService.MessageQuque.BusinessMQ.SystemRuntime.PartitionRuleHelper.GetPartitionIDInfo(model.partitionid);
                     //创建3天的表
                     var serverdate = conn.GetServerDate().Date;
                     for (int i = 0; i < 3; i++)
                     {
                         var currentdate = serverdate.AddDays(i);
                         var tablename   = XXF.BaseService.MessageQuque.BusinessMQ.SystemRuntime.PartitionRuleHelper.GetTableName(partitioninfo.TablePartition, currentdate);//
                         SqlHelper.ExcuteSql(DataConfig.DataNodeParConn(partitioninfo.DataNodePartition + ""), (c) =>
                         {
                             bool exsit = c.TableIsExist(tablename);
                             if (exsit != true)
                             {
                                 string cmd = DataConfig.MQCreateTableSql.Replace("{tablepartiton}", XXF.BaseService.MessageQuque.BusinessMQ.SystemRuntime.PartitionRuleHelper.PartitionNameRule(partitioninfo.TablePartition))
                                              .Replace("{daypartition}", currentdate.ToString("yyMMdd")).Replace("{datanodepartiton}", XXF.BaseService.MessageQuque.BusinessMQ.SystemRuntime.PartitionRuleHelper.PartitionNameRule(partitioninfo.DataNodePartition));
                                 c.ExecuteSql(cmd, new List <XXF.Db.ProcedureParameter>());
                             }
                         });
                     }
                     conn.Commit();
                 }
                 else
                 {
                     throw new Exception("更新错误");
                 }
             }
             catch (Exception exp)
             {
                 conn.Rollback();
                 throw exp;
             }
         }
         ReStartQuque(model.mqpathid);
         return(RedirectToAction("index"));
     }
     catch (Exception e)
     {
         ModelState.AddModelError("Error", e.Message);
         return(View(model));
     }
 }
Пример #35
0
		static DbConfigHelper()
		{
			ReflecionStore = new DbConfig();
		}
Пример #36
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var dbCache = new DbConfig(true);

            services.AddTransient <DbService>(provider => new DbService(Configuration, dbCache));
            var ffpmegPath = Configuration["ffpmegPath"];

            services.AddMediaToolkit(ffpmegPath);

            services.AddSingleton <MediaService>();
            services.AddSingleton <TitleEnumerationService>();
            services.AddSingleton <DbInitService>();
            services.AddSingleton <ThumbnailService>();
            services.AddSingleton <BufferedFileStreamResultExecutor>();
            services.AddSingleton <SetupHubAccess>();

            services.AddScoped <IUserStore <AppUser>, AppUserStore>();
            services.AddScoped <IRoleStore <AppRole>, AppRoleStore>();

            services.Configure <TokenSettings>(Configuration.GetSection("TokenSettings"));
            //services.AddSingleton<UserManager<AppUser>, AppUserManager>();
            //services.AddSingleton<RoleManager<AppRole>, AppRoleManager>();


            services.AddIdentity <AppUser, AppRole>()
            .AddUserStore <AppUserStore>()
            .AddUserManager <AppUserManager>()
            .AddRoleManager <AppRoleManager>()
            .AddSignInManager <AppUserSignInManager>()
            .AddDefaultTokenProviders();
            services.AddControllersWithViews();
            services.AddRazorPages();
            services.AddCors();
            services.AddSignalR();

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            //IdentityModelEventSource.ShowPII = true;
            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents();
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = Configuration.GetSection("TokenSettings").GetValue <string>("Issuer"),
                    ValidateIssuer   = false,
                    ValidAudience    = Configuration.GetSection("TokenSettings").GetValue <string>("Audience"),
                    ValidateAudience = false,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(Configuration.GetSection("TokenSettings").GetValue <string>("Key"))),
                    ValidateIssuerSigningKey = false,
                    ValidateLifetime         = false,
                };
            });

            InitServices = services.Where(e =>
                                          typeof(IRequireInit).IsAssignableFrom(e.ImplementationType) &&
                                          e.Lifetime == ServiceLifetime.Singleton)
                           .Select(f => f.ServiceType).ToArray();
            InitAsyncServices = services.Where(e =>
                                               typeof(IRequireInitAsync).IsAssignableFrom(e.ImplementationType) &&
                                               e.Lifetime == ServiceLifetime.Singleton)
                                .Select(f => f.ServiceType).ToArray();
        }
Пример #37
0
 public ListaZadanRepozytorium(IConfiguration csg)
 {
     db = new DbConfig();
     csg.GetSection("DB").Bind(db);
 }
Пример #38
0
 /// <summary>
 ///     Maps all propertys of typeof(T) into the Database columns
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 internal static IEnumerable <string> FilterDbSchemaMapping <T>(DbConfig config, params string[] ignore)
 {
     return(FilterDbSchemaMapping(config.GetOrCreateClassInfoCache(typeof(T)), ignore));
 }
Пример #39
0
        public object Post(SignupUserRequest req)
        {
            req.AdditionalData = "";
            req.Username       = req.Username.ToLower();

            // assert password is safe enough
            if (!req.Password.IsSafeAsPassword())
            {
                throw new ValidationException()
                      {
                          ErrorMessage = "Password is unsafe"
                      }
            }
            ;

            // assert username is not already taken
            using (var db = DbConfig.GetConnection()) {
                var user = db.FirstOrDefault <DBUser> (u => u.Username == req.Username);
                if (user != null)
                {
                    throw new ConflictException()
                          {
                              ErrorMessage = "A user by that name already exists"
                          }
                }
                ;
            }

            // assert email is not already registered
            using (var db = DbConfig.GetConnection()) {
                var user = db.FirstOrDefault <DBUser> (u => u.EmailAddress == req.EmailAddress);
                if (user != null)
                {
                    throw new ConflictException()
                          {
                              ErrorMessage = "The emailaddress is already registered"
                          }
                }
                ;
            }

            // assert all required fields are filled

            var db_user = new DBUser();

            db_user.PopulateWith(req);

            db_user.IsActivated = false;
            db_user.IsVerified  = false;

            db_user.VerifySecret = Guid.NewGuid().ToString().Replace("-", "");

            // write user to db
            using (var db = DbConfig.GetConnection()) {
                db.Insert <DBUser> (db_user);
            }

            return(new HttpResult()
            {
                StatusCode = HttpStatusCode.OK
            });
        }
Пример #40
0
 public static void SetFrame(string frameId, DbConfig.Frame frame)
 {
     HttpContext.Current.Session[frameId] = frame;
 }
 public void Setup()
 {
     _config = new DbConfig();
     _dbConfigurationBuilder = new DbConfigurationBuilder(_config);
 }
Пример #42
0
 /// <summary>
 /// 获取默认数据库类型
 /// </summary>
 /// <returns></returns>
 public static String getDatabaseType()
 {
     return(DbConfig.GetDatabaseType());
 }
Пример #43
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="DbAccessLayer" /> class.
        /// </summary>
        /// <param name="fullTypeNameToIDatabaseStrategy">The full type name to database strategy.</param>
        /// <param name="connection">The connection.</param>
        /// <param name="config">The configuration.</param>
        /// <exception cref="System.ArgumentNullException">fullTypeNameToIDatabaseStrategy</exception>
        public DbAccessLayer(string fullTypeNameToIDatabaseStrategy, string connection, DbConfig config = null)
            : this(config)
        {
            if (string.IsNullOrEmpty(fullTypeNameToIDatabaseStrategy))
            {
                throw new ArgumentNullException(nameof(fullTypeNameToIDatabaseStrategy));
            }

            ResolveDbType(fullTypeNameToIDatabaseStrategy);

            var database = GenerateStrategyFromExternal(fullTypeNameToIDatabaseStrategy, connection);

            Database = new DefaultDatabaseAccess(new InstanceConnectionController());
            Database.Attach(database);
            DatabaseStrategy = database;
        }
Пример #44
0
 public MySqlProxyDbContext(DbConfig dbconfig) : base(dbconfig)
 {
 }
Пример #45
0
 public ActionResult Update(HttpPostedFileBase TaskDll, tb_task_model model, string tempdatajson)
 {
     return(this.Visit(Core.EnumUserRole.Admin, () =>
     {
         try
         {
             tb_task_dal dal = new tb_task_dal();
             tb_version_dal dalversion = new tb_version_dal();
             tb_tempdata_dal tempdatadal = new tb_tempdata_dal();
             byte[] dllbyte = null;
             string filename = "";
             int change = model.taskversion;
             if (change == -1)
             {
                 if (TaskDll == null)
                 {
                     throw new Exception("没有文件!");
                 }
                 filename = TaskDll.FileName;
                 Stream dll = TaskDll.InputStream;
                 dllbyte = new byte[dll.Length];
                 dll.Read(dllbyte, 0, Convert.ToInt32(dll.Length));
                 //model.taskcreateuserid = Common.GetUserId(this);
             }
             using (DbConn PubConn = DbConfig.CreateConn(Config.TaskConnectString))
             {
                 PubConn.Open();
                 var task = dal.GetOneTask(PubConn, model.id);
                 if (task.taskstate == (int)Dyd.BaseService.TaskManager.Core.EnumTaskState.Running)
                 {
                     throw new Exception("当前任务在运行中,请停止后提交");
                 }
                 if (change == -1)
                 {
                     model.taskversion = dalversion.GetVersion(PubConn, model.id) + 1;
                 }
                 model.taskupdatetime = DateTime.Now;
                 dal.UpdateTask(PubConn, model);
                 if (change == -1)
                 {
                     dalversion.Add(PubConn, new tb_version_model()
                     {
                         taskid = model.id,
                         version = model.taskversion,
                         versioncreatetime = DateTime.Now,
                         zipfile = dllbyte,
                         zipfilename = System.IO.Path.GetFileName(filename)
                     });
                 }
                 tempdatadal.UpdateByTaskID(PubConn, new tb_tempdata_model()
                 {
                     taskid = model.id,
                     tempdatajson = tempdatajson,
                     tempdatalastupdatetime = DateTime.Now
                 });
                 return RedirectToAction("index");
             }
         }
         catch (Exception exp)
         {
             ModelState.AddModelError("", exp.Message);
             return View();
         }
     }));
 }
Пример #46
0
        private void Init(
            object assertNotDatabaseMember,
            bool useAssertion,
            DbConfig config,
            string property = null)
        {
            var plainType = typeof(T);

            _typeInfo = config.GetOrCreateClassInfoCache(plainType);
            if (_typeInfo.PrimaryKeyProperty == null && string.IsNullOrEmpty(property))
            {
                throw new NotSupportedException(string.Format("The type '{0}' does not define any PrimaryKey", plainType.Name));
            }

            if (string.IsNullOrEmpty(property))
            {
                property = _typeInfo.PrimaryKeyProperty.PropertyName;
            }

            ReturnTarget = Expression.Label(typeof(bool));
            var returnTrue = Expression.Return(ReturnTarget, Expression.Constant(true));

            Left  = Expression.Parameter(plainType);
            Right = Expression.Parameter(plainType);

            //left or right property null
            PropLeft = Expression.Property(Left, property);
            var propRight = Expression.Property(Right, property);
            ConditionalExpression resAssertionBlock = null;

            if (useAssertion)
            {
                Expression assertionObject = Expression.Constant(assertNotDatabaseMember);
                if (_typeInfo.PrimaryKeyProperty.PropertyType != assertNotDatabaseMember.GetType())
                {
                    if (DefaultRewrite)
                    {
                        Visit(ref PropLeft, ref assertionObject);
                    }
                    else
                    {
                        throw new NotSupportedException(string.Format("Unknown Type cast detected." +
                                                                      " Assert typ is '{0}' property is '{1}' " +
                                                                      "... sry i am good but not as this good! Try the PocoPkComparer.DefaultRewrite option",
                                                                      assertNotDatabaseMember.GetType().Name, _typeInfo.PrimaryKeyProperty.PropertyType.Name));
                    }
                }

                var eqLeftPropEqualsAssertion      = Expression.Equal(PropLeft, assertionObject);
                var eqRightPropEqualsAssertion     = Expression.Equal(propRight, assertionObject);
                var resLeftAndRightEqualsAssertion = Expression.And(eqLeftPropEqualsAssertion, eqRightPropEqualsAssertion);
                resAssertionBlock = Expression.IfThen(resLeftAndRightEqualsAssertion, returnTrue);
            }

            //equal
            var eqPropertyEqual = Expression.Equal(PropLeft, propRight);

            if (resAssertionBlock != null)
            {
                _assertionBlock = Wrap(resAssertionBlock);
            }
            _propEqual = Wrap(Expression.IfThen(eqPropertyEqual, returnTrue));

            if (typeof(IComparable).IsAssignableFrom(typeof(T)))
            {
                var directComparsion = Expression.Call(Left, "CompareTo", null, Right);
                _compareTo = Expression.Lambda <Func <T, T, int> >(directComparsion, Left, Right).Compile();
            }

            var returnhasCode = Expression.Label(typeof(int));

            var hashCode = Expression.Call(Left, "GetHashCode", null);

            _getHashCodeOfProp = Expression.Lambda <Func <T, int> >(Expression.Block(
                                                                        hashCode,
                                                                        Expression.Label(returnhasCode, Expression.Constant(-1))
                                                                        ), Left).Compile();
        }
Пример #47
0
        public override void Run()
        {
            List <tb_datanode_model>  nodeList = new List <tb_datanode_model>();
            List <tb_partition_model> list     = new List <tb_partition_model>();

            using (DbConn conn = DbConfig.CreateConn(this.AppConfig["BusinessMQManageConnectString"]))
            {
                conn.Open();
                nodeList = dataNodeDal.List(conn);
                list     = partitionDal.GetAllCanUsePartitionList(conn);
            }

            foreach (var item in nodeList)
            {
                string dataNode = PartitionRuleHelper.GetDataNodeName(item.datanodepartition);
                string nodeConn = string.Format("server={0};Initial Catalog={1};User ID={2};Password={3};", item.serverip, dataNode, item.username, item.password);

                try
                {
                    using (DbConn dataNodeConn = DbConfig.CreateConn(nodeConn))
                    {
                        dataNodeConn.Open();
                        foreach (var value in list)
                        {
                            PartitionIDInfo      info      = PartitionRuleHelper.GetPartitionIDInfo(value.partitionid);
                            string               partition = PartitionRuleHelper.PartitionNameRule(info.TablePartition);
                            ICollection <string> tableList = msgDal.GetTableNameListByPartition(dataNodeConn, partition);
                            if (tableList != null && tableList.Count > 0)
                            {
                                using (DbConn conn = DbConfig.CreateConn(this.AppConfig["BusinessMQManageConnectString"]))
                                {
                                    foreach (var table in tableList)
                                    {
                                        if (!dataNodeConn.TableIsExist(table))
                                        {
                                            continue;
                                        }
                                        long maxId = msgDal.GetMaxID(dataNodeConn, table);
                                        long minId = msgDal.GetMinID(dataNodeConn, table);
                                        tb_partition_messagequeue_report_model model = new tb_partition_messagequeue_report_model();
                                        model.partitionid = value.partitionid;
                                        if (maxId > 0 && minId > 0)
                                        {
                                            MQIDInfo mqInfo = PartitionRuleHelper.GetMQIDInfo(maxId);
                                            model.day            = mqInfo.Day;
                                            model.lastupdatetime = DateTime.Now;
                                            model.createtime     = DateTime.Now;
                                            model.mqmaxid        = maxId;
                                            model.mqminid        = minId;
                                            reportDal.AddReport(conn, model);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    base.OpenOperator.Error("节点不存在", ex);
                    continue;
                }
            }
        }
Пример #48
0
 /// <summary>
 ///     New Instance of the Auto Equality Comparer with no assertion on its default value for an Primary key
 /// </summary>
 public PocoPkComparer(DbConfig config)
     : this(DefaultAssertionObject, config, DefaultAssertionObject != null)
 {
 }
Пример #49
0
		public void FakeClassFunction()
		{
			var cache = new DbConfig(true);
			Assert.That(() =>
			{
				var fakeType = cache.GetFake("FakeType");

				fakeType.Mehtods.Add(new FakeMethodInfoCache((e, g) =>
				{
					return g[0] + (string) g[1];
				}, "TestMethod"));

				Assert.That(fakeType.Propertys, Is.Empty);
				Assert.That(fakeType.Mehtods.Count, Is.EqualTo(7));
				Assert.That(fakeType.Attributes, Is.Empty);

				var refElement = fakeType.DefaultFactory();

				Assert.That(refElement, Is.Not.Null.And.TypeOf(fakeType.Type));

				FakeMethodInfoCache propTest = (FakeMethodInfoCache)fakeType.Mehtods.FirstOrDefault(s => s.MethodName == "TestMethod");
				Assert.That(propTest, Is.Not.Null);
				var invoke = propTest.Invoke(refElement, "This is ", "an Test");
				Assert.That(invoke, Is.Not.Null.And.EqualTo("This is an Test"));
			}, Throws.Nothing);
		}
Пример #50
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="PocoPkComparer{T}" /> class.
 /// </summary>
 /// <param name="assertNotDatabaseMember">The assert not database member.</param>
 /// <param name="config">The configuration.</param>
 public PocoPkComparer(int assertNotDatabaseMember, DbConfig config)
     : this(assertNotDatabaseMember, config, true)
 {
 }
Пример #51
0
		public void ClassCreatingWithArguments()
		{
			var cache = new DbConfig(true);
			cache.Include<ClassCreatingWithArguments>();
			Assert.That(() => cache.SClassInfoCaches.First().DefaultFactory(), Throws.Exception);
		}
Пример #52
0
 private string CreateFieldValue(Field field)
 {
     return(field.IsParameterized ? DbConfig?.WithParameters(field.Value) : field.Value);
 }
Пример #53
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(AuthTest.JwtAuthentication.SetCookieSchemes)
            .AddCookie(AuthTest.JwtAuthentication.SetupCookie)
            // .AddJwtBearer(AuthTest.JwtAuthentication.SetupBearer)
            ;

            /*
             * services.AddAntiforgery(
             *  delegate (Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions options)
             *  {
             *       // https://damienbod.com/2017/05/09/anti-forgery-validation-with-asp-net-core-mvc-and-angular/
             *       options.HeaderName = "X-XSRF-TOKEN";
             *       //options.CookieDomain = "localhost";
             *       options.Cookie.Name = "XSRF";
             *  }
             * );
             */
            // services.AddMvc();

            // https://geeks.ms/clanderas/2016/10/18/asp-net-core-node-services-to-execute-your-nodejs-scripts/
            // https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp-net-core-with-javascriptservices/
            services.AddNodeServices(options => {
                // options.DebuggingPort
            });

            services.AddRouting(delegate(Microsoft.AspNetCore.Routing.RouteOptions options)
                                { });


            services.AddMvc(

                /*
                 * delegate (Microsoft.AspNetCore.Mvc.MvcOptions config)
                 * {
                 *  Microsoft.AspNetCore.Authorization.AuthorizationPolicy policy =
                 *      new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder()
                 *                   .RequireAuthenticatedUser()
                 *                   // .AddRequirements( new NoBannedIPsRequirement(new HashSet<string>() { "127.0.0.1", "0.0.0.1" } ))
                 *                   .Build();
                 *
                 *  config.Filters.Add(new Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter(policy));
                 * }
                 */
                )
            .AddJsonOptions(options =>
            {
#if DEBUG
                options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
#else
                options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None;
#endif
            });


            services.Configure <Microsoft.AspNetCore.Mvc.Razor.RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new CoreCMS.Routing.SubdomainViewLocationExpander());
            });



            Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions
            .Configure <ConfigData.SmtpConfig>(services, Configuration.GetSection("Smtp"));


            /*
             * Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions
             *  .Configure<Dictionary<string, ConfigData.cConnectionString>>(services
             *  , Configuration.GetSection("ConnectionStrings")
             * );
             *
             * Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions
             *  .Configure<ConfigData.cConnectionStrings>(services
             *      , Configuration.GetSection("DataBase"));
             *
             * string foo = Configuration.GetValue<string>("data:userID");
             * System.Console.WriteLine(foo);
             * // https://msdn.microsoft.com/en-us/magazine/mt632279.aspx
             */

            ConfigData.Databases dbs = Configuration.Get <ConfigData.Databases>();

            // System.Console.WriteLine(cs);
            // services.AddSingleton<ConfigData.Database>(cs);

            DbConfig dbConfig = null;

            if (dbs.ConnectionStrings.ContainsKey(System.Environment.MachineName))
            {
                dbConfig = dbs.ConnectionStrings[System.Environment.MachineName];
            }


            if (dbConfig == null)
            {
                if (dbs.ConnectionStrings.ContainsKey("server"))
                {
                    dbConfig = dbs.ConnectionStrings["server"];
                }
            }


            if (dbConfig == null)
            {
                throw new System.IO.InvalidDataException("Connection string not configured...");
            }


            CoreDb.DalConfig dalConfig =
                new CoreDb.DalConfig(dbConfig.ProviderName, dbConfig.ConnectionString);

            CoreDb.ReadDAL  readData  = new CoreDb.ReadDAL(dalConfig);
            CoreDb.WriteDAL writeData = new CoreDb.WriteDAL(dalConfig);

            services.AddSingleton <CoreDb.ReadDAL>(readData);
            services.AddSingleton <CoreDb.WriteDAL>(writeData);
        }
Пример #54
0
        private static string GetDisplayFields()
        {
            List <string> displayFields = new List <string>();

            ScrudHelper.AddDisplayField(displayFields, "core.account_masters.account_master_id", DbConfig.GetDbParameter(AppUsers.GetCurrentUserDB(), "AccountMasterDisplayField"));
            ScrudHelper.AddDisplayField(displayFields, "core.accounts.account_id", DbConfig.GetDbParameter(AppUsers.GetCurrentUserDB(), "AccountDisplayField"));
            ScrudHelper.AddDisplayField(displayFields, "core.currencies.currency_code", DbConfig.GetDbParameter(AppUsers.GetCurrentUserDB(), "CurrencyDisplayField"));
            return(string.Join(",", displayFields));
        }
 public TypeExigenceController(ILogger <TypeExigenceController> logger, DbConfig context) : base(logger, context)
 {
     TypeExigenceRepository = new TypeExigenceRepository(_context);
 }
Пример #56
0
 /// <summary>
 ///     Returns all Propertys that can be loaded due reflection
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 public static string CreatePropertyCsv <T>(DbConfig config, bool ignorePk = false)
 {
     return(CreatePropertyCsv(config.GetOrCreateClassInfoCache(typeof(T)), ignorePk));
 }
Пример #57
0
Файл: Db.cs Проект: jhgbrt/yadal
 /// <summary>
 /// Instantiate Db with existing connection. The connection is only used for creating commands; 
 /// it should be disposed by the caller when done.
 /// </summary>
 /// <param name="connection">The existing connection</param>
 /// <param name="config"></param>
 public Db(IDbConnection connection, DbConfig config)
 {
     _externalConnection = connection;
     Config = config ?? DbConfig.Default;
 }
Пример #58
0
        private void RegisterJavascript()
        {
            string script = JSUtility.GetVar("culture", CultureManager.GetCurrent().Name);

            script += JSUtility.GetVar("language", CultureManager.GetCurrent().TwoLetterISOLanguageName);

            script += JSUtility.GetVar("jqueryUIi18nPath", this.Page.ResolveUrl("~/Scripts/jquery-ui/i18n/"));

            script += JSUtility.GetVar("today", string.Format(CultureManager.GetCurrent(), CultureManager.GetCurrent().DateTimeFormat.ShortDatePattern, DateTime.Now));
            script += JSUtility.GetVar("now", DateTime.Now.ToString(CultureManager.GetCurrent()));
            script += JSUtility.GetVar("date", DateTime.Now.ToString(CultureInfo.InvariantCulture));

            script += JSUtility.GetVar("reportTemplatePath", PageUtility.ResolveUrl(DbConfig.GetScrudParameter(AppUsers.GetCurrentUserDB(), "TemplatePath")));
            script += JSUtility.GetVar("reportExportTemplatePath", PageUtility.ResolveUrl(DbConfig.GetScrudParameter(AppUsers.GetCurrentUserDB(), "ExportTemplatePath")));
            script += JSUtility.GetVar("reportHeaderPath", PageUtility.ResolveUrl(DbConfig.GetScrudParameter(AppUsers.GetCurrentUserDB(), "HeaderPath")));

            script += JSUtility.GetVar("userId", AppUsers.GetCurrent().View.UserId);
            script += JSUtility.GetVar("user", AppUsers.GetCurrent().View.UserName);
            script += JSUtility.GetVar("officeCode", AppUsers.GetCurrent().View.OfficeCode);
            script += JSUtility.GetVar("office", AppUsers.GetCurrent().View.OfficeName);

            script += JSUtility.GetVar("applicationDates", JsonConvert.SerializeObject(DatePersister.GetFrequencyDates(AppUsers.GetCurrentUserDB(), AppUsers.GetCurrent().View.OfficeId.ToInt())), false);
            script += JSUtility.GetVar("metaView", JsonConvert.SerializeObject(AppUsers.GetCurrent().View), false);
            script += JSUtility.GetVar("overridePath", this.OverridePath);

            script += JSUtility.GetVar("shortDateFormat", CultureManager.GetShortDateFormat());
            script += JSUtility.GetVar("longDateFormat", CultureManager.GetLongDateFormat());

            script += JSUtility.GetVar("thousandSeparator", CultureManager.GetThousandSeparator());
            script += JSUtility.GetVar("decimalSeparator", CultureManager.GetDecimalSeparator());
            script += JSUtility.GetVar("currencyDecimalPlaces", CultureManager.GetCurrencyDecimalPlaces());
            script += JSUtility.GetVar("currencySymbol", CultureManager.GetCurrencySymbol());


            script += JSUtility.GetVar("today", DateTime.Now.ToShortDateString());

            script += JSUtility.GetVar("shortDateFormat", CultureManager.GetShortDateFormat());
            script += JSUtility.GetVar("thousandSeparator", CultureManager.GetThousandSeparator());
            script += JSUtility.GetVar("decimalSeparator", CultureManager.GetDecimalSeparator());
            script += JSUtility.GetVar("currencyDecimalPlaces", CultureManager.GetCurrencyDecimalPlaces());
            script += JSUtility.GetVar("baseCurrencyCode", AppUsers.GetCurrent().View.CurrencyCode);


            script += JSUtility.GetVar("catalog", AppUsers.GetCurrentUserDB());

            script += JSUtility.GetVar("update", this.Update());

            script += JSUtility.GetVar("firstStepsPending", this.Context.Session["FirstStepsPending"]);

            script += JSUtility.GetVar("datepickerFormat", jQueryUI.GetDatePickerFormat());
            script += JSUtility.GetVar("datepickerShowWeekNumber", jQueryUI.ShowWeekNumber());
            script += JSUtility.GetVar("datepickerWeekStartDay", jQueryUI.GetWeekStartDay());
            script += JSUtility.GetVar("datepickerNumberOfMonths", jQueryUI.GetNumberOfMonths());


            ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "MixERPMasterPage", script, true);
        }
Пример #59
0
 /// <summary>
 /// 获取数据库的ConnectionString
 /// </summary>
 /// <param name="db"></param>
 /// <returns></returns>
 public static String getConnectionString(String db)
 {
     return(DbConfig.GetConnectionString(db));
 }
Пример #60
0
 /// <summary>
 ///     Maps propertys to database of given type
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 internal static IEnumerable <string> CreatePropertyNames <T>(DbConfig config, bool ignorePk = false)
 {
     return(ignorePk ? FilterDbSchemaMapping <T>(config, typeof(T).GetPK(config)) : FilterDbSchemaMapping <T>(config));
 }