/// <summary>
 /// Initializes a new instance of the <see cref="DatabaseManager"/> class.
 /// </summary>
 /// <param name="connectionProvider">The connection provider.</param>
 /// <param name="providerName">Name of the provider.</param>
 public DatabaseManager(DbProvider provider, string connectionString)
 {
     string providerName = provider.GetEnumMemberValue();
     this.connectionProvider = DbProviderFactories.GetFactory(providerName);
     this.providerName = providerName;
     this.connectionString = connectionString;
 }
        internal static string GetAssemblyName(DbProvider dbProvider)
        {
            if (!_map.ContainsKey(dbProvider))
                throw new ArgumentException(string.Format("specify dbProvider({0}) can not be found relatived assembly", dbProvider.ToString()));

            return _map[dbProvider];
        }
        public WebDatabase(DbConnectionConfig dbConnectionConfig)
        {
            this.dbConnectionConfig = dbConnectionConfig;

            dbProvider = dbConnectionConfig.DbProvider;
            connectionString = dbConnectionConfig.ConnectionString;
        }
Exemple #4
0
 public void Up(DbProvider db)
 {
     Table t = db.AddTable("Portals");
     t.AddColumn<int>("Id").PrimaryKey().AutoGenerate().NotNull();
     t.AddColumn<string>("Name", 256).NotNull();
     t.Save();
 }
Exemple #5
0
 public static OperatorSqlCriteria Create(DbProvider dbProvider, string dbColumn, Operator @operator) 
 {
     switch (@operator)
     { 
         case Operator.Equal:
             return new EqualSqlCriteria(dbProvider, dbColumn);
         case Operator.NotEqual:
             return new NotEqualSqlCriteria(dbProvider, dbColumn);
         case Operator.GreaterThan:
             return new GreaterThanSqlCriteria(dbProvider, dbColumn);
         case Operator.GreaterThanEqual:
             return new GreaterThanSqlCriteria(dbProvider, dbColumn);
         case Operator.LessThan:
             return new LessThanSqlCriteria(dbProvider, dbColumn);
         case Operator.LessThanEqual:
             return new LessThanEqualSqlCriteria(dbProvider, dbColumn);
         case Operator.Contains:
         case Operator.StartsWith:
         case Operator.EndsWith:
             return new LikeSqlCriteria(dbProvider, dbColumn);
         case Operator.In:
             return new InSqlCriteria(dbProvider, dbColumn);
         case Operator.NotIn:
             return new NotInSqlCriteria(dbProvider, dbColumn);
         default:
             return null;
     }
 }
 public SqlServerStatementFactory(DbProvider dbProvider) : base(dbProvider) 
 {
     this.parameterPrefix = dbProvider.ParameterPrefix;
     this.parameterLeftToken = dbProvider.ParameterLeftToken;
     this.parameterRightToken = dbProvider.ParameterRightToken;
     this.wildCharToken = dbProvider.WildCharToken;
     this.wildSingleCharToken = dbProvider.WildSingleCharToken;
 }
 public void Up(DbProvider db)
 {
     Table t = db.AddTable("PortalPrefixes");
     t.AddColumn<int>("Id").PrimaryKey().AutoGenerate().NotNull();
     t.AddColumn<int>("PortalId").References("Portals", "Id").NotNull();
     t.AddColumn<string>("Prefix", 256).NotNull();
     t.Save();
 }
Exemple #8
0
 protected OperatorSqlCriteria(DbProvider dbProvider, string dbColumn)
 {
     this.DbProvider = dbProvider;
     this.DbColumn = dbColumn;
     this.BuildedDbColumn = this.DbProvider.BuildColumnName(this.DbColumn).Trim();
     string tempParameterColumn = ParameterColumnCache.Instance.GetParameterColumn(dbColumn);
     this.ParameterColumn = this.DbProvider.BuildParameterName(tempParameterColumn).Trim();
 }
        public static TableSchema Create(DbProvider dbProvider, string connectionString, string sql)
        {
            DatabaseCore databaseCore = new DatabaseCore(dbProvider, connectionString);

            DataTable dt = GetTableSchema(databaseCore, sql);

            return new TableSchema(dt);
        }
 public void Up(DbProvider db)
 {
     Table users = db.AddTable("ACCOUNTS");
     users.AddColumn<int>("id").NotNull().PrimaryKey().AutoGenerate();
     users.AddColumn<long>("number").NotNull();
     users.AddColumn<short>("agency").NotNull();
     users.AddColumn<int>("person_id").NotNull().References("PEOPLE", "id");
     users.Save();
 }
 public void Up(DbProvider db)
 {
     Table users = db.AddTable("PEOPLE");
     users.AddColumn<int>("id").NotNull().PrimaryKey().AutoGenerate();
     users.AddColumn<string>("name", 100).NotNull().NotUnicode();
     users.AddColumn<string>("document", 20).NotNull().NotUnicode();
     users.AddColumn<string>("email", 50).NotUnicode();
     users.Save();
 }
 /// <summary>
 /// 处理qString;
 /// </summary>
 /// <param name="dbProvider"></param>
 /// <param name="dbTran"></param>
 void IProvider.SetDbProvider(DbProvider dbProvider, DbTrans dbTran)
 {
     if (creator != null)
     {
         var query = GetQuery(creator);
         query.SetDbProvider(dbProvider, dbTran);
         qString = query.GetTop(1).QueryString;
     }
 }
Exemple #13
0
 public void Up(DbProvider db)
 {
     Table t = db.AddTable("Pages");
     t.AddColumn<int>("Id").PrimaryKey().AutoGenerate().NotNull();
     t.AddColumn<int>("PortalId").References("Portals", "Id").NotNull();
     t.AddColumn<int>("ParentId").References("Pages", "Id");
     t.AddColumn<string>("Path", 1024).NotNull();
     t.AddColumn<string>("Title", 256).NotNull();
     t.Save();
 }
Exemple #14
0
 public void Up(DbProvider db)
 {
     Table t = db.AddTable("Modules");
     t.AddColumn<int>("Id").PrimaryKey().AutoGenerate().NotNull();
     t.AddColumn<int>("PageId").References("Pages", "Id").NotNull();
     t.AddColumn<string>("ZoneName", 50).NotNull();
     t.AddColumn<Guid>("ModuleApplicationId").NotNull();
     t.AddColumn<string>("Title", 256).NotNull();
     t.Save();
 }
Exemple #15
0
 public Command(string cmd, params object[] pms)
 {
     if (string.IsNullOrEmpty(cmd))
         cmd = "";
     this._cmd = new StringBuilder(cmd);
     this._pms = new NameValueList();
     if (pms != null)
         for (int i = 0; i < pms.Length; i++)
             this._pms.Add("@" + i, pms[i]);
     this._dbprovider = Burst.Data.DbProvider.Current;
 }
Exemple #16
0
 public Command(string cmd, NameValueList pms)
 {
     if (string.IsNullOrEmpty(cmd))
         cmd = "";
     this._cmd = new StringBuilder(cmd);
     this._pms = new NameValueList();
     if (pms != null)
         foreach (NameValue i in pms)
             this._pms.Add(i.Name, i.Value);
     this._dbprovider = Burst.Data.DbProvider.Current;
 }
 public void Up(DbProvider db)
 {
     Table t = db.AddTable("Movies");
     t.AddColumn<int>("Id").PrimaryKey().AutoGenerate();
     t.AddColumn<string>("Name", 100);
     t.AddColumn<DateTime>("ReleaseDate");
     t.AddColumn<decimal>("Runtime");
     t.AddColumn<string>("Rating", 5);
     t.AddColumn<string>("RatingDescription", 250);
     t.AddColumn<string>("Description", 5000);
     t.Save();
 }
Exemple #18
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="dbFactory">The DBPrivider which should be used</param>
        /// <param name="connectionString">The ConnectionString to the Database</param>
        public DB(DbProvider dbFactory, string connectionString)
        {
            try
            {
                InitializeDBProviderDictionary();

                ConnectionString = connectionString;
                _Factory = DbProviderFactories.GetFactory(_DbProviderDic[dbFactory]);
            }
            catch (Exception ex)
            {
                throw new DBException("Error getting DbFactory" + (string.IsNullOrEmpty(dbFactory.ToString()) ? "." : ": " + dbFactory.ToString()),
                    ex);
            }
        }
Exemple #19
0
        public async Task Clan(CommandContext ctx, [Description("The clan **tag**")] string clanTag, [Description("Put `true` to dump all members of the clan")] bool all = false)
        {
            if (!await CanExecute(ctx, Features.Clans))
            {
                return;
            }

            await ctx.TriggerTypingAsync();

            if (string.IsNullOrWhiteSpace(clanTag))
            {
                await ctx.RespondAsync($"You must send a clan tag as parameter, {ctx.User.Mention}.");

                return;
            }

            Log.Debug($"Requesting {nameof(Clan)}({clanTag}, {all})...");

            var cfg      = GuildConfiguration.FromGuild(ctx.Guild);
            var platform = GetPlatform(clanTag, cfg.Plataform, out clanTag);

            clanTag = clanTag.Trim('[', ']');
            clanTag = clanTag.ToUpperInvariant();

            if (!ClanTagRegex.IsMatch(clanTag))
            {
                await ctx.RespondAsync($"You must send a **valid** clan **tag** as parameter, {ctx.User.Mention}.");

                return;
            }

            var provider = new DbProvider(_connectionString);

            var clan = provider.GetClan(platform, clanTag);

            if (clan == null)
            {
                platform = platform == Platform.PS ? Platform.XBOX : Platform.PS;

                clan = provider.GetClan(platform, clanTag);
                if (clan == null)
                {
                    await ctx.RespondAsync(
                        $"Can't find on a clan with tag `[{clanTag}]`, {ctx.User.Mention}. Maybe my site doesn't track it yet... or you have the wrong clan tag.");

                    return;
                }
            }

            var sb = new StringBuilder();

            sb.Append($"Information about the `{clan.ClanTag}`");
            if (!string.IsNullOrWhiteSpace(clan.Country))
            {
                sb.Append($" ({clan.Country.ToUpperInvariant()})");
            }

            sb.AppendLine($", on the {clan.Plataform}, {ctx.User.Mention}:");

            if (!clan.Enabled)
            {
                sb.AppendLine($"Data collection for this clan is **disabled**, the reason for this is {clan.DisabledReason}.");
            }

            sb.AppendLine();

            sb.AppendLine($"Active Members: {clan.Active}; Total Members: {clan.Count};");
            sb.AppendLine($"Recent Win Rate: {clan.ActiveWinRate:P1}; Overall Win Rate: {clan.TotalWinRate:P1};");
            sb.AppendLine($"Recent WN8t15: {clan.Top15Wn8:N0}; Overall WN8: {clan.TotalWn8:N0};");
            if (clan.DeltaDayTop15Wn8.HasValue)
            {
                sb.AppendLine($"WN8t15 Variation from 1 day ago: {clan.DeltaDayTop15Wn8.Value:N0}");
            }

            if (clan.DeltaWeekTop15Wn8.HasValue)
            {
                sb.AppendLine($"WN8t15 Variation from 1 week ago: {clan.DeltaWeekTop15Wn8.Value:N0}");
            }

            if (clan.DeltaMonthTop15Wn8.HasValue)
            {
                sb.AppendLine($"WN8t15 Variation from 1 month ago: {clan.DeltaMonthTop15Wn8.Value:N0}");
            }

            sb.AppendLine($"Recent Actives Battles: {clan.ActiveBattles:N0}; Recent Avg Tier: {clan.ActiveAvgTier:N1}");

            sb.AppendLine();
            sb.AppendLine("**Top 15 Active Players**");
            foreach (var p in clan.Top15Players)
            {
                sb.AppendLine(
                    $"{Formatter.MaskedUrl(p.Name, new Uri(p.PlayerOverallUrl))}, {p.MonthBattles} battles, WN8: {p.MonthWn8:N0}");
            }

            var title = clan.ClanTag.EqualsCiAi(clan.Name) ? clan.ClanTag : $"{clan.ClanTag} - {clan.Name}";

            var color = clan.Top15Wn8.ToColor();

            var platformPrefix = clan.Plataform == Platform.PS ? "ps." : string.Empty;

            var embed = new DiscordEmbedBuilder
            {
                Title       = title,
                Description = sb.ToString(),
                Color       = new DiscordColor(color.R, color.G, color.B),
                Url         = $"https://{platformPrefix}wotclans.com.br/Clan/{clan.ClanTag}",
                Author      = new DiscordEmbedBuilder.EmbedAuthor
                {
                    Name = "WoTClans",
                    Url  = $"https://{platform}wotclans.com.br"
                },
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = $"Data calculated at {clan.Moment:yyyy-MM-dd HH:mm} UTC."
                }
            };

            Log.Debug($"Returned {nameof(Clan)}({clan.Plataform}.{clan.ClanTag})");

            await ctx.RespondAsync("", embed : embed);

            if (all)
            {
                // We need more responses, as discord limits the amount of data we can send on one message

                var       allPlayers = clan.Players.OrderByDescending(p => p.MonthBattles).ThenByDescending(p => p.TotalBattles).ToArray();
                const int pageSize   = 15;
                var       pages      = allPlayers.Length / pageSize + 1;

                color = clan.TotalWn8.ToColor();

                for (var currentPage = 0; currentPage < pages; ++currentPage)
                {
                    sb.Clear();

                    title = (clan.ClanTag.EqualsCiAi(clan.Name) ? clan.ClanTag : $"{clan.ClanTag} - {clan.Name}") +
                            $" - Page {currentPage + 1} of {pages}";

                    sb.Append($"All members of the `{clan.ClanTag}`");
                    if (!string.IsNullOrWhiteSpace(clan.Country))
                    {
                        sb.Append($" ({clan.Country.ToUpperInvariant()})");
                    }

                    sb.AppendLine($", on the {clan.Plataform}:");
                    sb.AppendLine();

                    foreach (var p in allPlayers.Skip(currentPage * pageSize).Take(pageSize))
                    {
                        sb.AppendLine($"{Formatter.MaskedUrl(p.Name, new Uri(p.PlayerOverallUrl))}, {p.MonthBattles} battles, WN8: {p.MonthWn8:N0}");
                    }

                    embed = new DiscordEmbedBuilder
                    {
                        Title       = title,
                        Description = sb.ToString(),
                        Color       = new DiscordColor(color.R, color.G, color.B),
                        Url         = $"https://{platformPrefix}wotclans.com.br/Clan/{clan.ClanTag}",
                        Author      = new DiscordEmbedBuilder.EmbedAuthor
                        {
                            Name = "WoTClans",
                            Url  = $"https://{platform}wotclans.com.br"
                        },
                        Footer = new DiscordEmbedBuilder.EmbedFooter
                        {
                            Text = $"Page {currentPage + 1} of {pages}"
                        }
                    };

                    await ctx.RespondAsync("", embed : embed);
                }
            }
        }
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="dbProvider">指定連接資料庫的DbProvider</param>
 /// <param name="connectionString">connectionString</param>
 public XDatabase(DbProvider dbProvider, string connectionString)
 {
     this.dbProvider = dbProvider;
     this.connectionString = connectionString;
 }
 public StoredProcBuilderTest(DbProvider dbProvider)
 {
     _dbProvider = dbProvider;
 }
 public WalletController(Filip_WEAAspOneFilipJakabContext ctx)
 {
     mapper     = new Mapper();
     dbProvider = new DbProvider(ctx);
 }
 public void Up(DbProvider db)
 {
     Table t = db.AlterTable("Movies");
     t.AddColumn<string>("PosterThumbnailUrl", 1024);
     t.Save();
 }
Exemple #24
0
        public async Task ClanTopOnTank(CommandContext ctx,
                                        [Description("The clan **tag**")] string clanTag,
                                        [Description("The Tank name, as it appears in battles. If it has spaces, enclose it on quotes.")][RemainingText] string tankName)
        {
            if (!await CanExecute(ctx, Features.Clans))
            {
                return;
            }

            await ctx.TriggerTypingAsync();

            if (string.IsNullOrWhiteSpace(clanTag))
            {
                await ctx.RespondAsync($"You must send a clan tag as parameter, {ctx.User.Mention}.");

                return;
            }

            Log.Debug($"Requesting {nameof(ClanTopOnTank)}({clanTag}, {tankName})...");

            var cfg      = GuildConfiguration.FromGuild(ctx.Guild);
            var platform = GetPlatform(clanTag, cfg.Plataform, out clanTag);

            if (!ClanTagRegex.IsMatch(clanTag))
            {
                await ctx.RespondAsync($"You must send a **valid** clan **tag** as parameter, {ctx.User.Mention}.");

                return;
            }

            var provider = new DbProvider(_connectionString);

            var clan = provider.GetClan(platform, clanTag);

            if (clan == null)
            {
                platform = platform == Platform.PS ? Platform.XBOX : Platform.PS;

                clan = provider.GetClan(platform, clanTag);
                if (clan == null)
                {
                    await ctx.RespondAsync(
                        $"Can't find on a clan with tag `[{clanTag}]`, {ctx.User.Mention}. Maybe my site doesn't track it yet... or you have the wrong clan tag.");

                    return;
                }
            }

            if (!clan.Enabled)
            {
                await ctx.RespondAsync(
                    $"Data collection for the `[{clan.ClanTag}]` is disabled, {ctx.User.Mention}. Maybe the clan went too small, or inactive.");

                return;
            }

            var tankCommands = new TankCommands();
            var tank         = tankCommands.FindTank(platform, tankName, out _);

            if (tank == null)
            {
                await ctx.RespondAsync($"Can't find a tank with `{tankName}` on the name, {ctx.User.Mention}.");

                return;
            }

            var tr = provider.GetTanksReferences(tank.Plataform, null, tank.TankId, false, false, false).FirstOrDefault();

            if (tr == null)
            {
                await ctx.RespondAsync($"Sorry, there is no tank statistics for the `{tank.Name}`, {ctx.User.Mention}.");

                return;
            }

            if (tr.Tier < 5)
            {
                await ctx.RespondAsync($"Sorry, this command is meant to be used only with tanks Tier 5 and above, {ctx.User.Mention}.");

                return;
            }

            var players = provider.GetClanPlayerIdsOnTank(platform, clan.ClanId, tr.TankId).ToList();

            if (players.Count <= 0)
            {
                await ctx.RespondAsync($"No players from the `[{clan.ClanTag}]` has battles on the `{tank.Name}`, {ctx.User.Mention}, as far as the database is up to date.");

                return;
            }

            var waitMsg = await ctx.RespondAsync($"Please wait as data for {players.Count} tankers is being retrieved, {ctx.User.Mention}...");

            var playerCommands = new PlayerCommands();

            var fullPlayers = new ConcurrentBag <Player>();
            var tasks       = players.Select(async p =>
            {
                var player = await playerCommands.GetPlayer(ctx, ((p.Plataform == Platform.XBOX) ? "x." : "ps.") + p.Name);
                if (player == null)
                {
                    await ctx.RespondAsync($"Sorry, could not get updated information for player `{p.Name}`, {ctx.User.Mention}.");
                    return;
                }

                fullPlayers.Add(player);
            });
            await Task.WhenAll(tasks);

            await waitMsg.DeleteAsync();

            var sb = new StringBuilder();

            var maxNameLength = fullPlayers.Max(p => p.Name.Length);

            //sb.AppendLine($"Here `[{clan.ClanTag}]` top players on the `{tank.Name}`, {ctx.User.Mention}:");
            //sb.AppendLine();
            sb.AppendLine("```");
            sb.AppendLine($"{platform.TagName().PadRight(maxNameLength)} {"Days".PadLeft(5)} {"Battles".PadLeft(7)} {"WN8".PadLeft(6)}");
            foreach (var p in fullPlayers.OrderByDescending(p => p.Performance.All[tank.TankId].Wn8).Take(25))
            {
                var tp = p.Performance.All[tank.TankId];
                sb.AppendLine($"{(p.Name ?? string.Empty).PadRight(maxNameLength)} {(DateTime.UtcNow - tp.LastBattle).TotalDays.ToString("N0").PadLeft(5)} {tp.Battles.ToString("N0").PadLeft(7)} {tp.Wn8.ToString("N0").PadLeft(6)}");
            }
            sb.AppendLine("```");
            sb.AppendLine();
            sb.AppendLine("This command is a **Premium** feature on the bot. For now it's free to use this command, but be advised that on the near future access will be restricted to Premium subscribers.");

            var color          = clan.Top15Wn8.ToColor();
            var platformPrefix = clan.Plataform == Platform.PS ? "ps." : string.Empty;

            var embed = new DiscordEmbedBuilder
            {
                Title        = $"`{clan.ClanTag}` top players on the `{tank.Name}`",
                Description  = sb.ToString(),
                Color        = new DiscordColor(color.R, color.G, color.B),
                ThumbnailUrl = tank.SmallImageUrl,
                Url          = $"https://{platformPrefix}wotclans.com.br/Clan/{clan.ClanTag}",
                Author       = new DiscordEmbedBuilder.EmbedAuthor
                {
                    Name = "WoTClans",
                    Url  = $"https://{platformPrefix}wotclans.com.br"
                },
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = $"Calculated at {DateTime.UtcNow:yyyy-MM-dd HH:mm} UTC"
                }
            };

            await ctx.RespondAsync("", embed : embed);
        }
        /// <summary>  </summary>
        private IScheduler Instantiate()
        {
            if (cfg == null)
            {
                Initialize();
            }

            if (initException != null)
            {
                throw initException;
            }

            ISchedulerExporter   exporter = null;
            IJobStore            js;
            IThreadPool          tp;
            QuartzScheduler      qs      = null;
            IDbConnectionManager dbMgr   = null;
            Type instanceIdGeneratorType = null;
            NameValueCollection tProps;
            bool            autoId         = false;
            TimeSpan        idleWaitTime   = TimeSpan.Zero;
            TimeSpan        dbFailureRetry = TimeSpan.FromSeconds(15);
            IThreadExecutor threadExecutor;

            SchedulerRepository schedRep = SchedulerRepository.Instance;

            // Get Scheduler Properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            string schedName   = cfg.GetStringProperty(PropertySchedulerInstanceName, "QuartzScheduler");
            string threadName  = cfg.GetStringProperty(PropertySchedulerThreadName, "{0}_QuartzSchedulerThread".FormatInvariant(schedName));
            string schedInstId = cfg.GetStringProperty(PropertySchedulerInstanceId, DefaultInstanceId);

            if (schedInstId.Equals(AutoGenerateInstanceId))
            {
                autoId = true;
                instanceIdGeneratorType = LoadType(cfg.GetStringProperty(PropertySchedulerInstanceIdGeneratorType)) ?? typeof(SimpleInstanceIdGenerator);
            }
            else if (schedInstId.Equals(SystemPropertyAsInstanceId))
            {
                autoId = true;
                instanceIdGeneratorType = typeof(SystemPropertyInstanceIdGenerator);
            }

            Type typeLoadHelperType = LoadType(cfg.GetStringProperty(PropertySchedulerTypeLoadHelperType));
            Type jobFactoryType     = LoadType(cfg.GetStringProperty(PropertySchedulerJobFactoryType, null));

            idleWaitTime = cfg.GetTimeSpanProperty(PropertySchedulerIdleWaitTime, idleWaitTime);
            if (idleWaitTime > TimeSpan.Zero && idleWaitTime < TimeSpan.FromMilliseconds(1000))
            {
                throw new SchedulerException("quartz.scheduler.idleWaitTime of less than 1000ms is not legal.");
            }

            dbFailureRetry = cfg.GetTimeSpanProperty(PropertySchedulerDbFailureRetryInterval, dbFailureRetry);
            if (dbFailureRetry < TimeSpan.Zero)
            {
                throw new SchedulerException(PropertySchedulerDbFailureRetryInterval + " of less than 0 ms is not legal.");
            }

            bool makeSchedulerThreadDaemon = cfg.GetBooleanProperty(PropertySchedulerMakeSchedulerThreadDaemon);
            long batchTimeWindow           = cfg.GetLongProperty(PropertySchedulerBatchTimeWindow, 0L);
            int  maxBatchSize = cfg.GetIntProperty(PropertySchedulerMaxBatchSize, 1);

            bool interruptJobsOnShutdown         = cfg.GetBooleanProperty(PropertySchedulerInterruptJobsOnShutdown, false);
            bool interruptJobsOnShutdownWithWait = cfg.GetBooleanProperty(PropertySchedulerInterruptJobsOnShutdownWithWait, false);

            NameValueCollection schedCtxtProps = cfg.GetPropertyGroup(PropertySchedulerContextPrefix, true);

            bool proxyScheduler = cfg.GetBooleanProperty(PropertySchedulerProxy, false);


            // Create type load helper
            ITypeLoadHelper loadHelper;

            try
            {
                loadHelper = ObjectUtils.InstantiateType <ITypeLoadHelper>(typeLoadHelperType ?? typeof(SimpleTypeLoadHelper));
            }
            catch (Exception e)
            {
                throw new SchedulerConfigException("Unable to instantiate type load helper: {0}".FormatInvariant(e.Message), e);
            }
            loadHelper.Initialize();


            // If Proxying to remote scheduler, short-circuit here...
            // ~~~~~~~~~~~~~~~~~~
            if (proxyScheduler)
            {
                if (autoId)
                {
                    schedInstId = DefaultInstanceId;
                }

                Type proxyType = loadHelper.LoadType(cfg.GetStringProperty(PropertySchedulerProxyType)) ?? typeof(RemotingSchedulerProxyFactory);
                IRemotableSchedulerProxyFactory factory;
                try
                {
                    factory = ObjectUtils.InstantiateType <IRemotableSchedulerProxyFactory>(proxyType);
                    ObjectUtils.SetObjectProperties(factory, cfg.GetPropertyGroup(PropertySchedulerProxy, true));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Remotable proxy factory '{0}' could not be instantiated.".FormatInvariant(proxyType), e);
                    throw initException;
                }

                string uid = QuartzSchedulerResources.GetUniqueIdentifier(schedName, schedInstId);

                RemoteScheduler remoteScheduler = new RemoteScheduler(uid, factory);

                schedRep.Bind(remoteScheduler);

                return(remoteScheduler);
            }


            IJobFactory jobFactory = null;

            if (jobFactoryType != null)
            {
                try
                {
                    jobFactory = ObjectUtils.InstantiateType <IJobFactory>(jobFactoryType);
                }
                catch (Exception e)
                {
                    throw new SchedulerConfigException("Unable to Instantiate JobFactory: {0}".FormatInvariant(e.Message), e);
                }

                tProps = cfg.GetPropertyGroup(PropertySchedulerJobFactoryPrefix, true);
                try
                {
                    ObjectUtils.SetObjectProperties(jobFactory, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobFactory of type '{0}' props could not be configured.".FormatInvariant(jobFactoryType), e);
                    throw initException;
                }
            }

            IInstanceIdGenerator instanceIdGenerator = null;

            if (instanceIdGeneratorType != null)
            {
                try
                {
                    instanceIdGenerator = ObjectUtils.InstantiateType <IInstanceIdGenerator>(instanceIdGeneratorType);
                }
                catch (Exception e)
                {
                    throw new SchedulerConfigException("Unable to Instantiate InstanceIdGenerator: {0}".FormatInvariant(e.Message), e);
                }
                tProps = cfg.GetPropertyGroup(PropertySchedulerInstanceIdGeneratorPrefix, true);
                try
                {
                    ObjectUtils.SetObjectProperties(instanceIdGenerator, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("InstanceIdGenerator of type '{0}' props could not be configured.".FormatInvariant(instanceIdGeneratorType), e);
                    throw initException;
                }
            }

            // Get ThreadPool Properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            Type tpType = loadHelper.LoadType(cfg.GetStringProperty(PropertyThreadPoolType)) ?? typeof(SimpleThreadPool);

            try
            {
                tp = ObjectUtils.InstantiateType <IThreadPool>(tpType);
            }
            catch (Exception e)
            {
                initException = new SchedulerException("ThreadPool type '{0}' could not be instantiated.".FormatInvariant(tpType), e);
                throw initException;
            }
            tProps = cfg.GetPropertyGroup(PropertyThreadPoolPrefix, true);
            try
            {
                ObjectUtils.SetObjectProperties(tp, tProps);
            }
            catch (Exception e)
            {
                initException = new SchedulerException("ThreadPool type '{0}' props could not be configured.".FormatInvariant(tpType), e);
                throw initException;
            }

            // Set up any DataSources
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            IList <string> dsNames = cfg.GetPropertyGroups(PropertyDataSourcePrefix);

            foreach (string dataSourceName in dsNames)
            {
                string datasourceKey = "{0}.{1}".FormatInvariant(PropertyDataSourcePrefix, dataSourceName);
                NameValueCollection propertyGroup = cfg.GetPropertyGroup(datasourceKey, true);
                PropertiesParser    pp            = new PropertiesParser(propertyGroup);

                Type cpType = loadHelper.LoadType(pp.GetStringProperty(PropertyDbProviderType, null));

                // custom connectionProvider...
                if (cpType != null)
                {
                    IDbProvider cp;
                    try
                    {
                        cp = ObjectUtils.InstantiateType <IDbProvider>(cpType);
                    }
                    catch (Exception e)
                    {
                        initException = new SchedulerException("ConnectionProvider of type '{0}' could not be instantiated.".FormatInvariant(cpType), e);
                        throw initException;
                    }

                    try
                    {
                        // remove the type name, so it isn't attempted to be set
                        pp.UnderlyingProperties.Remove(PropertyDbProviderType);

                        ObjectUtils.SetObjectProperties(cp, pp.UnderlyingProperties);
                        cp.Initialize();
                    }
                    catch (Exception e)
                    {
                        initException = new SchedulerException("ConnectionProvider type '{0}' props could not be configured.".FormatInvariant(cpType), e);
                        throw initException;
                    }

                    dbMgr = DBConnectionManager.Instance;
                    dbMgr.AddConnectionProvider(dataSourceName, cp);
                }
                else
                {
                    string dsProvider             = pp.GetStringProperty(PropertyDataSourceProvider, null);
                    string dsConnectionString     = pp.GetStringProperty(PropertyDataSourceConnectionString, null);
                    string dsConnectionStringName = pp.GetStringProperty(PropertyDataSourceConnectionStringName, null);

                    if (dsConnectionString == null && !String.IsNullOrEmpty(dsConnectionStringName))
                    {
                        ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[dsConnectionStringName];
                        if (connectionStringSettings == null)
                        {
                            initException = new SchedulerException("Named connection string '{0}' not found for DataSource: {1}".FormatInvariant(dsConnectionStringName, dataSourceName));
                            throw initException;
                        }
                        dsConnectionString = connectionStringSettings.ConnectionString;
                    }

                    if (dsProvider == null)
                    {
                        initException = new SchedulerException("Provider not specified for DataSource: {0}".FormatInvariant(dataSourceName));
                        throw initException;
                    }
                    if (dsConnectionString == null)
                    {
                        initException = new SchedulerException("Connection string not specified for DataSource: {0}".FormatInvariant(dataSourceName));
                        throw initException;
                    }
                    try
                    {
                        DbProvider dbp = new DbProvider(dsProvider, dsConnectionString);
                        dbp.Initialize();

                        dbMgr = DBConnectionManager.Instance;
                        dbMgr.AddConnectionProvider(dataSourceName, dbp);
                    }
                    catch (Exception exception)
                    {
                        initException = new SchedulerException("Could not Initialize DataSource: {0}".FormatInvariant(dataSourceName), exception);
                        throw initException;
                    }
                }
            }

            // Get object serializer properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            IObjectSerializer objectSerializer;
            string            objectSerializerType = cfg.GetStringProperty("quartz.serializer.type");

            if (objectSerializerType != null)
            {
                tProps = cfg.GetPropertyGroup(PropertyObjectSerializer, true);
                try
                {
                    objectSerializer = ObjectUtils.InstantiateType <IObjectSerializer>(loadHelper.LoadType(objectSerializerType));
                    log.Info("Using custom implementation for object serializer: " + objectSerializerType);

                    ObjectUtils.SetObjectProperties(objectSerializer, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Object serializer type '" + objectSerializerType + "' could not be instantiated.", e);
                    throw initException;
                }
            }
            else
            {
                log.Info("Using default implementation for object serializer");
                objectSerializer = new DefaultObjectSerializer();
            }

            // Get JobStore Properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            Type jsType = loadHelper.LoadType(cfg.GetStringProperty(PropertyJobStoreType));

            try
            {
                js = ObjectUtils.InstantiateType <IJobStore>(jsType ?? typeof(RAMJobStore));
            }
            catch (Exception e)
            {
                initException = new SchedulerException("JobStore of type '{0}' could not be instantiated.".FormatInvariant(jsType), e);
                throw initException;
            }


            SchedulerDetailsSetter.SetDetails(js, schedName, schedInstId);

            tProps = cfg.GetPropertyGroup(PropertyJobStorePrefix, true, new string[] { PropertyJobStoreLockHandlerPrefix });

            try
            {
                ObjectUtils.SetObjectProperties(js, tProps);
            }
            catch (Exception e)
            {
                initException = new SchedulerException("JobStore type '{0}' props could not be configured.".FormatInvariant(jsType), e);
                throw initException;
            }

            if (js is JobStoreSupport)
            {
                // Install custom lock handler (Semaphore)
                Type lockHandlerType = loadHelper.LoadType(cfg.GetStringProperty(PropertyJobStoreLockHandlerType));
                if (lockHandlerType != null)
                {
                    try
                    {
                        ISemaphore      lockHandler;
                        ConstructorInfo cWithDbProvider = lockHandlerType.GetConstructor(new Type[] { typeof(DbProvider) });

                        if (cWithDbProvider != null)
                        {
                            // takes db provider
                            IDbProvider dbProvider = DBConnectionManager.Instance.GetDbProvider(((JobStoreSupport)js).DataSource);
                            lockHandler = (ISemaphore)cWithDbProvider.Invoke(new object[] { dbProvider });
                        }
                        else
                        {
                            lockHandler = ObjectUtils.InstantiateType <ISemaphore>(lockHandlerType);
                        }

                        tProps = cfg.GetPropertyGroup(PropertyJobStoreLockHandlerPrefix, true);

                        // If this lock handler requires the table prefix, add it to its properties.
                        if (lockHandler is ITablePrefixAware)
                        {
                            tProps[PropertyTablePrefix]   = ((JobStoreSupport)js).TablePrefix;
                            tProps[PropertySchedulerName] = schedName;
                        }

                        try
                        {
                            ObjectUtils.SetObjectProperties(lockHandler, tProps);
                        }
                        catch (Exception e)
                        {
                            initException = new SchedulerException("JobStore LockHandler type '{0}' props could not be configured.".FormatInvariant(lockHandlerType), e);
                            throw initException;
                        }

                        ((JobStoreSupport)js).LockHandler = lockHandler;
                        Log.Info("Using custom data access locking (synchronization): " + lockHandlerType);
                    }
                    catch (Exception e)
                    {
                        initException = new SchedulerException("JobStore LockHandler type '{0}' could not be instantiated.".FormatInvariant(lockHandlerType), e);
                        throw initException;
                    }
                }
            }

            // Set up any SchedulerPlugins
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            IList <string> pluginNames = cfg.GetPropertyGroups(PropertyPluginPrefix);

            ISchedulerPlugin[] plugins = new ISchedulerPlugin[pluginNames.Count];
            for (int i = 0; i < pluginNames.Count; i++)
            {
                NameValueCollection pp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyPluginPrefix, pluginNames[i]), true);

                string plugInType = pp[PropertyPluginType];

                if (plugInType == null)
                {
                    initException = new SchedulerException("SchedulerPlugin type not specified for plugin '{0}'".FormatInvariant(pluginNames[i]));
                    throw initException;
                }
                ISchedulerPlugin plugin;
                try
                {
                    plugin = ObjectUtils.InstantiateType <ISchedulerPlugin>(LoadType(plugInType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("SchedulerPlugin of type '{0}' could not be instantiated.".FormatInvariant(plugInType), e);
                    throw initException;
                }
                try
                {
                    ObjectUtils.SetObjectProperties(plugin, pp);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobStore SchedulerPlugin '{0}' props could not be configured.".FormatInvariant(plugInType), e);
                    throw initException;
                }
                plugins[i] = plugin;
            }

            // Set up any JobListeners
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            IList <string> jobListenerNames = cfg.GetPropertyGroups(PropertyJobListenerPrefix);

            IJobListener[] jobListeners = new IJobListener[jobListenerNames.Count];
            for (int i = 0; i < jobListenerNames.Count; i++)
            {
                NameValueCollection lp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyJobListenerPrefix, jobListenerNames[i]), true);

                string listenerType = lp[PropertyListenerType];

                if (listenerType == null)
                {
                    initException = new SchedulerException("JobListener type not specified for listener '{0}'".FormatInvariant(jobListenerNames[i]));
                    throw initException;
                }
                IJobListener listener;
                try
                {
                    listener = ObjectUtils.InstantiateType <IJobListener>(loadHelper.LoadType(listenerType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobListener of type '{0}' could not be instantiated.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                try
                {
                    PropertyInfo nameProperty = listener.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
                    if (nameProperty != null && nameProperty.CanWrite)
                    {
                        nameProperty.GetSetMethod().Invoke(listener, new object[] { jobListenerNames[i] });
                    }
                    ObjectUtils.SetObjectProperties(listener, lp);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobListener '{0}' props could not be configured.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                jobListeners[i] = listener;
            }

            // Set up any TriggerListeners
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            IList <string> triggerListenerNames = cfg.GetPropertyGroups(PropertyTriggerListenerPrefix);

            ITriggerListener[] triggerListeners = new ITriggerListener[triggerListenerNames.Count];
            for (int i = 0; i < triggerListenerNames.Count; i++)
            {
                NameValueCollection lp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyTriggerListenerPrefix, triggerListenerNames[i]), true);

                string listenerType = lp[PropertyListenerType];

                if (listenerType == null)
                {
                    initException = new SchedulerException("TriggerListener type not specified for listener '{0}'".FormatInvariant(triggerListenerNames[i]));
                    throw initException;
                }
                ITriggerListener listener;
                try
                {
                    listener = ObjectUtils.InstantiateType <ITriggerListener>(loadHelper.LoadType(listenerType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("TriggerListener of type '{0}' could not be instantiated.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                try
                {
                    PropertyInfo nameProperty = listener.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
                    if (nameProperty != null && nameProperty.CanWrite)
                    {
                        nameProperty.GetSetMethod().Invoke(listener, new object[] { triggerListenerNames[i] });
                    }
                    ObjectUtils.SetObjectProperties(listener, lp);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("TriggerListener '{0}' props could not be configured.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                triggerListeners[i] = listener;
            }

            // Get exporter
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            string exporterType = cfg.GetStringProperty(PropertySchedulerExporterType, null);

            if (exporterType != null)
            {
                try
                {
                    exporter = ObjectUtils.InstantiateType <ISchedulerExporter>(loadHelper.LoadType(exporterType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Scheduler exporter of type '{0}' could not be instantiated.".FormatInvariant(exporterType), e);
                    throw initException;
                }

                tProps = cfg.GetPropertyGroup(PropertySchedulerExporterPrefix, true);

                try
                {
                    ObjectUtils.SetObjectProperties(exporter, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Scheduler exporter type '{0}' props could not be configured.".FormatInvariant(exporterType), e);
                    throw initException;
                }
            }

            bool tpInited = false;
            bool qsInited = false;


            // Get ThreadExecutor Properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            string threadExecutorClass = cfg.GetStringProperty(PropertyThreadExecutorType);

            if (threadExecutorClass != null)
            {
                tProps = cfg.GetPropertyGroup(PropertyThreadExecutor, true);
                try
                {
                    threadExecutor = ObjectUtils.InstantiateType <IThreadExecutor>(loadHelper.LoadType(threadExecutorClass));
                    log.Info("Using custom implementation for ThreadExecutor: " + threadExecutorClass);

                    ObjectUtils.SetObjectProperties(threadExecutor, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException(
                        "ThreadExecutor class '" + threadExecutorClass + "' could not be instantiated.", e);
                    throw initException;
                }
            }
            else
            {
                log.Info("Using default implementation for ThreadExecutor");
                threadExecutor = new DefaultThreadExecutor();
            }

            // Fire everything up
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            try
            {
                IJobRunShellFactory jrsf = new StdJobRunShellFactory();

                if (autoId)
                {
                    try
                    {
                        schedInstId = DefaultInstanceId;

                        if (js.Clustered)
                        {
                            schedInstId = instanceIdGenerator.GenerateInstanceId();
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Error("Couldn't generate instance Id!", e);
                        throw new SystemException("Cannot run without an instance id.");
                    }
                }


                if (js is JobStoreSupport)
                {
                    JobStoreSupport jjs = (JobStoreSupport)js;
                    jjs.DbRetryInterval = dbFailureRetry;
                    jjs.ThreadExecutor  = threadExecutor;
                    // object serializer
                    jjs.ObjectSerializer = objectSerializer;
                }

                QuartzSchedulerResources rsrcs = new QuartzSchedulerResources();
                rsrcs.Name                            = schedName;
                rsrcs.ThreadName                      = threadName;
                rsrcs.InstanceId                      = schedInstId;
                rsrcs.JobRunShellFactory              = jrsf;
                rsrcs.MakeSchedulerThreadDaemon       = makeSchedulerThreadDaemon;
                rsrcs.BatchTimeWindow                 = TimeSpan.FromMilliseconds(batchTimeWindow);
                rsrcs.MaxBatchSize                    = maxBatchSize;
                rsrcs.InterruptJobsOnShutdown         = interruptJobsOnShutdown;
                rsrcs.InterruptJobsOnShutdownWithWait = interruptJobsOnShutdownWithWait;
                rsrcs.SchedulerExporter               = exporter;

                SchedulerDetailsSetter.SetDetails(tp, schedName, schedInstId);

                rsrcs.ThreadExecutor = threadExecutor;
                threadExecutor.Initialize();

                rsrcs.ThreadPool = tp;

                tp.Initialize();
                tpInited = true;

                rsrcs.JobStore = js;

                // add plugins
                foreach (ISchedulerPlugin plugin in plugins)
                {
                    rsrcs.AddSchedulerPlugin(plugin);
                }

                qs       = new QuartzScheduler(rsrcs, idleWaitTime, dbFailureRetry);
                qsInited = true;

                // Create Scheduler ref...
                IScheduler sched = Instantiate(rsrcs, qs);

                // set job factory if specified
                if (jobFactory != null)
                {
                    qs.JobFactory = jobFactory;
                }

                // Initialize plugins now that we have a Scheduler instance.
                for (int i = 0; i < plugins.Length; i++)
                {
                    plugins[i].Initialize(pluginNames[i], sched);
                }

                // add listeners
                foreach (IJobListener listener in jobListeners)
                {
                    qs.ListenerManager.AddJobListener(listener, EverythingMatcher <JobKey> .AllJobs());
                }
                foreach (ITriggerListener listener in triggerListeners)
                {
                    qs.ListenerManager.AddTriggerListener(listener, EverythingMatcher <TriggerKey> .AllTriggers());
                }

                // set scheduler context data...
                foreach (string key in schedCtxtProps)
                {
                    string val = schedCtxtProps.Get(key);
                    sched.Context.Put(key, val);
                }

                // fire up job store, and runshell factory

                js.InstanceId     = schedInstId;
                js.InstanceName   = schedName;
                js.ThreadPoolSize = tp.PoolSize;
                js.Initialize(loadHelper, qs.SchedulerSignaler);

                jrsf.Initialize(sched);
                qs.Initialize();

                Log.Info("Quartz scheduler '{0}' initialized".FormatInvariant(sched.SchedulerName));

                Log.Info("Quartz scheduler version: {0}".FormatInvariant(qs.Version));

                // prevents the repository from being garbage collected
                qs.AddNoGCObject(schedRep);
                // prevents the db manager from being garbage collected
                if (dbMgr != null)
                {
                    qs.AddNoGCObject(dbMgr);
                }

                schedRep.Bind(sched);

                return(sched);
            }
            catch (SchedulerException)
            {
                if (qsInited)
                {
                    qs.Shutdown(false);
                }
                else if (tpInited)
                {
                    tp.Shutdown(false);
                }
                throw;
            }
            catch
            {
                if (qsInited)
                {
                    qs.Shutdown(false);
                }
                else if (tpInited)
                {
                    tp.Shutdown(false);
                }
                throw;
            }
        }
Exemple #26
0
 private static void AppendParameterName(StringBuilder sqlBuilder, DbProvider dbProvider, string paramName)
 {
     sqlBuilder.AppendFormat("{0}{1}", dbProvider.ParameterPrefix, paramName);
 }
Exemple #27
0
 private static void AppendColumnEqParameter(StringBuilder sqlBuilder, DbProvider dbProvider, ColumnAttribute column)
 {
     sqlBuilder.AppendFormat("{0}{1}{2}={3}{4}", dbProvider.ParameterNamePrefix, column.Name, dbProvider.ParameterNameSuffix, dbProvider.ParameterPrefix, column.Property.Name);
 }
Exemple #28
0
 public DbConnection GetNotWrapperedConnection()
 {
     return(DbProvider.GetNotWrapperedConnection(_connectionString));
 }
Exemple #29
0
 private static void AppendColumnName(StringBuilder sqlBuilder, DbProvider dbProvider, string paramName)
 {
     sqlBuilder.AppendFormat("{0}{1}{2}", dbProvider.ParameterNamePrefix, paramName, dbProvider.ParameterNameSuffix);
 }
Exemple #30
0
 public ConnectionWrapper GetWrapperedConnection()
 {
     return(DbProvider.GetWrapperedConnection(_connectionString));
 }
Exemple #31
0
 public override Task DowngradeAsync(DbTransaction transaction)
 {
     return(DbProvider.ExecuteScriptAsync(ScriptConstants.DownScript));
 }
 public IDbSqlProc <TEntity> SqlQuery <TEntity>(IQueue queue) where TEntity : class, new()
 {
     return(DbProvider.CreateSqlProc <TEntity>(this, queue));
 }
 public GreaterThanSqlCriteria(DbProvider dbProvider, string column) : base(dbProvider, column) { }
Exemple #34
0
 private static String WrapColumnEqParameter(DbProvider dbProvider, string paramName)
 {
     return($"{dbProvider.ParameterNamePrefix}{paramName}{dbProvider.ParameterNameSuffix}={dbProvider.ParameterPrefix}{paramName}");
 }
Exemple #35
0
 public void Down(DbProvider db)
 {
     db.DropTable("Portals");
 }
        /// <summary>
        /// 添加数据库上下文
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configure">配置</param>
        /// <param name="migrationAssemblyName">迁移类库名称</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddDatabaseAccessor(this IServiceCollection services, Action <IServiceCollection> configure = null, string migrationAssemblyName = default)
        {
            // 设置迁移类库名称
            if (!string.IsNullOrEmpty(migrationAssemblyName))
            {
                Db.MigrationAssemblyName = migrationAssemblyName;
            }

            // 配置数据库上下文
            configure?.Invoke(services);

            // 注册数据库上下文池
            services.TryAddScoped <IDbContextPool, DbContextPool>();

            // 注册 Sql 仓储
            services.TryAddScoped(typeof(ISqlRepository <>), typeof(SqlRepository <>));

            // 注册 Sql 非泛型仓储
            services.TryAddScoped <ISqlRepository, SqlRepository>();

            // 注册多数据库上下文仓储
            services.TryAddScoped(typeof(IRepository <,>), typeof(EFCoreRepository <,>));

            // 注册泛型仓储
            services.TryAddScoped(typeof(IRepository <>), typeof(EFCoreRepository <>));

            // 注册主从库仓储
            services.TryAddScoped(typeof(IMSRepository <,>), typeof(MSRepository <,>));
            services.TryAddScoped(typeof(IMSRepository <, ,>), typeof(MSRepository <, ,>));
            services.TryAddScoped(typeof(IMSRepository <, , ,>), typeof(MSRepository <, , ,>));
            services.TryAddScoped(typeof(IMSRepository <, , , ,>), typeof(MSRepository <, , , ,>));
            services.TryAddScoped(typeof(IMSRepository <, , , , ,>), typeof(MSRepository <, , , , ,>));
            services.TryAddScoped(typeof(IMSRepository <, , , , , ,>), typeof(MSRepository <, , , , , ,>));
            services.TryAddScoped(typeof(IMSRepository <, , , , , , ,>), typeof(MSRepository <, , , , , , ,>));

            // 注册非泛型仓储
            services.TryAddScoped <IRepository, EFCoreRepository>();

            // 注册多数据库仓储
            services.TryAddScoped(typeof(IDbRepository <>), typeof(DbRepository <>));

            // 解析数据库上下文
            services.AddTransient(provider =>
            {
                DbContext dbContextResolve(Type locator, ITransient transient)
                {
                    // 判断定位器是否绑定了数据库上下文
                    var isRegistered = Penetrates.DbContextWithLocatorCached.TryGetValue(locator, out var dbContextType);
                    if (!isRegistered)
                    {
                        throw new InvalidOperationException($"The DbContext for locator  `{locator.FullName}` binding was not found.");
                    }

                    // 动态解析数据库上下文,创建新的对象
                    var dbContext = provider.CreateScope().ServiceProvider.GetService(dbContextType) as DbContext;

                    // 实现动态数据库上下文功能,刷新 OnModelCreating
                    var dbContextAttribute = DbProvider.GetAppDbContextAttribute(dbContextType);
                    if (dbContextAttribute?.Mode == DbContextMode.Dynamic)
                    {
                        DynamicModelCacheKeyFactory.RebuildModels();
                    }

                    // 2021.01.15:修改瞬时数据库上下文逻辑,取消自动加入数据库上下文池
                    // 也就是不受工作单元影响
                    //// 添加数据库上下文到池中
                    //var dbContextPool = App.GetService<IDbContextPool>();
                    //dbContextPool?.AddToPool(dbContext);

                    return(dbContext);
                }
                return((Func <Type, ITransient, DbContext>)dbContextResolve);
            });

            services.AddScoped(provider =>
            {
                DbContext dbContextResolve(Type locator, IScoped scoped)
                {
                    // 判断定位器是否绑定了数据库上下文
                    var isRegistered = Penetrates.DbContextWithLocatorCached.TryGetValue(locator, out var dbContextType);
                    if (!isRegistered)
                    {
                        throw new InvalidOperationException($"The DbContext for locator `{locator.FullName}` binding was not found.");
                    }

                    // 动态解析数据库上下文
                    var dbContext = provider.GetService(dbContextType) as DbContext;

                    // 实现动态数据库上下文功能,刷新 OnModelCreating
                    var dbContextAttribute = DbProvider.GetAppDbContextAttribute(dbContextType);
                    if (dbContextAttribute?.Mode == DbContextMode.Dynamic)
                    {
                        DynamicModelCacheKeyFactory.RebuildModels();
                    }

                    // 添加数据库上下文到池中
                    var dbContextPool = App.GetService <IDbContextPool>();
                    dbContextPool?.AddToPool(dbContext);

                    return(dbContext);
                }
                return((Func <Type, IScoped, DbContext>)dbContextResolve);
            });

            // 注册 Sql 代理接口
            services.AddScopedDispatchProxyForInterface <SqlDispatchProxy, ISqlDispatchProxy>();

            // 注册全局工作单元过滤器
            services.AddMvcFilter <UnitOfWorkFilter>();

            return(services);
        }
Exemple #37
0
        public ApiResult <CommentModels> GetPaging(BaseCondition <CommentModels> condition)
        {
            var result = new ApiResult <CommentModels>();

            try
            {
                //Đặt tên cho stored procedures
                DbProvider.SetCommandText2("sp_Comment_GetPaging", CommandType.StoredProcedure);

                // Input params
                DbProvider.AddParameter("StartRow", condition.FromRecord, SqlDbType.Int);
                DbProvider.AddParameter("PageSize", condition.PageSize, SqlDbType.Int);

                // Sắp xếp dữ liệu
                if (!string.IsNullOrEmpty(condition.IN_SORT))
                {
                    DbProvider.AddParameter("IN_SORT", condition.IN_SORT, SqlDbType.NVarChar);
                }

                // Điều kiện tìm kiếm
                if (condition.HasCondition && !string.IsNullOrEmpty(condition.IN_WHERE))
                {
                    DbProvider.AddParameter("IN_WHERE", condition.IN_WHERE, SqlDbType.NVarChar);
                }

                // Output params
                DbProvider.AddParameter("TotalRecords", DBNull.Value, SqlDbType.Int, ParameterDirection.Output);
                DbProvider.AddParameter("ErrorCode", DBNull.Value, SqlDbType.NVarChar, 100, ParameterDirection.Output);
                DbProvider.AddParameter("ReturnMsg", DBNull.Value, SqlDbType.NVarChar, 4000, ParameterDirection.Output);


                result.DataList = DbProvider.ExecuteListObject <CommentModels>();
                try
                {
                    result.TotalRecords = int.Parse(DbProvider.Command.Parameters["TotalRecords"].Value.ToString());
                }
                catch (Exception)
                {
                    result.TotalRecords = 0;
                }

                // Kiểm tra kết quả trả về
                string errorCode = DbProvider.Command.Parameters["ErrorCode"].Value.ToString();
                if (!errorCode.Equals(Constants.SUCCESS))
                {
                    result.Failed(new ErrorObject()
                    {
                        Code        = DbProvider.Command.Parameters["ErrorCode"].Value.ToString(),
                        Description = DbProvider.Command.Parameters["ReturnMsg"].Value.ToString()
                    });
                }
            }
            catch (Exception ex)
            {
                result.Failed(new ErrorObject()
                {
                    Code        = Constants.ERR_EXCEPTION,
                    Description = ex.Message
                });
            }
            return(result);
        }
        public NHContextFactory(DbProvider provider, string connectionString, string cacheProvider, Assembly mappingsAssembly, IoCContainer container)
        {
            _DbProvider = provider;
            _connectionString = connectionString;

            FluentConfiguration cfg = null;

            switch (_DbProvider)
            {
                case DbProvider.MsSqlProvider:
                {
                    cfg = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008
                        .Raw("format_sql", "true")
                        .ConnectionString(_connectionString))
                        .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.SqlExceptionConverter, typeof(SqlExceptionHandler).AssemblyQualifiedName))
                        .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.DefaultSchema, "dbo"));

                    break;
                }
                case DbProvider.SQLiteProvider:
                {
                    cfg = Fluently.Configure().Database(SQLiteConfiguration.Standard
                        .Raw("format_sql", "true")
                        .ConnectionString(_connectionString));

                    _InMemoryDatabase = _connectionString.ToUpperInvariant().Contains(":MEMORY:");

                    break;
                }
                case DbProvider.SqlCe:
                {
                    cfg = Fluently.Configure().Database(MsSqlCeConfiguration.Standard
                            .Raw("format_sql", "true")
                            .ConnectionString(_connectionString))
                            .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.SqlExceptionConverter, typeof(SqlExceptionHandler).AssemblyQualifiedName));
                        
                    _validationSupported = false;

                    break;
                }
                case DbProvider.Firebird:
                {
                    cfg = Fluently.Configure().Database(new FirebirdConfiguration()
                            .Raw("format_sql", "true")
                            .ConnectionString(_connectionString));

                    break;
                }
				case DbProvider.PostgreSQLProvider:
                {
                    cfg = Fluently.Configure().Database(PostgreSQLConfiguration.PostgreSQL82
                            .Raw("format_sql", "true")
                            .ConnectionString(_connectionString));
				
					_validationSupported = false;

                    break;
                }
            }

            Guard.IsNotNull(cfg, string.Format("Db provider {0} is currently not supported.", _DbProvider.GetEnumMemberValue()));

            var pinfo = typeof(FluentConfiguration)
                .GetProperty("Configuration", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

            var nhConfiguration = pinfo.GetValue(cfg, null);
            container.RegisterInstance<Configuration>(nhConfiguration);

            cfg.Mappings(m => m.FluentMappings.Conventions.AddAssembly(typeof(NHContextFactory).Assembly))
                .Mappings(m => m.FluentMappings.Conventions.AddAssembly(mappingsAssembly))
                .Mappings(m => m.FluentMappings.AddFromAssembly(mappingsAssembly))
                .Mappings(m => m.HbmMappings.AddFromAssembly(typeof(NHContextFactory).Assembly))
                .Mappings(m => m.HbmMappings.AddFromAssembly(mappingsAssembly))
				.ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.BatchSize, "100"))
                .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.UseProxyValidator, "true"));

            if (!string.IsNullOrEmpty(cacheProvider))
            {
                cfg.ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.CacheProvider, cacheProvider)) //"NHibernate.Cache.HashtableCacheProvider"
                    .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.UseSecondLevelCache, "true"))
                    .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.UseQueryCache, "true"));
            }

            _builtConfiguration = cfg.BuildConfiguration();
            _builtConfiguration.SetProperty(NHibernate.Cfg.Environment.ProxyFactoryFactoryClass, 
                typeof(NHibernate.ByteCode.Castle.ProxyFactoryFactory).AssemblyQualifiedName);

            #region Add Listeners to NHibernate pipeline....

            _builtConfiguration.SetListeners(ListenerType.FlushEntity,
                new IFlushEntityEventListener[] { new AuditFlushEntityEventListener() });

            _builtConfiguration.SetListeners(ListenerType.PreInsert,
                _builtConfiguration.EventListeners.PreInsertEventListeners.Concat<IPreInsertEventListener>(
                new IPreInsertEventListener[] { new ValidateEventListener(), new AuditEventListener() }).ToArray());

            _builtConfiguration.SetListeners(ListenerType.PreUpdate,
                _builtConfiguration.EventListeners.PreUpdateEventListeners.Concat<IPreUpdateEventListener>(
                new IPreUpdateEventListener[] { new ValidateEventListener(), new AuditEventListener() }).ToArray());

            #endregion
        }
Exemple #39
0
 public SqlQuery(DbProvider dbProvider)
     : this(new SqlBuilder(dbProvider))
 {
 }
 public LessThanEqualSqlCriteria(DbProvider dbProvider, string column) : base(dbProvider, column) { }
        public void DeletePlatform(List <string> ids)
        {
            var collection = DbProvider.Collection <Entity.Platform>();

            DbProvider.DeleteByIds <Entity.Platform>(ids);
        }
        public override string PassThroughSQL(DbProvider provider)
        {
            switch (provider)
            {
            case DbProvider.MSSQL:
                return(String.Format(
                           @"CREATE VIEW dbo.vwrpt02OrgBase

AS 

SELECT 
  MIN(O.OrgID) AS OrgID,
  O.OrgCODivision,
  (SELECT Abbrev FROM org02Tree D WHERE MAX(O.CategoryID)>={0} AND D.Continuum=O.OrgCODivision AND D.ValidTo IS NULL) AS OrgCapDivision,
  O.OrgCORegion,
  (SELECT Abbrev FROM org02Tree R WHERE MAX(O.CategoryID)>={1} AND R.Continuum=O.OrgCORegion AND R.ValidTo IS NULL) AS OrgCapRegion,
  O.OrgCOLocation,
  (SELECT ShortCap FROM org02Tree L WHERE MAX(O.CategoryID)>={2} AND L.Continuum=O.OrgCOLocation AND L.ValidTo IS NULL) AS OrgCapLocation,
  O.OrgCODepartment,
  (SELECT LongCap FROM org02Tree D WHERE MAX(O.CategoryID)>={3} AND D.Continuum=O.OrgCODepartment AND D.ValidTo IS NULL) AS OrgCapDepartment
FROM org02Tree O
WHERE O.CategoryID BETWEEN {0} AND {3}
AND O.ValidTo IS NULL
GROUP BY 
  O.OrgCODivision,
  O.OrgCORegion,
  O.OrgCOLocation,
  O.OrgCODepartment",
                           (int)orgcategories.oc_division,
                           (int)orgcategories.oc_region,
                           (int)orgcategories.oc_location,
                           (int)orgcategories.oc_department
                           ));

            case DbProvider.Oracle:
                return(String.Format(
                           @"CREATE OR REPLACE VIEW vwrpt02OrgBase

AS 

SELECT 
  MIN(O.OrgID) AS OrgID,
  O.OrgCODivision,
  (SELECT Abbrev FROM org02Tree D WHERE O.CategoryID>={0} AND D.Continuum=O.OrgCODivision AND D.ValidTo IS NULL) AS OrgCapDivision,
  O.OrgCORegion,
  (SELECT Abbrev FROM org02Tree R WHERE O.CategoryID>={1} AND R.Continuum=O.OrgCORegion AND R.ValidTo IS NULL) AS OrgCapRegion,
  O.OrgCOLocation,
  (SELECT ShortCap FROM org02Tree L WHERE O.CategoryID>={2} AND L.Continuum=O.OrgCOLocation AND L.ValidTo IS NULL) AS OrgCapLocation,
  O.OrgCODepartment,
  (SELECT LongCap FROM org02Tree D WHERE O.CategoryID>={3} AND D.Continuum=O.OrgCODepartment AND D.ValidTo IS NULL) AS OrgCapDepartment
FROM org02Tree O
WHERE O.CategoryID BETWEEN {0} AND {3}
AND O.ValidTo IS NULL
GROUP BY 
  O.CategoryID,
  O.OrgCODivision, 
  O.OrgCORegion, 
  O.OrgCOLocation, 
  O.OrgCODepartment",
                           (int)orgcategories.oc_division,
                           (int)orgcategories.oc_region,
                           (int)orgcategories.oc_location,
                           (int)orgcategories.oc_department
                           ));

            default:
                throw new NotSupportedException(provider.ToString());
            }
        }
 public DatabaseManager(DbProvider provider, string connectionString)
 {
     this.providerName = provider.GetDescription();
     this.connectionString = connectionString;
     this.connectionProvider = DbProviderFactories.GetFactory(providerName);
 }
Exemple #44
0
        protected override void ShowPage()
        {
            pagetitle = "编辑图片信息";

            #region 验证
            if (userid == -1)
            {
                AddErrLine("请先登录");
                return;
            }
            user = Users.GetUserInfo(userid);
            if (config.Enablealbum != 1)
            {
                AddErrLine("相册功能已被关闭");
                return;
            }
            if (photoid < 1)
            {
                AddErrLine("不存在的图片Id");
                return;
            }
            photo = DTOProvider.GetPhotoInfo(photoid, 0, 0);
            if (photo == null)
            {
                AddErrLine("图片不存在");
                return;
            }
            if (photo.Userid != userid)
            {
                AddErrLine("您没有编辑此图片的权限");
                return;
            }
            #endregion

            if (!DNTRequest.IsPost())
            {
                photo.Filename = Globals.GetThumbnailImage(photo.Filename);
                commentstatus  = (int)photo.Commentstatus;
                tagstatus      = (int)photo.Tagstatus;
                tags           = AlbumTags.GetTagsByPhotoId(photoid);
            }
            else
            {
                photo.Title       = DNTRequest.GetString("title");
                photo.Description = DNTRequest.GetString("description");

                if (commentstatus < 0 || commentstatus > 2)
                {
                    commentstatus = 2;
                }

                photo.Commentstatus = (PhotoStatus)commentstatus;

                string   newtags   = DNTRequest.GetString("phototag").Trim();
                string[] tagsArray = null;
                if (config.Enabletag == 1 && newtags != string.Empty && newtags != tags)
                {
                    tagsArray = Utils.SplitString(newtags, " ", true, 10);
                    if (tagsArray.Length > 0 && string.Join(" ", tagsArray) != tags)
                    {
                        DbProvider.GetInstance().DeletePhotoTags(photoid);
                        DbProvider.GetInstance().CreatePhotoTags(string.Join(" ", tagsArray), photoid, userid, Utils.GetDateTime());
                        AlbumTags.WritePhotoTagsCacheFile(photoid);
                    }
                }

                DTOProvider.UpdatePhotoInfo(photo);

                //生成json数据
                Albums.CreateAlbumJsonData(photo.Albumid);
                //生成图片标题
                Albums.CreatePhotoTitleImage(photo.Photoid, photo.Title);
                //生成用户名图片
                Albums.CreateUserImage(photo.Userid, photo.Username);

                AddMsgLine("图片信息修改成功, 将返回图片列表");
                SetUrl("usercpspacemanagephoto.aspx?albumid=" + photo.Albumid);
                SetMetaRefresh();
            }
        }
Exemple #45
0
        public NHUnitOfWorkFactory(
            DbProvider provider,
            string connectionString,
            string cacheProvider,
            Assembly[] mappingAssemblies)
        {
            NHUnitOfWorkFactory.dbProvider       = provider;
            NHUnitOfWorkFactory.connectionString = connectionString;

            FluentConfiguration cfg = null;

            switch (dbProvider)
            {
            case DbProvider.MsSqlProvider:
            {
                cfg = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008
                                                    .Raw("format_sql", "true")
                                                    .ConnectionString(connectionString))
                      .ExposeConfiguration(
                    c =>
                    c.Properties.Add(
                        Environment.SqlExceptionConverter,
                        typeof(SqlExceptionHandler).AssemblyQualifiedName))
                      .ExposeConfiguration(c => c.Properties.Add(Environment.DefaultSchema, "dbo"));

                break;
            }

            case DbProvider.SQLiteProvider:
            {
                cfg = Fluently.Configure().Database(SQLiteConfiguration.Standard
                                                    .Raw("format_sql", "true")
                                                    .ConnectionString(connectionString));

                inMemoryDatabase = connectionString.ToUpperInvariant().Contains(":MEMORY:");

                break;
            }

            case DbProvider.SqlCe:
            {
                cfg = Fluently.Configure().Database(MsSqlCeConfiguration.Standard
                                                    .Raw("format_sql", "true")
                                                    .ConnectionString(connectionString))
                      .ExposeConfiguration(
                    c =>
                    c.Properties.Add(
                        Environment.SqlExceptionConverter,
                        typeof(SqlExceptionHandler).AssemblyQualifiedName));

                validationSupported = false;

                break;
            }

            case DbProvider.Firebird:
            {
                cfg = Fluently.Configure().Database(new FirebirdConfiguration()
                                                    .Raw("format_sql", "true")
                                                    .ConnectionString(connectionString));

                break;
            }

            case DbProvider.PostgreSQLProvider:
            {
                cfg = Fluently.Configure().Database(PostgreSQLConfiguration.PostgreSQL82
                                                    .Raw("format_sql", "true")
                                                    .ConnectionString(connectionString));

                validationSupported = false;

                break;
            }
            }

            Guard.IsNotNull(
                cfg,
                string.Format(
                    "Db provider {0} is currently not supported.",
                    EnumExtensions.GetEnumMemberValue(dbProvider)));

            PropertyInfo pinfo = typeof(FluentConfiguration)
                                 .GetProperty(
                "Configuration",
                BindingFlags.Instance | BindingFlags.NonPublic);

            Configuration nhConfiguration = pinfo.GetValue(cfg, null) as Configuration;

            IoC.RegisterInstance <Configuration>(nhConfiguration);

            cfg.Mappings(m =>
            {
                m.FluentMappings.Conventions.AddAssembly(typeof(NHUnitOfWorkFactory).Assembly);
                foreach (Assembly mappingAssembly in mappingAssemblies)
                {
                    m.FluentMappings.Conventions.AddAssembly(mappingAssembly);
                }
            })
            .Mappings(m =>
            {
                m.FluentMappings.AddFromAssembly(typeof(NHUnitOfWorkFactory).Assembly);
                foreach (Assembly mappingAssembly in mappingAssemblies)
                {
                    m.FluentMappings.AddFromAssembly(mappingAssembly);
                }
            })
            .Mappings(m =>
            {
                m.HbmMappings.AddFromAssembly(typeof(NHUnitOfWorkFactory).Assembly);
                foreach (Assembly mappingAssembly in mappingAssemblies)
                {
                    m.HbmMappings.AddFromAssembly(mappingAssembly);
                }
            })
            .ExposeConfiguration(c => c.Properties.Add(Environment.BatchSize, "100"))
            .ExposeConfiguration(c => c.Properties.Add(Environment.UseProxyValidator, "true"));

            if (!string.IsNullOrEmpty(cacheProvider))
            {
                cfg.ExposeConfiguration(c => c.Properties.Add(Environment.CacheProvider, cacheProvider))
                .ExposeConfiguration(c => c.Properties.Add(Environment.UseSecondLevelCache, "true"))
                .ExposeConfiguration(c => c.Properties.Add(Environment.UseQueryCache, "true"));
            }

            NHUnitOfWorkFactory.builtConfiguration = cfg.BuildConfiguration();
            NHUnitOfWorkFactory.builtConfiguration.SetProperty(
                Environment.ProxyFactoryFactoryClass,
                typeof(DefaultProxyFactoryFactory).AssemblyQualifiedName);
        }
Exemple #46
0
        public async Task ClanInactives(CommandContext ctx,
                                        [Description("The clan **tag**")] string clanTag)
        {
            try
            {
                if (!await CanExecute(ctx, Features.Clans))
                {
                    return;
                }

                await ctx.TriggerTypingAsync();

                if (string.IsNullOrWhiteSpace(clanTag))
                {
                    await ctx.RespondAsync($"You must send a clan tag as parameter, {ctx.User.Mention}.");

                    return;
                }

                Log.Debug($"Requesting {nameof(ClanInactives)}({clanTag})...");

                var cfg      = GuildConfiguration.FromGuild(ctx.Guild);
                var platform = GetPlatform(clanTag, cfg.Plataform, out clanTag);

                clanTag = clanTag.Trim('[', ']');
                clanTag = clanTag.ToUpperInvariant();

                if (!ClanTagRegex.IsMatch(clanTag))
                {
                    await ctx.RespondAsync($"You must send a **valid** clan **tag** as parameter, {ctx.User.Mention}.");

                    return;
                }

                var provider = new DbProvider(_connectionString);

                var clan = provider.GetClan(platform, clanTag);
                if (clan == null)
                {
                    platform = platform == Platform.PS ? Platform.XBOX : Platform.PS;

                    clan = provider.GetClan(platform, clanTag);
                    if (clan == null)
                    {
                        await ctx.RespondAsync(
                            $"Can't find on a clan with tag `[{clanTag}]`, {ctx.User.Mention}. Maybe my site doesn't track it yet... or you have the wrong clan tag.");

                        return;
                    }
                }

                if (!clan.Enabled)
                {
                    await ctx.RespondAsync($"Data collection for this clan is **disabled**, the reason for this is {clan.DisabledReason}, {ctx.User.Mention}.");

                    return;
                }

                var inactives = clan.Players.Where(p => !p.IsActive).ToArray();
                if (inactives.Length <= 0)
                {
                    await ctx.RespondAsync($"There are no inactive tankers on this clan, {ctx.User.Mention}.");

                    return;
                }

                // To retrieve the last battle
                for (int i = 0; i < inactives.Length; i++)
                {
                    inactives[i] = provider.GetPlayer(inactives[i].Id, true);
                }

                inactives = inactives.OrderBy(p => p.MonthBattles).ThenBy(p => p.LastBattle ?? DateTime.Today.AddYears(-5)).ToArray();

                var sb = new StringBuilder();

                sb.Append($"Information about `{clan.ClanTag}`'s {inactives.Length} inactives tankers on the {clan.Plataform}, {ctx.User.Mention}:");
                sb.AppendLine();

                var maxNameLength = inactives.Max(p => p.Name.Length);

                sb.AppendLine("```");
                sb.AppendLine($"{platform.TagName().PadRight(maxNameLength)} {"Days".PadLeft(5)} {"Battles".PadLeft(7)} {"WN8".PadLeft(6)}");
                foreach (var p in inactives.Take(30))
                {
                    sb.AppendLine($"{(p.Name ?? string.Empty).PadRight(maxNameLength)} {(DateTime.UtcNow - (p.LastBattle ?? DateTime.Today.AddYears(-5))).TotalDays.ToString("N0").PadLeft(5)} {p.MonthBattles.ToString("N0").PadLeft(7)} {p.TotalWn8.ToString("N0").PadLeft(6)}");
                }
                sb.AppendLine("```");

                var color          = clan.InactivesWn8.ToColor();
                var platformPrefix = clan.Plataform == Platform.PS ? "ps." : string.Empty;

                var embed = new DiscordEmbedBuilder
                {
                    Title       = $"{clan.ClanTag}'s Inactives Tankers",
                    Description = sb.ToString(),
                    Color       = new DiscordColor(color.R, color.G, color.B),
                    Url         = $"https://{platformPrefix}wotclans.com.br/Clan/{clan.ClanTag}",
                    Author      = new DiscordEmbedBuilder.EmbedAuthor
                    {
                        Name = "WoTClans",
                        Url  = $"https://{platformPrefix}wotclans.com.br"
                    },
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = $"Calculated at {DateTime.UtcNow:yyyy-MM-dd HH:mm} UTC"
                    }
                };

                await ctx.RespondAsync("", embed : embed);
            }
            catch (Exception ex)
            {
                Log.Error($"Error calling {nameof(ClanInactives)}({clanTag})", ex);
                await ctx.RespondAsync(
                    $"Sorry, {ctx.User.Mention}. There was an error... the *Coder* will be notified of `{ex.Message}`.");
            }
        }
Exemple #47
0
 public Connection(DbProvider provider)
 {
     _oriConnection = provider.CreateConnection();
     _transactions = new List<Transaction>();
     this.Status = ConnectionStatus.Initialized;
 }
 public WeatherForecastRepository()
 {
     _dbProvider = new DbProvider();
 }
 public void Down(DbProvider db)
 {
     db.DropTable("ACCOUNTS");
 }
Exemple #50
0
        public virtual ISqlParam ToList(int top = 0, bool isDistinct = false, bool isRand = false)
        {
            var strSelectSql   = SelectVisitor.Visit(ExpBuilder.ExpSelect);
            var strWhereSql    = WhereVisitor.Visit(ExpBuilder.ExpWhere);
            var strOrderBySql  = OrderByVisitor.Visit(ExpBuilder.ExpOrderBy);
            var strTopSql      = top > 0 ? string.Format("TOP {0} ", top) : string.Empty;
            var strDistinctSql = isDistinct ? "Distinct " : string.Empty;

            if (!string.IsNullOrWhiteSpace(strWhereSql))
            {
                strWhereSql = "WHERE " + strWhereSql;
            }
            if (!string.IsNullOrWhiteSpace(strOrderBySql))
            {
                strOrderBySql = "ORDER BY " + strOrderBySql;
            }

            if (!isRand)
            {
                Sql.AppendFormat("SELECT {0}{1}{2} FROM {3} {4} {5}", strDistinctSql, strTopSql, strSelectSql, DbProvider.KeywordAegis(Name), strWhereSql, strOrderBySql);
            }
            else if (string.IsNullOrWhiteSpace(strOrderBySql))
            {
                Sql.AppendFormat("SELECT {0}{1}{2}{5} FROM {3} {4} ORDER BY NEWID()", strDistinctSql, strTopSql, strSelectSql, DbProvider.KeywordAegis(Name), strWhereSql, isDistinct ? ",NEWID() as newid" : "");
            }
            else
            {
                Sql.AppendFormat("SELECT {2} FROM (SELECT {0} {1} *{6} FROM {3} {4} ORDER BY NEWID()) a {5}", strDistinctSql, strTopSql, strSelectSql, DbProvider.KeywordAegis(Name), strWhereSql, strOrderBySql, isDistinct ? ",NEWID() as newid" : "");
            }
            return(this);
        }
Exemple #51
0
        protected void btnExcel_Click(object sender, EventArgs e)
        {
            int    locationId = 0;
            int    perPage    = 0;
            int    shefId     = 0;
            string strKey     = string.Empty;
            string strUPC     = string.Empty;
            string image      = string.Empty;

            locationId = Convert.ToInt32(Request.QueryString["loc"]);
            shefId     = Convert.ToInt32(Request.QueryString["shefId"]);
            strKey     = Request.QueryString["strKey"];

            perPage = Convert.ToInt32(Request.QueryString["perPage"]);
            DataSet dsProductList = new DataSet();
            double  price         = 0;
            double  preprice      = 0;
            double  buyprice      = 0;

            dsProductList = dbListInfo.GetProductListDeatils1(locationId, shefId, strKey);
            DataTable dt1         = dsProductList.Tables[0];
            string    strFileName = "/ProductDetail.csv";
            // CreateCSVFile(dt1,strFileName);

            HttpContext context = HttpContext.Current;

            context.Response.Clear();
            context.Response.ContentType = "text/csv";
            context.Response.AddHeader("content-disposition", "attachment;filename=" + strFileName);
            //StreamWriter sw = new StreamWriter(strFilePath, false);
            //Response.AddHeader("content-disposition", "attachment;filename=" + strFileName);

            if (dsProductList.Tables.Count > 0)
            {
                if (dsProductList != null && dsProductList.Tables.Count > 0 && dsProductList.Tables[0].Rows.Count > 0)
                {
                    DbProvider dbGetCompanyName = new DbProvider();
                    DataSet    dsGetCompanyName = new DataSet();
                    dsGetCompanyName = dbGetCompanyName.getShortCompanyName();

                    if (dsGetCompanyName.Tables.Count > 0)
                    {
                        if (dsGetCompanyName != null && dsGetCompanyName.Tables.Count > 0 && dsGetCompanyName.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow dtrow in dsGetCompanyName.Tables[0].Rows)
                            {
                                Page.Header.Title = Convert.ToString(dtrow["CompanyShortName"]) + AppConstants.shoppingListPageTitle;
                            }
                        }
                    }


                    if (dsProductList.Tables.Count > 0)
                    {
                        string enxportstr = string.Empty;


                        int iColCount = dt1.Columns.Count;


                        for (int i = 0; i <= dt1.Columns.Count - 1; i++)
                        {
                            context.Response.Write(dt1.Columns[i]);

                            if (i < iColCount - 1)
                            {
                                context.Response.Write(",");
                            }
                        }

                        context.Response.Write(Environment.NewLine);



                        //now we want to write the columns headers of the table
                        //for (int i = 0; i <= dt1.Columns.Count - 1; i++)
                        //{
                        //    if (i < 0)
                        //    {
                        //        //adding comma in between columns...
                        //        context.Response.Write(",");
                        //    }
                        //    context.Response.Write(dt1.Columns[i].ColumnName);
                        //}


                        //context.Response.Write(Environment.NewLine);

                        //Write data into context

                        foreach (DataRow dr in dt1.Rows)
                        {
                            for (int i = 0; i < iColCount; i++)
                            {
                                if (!Convert.IsDBNull(dr[i]))
                                {
                                    context.Response.Write(dr[i].ToString().Replace(",", ";"));
                                }

                                if (i < iColCount - 1)
                                {
                                    context.Response.Write(",");
                                }
                            }

                            context.Response.Write(Environment.NewLine);
                        }
                        context.Response.End();



                        //foreach (DataRow row in dt1.Rows)
                        //{
                        //    //  here we are again going into loop because we want "comma" in between columns
                        //    for (int i = 0; i <= dt1.Columns.Count - 1; i++)
                        //    {
                        //        if (i < 0)
                        //        {
                        //            context.Response.Write(",");
                        //        }
                        //        context.Response.Write(row[i]);
                        //    }
                        //    context.Response.Write(Environment.NewLine);
                        //}
                        //context.Response.End();
                    }

                    lblMsg.Text = "File export";
                }
            }
        }
Exemple #52
0
 /// <summary>
 /// 创建数据库事务
 /// </summary>
 /// <returns></returns>
 internal IDbTransactionContext CreateTransaction()
 {
     return(DbProvider.CreateTransaction(this) ?? throw new NotSupportedException());
 }
Exemple #53
0
 public Database(DbProvider dbProvider)
     : this()
 {
     this.dbProvider = dbProvider;
 }
Exemple #54
0
 /// <summary>
 /// 获取查询执行器
 /// </summary>
 /// <returns></returns>
 public IDbExecutor GetExecutor()
 {
     return(DbProvider.GetDbExecutor(this));
 }
Exemple #55
0
 public NotEqualSqlCriteria(DbProvider dbProvider, string column) : base(dbProvider, column) { }
Exemple #56
0
 /// <summary>
 /// 获取异步查询执行器
 /// </summary>
 /// <returns></returns>
 public IAsyncDbExecutor GetAsyncExecutor()
 {
     return(DbProvider.GetAsyncDbExecutor(this));
 }
Exemple #57
0
 public void Dispose()
 {
     DbProvider.Dispose();
 }
 public SqlLiteStatementFactory(DbProvider dbProvider) : base(dbProvider)
 {
 }
Exemple #59
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="dbProvider">The DBPrivider which should be used</param>
 /// <param name="connectionStr">The ConnectionString to the Database</param>
 public TaskForceDB(DbProvider dbProvider, string connectionStr)
     : base(dbProvider, connectionStr)
 {
 }
 public GreaterThanEqualSqlCriteria(DbProvider dbProvider, string column) : base(dbProvider, column)
 {
 }