public async Task Pick(CommandContext ctx,
                               [RemainingText, Description("Person you want to pick.")]
                               DiscordMember pick)
        {
            try
            {
                Set playerMatch = Matchmaker.Sets.FirstOrDefault(e => e.GetPickingTeam().IsCaptain(ctx.Message.Author.Id));

                Logger.Warn(string.Join(",", Matchmaker.Sets[0].BravoTeam.Players.Select(x => x.Nickname)));

                if (playerMatch == null || !CommandHelper.SetChannelIds.Contains(ctx.Channel.Id))
                {
                    return;
                }

                SdlPlayer sdlPlayer = await MySqlClient.RetrieveSdlPlayer(pick.Id);

                await PickPlayer(playerMatch, sdlPlayer, ctx.Channel);
            }
            catch (Exception e)
            {
                Logger.Error(e);
                throw;
            }
        }
예제 #2
0
 internal void Awake()
 {
     Client      = new DiscordSocketClient();
     MySqlClient = new MySqlClient(EnvManager.Server, EnvManager.Database, EnvManager.Table, EnvManager.UserId, EnvManager.Password);
     RoleMonitor = new RoleMonitor(MySqlClient);
     UserMonitor = new UserMonitor(MySqlClient);
 }
예제 #3
0
        public async Task SetRole(CommandContext ctx,
                                  [Description("One of four options: front, mid, back, flex.")]
                                  string role)
        {
            role = role[0].ToString().ToUpper() + string.Join(string.Empty, role.Skip(1));

            SdlPlayer player;

            try
            {
                player = await MySqlClient.RetrieveSdlPlayer(ctx.User.Id);
            }
            catch (SdlMySqlException e)
            {
                /*await e.OutputToDiscordUser(ctx);*/
                throw;
            }

            if (role == "Front" || role == "Back" || role == "Mid" || role == "Flex")
            {
                // TODO roleNum parameter
                await MySqlClient.SetRoleAsync(player, role, 1);
            }
            else
            {
                await ctx.RespondAsync("You must specify Front, Flex, Mid, or Back!");

                return;
            }

            await ctx.RespondAsync($"Your role has been set to {role}.");
        }
예제 #4
0
        public async Task FriendCode(CommandContext ctx,
                                     [Description("Friend code in the format 0000-0000-0000 or SW-0000-0000-0000")]
                                     string code)
        {
            code = code.Replace("SW-", string.Empty);

            if (code.Split('-').Length != 3 || code.Split('-').Any(e => !int.TryParse(e, out int _) || e.Length != 4))
            {
                await ctx.RespondAsync("Please use the format 0000-0000-0000!");

                return;
            }

            SdlPlayer player;

            try
            {
                player = await MySqlClient.RetrieveSdlPlayer(ctx.User.Id);
            }
            catch (SdlMySqlException e)
            {
                /*await e.OutputToDiscordUser(ctx);*/
                throw;
            }

            await MySqlClient.SetFriendCodeAsync(player, code);

            await ctx.RespondAsync($"Set your friend code to {code}!");
        }
예제 #5
0
        public bool mysql_init()
        {
            st          = new Settings();
            mysqlClient = new MySqlClient(
                st.db_host,
                st.db_port,
                st.db_username,
                st.db_password,
                st.db_database
                );

            bool is_true = mysqlClient.Test_Connection();

            if (!is_true)
            {
                Console.WriteLine("MySQL connection is incorrect.");
                return(false);
            }

            Console.WriteLine("MySQL connection is good.");
            mysqlQuery = new MySqlQuery(mysqlClient);
            myRequest  = new Request(mysqlClient, st.api_webhook, st.api_access_token);
            myRequest.Start();
            return(true);
        }
예제 #6
0
		public static void Main(string[] args)
		{
			if (args.Length < 2) {
				Console.WriteLine("<database> <tablename>");
				return;
			}

			var loop = Loop.Default;

			MySqlClient client = new MySqlClient(loop);
			
			client.IPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3306);
			client.Username = "******";
			client.Password = "";

			client.Connect()
				.OnError((error) => {
					Console.WriteLine(error.Message);
					client.Disconnect();
				});

			client.Query(string.Format("use {0}", args[0]));
			Query(client, args[0], args[1]);

			loop.Run();
		}
예제 #7
0
        /// <summary>
        /// For SelfTest, the user's QfRuntimeConnection will be called by the generated code. We still need the provider
        /// </summary>
        /// <param name="connection">Must be open</param>
        /// <param name="provider">Must be a built-in provider. No DI for self-test.</param>
        /// <param name="Query">The query text</param>
        /// <returns></returns>
        public List <ResultFieldDetails> GetFields(IDbConnection connection, string provider, string Query)
        {
            // how do I be registering with tiny inside someone else's program ?
            IProvider prov = null;

            switch (provider)
            {
            case "System.Data.SqlClient":
                prov = new SqlClient();
                break;

            case "Npgsql":
                prov = new Providers.Npgsql();
                break;

            case "MySql.Data.MySqlClient":
                prov = new MySqlClient();
                break;
            }
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
            return(GetFields(connection, prov, Query));
        }
예제 #8
0
        public bool mysql_init()
        {
            string guid = Guid.NewGuid().ToString();

            lblLabelStatus.Text = "Service connecting...";
            st          = new Settings();
            mysqlClient = new MySqlClient(
                st.db_host,
                st.db_port,
                st.db_username,
                st.db_password,
                st.db_database
                );

            bool is_true = mysqlClient.Test_Connection();

            if (!is_true)
            {
                Console.WriteLine("Service connection is incorrect.");
                lblLabelStatus.Text = "Service connection is incorrect.";
                return(false);
            }

            Console.WriteLine("Service connection is good.");
            lblLabelStatus.Text     = "Service Looks Good.";
            mysqlQuery              = new MySqlQuery(mysqlClient);
            myRequest               = new Request(mysqlClient, st.api_webhook, st.api_access_token);
            myRequest.Status_Event += new Request.StatusEventHandler(Status_Logs);
            myRequest.Start();
            return(true);
        }
예제 #9
0
        public static string GenerateDetailOrderID()
        {
            mutex.WaitOne();
            string detailId = default(string);

            _count++;
            string sql = "SELECT Max(DetailID) FROM DetailedOrder";

            if (mySqlclient == null)
            {
                mySqlclient = MySqlClient.GetMySqlClient();
            }
            detailId = mySqlclient.ExecuteScalar(sql, null) as string;
            if (detailId == null)
            {
                detailId = "DP" + DateTime.Now.ToString("yyyyMMdd") + _count.ToString("0000");
            }
            else
            {
                string temp = detailId.Substring(2, 8);
                string comp = DateTime.Today.Date.ToString("yyyyMMdd");
                if (temp.Equals(comp))
                {
                    string tmp = detailId.Substring(2);
                    detailId = "DP" + (Convert.ToInt64(tmp) + _count);
                }
                else
                {
                    detailId = "DP" + DateTime.Now.ToString("yyyyMMdd") + _count.ToString("00000");
                }
            }
            mutex.ReleaseMutex();
            return(detailId);
        }
예제 #10
0
        public async Task <ApiUser> Authenticate(string username, string password)
        {
            ApiUser[] users = await MySqlClient.GetApiUsers();

            ApiUser user = users.SingleOrDefault(x => x.UserName == username && x.PasswordHash == password);

            // return null if user not found
            if (user == null)
            {
                return(null);
            }

            // authentication successful so generate jwt token
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

            byte[] key = Encoding.ASCII.GetBytes(this.appSettings.Secret);
            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, user.Id)
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);

            user.Token = tokenHandler.WriteToken(token);

            return(user);
        }
예제 #11
0
        public static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("<database> <tablename>");
                return;
            }

            var loop = Loop.Default;

            MySqlClient client = new MySqlClient(loop);

            client.IPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3306);
            client.Username   = "******";
            client.Password   = "";

            client.Connect()
            .OnError((error) => {
                Console.WriteLine(error.Message);
                client.Disconnect();
            });

            client.Query(string.Format("use {0}", args[0]));
            Query(client, args[0], args[1]);

            loop.Run();
        }
        public static async Task <decimal> ReportScores(Set playerSet, bool forgiveLosing = false)
        {
            decimal points = CalculatePoints(playerSet);

            if (forgiveLosing)
            {
                DiscordMessage feedMessage = await(await Program.Client.GetGuildAsync(570743985530863649))
                                             .GetChannel(666563839646760960).GetMessageAsync(OrderedFeedMessages[playerSet.SetNumber - 1]);
                await feedMessage.ModifyAsync(embed : playerSet.GetFeedEmbedBuilder(null)
                                              .WithDescription("The set ended unnaturally.").Build());
            }

            //TimePeriod happyPeriod = new TimePeriod(TimeSpan.Parse("20:00"), TimeSpan.Parse("21:00"));
            //TimePeriod halfPeriod = new TimePeriod(TimeSpan.Parse("1:00"), TimeSpan.Parse("2:00"));

            if (forgiveLosing)
            {
                await MySqlClient.ReportScores(playerSet, points, 0);
            }
            //else if (happyPeriod.IsWithinPeriod(playerSet.StartTime.GetValueOrDefault()) ||
            //         halfPeriod.IsWithinPeriod(playerSet.StartTime.GetValueOrDefault()))
            //{
            //    await AirTableClient.ReportScores(playerSet, points, points / 2);
            //}
            else
            {
                await MySqlClient.ReportScores(playerSet, points, points);
            }

            await Program.UpdateStandingsAsync();

            return(points);
        }
예제 #13
0
        private bool ViewTx(string txid)
        {
            DataTable dt, dttx;

            using (var sqlc = new MySqlClient(SiaClassicLib.Config.ConnectionString))
            {
                dt   = sqlc.FillTable($"SELECT value,unlockhash FROM siacoinoutputs WHERE tx_id='{txid}'");
                dttx = sqlc.FillTable($"SELECT height,timestamp FROM txs JOIN blocks on height=blockheight WHERE txs.id='{txid}'");
            }
            if (dttx.Rows.Count == 0)
            {
                return(false);
            }

            dttx.AddTimeColumn("time", "timestamp");
            var height = dttx.Rows[0]["height"].ToString();

            TxViewPanel.Visible       = true;
            TxViewListView.DataSource = dt;
            TxViewListView.DataBind();
            TxViewIdLabel.Text = txid;
            TxViewHeightHyperLink.NavigateUrl = $"/Default?block={height}";
            TxViewHeightHyperLink.Text        = "Block " + height;
            TxViewTimeLabel.Text = dttx.Rows[0]["time"].ToString();
            return(true);
        }
예제 #14
0
        public async Task ForceRegister(CommandContext ctx, DiscordMember player, int startingPower, [RemainingText] string nickname)
        {
            try
            {
                if ((await MySqlClient.RetrieveAllSdlPlayers()).Any(x => x.DiscordId == player.Id))
                {
                    await ctx.RespondAsync("This player is already in the database and cannot be force registered.");

                    return;
                }

                await MySqlClient.RegisterPlayer(player.Id, startingPower, nickname);
            }
            catch (Exception e)
            {
                await ctx.RespondAsync($"Failed to force register user.\nException: {e}");
            }

            DiscordChannel registeredChannel = await ctx.Client.GetChannelAsync(588806681303973931);

            await registeredChannel.SendMessageAsync($"Manually registered {player.Mention} " +
                                                     $"with a starting power of {startingPower} " +
                                                     $"and the nickname `{nickname}`.");

            await ctx.RespondAsync("Successfully force registered user.");
        }
예제 #15
0
        public IQueryAdapter GetQueryReactor()
        {
            IDatabaseClient databaseClient = new MySqlClient(this);

            databaseClient.Connect();

            return(databaseClient.GetQueryReactor());
        }
예제 #16
0
        public IQueryAdapter GetQueryReactor()
        {
            IDatabaseClient databaseClient = new MySqlClient(this);

            databaseClient.Connect();

            return databaseClient.GetQueryReactor();
        }
        public async Task PickFor(CommandContext ctx, int setNumber, DiscordMember pick)
        {
            Set playerMatch = Matchmaker.Sets[setNumber - 1];

            SdlPlayer sdlPlayer = await MySqlClient.RetrieveSdlPlayer(pick.Id);

            await PickPlayer(playerMatch, sdlPlayer, ctx.Channel);
        }
        public async Task DistributeRoles(CommandContext ctx)
        {
            DiscordRole classOneRole   = ctx.Guild.GetRole(600770643075661824);
            DiscordRole classTwoRole   = ctx.Guild.GetRole(600770814521901076);
            DiscordRole classThreeRole = ctx.Guild.GetRole(600770862307606542);
            DiscordRole classFourRole  = ctx.Guild.GetRole(600770905282576406);

            foreach (SdlPlayer sdlPlayer in await MySqlClient.RetrieveAllSdlPlayers())
            {
                try
                {
                    DiscordMember sdlGuildUser = await ctx.Guild.GetMemberAsync(sdlPlayer.DiscordId);

                    switch (Matchmaker.GetClass(sdlPlayer.PowerLevel))
                    {
                    case SdlClass.Zero:
                        break;

                    case SdlClass.One:
                        if (sdlGuildUser.Roles.All(e => e.Id != classOneRole.Id))
                        {
                            await sdlGuildUser.GrantRoleAsync(classOneRole);
                        }
                        break;

                    case SdlClass.Two:
                        if (sdlGuildUser.Roles.All(e => e.Id != classTwoRole.Id))
                        {
                            await sdlGuildUser.GrantRoleAsync(classTwoRole);
                        }
                        break;

                    case SdlClass.Three:
                        if (sdlGuildUser.Roles.All(e => e.Id != classThreeRole.Id))
                        {
                            await sdlGuildUser.GrantRoleAsync(classThreeRole);
                        }
                        break;

                    case SdlClass.Four:
                        if (sdlGuildUser.Roles.All(e => e.Id != classFourRole.Id))
                        {
                            await sdlGuildUser.GrantRoleAsync(classFourRole);
                        }
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            await ctx.RespondAsync("I'm Sam, the dancing Matzo man. Making Matzos fast I can. I'm Sam the dancing Matzo man.");
        }
예제 #19
0
        public static void CreateMediaStoreAssembly(MediaStoreSystem system, string suffix)
        {
            var webForm = new WebForm()
            {
                Name = "WebForm" + suffix
            };
            var audioStore = new AudioStore()
            {
                Name = "AudioStore" + suffix
            };
            var encodingadapter = new EncodingAdapter()
            {
                Name = "EncodingAdapter" + suffix
            };
            var encoder = new OggEncoder()
            {
                Name = "OggEncoder" + suffix
            };
            var userMgmt = new UserManagement()
            {
                Name = "UserManagement" + suffix
            };
            var dbAdapter = new DBAdapter()
            {
                Name = "DBAdapter" + suffix
            };
            var mySqlClient = new MySqlClient()
            {
                Name = "MySqlClient" + suffix
            };

            system.AssemblyContexts.Add(webForm);
            system.AssemblyContexts.Add(audioStore);
            system.AssemblyContexts.Add(userMgmt);
            system.AssemblyContexts.Add(encodingadapter);
            system.AssemblyContexts.Add(encoder);
            system.AssemblyContexts.Add(dbAdapter);
            system.AssemblyContexts.Add(mySqlClient);

            webForm.Application = audioStore;

            audioStore.UserManagement = userMgmt;
            audioStore.AudioDB        = encodingadapter;

            userMgmt.Database = dbAdapter;

            encodingadapter.Encoder  = encoder;
            encodingadapter.Database = dbAdapter;

            dbAdapter.Command    = mySqlClient;
            dbAdapter.Connection = mySqlClient;
            dbAdapter.DataReader = mySqlClient;

            system.Frontend = webForm;
        }
        public static async Task UpdateStandingsAsync()
        {
            DiscordChannel standingChannel = await Client.GetChannelAsync(592230066654674945);

            foreach (DiscordMessage discordMessage in await standingChannel.GetMessagesAsync())
            {
                await standingChannel.DeleteMessageAsync(discordMessage, "Standings update.");
            }

            SdlPlayer[] players = await MySqlClient.RetrieveAllSdlPlayers();

            List <SdlPlayer> orderedPlayers = players
                                              .Where(x => standingChannel.Guild.Members.Any(y =>
                                                                                            y.Id == x.DiscordId &&
                                                                                            MySqlClient.CheckHasPlayedSet(x).Result&&
                                                                                            y.Roles.Any(z =>
                                                                                                        z.Name.Equals("player", StringComparison.InvariantCultureIgnoreCase))))
                                              .OrderByDescending(x => x.PowerLevel).ToList();

            var playerStandings = orderedPlayers.Select(x => new { Player = x, Rank = orderedPlayers.FindLastIndex(y => y.PowerLevel == x.PowerLevel) + 1 });

            List <DiscordEmbedBuilder> standingEmbeds = new List <DiscordEmbedBuilder>
            {
                new DiscordEmbedBuilder().WithDescription("").WithColor(Color.Gold)
            };

            int startStanding = 1;
            int endStanding   = 0;

            foreach (var playerStanding in playerStandings)
            {
                string standingLine = $"\n{playerStanding.Rank}: {playerStanding.Player.DiscordId.ToUserMention()} [{playerStanding.Player.PowerLevel}]";

                if (standingEmbeds.Last().Description.Length + standingLine.Length > 2048)
                {
                    standingEmbeds.Last().Title = $"Standings ({startStanding} - {endStanding})";

                    standingEmbeds.Add(new DiscordEmbedBuilder().WithDescription("").WithColor(Color.Silver));

                    startStanding = endStanding + 1;
                    endStanding   = startStanding;
                }

                standingEmbeds.Last().Description += standingLine;

                endStanding++;
            }

            standingEmbeds.Last().Title = $"Standings ({startStanding} - {endStanding})";

            foreach (DiscordEmbedBuilder standingEmbed in standingEmbeds)
            {
                await standingChannel.SendMessageAsync(embed : standingEmbed.Build());
            }
        }
 private static async Task Commands_CommandExecuted(CommandExecutionEventArgs e)
 {
     try
     {
         if (!MySqlClient.IsConnectionOpen())
         {
             await MySqlClient.RefreshConnectionAsync();
         }
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception);
         await e.Context.RespondAsync("<@&572539082039885839> Unable to refresh MySQL connection!");
     }
 }
        public async Task Stage(CommandContext ctx)
        {
            try
            {
                Stage[] stages = await MySqlClient.GetMapList();

                Stage selectedStage = stages[Globals.Random.Next(0, stages.Length - 1)];

                await ctx.RespondAsync(embed : selectedStage.GetEmbedBuilder().Build());
            }
            catch (Exception e)
            {
                Logger.Error(e);
                throw;
            }
        }
예제 #23
0
        private void UpdateAtHeight(MySqlClient sqlc, int height)
        {
            Console.WriteLine(DateTime.Now + " Updating at height=" + height);

            dynamic b = wc.GetObject("consensus/blocks?height=" + height);

            // ONLY outputs NOW
            string sql = string.Empty;

            //var minerpayouts = "0";
            //using (var h = new Hastings())
            //{
            //    if (b.minerpayouts != null)
            //        foreach (var v in b.minerpayouts)
            //            h.Add(v.value.Value);
            //    minerpayouts = h.ToString();
            //}

            //var sql = $"INSERT INTO `blocks` VALUES('{b.height}', '{b.id}', '{b.parentid}', '{b.timestamp}', " +
            //    $"'{minerpayouts}', '{b.transactions.Count}');\n"
            //    ;

            foreach (dynamic tx in b.transactions)
            {
                //sql += $"INSERT INTO `txs` VALUES('{tx.id}', '{b.height}', '{tx.siacoininputs.Count}','{tx.siacoinoutputs.Count}'," +
                //    $" '{tx.filecontracts.Count}','{tx.filecontractrevisions.Count}','{tx.storageproofs.Count}','{tx.siafundinputs.Count}'," +
                //    $" '{tx.siafundoutputs.Count}','{tx.minerfees.Count}','{tx.arbitrarydata.Count}','{tx.transactionsignatures.Count}');\n";

                foreach (dynamic output in tx.siacoinoutputs)
                {
                    //using (var h = new Hastings())
                    //{
                    //    h.Add(output.value.Value);
                    //    sql += $"INSERT INTO `siacoinoutputs` VALUES('{output.id}', '{b.height}', '{tx.id}', '{h.ToString()}', '{output.unlockhash}');\n";
                    //}
                    sql += $"UPDATE siacoinoutputs SET unlockhash='{output.unlockhash}' WHERE id='{output.id}';\n";
                }
            }

            //sqlc.ExecuteNonQuery($"START TRANSACTION;\n{sql}COMMIT;");
            if (sql.Length > 0)
            {
                sqlc.ExecuteNonQuery(sql);
            }
        }
        private static async Task Commands_CommandErrored(CommandErrorEventArgs e)
        {
            try
            {
                if (!MySqlClient.IsConnectionOpen())
                {
                    await MySqlClient.RefreshConnectionAsync();

                    await e.Context.RespondAsync("The MySQL connection is being refreshed. " +
                                                 "Please wait around a minute before attempting the command again.");
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                await e.Context.RespondAsync("<@&572539082039885839> Unable to refresh MySQL connection!");
            }
        }
예제 #25
0
        private void InsertAtHeight(MySqlClient sqlc, int height)
        {
            Console.WriteLine(DateTime.Now + " Writing block height=" + height);

            dynamic b = wc.GetObject("consensus/blocks?height=" + height);

            var minerpayouts = "0";

            using (var h = new Hastings())
            {
                if (b.minerpayouts != null)
                {
                    foreach (var v in b.minerpayouts)
                    {
                        h.Add(v.value.Value);
                    }
                }
                minerpayouts = h.ToString();
            }

            var sql = $"INSERT INTO `blocks` VALUES('{b.height}', '{b.id}', '{b.parentid}', '{b.timestamp}', " +
                      $"'{minerpayouts}', '{b.transactions.Count}');\n"
            ;

            foreach (dynamic tx in b.transactions)
            {
                sql += $"INSERT INTO `txs` VALUES('{tx.id}', '{b.height}', '{tx.siacoininputs.Count}','{tx.siacoinoutputs.Count}'," +
                       $" '{tx.filecontracts.Count}','{tx.filecontractrevisions.Count}','{tx.storageproofs.Count}','{tx.siafundinputs.Count}'," +
                       $" '{tx.siafundoutputs.Count}','{tx.minerfees.Count}','{tx.arbitrarydata.Count}','{tx.transactionsignatures.Count}');\n";

                foreach (dynamic output in tx.siacoinoutputs)
                {
                    using (var h = new Hastings())
                    {
                        h.Add(output.value.Value);
                        sql += $"INSERT INTO `siacoinoutputs` VALUES('{output.id}', '{b.height}', '{tx.id}', '{h.ToString()}', '{output.unlockhash}');\n";
                    }
                }
            }

            //sqlc.ExecuteNonQuery($"START TRANSACTION;\n{sql}COMMIT;");
            sqlc.ExecuteNonQuery(sql);
        }
예제 #26
0
        public Request(MySqlClient mysqlClient, string api_webhook, string api_access_token)
        {
            mysqlQuery = new MySqlQuery(mysqlClient);

            notification = new Notification(mysqlClient);

            thread_command = new Thread(process_sms_commmand);

            thread_sms = new Thread(process_sms);

            //thread_wallet = new Thread(monitor_wallet);

            Json.ApiUrl = api_webhook;

            Json.AccessToken = api_access_token;

            Die = false;

            KeepAlive = false;
        }
예제 #27
0
 public void UpdateOutput(int heightStart = 180000, int heightEnd = 212578)
 {
     try
     {
         using (var sqlc = new MySqlClient(connStr))
             for (int height = heightStart; height <= heightEnd; ++height)
             {
                 if (Console.KeyAvailable && Console.ReadKey().KeyChar == 27)
                 {
                     break;
                 }
                 UpdateAtHeight(sqlc, height);
             }
     }
     catch (Exception x)
     {
         Console.WriteLine(x.Message);
         Console.WriteLine(x.StackTrace);
     }
 }
예제 #28
0
        public async Task Penalty(CommandContext ctx, DiscordMember user, int amount, [RemainingText] string notes)
        {
            try
            {
                if (amount <= 0)
                {
                    await ctx.RespondAsync("Amount should be greater than zero.");

                    return;
                }

                await MySqlClient.PenalizePlayer(await MySqlClient.RetrieveSdlPlayer(user.Id), amount, notes);
            }
            catch (Exception e)
            {
                Logger.Error(e);
                throw;
            }

            await ctx.RespondAsync($"Penalized {user.Mention} {amount} points.");
        }
예제 #29
0
        private bool ViewBlockList(int offset)
        {
            DataTable dt;

            using (var sqlc = new MySqlClient(SiaClassicLib.Config.ConnectionString))
            {
                dt = sqlc.FillTable($"SELECT height,timestamp,minerpayouts,tx_count FROM blocks ORDER BY height DESC LIMIT {offset},20");
            }
            if (dt.Rows.Count == 0)
            {
                return(false);
            }

            dt.AddTimeColumn("time", "timestamp");

            BlockListPanel.Visible   = true;
            BlockListView.DataSource = dt;
            BlockListView.DataBind();
            BlockListOffsetLabel.Text = offset.ToString();
            return(true);
        }
예제 #30
0
        public static string GenerateStaffID()
        {
            mutex.WaitOne();
            string staffId = default(string);
            Random ran     = new Random();

            staffId = "S" + DateTime.Now.ToString("yyyyMMdd") + ran.Next(100, 999).ToString();
            string sql = "SELECT Count(StaffId) FROM StaffInfo Where StaffId='" + staffId + "'";

            if (mySqlclient == null)
            {
                mySqlclient = MySqlClient.GetMySqlClient();
            }
            int count = Convert.ToInt32(mySqlclient.ExecuteScalar(sql, null));

            if (count > 0)
            {
                GenerateStaffID();
            }
            mutex.ReleaseMutex();
            return(staffId);
        }
예제 #31
0
        private static void DataAccessTest()
        {
            //SqlClient client = new SqlClient("SqlServerConnectionStr");

            //IList<ISort> sortRules = new List<ISort> { new Sort { PropertyName = "IMUMemberId", Ascending = true } };

            //string sql = "SELECT IMUId,IMUMemberId FROM IMUserInfo WITH(NOLOCK) WHERE IMUId<@IMUId";
            //List<IMUserInfo> ressult = client.QueryByPage<IMUserInfo>(sql, 0, 10, new { IMUId = 3 }, sortRules);
            //IMUserInfo entity = client.GetEntityById<IMUserInfo>(3);

            BaseClient myClient = new MySqlClient("MySqlConnectionStr");
            //IList<ISort> mySortRules = new List<ISort> { new Sort { PropertyName = "Id", Ascending = false } };
            string sql = "DELETE FROM PersonInfo WHERE Id=@Id";

            //var list = myClient.QueryByPage<PersonInfo>(sql, 0, 5, new { Id = 5 }, mySortRules);
            //var entity = myClient.GetEntityById<PersonInfo>(5);
            //PersonInfo pi = new PersonInfo { Id = 10, Name = "Leon100" };
            //int isSuccess = myClient.ExcuteNonQuery(sql, new { Id = 9 });

            //transaction
            myClient.GetConnection().Open();
            IDbTransaction tran = myClient.GetConnection().BeginTransaction();

            try
            {
                int isSuccess1 = myClient.ExcuteNonQuery(sql, new { Id = 1 }, tran);
                int isSuccess2 = myClient.ExcuteNonQuery(sql, new { Id = 2 }, tran);
                int isSuccess3 = myClient.ExcuteNonQuery(sql, new { Id = 3 }, tran);
                throw new Exception("执行不下去了");
            }
            catch (Exception e)
            {
                tran.Rollback();
                myClient.GetConnection().Close();
                return;
            }
            tran.Commit();
            myClient.GetConnection().Close();
        }
예제 #32
0
		public static void Query(MySqlClient client, string database, string table)
		{
			client.Query(string.Format("SELECT * FROM {0}", table))
				.On(fields: (fields) => {
					foreach (var field in fields) {
						Console.Write("{0}({1})\t", field.Type, field.Length);
					}
					Console.WriteLine();
				})
				.On(row: (data) => {
					for (int i = 0; i < data.Length; i++) {
						Console.Write(data.GetRawValue(i));
						Console.Write("\t");
					}
					Console.WriteLine();
				}).On(end: () => {
					client.Disconnect();
				}).On(error: (error) => {
					Console.WriteLine("Error: {0}", error.Message);
					client.Disconnect();
				});
		}
예제 #33
0
        private bool ViewBlock(int height)
        {
            DataTable dt;
            string    ts;

            using (var sqlc = new MySqlClient(SiaClassicLib.Config.ConnectionString))
            {
                dt = sqlc.FillTable($"SELECT id,siacoininputs,siacoinoutputs,filecontracts,filecontractrevisions,storageproofs,"
                                    + "siafundinputs,siafundoutputs,minerfees,arbitrarydata,transactionsignatures FROM txs WHERE blockheight=" + height);
                ts = sqlc.ExecuteScalar($"SELECT timestamp FROM blocks WHERE height=" + height)?.ToString();
            }
            if (dt.Rows.Count == 0)
            {
                return(false);
            }

            BlockViewPanel.Visible       = true;
            BlockViewListView.DataSource = dt;
            BlockViewListView.DataBind();
            BlockHeightLabel.Text = height.ToString();
            BlockTimeLabel.Text   = ClassLibrary.Extensions.TimeStampToString(ts);
            return(true);
        }
예제 #34
0
 internal QueryAdapter(MySqlClient client)
 {
     this.client = client;
 }
예제 #35
0
파일: MySql.cs 프로젝트: txdv/sharpmod
 public MySqlDatabase()
 {
     Client = new MySqlClient(SharpMod.Context);
 }
예제 #36
0
 internal NormalQueryReactor(MySqlClient client)
     : base(client)
 {
     base.command = client.getNewCommand();
 }
예제 #37
0
		internal TransactionQueryReactor(MySqlClient client) : base(client)
		{
			this.initTransaction();
		}