Esempio n. 1
0
        static void Main(string[] args)
        {
            try
            {
                DapperConfiguration.Initialize();
                ConnectionProvider provider = new ConnectionProvider();
                UserAccountDapper  dapper   = new UserAccountDapper();

                // UserAccountBroker userDataBroker = new UserAccountBroker(provider);
                //UserAccount user = userDataBroker.GetUserAccount("florian", "pwd");
                UserAccount user = null;
                IEnumerable <UserAccount> accounts = dapper.GetAllContact(provider.GetConnection(), 1);

                user = dapper.GetUserAccount(provider.GetConnection(), "florian", "pwd");

                if (user != null)
                {
                    Console.WriteLine(user.Firstname);
                    Console.WriteLine(user.Lastname);
                }
                else
                {
                    Console.WriteLine("Not found");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
            }
            Console.Read();
        }
        public void Build(DapperConfiguration configuration)
        {
            object container;
            bool success = configuration.ContainerCustomisations.Settings().TryGetValue("ExistingContainer", out container);
            if (success == false) throw new NullReferenceException("ExistingContainer not found");

            var windsorContainer = (Castle.Windsor.WindsorContainer)container;
            var sessionContext = Component.For<IDapperSessionContext>()
                .ImplementedBy<DapperSessionContext>()
                .LifestylePerThread();

            windsorContainer.Register(Component.For(typeof(IRepository<>))
                .ImplementedBy(typeof(DapperRepository<>))
                .LifestylePerThread());

            foreach (var assembly in configuration.Assemblies)
            {
                windsorContainer.Register(
                    Classes.FromAssembly(assembly)
                    .BasedOn(typeof(DapperRepository<>))
                    .LifestylePerThread());
            }

            windsorContainer.Register(Component.For<IDapperSessionFactory>()
                .ImplementedBy<DapperSessionFactory>()
                .DependsOn(Dependency.OnValue<DapperConfiguration>(configuration)),
                sessionContext);
        }
Esempio n. 3
0
        public void Build(DapperConfiguration configuration)
        {
            object container;
            bool   success = configuration.ContainerCustomisations.Settings().TryGetValue("ExistingContainer", out container);

            if (success == false)
            {
                throw new NullReferenceException("ExistingContainer not found");
            }

            var windsorContainer = (Castle.Windsor.WindsorContainer)container;
            var sessionContext   = Component.For <IDapperSessionContext>()
                                   .ImplementedBy <DapperSessionContext>()
                                   .LifestylePerThread();

            windsorContainer.Register(Component.For(typeof(IRepository <>))
                                      .ImplementedBy(typeof(DapperRepository <>))
                                      .LifestylePerThread());

            foreach (var assembly in configuration.Assemblies)
            {
                windsorContainer.Register(
                    Classes.FromAssembly(assembly)
                    .BasedOn(typeof(DapperRepository <>))
                    .LifestylePerThread());
            }

            windsorContainer.Register(Component.For <IDapperSessionFactory>()
                                      .ImplementedBy <DapperSessionFactory>()
                                      .DependsOn(Dependency.OnValue <DapperConfiguration>(configuration)),
                                      sessionContext);
        }
Esempio n. 4
0
        public async Task <List <Slider> > GetAll()
        {
            using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                //A transactionscope must be disposed on the same thread that it was created
                try
                {
                    DapperConfiguration.OpenConnection(1);

                    var data = await DapperConfiguration.db.QueryAsync <Slider>("usp_spa_Slider",
                                                                                new { Id = GlobalVariables.IsTransParameter },
                                                                                commandType : System.Data.CommandType.StoredProcedure);

                    DapperConfiguration.CloseConnection();

                    scope.Complete();
                    return(data.ToList());
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                    return(null);
                }
            }
        }
Esempio n. 5
0
        public void RunBeforeAnyTests()
        {
            using (var mySqlConnection = new MySqlConnection("Server=localhost;Port=3306;uid=root;password=password!"))
            {
                mySqlConnection.Execute(string.Format("CREATE DATABASE IF NOT EXISTS `{0}`", DatabaseName));
            }

            Container = new Castle.Windsor.WindsorContainer();

            DapperConfiguration
            .Use()
            .UseClassMapper(typeof(AutoClassMapper <>))
            .UseContainer <ContainerForWindsor>(cfg => cfg.UseExisting(Container))
            .UseSqlDialect(new MySqlDialect())
            .WithDefaultConnectionStringNamed("__DefaultMySql")
            .FromAssembly("Dapper.Extensions.Linq.Test.Entities")
            .FromAssembly("Dapper.Extensions.Linq.Test.Maps")
            .Build();

            var connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["__DefaultMySql"].ConnectionString);
            var files      = new List <string>
            {
                ReadScriptFile("CreateAnimalTable"),
                ReadScriptFile("CreateFooTable"),
                ReadScriptFile("CreateMultikeyTable"),
                ReadScriptFile("CreatePersonTable"),
                ReadScriptFile("CreateCarTable"),
                ReadScriptFile("CreatePhoneTable")
            };

            foreach (var setupFile in files)
            {
                connection.Execute(setupFile);
            }
        }
Esempio n. 6
0
        public virtual T TCommitData <T>(List <T> list, string proc, char action, short instance = 1, string ignoreParas = "")
        {
            string    fields = string.Empty;
            DataTable table  = CreateDataTable(list, ignoreParas);
            var       para   = DataTableToSqlParameterArray(table, action, ref fields);

            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    try
                    {
                        DapperConfiguration.OpenConnection(instance);

                        var data = (T)DapperConfiguration.db.Query <T>(proc, para, commandType: System.Data.CommandType.StoredProcedure);

                        DapperConfiguration.CloseConnection();

                        scope.Complete();
                        return(data);
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                        return(default(T));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                return(default(T));
            }
        }
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // Application commands
            containerRegistry.Register <IApplicationCommands, ApplicationCommandsProxy>();
            // Flyout service
            containerRegistry.RegisterInstance <IFlyoutService>(Container.Resolve <FlyoutService>());

            // Localizer service
            // Localizer-Service
            LoggerFactory var = new LoggerFactory();

            containerRegistry.RegisterInstance(typeof(ILocalizerService), new LocalizerService("de-DE"));
            var envBuilder   = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            var envConfig    = envBuilder.Build();
            var dapperConfig = DapperConfiguration
                               .Use(GetAllConnectionStrings(envConfig), var)
                               .UseClassMapper(typeof(AutoClassMapper <>))
                               .UseSqlDialect(new MySqlDialect())
                               .WithDefaultConnectionStringNamed("DefaultConnectionString")
                               .FromAssemblies(GetEntityAssemblies())
                               .Build();

            containerRegistry.RegisterInstance(typeof(IDapperConfiguration), dapperConfig);

            containerRegistry.RegisterSingleton <IConnectionStringProvider, StaticConnectionStringProvider>();
            containerRegistry.RegisterSingleton <IDapperSessionFactory, DapperSessionFactory>();
            containerRegistry.Register <IDapperSessionContext, DapperSessionContext>();
            containerRegistry.Register <ISqlGenerator, SqlGeneratorImpl>();
            containerRegistry.Register <IDapperImplementor, DapperImplementor>();
            containerRegistry.Register(typeof(IRepository <>), typeof(DapperRepository <>));
        }
Esempio n. 8
0
        public static void AddData(this IServiceCollection services, IConfiguration configuration)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            IDapperConfiguration getConfiguration(ILoggerFactory loggerFactory) =>
            DapperConfiguration
            .Use(GetAllConnectionStrings(configuration), loggerFactory)
            .UseClassMapper(typeof(AutoClassMapper <>))
            .UseSqlDialect(new MySqlDialect())
            .WithDefaultConnectionStringNamed("DefaultConnectionString")
            .FromAssemblies(GetEntityAssemblies())
            .Build();

            services.AddSingleton(x => getConfiguration(x.GetRequiredService <ILoggerFactory>()));
            services.AddSingleton <IConnectionStringProvider, StaticConnectionStringProvider>();
            services.AddSingleton <IDapperSessionFactory, DapperSessionFactory>();
            services.AddScoped <IDapperSessionContext, DapperSessionContext>();
            services.AddScoped <ISqlGenerator, SqlGeneratorImpl>();
            services.AddScoped <IDapperImplementor, DapperImplementor>();
            services.AddScoped(typeof(IRepository <>), typeof(DapperRepository <>));
        }
Esempio n. 9
0
        public virtual async Task <IEnumerable <Q> > CommitData <T, Q>(T obj, string proc, byte instance = 1, string ignoreParas = "")
        {
            string fields = string.Empty;
            var    para   = GetPropertyObject <T>(obj, ignoreParas, ref fields);
            var    data   = default(IEnumerable <Q>);

            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        using (IDbConnection dapper = DapperConfiguration.Open(instance))
                        {
                            data = await dapper.QueryAsync <Q>(proc, para, commandType : System.Data.CommandType.StoredProcedure);

                            scope.Complete();
                            return(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                        return(data);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                return(data);
            }
        }
Esempio n. 10
0
        public override string ToString()
        {
            var mapper = DapperConfiguration.GetMapper <TEntity>();
            var query  = new QueryBuilder(mapper);

            return(query.Build(Expression));
        }
        protected void AndGivenAUnitOfWork()
        {
            // instance be application scope
            var config = DapperConfiguration
                         .Use()
                         .UseSqlDialect(new SqlServerDialect());

            var classMapper = new CustomEntityMap <MyEntity>();

            classMapper.SetIdentityGenerated(m => m.Id);

            var classMappers = new List <IClassMapper>
            {
                classMapper
            };

            classMappers.Each(m => config.Register(m));

            // only one supported for the time being
            var tranCommitPolicy = new CommitPolicyNoOp();

            this._unitOfWork = new UnitOfWorkLinq <MyEntity, int>(
                session => new RepositoryLinq <MyEntity, int>(session),
                new SessionFactory(_conString, config),
                tranCommitPolicy);
        }
Esempio n. 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            DapperConfiguration.Configure();

            IDatabaseConfig dbConfig = this.Configuration.GetSection("DatabaseConfig").Get <DatabaseConfiguration>();

            services.AddSingleton(dbConfig);


            services.AddControllersWithViews()
#if DEBUG
            .AddRazorRuntimeCompilation()
#endif
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            });

            if (dbConfig.InMemoryMode)
            {
                services.AddMemoryDatabaseModeServices();
            }
            else
            {
                services.AddMySqlDatabaseModeServices();
            }

            services.AddRealtimeServices();
            services.AddSignalR();
        }
Esempio n. 13
0
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            //register dapper configuration
            builder.Register(m =>
            {
                var classMappers = m.Resolve <IEnumerable <IClassMapper> >();

                // instance be application scope
                var config = DapperConfiguration
                             .Use()
                             .UseSqlDialect(new SqlServerDialect());

                classMappers.Each(n => config.Register(n));

                return(config.Build());
            })
            .As <IDapperConfiguration>()
            .SingleInstance()
            .AsImplementedInterfaces()
            .PreserveExistingDefaults();

            //regiser session factory
            builder.Register(m =>
            {
                var componentContext = m.Resolve <IComponentContext>();

                return(new SessionFactory(ConnectionString, componentContext.Resolve <IDapperConfiguration>()));
            })
            .AsSelf()
            .AsImplementedInterfaces();

            // guid key'ed entities
            builder.RegisterGeneric(typeof(RepositoryLinq <>))
            .AsSelf()
            .As(typeof(IRepositoryLinq <>))
            .As(typeof(IRepository <>))
            .As(typeof(ILinqReader <>))
            .Named("Default", typeof(IRepositoryLinq <>))
            .Named("Default", typeof(IRepository <>))
            .Named("Default", typeof(ILinqReader <>));

            // generic key
            builder.RegisterGeneric(typeof(RepositoryLinq <,>))
            .AsSelf()
            .As(typeof(IRepositoryLinq <,>))
            .As(typeof(ILinqReader <,>))
            .As(typeof(IRepository <,>))
            .Named("Default", typeof(IRepositoryLinq <,>))
            .Named("Default", typeof(IRepository <,>))
            .Named("Default", typeof(ILinqReader <,>));

            // use transactions
            builder.Register(m => new CommitPolicy())
            .AsSelf()
            .AsImplementedInterfaces()
            .SingleInstance();
        }
Esempio n. 14
0
        private object ExecuteInternal(Expression expression)
        {
            var mapper       = DapperConfiguration.GetMapper <TEntity>();
            var queryBuilder = new QueryBuilder(mapper);

            var sql = queryBuilder.Build(expression);

            return(this.Query(sql));
        }
Esempio n. 15
0
        protected virtual IClassMapper GetClassMapper(Type type, DapperConfiguration configuration)
        {
            IClassMapper map = configuration.GetMap(type);

            if (map == null)
            {
                throw new NullReferenceException(string.Format("Map was not found for {0}", type));
            }

            return(map);
        }
Esempio n. 16
0
        //TODO: multiple para output
        //public virtual async Task<Tuple<IEnumerable<T>, List<ReturnOuputModel>>> QueryData<T>(Dictionary<string, dynamic> obj, List<OutputModel> outputparams, string proc, byte instance = 1)
        //{
        //    string fields = string.Empty;
        //    bool isOutput = (outputparams != null && outputparams.Count > 0);

        //    var para = (obj == null ? null : (!isOutput ? GetPropertyObject(obj, ref fields) : GetPropertyObject(obj, outputparams, ref fields)));
        //    var data = default(IEnumerable<T>);
        //    var output = default(List<ReturnOuputModel>);
        //    try
        //    {
        //        using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        //        {

        //            try
        //            {
        //                using (IDbConnection dapper = DapperConfiguration.Open(instance))
        //                {
        //                    //DapperConfiguration.OpenConnection(instance);
        //                    if (para != null)
        //                    {
        //                        data = await dapper.QueryAsync<T>(proc, para, commandType: System.Data.CommandType.StoredProcedure);
        //                        if (isOutput)
        //                        {

        //                            foreach (var item in outputparams)
        //                            {
        //                                var opdata = new ReturnOuputModel();
        //                                opdata.TName = item.TName;
        //                                Type type = DbTypeToType[item.TValue];
        //                                opdata.TValue = para.Get<string>(item.TName);

        //                                output.Add()
        //                            }

        //                        }
        //                    }
        //                    else
        //                        data = await dapper.QueryAsync<T>(proc, commandType: System.Data.CommandType.StoredProcedure);

        //                    //DapperConfiguration.CloseConnection();
        //                    scope.Complete();
        //                    return data;
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                Logger.LogError(ex);
        //                return Tuple.Create(data, output);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Logger.LogError(ex);
        //        return Tuple.Create(data, output);
        //    }
        //}

        public virtual async Task <T> QueryData <T>(Dictionary <string, dynamic> obj, string proc, byte instance = 1, DataConfiguration.DapperQueryOption queryOption = DataConfiguration.DapperQueryOption.FirstOrDefault)
        {
            string fields = string.Empty;
            var    para   = GetPropertyObject(obj, ref fields);
            var    data   = default(T);

            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        using (IDbConnection dapper = DapperConfiguration.Open(instance))
                        {
                            switch (queryOption)
                            {
                            case DataConfiguration.DapperQueryOption.Single:
                                data = await dapper.QuerySingleAsync <T>(proc, para, commandType : System.Data.CommandType.StoredProcedure);

                                break;

                            case DataConfiguration.DapperQueryOption.SingleOrDefault:
                                data = await dapper.QuerySingleAsync <T>(proc, para, commandType : System.Data.CommandType.StoredProcedure);

                                break;

                            case DataConfiguration.DapperQueryOption.First:
                                data = await dapper.QueryFirstOrDefaultAsync <T>(proc, para, commandType : System.Data.CommandType.StoredProcedure);

                                break;

                            case DataConfiguration.DapperQueryOption.FirstOrDefault:
                                data = await dapper.QueryFirstOrDefaultAsync <T>(proc, para, commandType : System.Data.CommandType.StoredProcedure);

                                break;
                            }

                            scope.Complete();
                            return(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                        return(data);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                return(data);
            }
        }
Esempio n. 17
0
 private static void Init()
 {
     DapperConfiguration
     .Use()
     .UseClassMapper(typeof(AutoClassMapper <>))
     .UseContainer <ContainerForWindsor>(cfg => cfg.UseExisting(_container))
     .UseSqlDialect(new SqlServerDialect())
     .WithDefaultConnectionStringNamed("__DefaultSqlServer")
     .FromAssembly("ConsoleApp.Domains")
     .FromAssembly("ConsoleApp.Maps")
     .Build();
 }
Esempio n. 18
0
        public void RunBeforeAnyTests()
        {
            _container = new Castle.Windsor.WindsorContainer();

            DapperConfiguration
            .Use()
            .UseClassMapper(typeof(AutoClassMapper <>))
            .UseContainer <Dapper.Extensions.Linq.CastleWindsor.ContainerForWindsor>(c => c.UseExisting(_container))
            .UseSqlDialect(new SqlServerDialect())
            .WithDefaultConnectionStringNamed("__DefaultSqlServer")
            .Build();
        }
Esempio n. 19
0
        public void RunBeforeAnyTests()
        {
            Container = new Castle.Windsor.WindsorContainer();

            DapperConfiguration
            .Use()
            .UseClassMapper(typeof(AutoClassMapper <>))
            .UseContainer <ContainerForWindsor>(cfg => cfg.UseExisting(Container))
            .UseSqlDialect(new SQLiteDialect())
            .FromAssembly("Dapper.Extensions.Linq.Test.Entities")
            .Build();
        }
        public void CanOpenAndCloseSession()
        {
            var subject = new SessionFactory(ConnectionString, DapperConfiguration.Use());

            using (
                var session = subject.Create())
            {
                var tran = session.BeginTran();

                tran.Commit();
            }
        }
Esempio n. 21
0
        private static void AddDapper(this IServiceCollection services, string connectionString)
        {
            services.AddTransient(typeof(IRepository <>), typeof(DapperRepository <>));
            services.AddScoped <IUnitOfWork, DapperUnitOfWork>();
            services.AddTransient <IQueryService>(provider => {
                var dapperQueryService = new DapperQueryService(provider.GetRequiredService <IDbConnectionFactory>(), connectionString);
                return(dapperQueryService);
            });
            services.AddSingleton <IDbConnectionFactory, DapperDbConnectionFactory <SqlConnection> >();
            services.AddTransient <IDbConnection>(provider => { return(new SqlConnection(connectionString)); });

            DapperConfiguration.Initialize();
        }
Esempio n. 22
0
        public virtual async Task <IEnumerable <T> > QueryData <T>(Dictionary <string, dynamic> obj, string proc, byte instance = 1)
        {
            //Check data
            if (obj != null && obj.Count > 0 && obj.ContainsKey("AvailableData"))
            {
                proc += "_Available";
                obj.Remove("AvailableData");
            }

            string fields = string.Empty;
            var    para   = (obj == null? null: GetPropertyObject(obj, ref fields));
            var    data   = default(IEnumerable <T>);

            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        using (IDbConnection dapper = DapperConfiguration.Open(instance))
                        {
                            //DapperConfiguration.OpenConnection(instance);
                            if (para != null)
                            {
                                data = await dapper.QueryAsync <T>(proc, para, commandType : System.Data.CommandType.StoredProcedure);
                            }
                            else
                            {
                                data = await dapper.QueryAsync <T>(proc, commandType : System.Data.CommandType.StoredProcedure);
                            }

                            //DapperConfiguration.CloseConnection();
                            scope.Complete();
                            return(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                        return(data);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                return(data);
            }
        }
Esempio n. 23
0
        public virtual async Task <Tuple <IEnumerable <T>, int> > QueryDataOut <T>(Dictionary <string, dynamic> obj, string proc, string outParaName, byte instance = 1)
        {
            string fields   = string.Empty;
            var    para     = (obj == null ? null : GetPropertyObject(obj, outParaName, ref fields));
            var    data     = default(IEnumerable <T>);
            bool   isOutput = (outParaName != null && outParaName.Length > 0);
            int    outValue = 0;

            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        using (IDbConnection dapper = DapperConfiguration.Open(instance))
                        {
                            //DapperConfiguration.OpenConnection(instance);
                            if (para != null)
                            {
                                data = await dapper.QueryAsync <T>(proc, para, commandType : System.Data.CommandType.StoredProcedure);

                                if (isOutput)
                                {
                                    outValue = para.Get <int>(outParaName);
                                }
                            }
                            else
                            {
                                data = await dapper.QueryAsync <T>(proc, commandType : System.Data.CommandType.StoredProcedure);
                            }

                            //DapperConfiguration.CloseConnection();
                            scope.Complete();
                            return(Tuple.Create(data, outValue));
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                        return(Tuple.Create(data, outValue));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                return(Tuple.Create(data, outValue));
            }
        }
Esempio n. 24
0
        public void RunBeforeAnyTests()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["__DefaultSqlCe"].ConnectionString;

            string[] connectionParts = connectionString.Split(';');
            string   file            = connectionParts
                                       .ToDictionary(k => k.Split('=')[0], v => v.Split('=')[1])
                                       .Where(d => d.Key.Equals("Data Source", StringComparison.OrdinalIgnoreCase))
                                       .Select(k => k.Value).Single();

            if (File.Exists(file))
            {
                File.Delete(file);
            }

            using (SqlCeEngine ce = new SqlCeEngine(connectionString))
            {
                ce.CreateDatabase();
            }

            Container = new Castle.Windsor.WindsorContainer();

            DapperConfiguration
            .Use()
            .UseClassMapper(typeof(AutoClassMapper <>))
            .UseContainer <ContainerForWindsor>(cfg => cfg.UseExisting(Container))
            .UseSqlDialect(new SqlCeDialect())
            .WithDefaultConnectionStringNamed("__DefaultSqlCe")
            .FromAssembly("Dapper.Extensions.Linq.Test.Entities")
            .FromAssembly("Dapper.Extensions.Linq.Test.Maps")
            .Build();

            _connection = new SqlCeConnection(connectionString);
            var files = new List <string>
            {
                ReadScriptFile("CreateAnimalTable"),
                ReadScriptFile("CreateFooTable"),
                ReadScriptFile("CreateMultikeyTable"),
                ReadScriptFile("CreatePersonTable"),
                ReadScriptFile("CreateCarTable"),
                ReadScriptFile("CreatePhoneTable")
            };

            foreach (var setupFile in files)
            {
                _connection.Execute(setupFile);
            }
        }
Esempio n. 25
0
        public static void Register(HttpConfiguration config)
        {
            // Web-API-Konfiguration und -Dienste

            // Web-API-Routen
            DapperConfiguration.Map();
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
                new MediaTypeHeaderValue("text/html"));
        }
Esempio n. 26
0
        protected void AndGivenADapperConfiguration()
        {
            // instance be application scope
            _config = DapperConfiguration
                      .Use()
                      .UseSqlDialect(new SqlServerDialect());

            var classMapper = new CustomEntityMap <MyEntity>();

            classMapper.SetIdentityGenerated(m => m.Id);

            var classMappers = new List <IClassMapper>
            {
                classMapper
            };

            classMappers.Each(n => _config.Register(n));
        }
Esempio n. 27
0
        static UnitOfWorkManagesTransactionsStoryBase()
        {
            // can only be configured once per entity
            _config = DapperConfiguration
                      .Use()
                      .UseSqlDialect(new SqlServerDialect());

            var classMapper = new CustomEntityMap <TestEntity>();

            classMapper.SetIdentityGenerated(m => m.Id);

            var classMappers = new List <IClassMapper>
            {
                classMapper
            };

            classMappers.Each(n => _config.Register(n));
        }
Esempio n. 28
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            DapperConfiguration.Initialize();

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
                new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
        }
        public static Castle.Windsor.WindsorContainer Configuration()
        {
            using (var sqlConnection = new SqlConnection("Data Source=.;Integrated security=True;"))
            {
                const string sqlCreateDatabase = @"
                IF NOT EXISTS(SELECT * FROM sys.databases WHERE name = '{0}')
                BEGIN
                    CREATE DATABASE {0};
                END
                ";
                sqlConnection.Execute(string.Format(sqlCreateDatabase, DatabaseName));
            }

            var container = new Castle.Windsor.WindsorContainer();

            DapperConfiguration
            .Use()
            .UseClassMapper(typeof(AutoClassMapper <>))
            .UseContainer <ContainerForWindsor>(cfg => cfg.UseExisting(container))
            .UseSqlDialect(new SqlServerDialect())
            .WithDefaultConnectionStringNamed("__DefaultSqlServer")
            .FromAssembly("Dapper.Extensions.Linq.Test.Entities")
            .FromAssembly("Dapper.Extensions.Linq.Test.Maps")
            .Build();

            var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["__DefaultSqlServer"].ConnectionString);
            var files      = new List <string>
            {
                ReadScriptFile("CreateAnimalTable"),
                ReadScriptFile("CreateFooTable"),
                ReadScriptFile("CreateMultikeyTable"),
                ReadScriptFile("CreatePersonTable"),
                ReadScriptFile("CreateCarTable"),
                ReadScriptFile("CreatePhoneTable")
            };

            foreach (var setupFile in files)
            {
                connection.Execute(setupFile);
            }

            return(container);
        }
Esempio n. 30
0
        public List <PostStateHistory> GetAll()
        {
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    DapperConfiguration.OpenConnection(1);

                    var data = DapperConfiguration.db.Query <PostStateHistory>("usp_PostStateHistory", commandType: System.Data.CommandType.StoredProcedure).ToList();

                    DapperConfiguration.CloseConnection();

                    scope.Complete();
                    return(data);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("Execute Category get data: " + ex.Message);
                    return(null);
                }
            }
        }
Esempio n. 31
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("appsettings.json", false, true)
                         .Build();
            var appConfig = new DapperConfiguration();

            config.Bind("DapperConfiguration", appConfig);

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSingleton(appConfig);
            services.AddSingleton <IProductsStore, ProductsStore>();
            services.AddSingleton <IProductsService, ProductsService>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
 public DapperSessionFactory(DapperConfiguration configuration)
 {
     _configuration = configuration;
 }