Beispiel #1
0
        public static IServiceCollection AddDapperDatabase(this IServiceCollection services)
        {
            services.AddSingleton <ISQLDataAccess, SQLDataAccess>();
            services.AddSingleton <IUserReadRepo, UserReadRepo>();

            SqlMapper.AddTypeHandler(new PostgreGuidTypeHandler());
            SqlMapper.RemoveTypeMap(typeof(Guid));
            SqlMapper.RemoveTypeMap(typeof(Guid?));

            return(services);
        }
Beispiel #2
0
        public FormRepository(IOptions <ConnectionStringsOptions> connectionStrings, IQueryGenerator queryGenerator)
            : base(connectionStrings.Value.Vendora)
        {
            _queryFactory = queryGenerator.GetFactory <Form>();

            _queryLanguage        = _queryFactory.GetColumnProperty(" = @", nameof(Form.Language));
            _queryName            = _queryFactory.GetColumnProperty(" = @", nameof(Form.Name));
            _queryOrderByCreation = $"ORDER BY {_queryFactory.GetColumn(nameof(Form.CreatedDate))}";

            SqlMapper.AddTypeHandler(typeof(FormMetadata), new JsonTypeHandler());
        }
Beispiel #3
0
        public void Map()
        {
            SqlMapper.SetTypeMap(typeof(T), new ColumnAttributeTypeMapper <T>());

            // For each of the custom type members, map it as a Json object:

            foreach (var memberAttribute in Settings.Members.Where(memberAttribute => !memberAttribute.Value.Type.IsBasicType()))
            {
                SqlMapper.AddTypeHandler(memberAttribute.Value.Type, new JsonObjectTypeHandler());
            }
        }
        public static void Register(ContainerBuilder builder)
        {
            SqlMapper.AddTypeHandler(new MySqlGuidTypeHandler());
            SqlMapper.RemoveTypeMap(typeof(Guid));
            SqlMapper.RemoveTypeMap(typeof(Guid?));

            builder.RegisterType <Processor>().As <IProcessor>().InstancePerRequest();
            builder.RegisterType <DomainNotificationHandler>().As <IDomainNotification>().InstancePerRequest();
            builder.AddCqrsAutoFac <CustomerCommandHandler>();
            builder.RegisterType <ArchContext>();
            builder.RegisterType <EventSourcingContext>().InstancePerRequest();
        }
        static DataSource()
        {
            SqlMapper.AddTypeHandler <JObject>(new JObjectHandler());

            FluentMapper.Initialize(config =>
            {
                config.AddMap(new TokenDbMap());
                config.ApplyToDommel();
            });

            DommelMapper.SetPropertyResolver(new DommelPropertyResolverForCustomTypes());
        }
Beispiel #6
0
        public async Task Test1()
        {
            new EFExampleBugDb()
            .alpha_beta_key
            .ToList();

            SqlMapper.AddTypeHandler(InstantHandler.Default);
            var conn = new NpgsqlConnection("Host=localhost;Database=CardOverflow;Username=postgres;");
            await conn.OpenAsync();

            var dateCounts = await conn.QueryAsync <object>("SELECT * FROM history WHERE created >= @yearishago", new { yearishago = SystemClock.Instance.GetCurrentInstant() });
        }
        /// <summary>Register specific Id&lt;T&gt;s for use in Dapper queries. Ensure each Id&lt;T&gt; is registered before attempting to use them in Dapper queries.</summary>
        /// <param name="idOfTTypes">One or many Id&lt;T&gt; types to be registered in Dapper</param>
        public static void RegisterTypeHandlerForIds(params Type[] idOfTTypes)
        {
            foreach (var propertyType in idOfTTypes)
            {
                var identifierKey           = propertyType.GenericTypeArguments[0];
                var typeForTypeHandlerForId = typeof(TypeHandlerForIdOf <>).MakeGenericType(identifierKey);

                var typeHandlerForPropertyType = (SqlMapper.ITypeHandler)Activator.CreateInstance(typeForTypeHandlerForId);

                SqlMapper.AddTypeHandler(propertyType, typeHandlerForPropertyType);
            }
        }
 public static void InstallDateTimeOffsetMapper()
 {
     // Assumes SqlMapper.ResetTypeHandlers() is never called.
     if (Interlocked.CompareExchange(ref DateTimeOffsetMapperInstalled, 1, 0) == 0)
     {
         // First remove the default type map between typeof(DateTimeOffset) => DbType.DateTimeOffset (not valid for MySQL)
         SqlMapper.RemoveTypeMap(typeof(DateTimeOffset));
         SqlMapper.RemoveTypeMap(typeof(DateTimeOffset?));
         // This handles nullable value types automatically e.g. DateTimeOffset?
         SqlMapper.AddTypeHandler(typeof(DateTimeOffset), new DateTimeOffsetTypeHandler());
     }
 }
Beispiel #9
0
        public void Add(Aluno aluno)
        {
            using (IDbConnection dbConnection = Connection)
            {
                SqlMapper.AddTypeHandler(new JsonObjectTypeHandler <Professor>());

                string sQuery = @"INSERT INTO Alunos ( nome,  sobrenome,  dataNascimento,  id_professor) 
                                              VALUES (@nome, @sobrenome, @dataNascimento, @id_professor)";
                dbConnection.Open();
                dbConnection.Execute(sQuery, aluno);
            }
        }
Beispiel #10
0
 public static void Init()
 {
     NpgsqlConnection.GlobalTypeMapper.UseJsonNet().UseNodaTime();
     DefaultTypeMap.MatchNamesWithUnderscores = true;
     SqlMapper.AddTypeHandler(new PassthroughTypeHandler <Instant>(NpgsqlDbType.TimestampTz));
     SqlMapper.AddTypeHandler(new JsonTypeHandler <JToken>());
     SqlMapper.AddTypeHandler(new JsonTypeHandler <JValue>());
     SqlMapper.AddTypeHandler(new JsonTypeHandler <JArray>());
     SqlMapper.AddTypeHandler(new JsonTypeHandler <JObject>());
     SqlMapper.AddTypeHandler(new JsonTypeHandler <JObject>());
     SqlMapper.AddTypeHandler(new STJsonTypeHandler());
 }
Beispiel #11
0
        private static void RegisterProviderSettingConverter()
        {
            var settingTypes = typeof(IProviderConfig).Assembly.ImplementationsOf <IProviderConfig>()
                               .Where(x => !x.ContainsGenericParameters);

            var providerSettingConverter = new ProviderSettingConverter();

            foreach (var embeddedType in settingTypes)
            {
                SqlMapper.AddTypeHandler(embeddedType, providerSettingConverter);
            }
        }
Beispiel #12
0
        public void Setup()
        {
            SqlMapper.AddTypeHandler <Guid>(new GuidTypeHandler());
            SqlMapper.AddTypeHandler(new NullableLongHandler());
            SqlMapper.AddTypeHandler(new NullableIntHandler());

            RegisterLicence();
            RemoveTestsFilesDbs();

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console()
                         .CreateLogger();

            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json")
                         .Build();

            EmrConnectionString   = GenerateConnection(config, "emrConnection", false);
            ConnectionString      = GenerateConnection(config, "dwapiConnection");
            MsSqlConnectionString = config.GetConnectionString("mssqlConnection");
            MySqlConnectionString = config.GetConnectionString("mysqlConnection");

            var connection = new SqliteConnection(ConnectionString);

            connection.Open();

            var services = new ServiceCollection();

            services.AddDbContext <SettingsContext>(x => x.UseSqlite(connection));

            services.AddTransient <IAppDatabaseManager, AppDatabaseManager>();
            services.AddTransient <IDatabaseManager, DatabaseManager>();

            services.AddTransient <IAppMetricRepository, AppMetricRepository>();
            services.AddTransient <ICentralRegistryRepository, CentralRegistryRepository>();
            services.AddTransient <IDatabaseProtocolRepository, DatabaseProtocolRepository>();
            services.AddTransient <IDocketRepository, DocketRepository>();
            services.AddTransient <IEmrSystemRepository, EmrSystemRepository>();
            services.AddTransient <IExtractRepository, ExtractRepository>();
            services.AddTransient <IRestProtocolRepository, RestProtocolRepository>();

            services.AddTransient <IEmrManagerService, EmrManagerService>();
            services.AddTransient <IExtractManagerService, ExtractManagerService>();
            services.AddTransient <IRegistryManagerService, RegistryManagerService>();

            services.AddTransient <IIntegrityCheckRepository, IntegrityCheckRepository>();

            services.AddMediatR(typeof(GetAppMetricHandler));

            ServiceProvider = services.BuildServiceProvider();
        }
Beispiel #13
0
 static Db()
 {
     SqlMapper.AddTypeHandler(InstantHandler.Default);
     SqlMapper.AddTypeHandler(LocalDateHandler.Default);
     SqlMapper.AddTypeHandler(LocalDateTimeHandler.Default);
     SqlMapper.AddTypeHandler(LocalTimeHandler.Default);
     SqlMapper.AddTypeHandler(OffsetDateTimeHandler.Default);
     SqlMapper.AddTypeHandler(NullableInstantHandler.Default);
     SqlMapper.AddTypeHandler(NullableLocalDateHandler.Default);
     SqlMapper.AddTypeHandler(NullableLocalDateTimeHandler.Default);
     SqlMapper.AddTypeHandler(NullableLocalTimeHandler.Default);
     SqlMapper.AddTypeHandler(NullableOffsetDateTimeHandler.Default);
 }
Beispiel #14
0
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            SimpleCRUD.SetDialect(SimpleCRUD.Dialect.SQLite);
            SqlMapper.AddTypeHandler(new GuidTypeHandler());
            SqlMapper.RemoveTypeMap(typeof(Guid));
            SqlMapper.RemoveTypeMap(typeof(Guid?));

            var db = new DataStorage();

            db.MigrateDatabase().Wait();
        }
        public SqliteEventRepository(string connectionString)
        {
            // In-memory:  = @"Data Source=:memory:"
            var builder = new SQLiteConnectionStringBuilder(connectionString)
            {
                BinaryGUID = false
            };

            _connectionString = builder.ConnectionString;

            // Then you add follow line at where you app beigns to run.
            SqlMapper.AddTypeHandler(new GuidAsCharHandler());
        }
Beispiel #16
0
        /// <summary>
        /// Configures and registers database-related services.
        /// </summary>
        private void ConfigureDatabaseServices(IServiceCollection services)
        {
            services.AddDbContext <AppDbContext>(opts => opts.UseNpgsql(Configuration.GetConnectionString("Database")));

            services.AddIdentity <AppUser, IdentityRole>()
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders();

            SqlMapper.AddTypeHandler(new FuzzyDate.FuzzyDateTypeHandler());
            SqlMapper.AddTypeHandler(new FuzzyDate.NullableFuzzyDateTypeHandler());
            SqlMapper.AddTypeHandler(new FuzzyRange.FuzzyRangeTypeHandler());
            SqlMapper.AddTypeHandler(new FuzzyRange.NullableFuzzyRangeTypeHandler());
        }
Beispiel #17
0
        public static void SelectRequest()
        {
            string sql = " Select p.id, p.first_name, p.last_name, t.telephone " +
                         "from people p left join(SELECT owner_id, string_agg(telephone, ',') as telephone FROM telephone" +
                         " GROUP BY owner_id) t on p.id = t.owner_id";

            using (NpgsqlConnection connection = new NpgsqlConnection(sqlconnect))
            {
                SqlMapper.ResetTypeHandlers();
                SqlMapper.AddTypeHandler(new TelephonesTypeHandler());
                employees = connection.Query <Employee>(sql).ToList();
            }
        }
Beispiel #18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Map sting[] and object properties in model to JSON column in database.
            SqlMapper.AddTypeHandler(typeof(string[]), new StringArrayJsonMapper());
            SqlMapper.AddTypeHandler(typeof(object), new ObjectJsonMapper());

            string ConnString = Configuration["ConnectionStrings:ProductCatalog"];

            services.AddTransient <IDbConnection>(_ => new SqlConnection(ConnString));

            // Add framework services.
            services.AddMvc();
        }
Beispiel #19
0
        /// <summary>
        /// STATIC CTOR
        /// </summary>
        static BaseDbRepository()
        {
            // set mappings source assemlby
            var assembly = Assembly.GetExecutingAssembly();

            DapperExtensions.DapperExtensions.SetMappingAssemblies(new List <Assembly> {
                assembly
            });
            // custom mapping
            //SqlMapper.AddTypeMap(typeof(EmitDateTime), DbType.DateTime);
            //SqlMapper.AddTypeMap(typeof(EmitDateTime), DbType.DateTime2);
            SqlMapper.AddTypeHandler(typeof(Instant), new InstantTimeHandler());
        }
Beispiel #20
0
        static Store()
        {
            SqlMapper.ResetTypeHandlers();

            // Databases that don't support DateTimeOffset natively will store these in string columns.
            SqlMapper.AddTypeHandler(new DateTimeOffsetHandler());

            // Required by Sqlite. Guids are stored as text (uniqueidentifier) and are converted back to Guid with this handler.
            SqlMapper.AddTypeHandler(new GuidHandler());

            // Databases that don't support TimeSpan natively will store these in int columns as ticks.
            SqlMapper.AddTypeHandler(new TimeSpanHandler());
        }
Beispiel #21
0
        public void ConfigureServices(IServiceCollection services)
        {
            SqlMapper.AddTypeHandler(new GuidTypeHandler());

            services.AddDbContext <ApiDbContext>(o =>
            {
                o.UseSqlite(ConnectionString);
            });

            services.AddMvc();

            services.AddSwaggerGen();
        }
Beispiel #22
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)
        {
            // DB Context
            services.AddDbContext <AuthDbContext>(options =>
                                                  options.UseNpgsql(
                                                      Configuration.GetConnectionString("AuthDb"),
                                                      o => o.UseNodaTime()
                                                      )
                                                  );

            // Identity
            services.AddScoped <CookieAuthenticationEventListener>();
            services.AddIdentity <AppUser, IdentityRole <Guid> >(config =>
            {
                config.SignIn.RequireConfirmedEmail = true;
            })
            .AddEntityFrameworkStores <AuthDbContext>()
            .AddDefaultTokenProviders();
            services
            .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie();
            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.Name = "asid";
                options.LoginPath   = "/login";
                options.EventsType  = typeof(CookieAuthenticationEventListener);
            });

            // Framework
            services.AddGrpc();
            services.AddControllersWithViews();
            services.AddRazorPages();

            // Email
            services.AddScoped <IEmailSender, SmtpEmailSender>();

            // Authentication
            services.AddScoped <SessionManager>();

            // Hangfire
            SqlMapper.AddTypeHandler(new NodaDateTimeHandler());
            services.AddHangfire(config =>
                                 config.UsePostgreSqlStorage(Configuration.GetConnectionString("HangfireDb")));

            // Miniprofiler
            services.AddMiniProfiler()
            .AddEntityFramework();

            // Reverse Proxy
            services.AddReverseProxy().LoadFromConfig(Configuration.GetSection("ReverseProxy"));
        }
Beispiel #23
0
        // This method gets called by the runtime. Use this method to add
        // services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            });

            SqlMapper.AddTypeHandler(new TimeSpanTypeHandler());
            SqlMapper.AddTypeHandler(new BearerTokenTypeHandler());

            services.AddSingleton <IConnectionFactory>(new ConnectionStringConnectionFactory(Configuration.GetConnectionString("Main")));

            services.AddSingleton <IDataService, DataService>();
        }
        public static IServiceCollection AddRepositories(this IServiceCollection services)
        {
            services.AddScoped <ISQLDataAccess, SQLDataAccess>();
            services.AddScoped <IUserReadRepo, UserReadRepo>();
            services.AddScoped <IUserAddRepo, UserAddRepo>();

            services.AddSingleton <IModelConverter, ModelConverter>();

            SqlMapper.AddTypeHandler(new PostgreGuidTypeHandler());
            SqlMapper.RemoveTypeMap(typeof(Guid));
            SqlMapper.RemoveTypeMap(typeof(Guid?));

            return(services);
        }
Beispiel #25
0
        static ORM()
        {
            LoadCheckConnString();

            //System.Data.SQLite.SQLiteLog.Enabled = true;
            //System.Data.SQLite.SQLiteLogEventHandler handler = new System.Data.SQLite.SQLiteLogEventHandler (delegate(object sender, System.Data.SQLite.LogEventArgs e) {
            //	LogWriter.WriteLog (string.Format ("SQLite Log Entry: {0} - {1} {2} {3}", e.Message, e.ErrorCode, e.Data, e.GetHashCode ()));
            //});

            //TODO: Change this to dynamically set the dialect
            DapperExtensions.DapperExtensions.SqlDialect = new DapperExtensions.Sql.SqliteDialect();

            SqlMapper.AddTypeHandler(new TimeStampTypeHandler());
        }
Beispiel #26
0
        static DapperRepository()
        {
            //var jsonObjectTypeHandler = new JsonObjectTypeHandler();
            SqlMapper.AddTypeHandler(new DapperCultureInfoTypeHandler());
            //used in tutor search query
            SqlMapper.AddTypeHandler(typeof(IEnumerable <string>), new JsonArrayTypeHandler());
            //SqlMapper.AddTypeHandler(typeof(FeedDto), new JsonObjectTypeHandler());


            //SqlMapper.AddTypeHandler(typeof(QuestionFeedDto), new JsonObjectTypeHandler());
            //SqlMapper.AddTypeHandler(typeof(DocumentFeedDto), new JsonObjectTypeHandler());

            //SqlMapper.AddTypeHandler(typeof(FeedDto), new JsonObjectTypeHandler());
        }
        static void Main(string[] args)
        {
            //添加处理对象
            SqlMapper.AddTypeHandler(new MyTypeHandler <Data>());
            var constring = Server = 127.0 .0 .1; Port = 5432; UserId = postgres; Password = postgres; Database = TestDB;;

            using (var con = new Npgsql.NpgsqlConnection(constring))
            {
                //注意json字段参数后要跟  ::json
                var results = con.Execute(insert into test(id, data) values(@ID, @Data::json), new Test {
                    ID = 10, Data = new Data {
                        IDs = 2, Age = 33, Name =, Sex = true
                    }
                });
Beispiel #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            SqlMapper.AddTypeHandler(new SqlGuidTypeHandler());
            services.AddDbContext <SampleAppContext>();
            services.AddTransient <UserService>();

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "App.API", Version = "v1"
                });
            });
        }
        // ConfigureContainer is where you can register things directly
        // with Autofac. This runs after ConfigureServices so the things
        // here will override registrations made in ConfigureServices.
        // Don't build the container; that gets done for you by the factory.
        public void ConfigureContainer(ContainerBuilder builder)
        {
            // builder.RegisterModule(new MyApplicationModule());

            builder.RegisterModule(new MediatrModule());
            builder.RegisterModule(new ValidationModule());
            builder.RegisterModule(new AutoMapperModule(Environment.IsDevelopment(), typeof(Startup).Assembly));
            builder.RegisterModule(new IndexingModule(Configuration));
            builder.RegisterType <BackgroundMessageDispatcher>().As <IDomainEventDispatcher>().InstancePerLifetimeScope();

            SqlMapper.AddTypeHandler(InstantHandler.Default);
            builder.Register(_ => new PostgresDatabase(Configuration.GetConnectionString("Postgres")))
            .AsImplementedInterfaces();
        }
Beispiel #30
0
        public static void Init()
        {
            SqlMapper.AddTypeHandler(new GuidTypeHandler());
            SqlMapper.RemoveTypeMap(typeof(Guid));
            SqlMapper.RemoveTypeMap(typeof(Guid?));

            SqlMapper.AddTypeHandler(new BoolTypeHandler());
            SqlMapper.RemoveTypeMap(typeof(bool));
            SqlMapper.RemoveTypeMap(typeof(bool?));

            SqlMapper.AddTypeHandler(new DateTimeOffsetTypeHandler());
            SqlMapper.RemoveTypeMap(typeof(DateTimeOffset));
            SqlMapper.RemoveTypeMap(typeof(DateTimeOffset?));
        }