Exemplo n.º 1
1
 public static void CreateAccount(string accountName, string friendlyName, string adminPassword, string adminEmail, int planType)
 {
     using (var ts = new TransactionScope())
     {
         using (MySqlConnection sqlConnection = new MySqlConnection(UtilityHelper.GetConnectionString()))
         {
             string salt = Guid.NewGuid().ToString();
             sqlConnection.Open();
             sqlConnection.Execute(@"insert into Account(Name,FriendlyName,IsActive,PlanType) values (@Name,@FriendlyName,@IsActive,@PlanType)", new { Name = accountName, FriendlyName = friendlyName, IsActive = true, PlanType = planType });
             sqlConnection.Execute(@"insert into User(Username,Account,Password,Salt,IsActive,IsAdmin,Email) values (@Username,@Account,@Password,@Salt,@IsActive,@IsAdmin,@Email)", new { Username = "******", Account = accountName, Password = UtilityHelper.HashPassword(adminPassword, salt), Salt = salt, IsActive = true, IsAdmin = true, Email = adminEmail });
         }
         ts.Complete();
     }
 }
Exemplo n.º 2
0
        public void UpdateMatchup(MatchupModel model)
        {
            using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(GlobalConfig.ConnString(db)))
            {
                var p = new DynamicParameters();
                if (model.Winner != null)
                {
                    p.Add("inp_Id", model.Id);
                    p.Add("inp_WinnerId", model.Winner.Id);

                    connection.Execute("sp_Matchups_Update", p, commandType: CommandType.StoredProcedure);
                }



                foreach (MatchupEntryModel me in model.Entries)
                {
                    if (me.TeamCompeting != null)
                    {
                        p = new DynamicParameters();
                        p.Add("inp_Id", me.Id);
                        p.Add("inp_TeamCompetingId", me.TeamCompeting.Id);
                        p.Add("inp_Score", me.Score);

                        connection.Execute("sp_MatchupEntries_Update", p, commandType: CommandType.StoredProcedure);
                    }
                }
            }
        }
Exemplo n.º 3
0
        public TeamModel CreateTeam(TeamModel model)
        {
            using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(GlobalConfig.ConnString(db)))
            {
                var p = new DynamicParameters();
                p.Add("inp_TeamName", model.TeamName);
                p.Add("out_id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);

                connection.Execute("sp_Teams_Insert", p, commandType: CommandType.StoredProcedure);
                model.Id = p.Get <int>("out_id");


                foreach (PersonModel tm in model.TeamMembers)
                {
                    p = new DynamicParameters();
                    p.Add("inp_TeamId", model.Id);
                    p.Add("inp_PersonId", tm.Id);
                    p.Add("out_id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);

                    connection.Execute("sp_TeamMembers_Insert", p, commandType: CommandType.StoredProcedure);
                }

                return(model);
            }
        }
        public void AddPayment(IPayment payment)
        {
            try
            {
                if (!IsEnabled)
                    return;

                using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString))
                {
                    connection.Execute(
                        @"INSERT INTO Payment(Block, AccountId, Amount, CreatedAt) VALUES(@blockId, @accountId, @amount, @createdAt)",
                        new
                        {
                            blockId = payment.BlockId,
                            accountId = payment.AccountId,
                            amount = payment.Amount,
                            createdAt = DateTime.Now
                        });
                }
            }
            catch (Exception e)
            {
                _logger.Error("An exception occured while committing payment; {0:l}", e.Message);
            }
        }
Exemplo n.º 5
0
 public static DataModel.User GetValidatedUser(string username, string password, string account)
 {
     using (MySqlConnection sqlConnection = new MySqlConnection(UtilityHelper.GetConnectionString()))
     {
         sqlConnection.Open();
         DataModel.User userObj = sqlConnection.Query<DataModel.User>("Select * from User where Username=@Username and Account=@Account", new { Username = username, Account = account }).FirstOrDefault();
         if (userObj != null)
         {
             if (string.IsNullOrEmpty(userObj.Salt))
             {
                 if (password.Equals(userObj.Password))
                 {
                     string salt = Guid.NewGuid().ToString();
                     sqlConnection.Execute(@"update User set Salt=@Salt, Password=@Password where Username=@Username and Account=@Account", new { Salt = salt, Password = UtilityHelper.HashPassword(userObj.Password, salt), Username = username, Account = account });
                     return userObj;
                 }
             }
             else
             {
                 password=UtilityHelper.HashPassword(password,userObj.Salt);
                 if (password.Equals(userObj.Password))
                 {
                     return userObj;
                 }
             }
         }
     }
     return null;
 }
        public void UpdateBlock(IPersistedBlock block)
        {
            try
            {
                if (!IsEnabled)
                    return;

                using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString))
                {
                    connection.Execute(
                        @"UPDATE Block SET Orphaned = @orphaned, Confirmed = @confirmed, Accounted = @accounted, Reward = @reward WHERE Height = @height",
                        new
                        {
                            orphaned = block.Status == BlockStatus.Orphaned,
                            confirmed = block.Status == BlockStatus.Confirmed,
                            accounted = block.Accounted,
                            reward = block.Reward,
                            height = block.Height
                        });
                }
            }
            catch (Exception e)
            {
                _logger.Error("An exception occured while updating block; {0:l}", e.Message);
            }
        }
        public void RunBeforeAnyTests()
        {
            using (var mySqlConnection = new MySqlConnection("Server=localhost;Port=3306;uid=root;password=password!"))
            {
                mySqlConnection.Execute(string.Format("CREATE DATABASE IF NOT EXISTS `{0}`", DatabaseName));
            }

            Container = new Castle.Windsor.WindsorContainer();

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

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

            foreach (var setupFile in files)
            {
                connection.Execute(setupFile);
            }
        }
Exemplo n.º 8
0
 public void Activate(Promocion p)
 {
     using (MySqlConnection conn = new MySqlConnection(Constants.QueryConn))
     {
         try
         {
             conn.Open();
             var platos = GetPlatosByPromo(p);
             PlatoDao platoDao = new PlatoDao();
             foreach (var pl in platos)
             {
                 var plato = platoDao.GetOne(pl.Plato_Id);
                 if (plato.Estado != "DISPONIBLE")
                 {
                     throw new DataException("No se puede marcar como DISPONIBLE una promoción que contiene platos NO DISPONIBLES");
                 }
             }
             if (conn.Execute(Constants.ActivatePromo, p, null, null, CommandType.Text) == -1)
             {
                 throw new DataException("No se actualizó la promoción como DISPONIBLE");
             }
         }
         catch (Exception ex)
         {
             throw ex;
         }
         finally
         {
             conn.Close();
         }
     }
 }
        public void CreateOfficeDepartment(DepartmentToUser departmentToUser)
        {
            using (MySqlConnection db = new MySqlConnection(ConfigurationValues.GroveHillConnection))
            {
                departmentToUser.UniqueID = Guid.NewGuid().ToString();

                try
                {
                    const string query = "insert into officenames(UniqueID,Name,Department)"
                        + " values(@UniqueID,@Name,@Department)";
                    int rowsAffectd = db.Execute(query, new
                    {
                        @UniqueID = departmentToUser.UniqueID,
                        @Name = departmentToUser.Name,
                        @Department = departmentToUser.Department
                    });
                    int r = 5;
                }
                catch (Exception er)
                {
                    string s1 = er.ToString();
                    //Log.LogMessage(er.ToString());
                }
            }
        }
        public void AddBlock(IShare share)
        {
            try
            {
                if (!IsEnabled)
                    return;

                using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString))
                {
                    connection.Execute(
                        @"INSERT INTO Block(Height, BlockHash, TxHash, Amount, CreatedAt) VALUES (@height, @blockHash, @txHash, @amount, @createdAt)",
                        new
                        {
                            height = share.Block.Height,
                            blockHash = share.BlockHash.ToHexString(),
                            txHash = share.Block.Tx.First(),
                            amount = (decimal)share.GenerationTransaction.TotalAmount,
                            createdAt = share.Block.Time.UnixTimestampToDateTime()
                        });
                }
            }
            catch (Exception e)
            {
                _logger.Error("An exception occured while adding block; {0:l}", e.Message);
            }
        }
Exemplo n.º 11
0
        private void CreateDatabaseIfNeeded()
        {
            using (var conn = new MySqlConnection(_connectionString))
                conn.Execute($"CREATE DATABASE IF NOT EXISTS {_databaseName}");

            using (var conn = OpenConnection())
            {
                if (!DoesTableExists(conn, "EndpointConfig"))
                    CreateEndpointConfig(conn);
                if (!DoesColumnExists(conn, "EndpointConfig", "Tags"))
                    CreateColumn(conn, "EndpointConfig", "Tags", "varchar(4096)");
                if (!DoesColumnExists(conn, "EndpointConfig", "Password"))
                    CreateColumn(conn, "EndpointConfig", "Password", "varchar(64)");
                var date = DateTime.UtcNow;
                if (!DoesColumnExists(conn, "EndpointConfig", "RegisteredOnUtc"))
                    CreateColumnAndSetValue(conn, "EndpointConfig", "RegisteredOnUtc", "datetime not null", date);
                if (!DoesColumnExists(conn, "EndpointConfig", "RegistrationUpdatedOnUtc"))
                    CreateColumnAndSetValue(conn, "EndpointConfig", "RegistrationUpdatedOnUtc", "datetime not null", date);
                if (!DoesColumnExists(conn, "EndpointConfig", "MonitorTag"))
                    CreateColumn(conn, "EndpointConfig", "MonitorTag", "varchar(1024) default 'default'");
                if (!DoesTableExists(conn, "EndpointStats"))
                    CreateEndpointStats(conn);
                if (!DoesTableExists(conn, "HealthMonitorTypes"))
                    CreateHealthMonitorTypesTable(conn);
                if (!DoesIndexExists(conn, "EndpointStats", "EndpointStats_EndpointIdCheckTimeUtc_idx"))
                    CreateEndpointStatsIndex(conn);
                if (!DoesIndexExists(conn, "EndpointConfig", "EndpointConfig_MonitorTag_idx"))
                    CreateMonitorTagIndex(conn);
                if (!DoesIndexExists(conn, "EndpointConfig", "EndpointConfig_MonitorType_idx"))
                    CreateMonitorTypeIndex(conn);
            }
        }
        //***************************************************Australia***************************************
        //Australia Yellow Pages Category

        #region --For InsertSiteCatUrlTableAusYp
        public int InsertSiteCatUrlTableAusYp(string SiteName, string SiteUrl, string Category, DateTime CrawlDate, string Status)
        {
            using (MySqlConnection conn = new MySqlConnection(BG_Db_Class.getConnectionString()))
            try
            {
               {
                   if (conn.State != ConnectionState.Open)
                       try
                       {
                           conn.Open();
                       }
                       catch (MySqlException ex)
                       {
                           throw (ex);
                       }

                    int rowAffected = conn.Execute(@"INSERT INTO Bus_Data_AusYPCatUrl(SiteName,Url,Category,date,Status) VALUES(@SiteName,@SiteUrl,@Category,@date,@Status)", new { SiteName = SiteName, SiteUrl = SiteUrl, Category = Category, date = CrawlDate, Status = Status });
                    return rowAffected;
                }
            }
            catch (Exception ex)
            {
                return 0;
            }
            finally
            {
                conn.Close();
            }

        }
Exemplo n.º 13
0
 public static void DeleteUser(string account, string username)
 {
     using (MySqlConnection sqlConnection = new MySqlConnection(UtilityHelper.GetConnectionString()))
     {
         sqlConnection.Open();
         sqlConnection.Execute(@"update User set IsActive=false where Username=@Username and Account=@Account", new { Username = username, Account = account });
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// 注册
        /// </summary>
        public void register()
        {
            new driverService().Register();
            new MessgeService().Register();
            new orderService().Register();

            var ws = UseSocket.CreateSocket();

            ws.Message = (username, message) =>
            {
                var request = Newtonsoft.Json.JsonConvert.DeserializeObject <Request>(message);
                request.Head.Add("wxcount", username);
                if (request.ClientType.Other.Equals("uploadLocation"))
                {
                    request.AddService = () =>
                    {
                        IDbConnection con         = new MySqlConnection(this.Configuration["mysql"]);
                        var           driverState = con.ExecuteScalar <long>("select count(1) from orders where driverid=" + request.Head["KeyID"] + " and state=2");
                        return(driverState.ToString());
                    }
                }
                ;
                var result = Hup.CreateMsg.Run(request);
            };
        }

        void outTimeOrders()
        {
            var           t  = Startup.GlobConfiguration["mysql"];
            IDbConnection db = new MySql.Data.MySqlClient.MySqlConnection(this.Configuration["mysql"]);

            db.Open();
            JObject obj = new JObject();

            obj.Add("state", 3);
            var lists = db.Query <orders>("select * from orders where state='0' ");
            TaskManagerService tak   = TaskManagerService.Factory();
            TokenService       token = new TokenService(this.Configuration["appsecret"], this.Configuration["AppID"]);

            foreach (var key in lists)
            {
                Task.Run(async() =>
                {
                    await tak.AutoRun(key.StartTime, keys =>
                    {
                        IDbConnection _db = new MySql.Data.MySqlClient.MySqlConnection(this.Configuration["mysql"]);
                        JObject js        = JObject.Parse(key.ordersInfo);
                        string sql        = uilt.uiltT.Update(obj, "orders", " where id='" + key.id + "' ");
                        _db.Execute(sql);
                        uilt.uiltT.SendWxMessage(token, "您的订单从" + js["startingPoint"] + "到" + js["endingPoint"] + "的   行程,由于长时间没有司机接单已经超时,请重新创建行程。", js["openid"].ToString());
                        _db.Close();
                        return(Task.CompletedTask);
                    });
                });
            }
            db.Close();
        }
    }
Exemplo n.º 15
0
        public bool DeleteCoord(int id)
        {
            using (var cn = new MySqlConnection(_connectionString))
            {
                const string sql = "DELETE FROM `geopoints` WHERE `ID`=@id;";

                return cn.Execute(sql, new {ID = id}) > 0;
            }
        }
Exemplo n.º 16
0
 public static void CreateUser(string username, string accountName, string password, string email, bool? isAdmin)
 {
     using (MySqlConnection sqlConnection = new MySqlConnection(UtilityHelper.GetConnectionString()))
     {
         string salt = Guid.NewGuid().ToString();
         sqlConnection.Open();
         sqlConnection.Execute(@"insert into User(Username,Account,Password,Salt,IsActive,IsAdmin,Email) values (@Username,@Account,@Password,@Salt,@IsActive,@IsAdmin,@Email)", new { Username = username, Account = accountName, Password = UtilityHelper.HashPassword(password, salt), Salt = salt, IsActive = true, IsAdmin = isAdmin, Email = email });
     }
 }
        /// <summary>
        /// Deletes an image from the DB
        /// </summary>
        /// <param name="imageId">The Id of the image to delete</param>
        public void DeleteImage(int imageId)
        {
            using (var connection = new MySqlConnection(Common.ConnectionString))
            {
                connection.Open();

                connection.Execute("osae_sp_image_delete",
                    new { pimage_id = imageId },
                    commandType: CommandType.StoredProcedure);
            }
        }
Exemplo n.º 18
0
 public int DeleteAllPlatos(Promocion p, MySqlConnection conn, MySqlTransaction trans)
 {
     try
     {
         return conn.Execute(Constants.DeletePlatosByPromo, p, trans, null, CommandType.Text);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        private static void DropDatabase()
        {
            var recreateDatabaseSql = String.Format(
                   @"DROP DATABASE IF EXISTS `{0}`",
                   ConnectionUtils.GetDatabaseName());

            using (var connection = new MySqlConnection(
                ConnectionUtils.GetMasterConnectionString()))
            {
                connection.Execute(recreateDatabaseSql);
            }
        }
Exemplo n.º 20
0
        public void FixtureSetup()
        {
            this.DatabaseName = this.GetType().Name + DateTime.UtcNow.ToString("yyyy_MM_dd__HH_mm_ss");
            using (var connection = new MySqlConnection(ConnectionString))
            {
                connection.Open();
                connection.Execute(string.Format("CREATE DATABASE IF NOT EXISTS `{0}`", this.DatabaseName));
            }

            var connectionStringBuilder = new MySqlConnectionStringBuilder(ConnectionString) { Database = this.DatabaseName };
            this.connectionString = connectionStringBuilder.ConnectionString;
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            var conn = new MySqlConnection(ConfigurationSettings.AppSettings["mysql_conn_str"]);
            conn.Open();
            try
            {
                using (var tns = conn.BeginTransaction())
                {
                    {
                        var sql = @"CREATE TABLE `PubList` (
    `id` BIGINT PRIMARY KEY AUTO_INCREMENT,
    `pubkey` VARBINARY(512) NOT NULL UNIQUE,
    `last_seen` DATETIME NOT NULL,
    INDEX pubkey_ind (pubkey),
    INDEX date_ind (last_seen)
) engine = InnoDB;
CREATE TABLE `Msg` (
    `id` BIGINT PRIMARY KEY AUTO_INCREMENT,
    `recipient_id` BIGINT NOT NULL,
    `msg` VARBINARY(8192) NOT NULL,
    INDEX reci_ind (recipient_id),
    FOREIGN KEY (recipient_id) REFERENCES PubList(id)
) engine = InnoDB;";
                        conn.Execute(sql, new { });
                        tns.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
            }

            //openssl genrsa -out server.pem 1024
            var pemfn = ConfigurationSettings.AppSettings["pem_prv_key"];
            var pem_pw = ConfigurationSettings.AppSettings["pem_prv_key_pw"];
            if (Shared.LoadKey(pemfn, new PasswordFinder(pem_pw == null ? null : pem_pw.ToCharArray()), out key1) == false)
                throw new Exception("PEM file must have private key");

            var listen_ip_addr = IPAddress.Parse(ConfigurationSettings.AppSettings["ip_addr"]);
            var port = Int16.Parse(ConfigurationSettings.AppSettings["port"]);
            var backlog = int.Parse(ConfigurationSettings.AppSettings["backlog"]);
            var server = new TcpListener(listen_ip_addr, port);
            server.Start(backlog);
            while (true)
            {
                DoBeginAcceptTcpClient(server);
            }
        }
Exemplo n.º 22
0
        public PersonModel CreatePerson(PersonModel model)
        {
            using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(GlobalConfig.ConnString(db)))
            {
                var p = new DynamicParameters();
                p.Add("inp_FirstName", model.FirstName);
                p.Add("inp_LastName", model.LastName);
                p.Add("inp_EmailAddress", model.EmailAddress);
                p.Add("inp_CellphoneNumber", model.CellphoneNumber);
                p.Add("out_id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);

                connection.Execute("sp_Person_Insert", p, commandType: CommandType.StoredProcedure);
                model.Id = p.Get <int>("out_id");

                return(model);
            }
        }
Exemplo n.º 23
0
        public PrizeModel CreatePrize(PrizeModel model)
        {
            using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(GlobalConfig.ConnString(db)))
            {
                var p = new DynamicParameters();
                p.Add("inp_PlaceNumber", model.PlaceNumber);
                p.Add("inp_PlaceName", model.PlaceName);
                p.Add("inp_PrizeAmount", model.PrizeAmount);
                p.Add("inp_PrizePercentage", model.PrizePercentage);
                p.Add("out_id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);

                connection.Execute("sp_Prizes_Insert", p, commandType: CommandType.StoredProcedure);

                model.Id = p.Get <int>("out_id");

                return(model);
            }
        }
        private static void CreateAndInitializeDatabase()
        {
            var recreateDatabaseSql = String.Format(
                @"CREATE DATABASE IF NOT EXISTS `{0}`",
                ConnectionUtils.GetDatabaseName());

            using (var connection = new MySqlConnection(
                ConnectionUtils.GetMasterConnectionString()))
            {
                connection.Execute(recreateDatabaseSql);
            }

            using (var connection = new MySqlConnection(
                ConnectionUtils.GetConnectionString()))
            {
                MySqlObjectsInstaller.Install(connection);
            }
        }
Exemplo n.º 25
0
        public void CleanUpPackages()
        {
            var dbType = ConfigurationSettings.AppSettings["DbType"].ToLowerInvariant();
            if (dbType == "mysql")
            {
                using (IDbConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["phpnuget"].ConnectionString))
                {
                    string query = "TRUNCATE TABLE nugetdb_pkg";
                    connection.Execute(query);
                }
            }
            else
            {
                var dbfile = Path.Combine(PhpSrc, "data", "db", "nugetdb_pkg.txt");
                if (File.Exists(dbfile)) File.Delete(dbfile);

            }
        }
Exemplo n.º 26
0
 public int DeleteAllPlatos(Promocion p)
 {
     using (MySqlConnection conn = new MySqlConnection(Constants.QueryConn))
     {
         try
         {
             conn.Open();
             return conn.Execute(Constants.DeletePlatosByPromo, p, null, null, CommandType.Text);
         }
         catch (Exception ex)
         {
             throw ex;
         }
         finally
         {
             conn.Close();
         }
     }
 }
Exemplo n.º 27
0
 public int Activate(Plato p)
 {
     using (MySqlConnection conn = new MySqlConnection(Constants.QueryConn))
     {
         try
         {
             conn.Open();
             return conn.Execute(Constants.ActivatePlato, p, null, null, CommandType.Text);
         }
         catch (Exception ex)
         {
             throw ex;
         }
         finally
         {
             conn.Close();
         }
     }
 }
        public static void Install(MySqlConnection connection)
        {
            if (connection == null) throw new ArgumentNullException("connection");

            if (TablesExists(connection))
            {
                Log.Info("DB tables already exist. Exit install");
                return;
            }

            Log.Info("Start installing Hangfire SQL objects...");

            var script = GetStringResource(
                typeof(MySqlObjectsInstaller).Assembly,
                "Hangfire.MySql.Install.sql");

            connection.Execute(script);

            Log.Info("Hangfire SQL objects installed.");
        }
Exemplo n.º 29
0
        public virtual void Setup()
        {
            var connection = new MySqlConnection("Server=localhost;Port=3306;Database=dapperTest;uid=root;password=password!");
            var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper<>), new List<Assembly>(), new MySqlDialect());
            var sqlGenerator = new SqlGeneratorImpl(config);
            Db = new Database(connection, sqlGenerator);
            var files = new List<string>
                                {
                                    ReadScriptFile("CreateFooTable"),
                                    ReadScriptFile("CreateMultikeyTable"),
                                    ReadScriptFile("CreatePersonTable"),
                                    ReadScriptFile("CreateCarTable"),
                                    ReadScriptFile("CreateAnimalTable")
                                };

            foreach (var setupFile in files)
            {
                connection.Execute(setupFile);
            }
        }
Exemplo n.º 30
0
        public void AddShare(IShare share)
        {
            try
            {
                if (!IsEnabled)
                    return;

                var ourResult = share.IsValid ? 'Y' : 'N';
                var upstreamResult = share.IsBlockCandidate ? 'Y' : 'N';

                object errorReason;

                if (share.Error != ShareError.None)
                    errorReason = share.Error;
                else
                    errorReason = null;

                using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString))
                {
                    connection.Execute(
                        @"INSERT INTO shares(rem_host, username, our_result, upstream_result, reason, solution, difficulty,time)
                            VALUES (@rem_host, @username, @our_result, @upstream_result, @reason, @solution, @difficulty, @time)",
                        new
                        {
                            rem_host = ((IClient) share.Miner).Connection.RemoteEndPoint.Address.ToString(),
                            username = share.Miner.Username,
                            our_result = ourResult,
                            upstream_result = upstreamResult,
                            reason = errorReason,
                            solution = share.BlockHash.ToHexString(),
                            difficulty = share.Difficulty, // should we consider mpos difficulty multiplier here?
                            time = DateTime.Now
                        });
                }
            }
            catch (Exception e)
            {
                _logger.Error("An exception occured while comitting share; {0:l}", e.Message);
            }
        }
Exemplo n.º 31
0
        public void UpdateDifficulty(IStratumMiner miner)
        {
            try
            {
                if (!IsEnabled)
                    return;

                using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString))
                {
                    connection.Execute(
                        "UPDATE pool_worker SET difficulty = @difficulty WHERE username = @username", new
                        {
                            difficulty = miner.Difficulty,
                            username = miner.Username
                        });
                }
            }
            catch (Exception e)
            {
                _logger.Error("An exception occured while updating difficulty for miner; {0:l}", e.Message);
            }
        }
        public void UpdatePayment(IPayment payment)
        {
            try
            {
                if (!IsEnabled)
                    return;

                using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString))
                {
                    connection.Execute(
                        @"UPDATE Payment SET Completed = @completed WHERE Id = @id",
                        new
                        {
                            completed = payment.Completed,
                            id = payment.Id
                        });
                }
            }
            catch (Exception e)
            {
                _logger.Error("An exception occured while updating payment; {0:l}", e.Message);
            }
        }
        public void UpdateNotes(string notes)
        {
            using (MySqlConnection db = new MySqlConnection(Database.ReminderConnection))
            {
                try
                {
                    string query =
                        "update notes"
                        + " set notes = @notes"
                        + " where id = 1";

                    int rowsAffectd = db.Execute(query, new
                    {
                        @notes = notes,
                    }
                        );
                }
                catch (Exception er)
                {
                    Log.LogMessage(er.ToString());
                }
            }

        }
        public void AddAccount(IAccount account)
        {
            try
            {
                if (!IsEnabled)
                    return;

                using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString))
                {
                    connection.Execute(
                        @"INSERT INTO Account(Username, Address, CreatedAt) VALUES (@username, @address, @createdAt)",
                        new
                        {
                            username = account.Username,
                            address = account.Address,
                            createdAt = DateTime.Now
                        });
                }
            }
            catch (Exception e)
            {
                _logger.Error("An exception occured while creating account; {0:l}", e.Message);
            }
        }
        public void CreateOfficeDepartment(DepartmentToUser departmentToUser)
        {
            using (MySqlConnection db = new MySqlConnection(ConfigurationValues.GroveHillConnection))
            {
                departmentToUser.UniqueID = Guid.NewGuid().ToString();

                try
                {
                    const string query = "insert into officenames(UniqueID,Name,Department)"
                        + " values(@UniqueID,@Name,@Department)";
                    int rowsAffectd = db.Execute(query, new
                    {
                        @UniqueID = departmentToUser.UniqueID,
                        @Name = departmentToUser.Name,
                        @Department = departmentToUser.Department
                    });
                }
                catch (Exception er)
                {
                  EmployeeDesktop.API.Exceptions.ExceptionHandling.InsertErrorMessage(er.ToString());
                  EmployeeDesktop.API.Exceptions.ExceptionHandling.SendErrorEmail(er.ToString(), ConfigurationValues.EmailFromFriendly, ConfigurationValues.EmailSendToFriendly, ConfigurationValues.EmailSubject);
                }
            }
        }
Exemplo n.º 36
0
 public void SearchInitial(List <string> startList)
 {
     try
     {
         conn.Open();
         conn.Execute("delete  from ImgContent where ImgId>=0");
         conn.Execute("delete  from UrlContent where ListId>=0");
         for (int i = 0; i < startList.Count; i++)
         {
             conn.Execute("insert into UrlContent(Url,depth) values(@url,0)", new { url = startList[i] });
         }
     }
     catch (Exception)
     {
         //ignore
         throw;
     }
     finally
     {
         conn.Close();
     }
 }