Example #1
0
 private static object PullSql(string conn, string db, string query, string error, SQLReturn type)
 {
     var result = new object();
     try
     {
         using (var c = new SqlConnection(conn))
         {
             c.Open();
             c.ChangeDatabase(db);
             SqlDataReader reader = new SqlCommand(query, c).ExecuteReader();
             switch (type)
             {
                 case SQLReturn.Bool:
                     result = false;
                     while (reader.Read())
                     {
                         if (reader != null)
                         {
                             result = true;
                             break;
                         }
                     }
                     break;
                 case SQLReturn.Item:
                     result = String.Empty;
                     while (reader.Read())
                     {
                         if (reader != null)
                         {
                             result = reader[0].ToString();
                             break;
                         }
                     }
                     break;
                 case SQLReturn.List:
                     var Results = new List<string>();
                     while (reader.Read())
                     {
                         Results.Add(reader[0].ToString());
                     }
                     result = Results;
                     break;
             }
         }
     }
     catch (SqlException e)
     {
         Messaging.ThrowException(error, e);
     }
     catch (Exception e)
     {
         Messaging.ThrowException(error, e);
     }
     return result;
 }
Example #2
0
        public List<AccountBase> FillAccountBaseFromSql()
        {
            var Accounts= new List<AccountBase>();

            using(var myConnection = new SqlConnection(Connect.sTalismanConStr))
            {
                myConnection.Open();
                string sSql = "Select top 1 * from existing_clients";
                var Reader = new SqlCommand(sSql, myConnection).ExecuteReader();
                while (Reader.Read())
                {
                    var AccountBase = new AccountBase();
                    AccountBase.sAccountName = Reader["sName"].ToString();
                    AccountBase.sAddressLine1 = Reader["sAddressLine1"].ToString();
                    AccountBase.sAddressLine2 = Reader["sAddressLine2"].ToString();
                    AccountBase.sAddressLine3 = Reader["sAddressLine3"].ToString();
                    AccountBase.sCustomerNumber = Reader["sClientNumber"].ToString();
                    AccountBase.sEmail = Reader["sEmail"].ToString();
                    AccountBase.sPostCode = Reader["sPostalCode"].ToString();
                    AccountBase.sTelephone = Reader["sTelephone"].ToString();
                    //MessageBox.Show(AccountBase.sAccountName);
                    //MessageBox.Show(AccountBase.sTelephone);
                    Accounts.Add(AccountBase);
                }
                Reader.Close();
                myConnection.Close();
            }

            return Accounts;
        }
Example #3
0
        private List<string> GetNodeMatches(string lookupText)
        {
            List<string> foundNodes = new List<string>();

            string sConn = ConfigurationManager.ConnectionStrings["EEREDB"].ToString();
            sConn += System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(ConfigurationManager.AppSettings["word"].ToString()));

            using (SqlConnection conn = new SqlConnection(sConn))
            {
                conn.Open();
                using (SqlDataReader reader = new SqlCommand("SELECT DrupalNode FROM dbo.NodeLookup WHERE WebURL LIKE '%" + lookupText + "%' ", conn).ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            foundNodes.Add(reader.GetString(0));
                        }
                    }
                }
                conn.Close();
            }

            return foundNodes;
        }
Example #4
0
 public virtual object[] getDataAry(string argString)
 {
     this.rState = 0;
     string cmdText = argString;
     object[] objArray = null;
     try
     {
         SqlConnection connection = new SqlConnection(this.connStr);
         connection.Open();
         SqlDataReader reader = new SqlCommand(cmdText, connection).ExecuteReader();
         int fieldCount = reader.FieldCount;
         object[,] objArray2 = null;
         while (reader.Read())
         {
             objArray2 = new object[fieldCount, 2];
             for (int i = 0; i < fieldCount; i++)
             {
                 objArray2[i, 0] = reader.GetName(i);
                 objArray2[i, 1] = reader.GetValue(i);
             }
             objArray = cls.mergeAry(objArray, objArray2);
         }
         reader.Close();
         connection.Close();
     }
     catch (Exception exception)
     {
         this.rState = 1;
         objArray = null;
         this.eMessage = exception.Message;
     }
     return objArray;
 }
 protected override void PopulateVersionAndTypes()
 {
     base._sqlVersion = "10";
     List<KeyValuePair<int, byte>> list = new List<KeyValuePair<int, byte>>();
     using (SqlDataReader reader = new SqlCommand("select system_type_id, user_type_id, name from sys.types where system_type_id = user_type_id", base._cx).ExecuteReader())
     {
         while (reader.Read())
         {
             DbTypeInfo dbTypeInfo = SqlSchemaReader.GetDbTypeInfo(reader.GetString(2));
             if (!((dbTypeInfo == null) || base._sqlTypes.ContainsKey(reader.GetInt32(1))))
             {
                 base._sqlTypes.Add(reader.GetInt32(1), dbTypeInfo);
             }
             else
             {
                 list.Add(new KeyValuePair<int, byte>(reader.GetInt32(1), reader.GetByte(0)));
             }
         }
     }
     foreach (KeyValuePair<int, byte> pair in list)
     {
         if (base._sqlTypes.ContainsKey(pair.Value))
         {
             base._sqlTypes[pair.Key] = base._sqlTypes[pair.Value];
         }
     }
 }
 public Method1Form()
 {
     InitializeComponent();
     cboxGroup.SelectedIndex = 1;
     cboxGroup.SelectionChangeCommitted += new EventHandler(btnMethod1_Click);
     using (SqlConnection connection = new SqlConnection(MainForm.STRCONN))
     {
         connection.Open();
         string q = @"SELECT ID FROM dbo.Leagues WHERE Season='2011/12' ORDER BY GuessedPercent DESC";
         using (SqlDataReader reader = new SqlCommand(q, connection).ExecuteReader())
         {
             int i = 1;
             cboxTopLeagues.Items.Add("All Leagues");
             while (reader.Read()) cboxTopLeagues.Items.Add(String.Format("TOP {0}", i++));
             cboxTopLeagues.Items.RemoveAt(cboxTopLeagues.Items.Count - 1);
             if (cboxTopLeagues.Items.Count == 0) return;
             cboxTopLeagues.SelectedIndex = 0;
             cboxTopLeagues.SelectionChangeCommitted += new EventHandler(btnMethod1_Click);
         }
     }
     //browser.AllowWebBrowserDrop = false;
     //browser.IsWebBrowserContextMenuEnabled = false;
     //browser.WebBrowserShortcutsEnabled = false;
     browser.ObjectForScripting = this;
 }
Example #7
0
        public void TestInsert()
        {
            var students = StudentHelper.CreateSample(10).ToArray();
            using (var sqlConnection = DatabaseHelper.OpenSqlConnection(DatabaseName))
            {
                var sqlUpserter = new SqlUpserter<Student>(StudentMapper, TableName, students);
                sqlUpserter.Execute(sqlConnection);

                var selectText = "SELECT " + string.Join(",", StudentMapper.Columns.Select(column => column.Name)) +
                                 " FROM " + TableName;
                var reader = new SqlCommand(selectText, sqlConnection).ExecuteReader();
                var row = 0;
                while (reader.Read())
                {
                    var student = students[row];
                    for (var column = 0; column < reader.FieldCount; column++)
                    {
                        var expected = StudentMapper.GetValueAt(column, student);
                        var actual = reader.GetValue(column);
                        Assert.AreEqual(expected, actual);
                    }
                    row++;
                }
            }
        }
        public static void Tweak()
        {
            List<Item> items = new List<Item>();
            HashSet<int> recipes = new HashSet<int>();

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TdbConnectionString"].ConnectionString))
            {
                conn.Open();

                using (SqlDataReader reader = new SqlCommand("SELECT * FROM Items WHERE JSON IS NOT NULL", conn).ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine(reader["Name"].ToString());
                        using (MemoryStream m = new MemoryStream(Encoding.UTF8.GetBytes(reader["JSON"].ToString())))
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Item));
                            items.Add((Item)ser.ReadObject(m));
                        }
                    }
                }

                using (SqlDataReader reader = new SqlCommand("SELECT RecipeId FROM Recipes", conn).ExecuteReader())
                {
                    while (reader.Read())
                    {
                        recipes.Add((int)reader["RecipeId"]);
                    }
                }
            }

            using (SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["TdbConnectionString"].ConnectionString))
            {
                conn2.Open();
                foreach (Item i in items)
                {
                    using (SqlCommand cmd = new SqlCommand("UPDATE Items SET Name = @Name, BindOnPickup = @BindOnPickup, Icon = @Icon, Quality = @Quality, SourceId = @SourceId, SourceType = @SourceType, RecipeId = @RecipeId WHERE ItemId = @ItemId", conn2))
                    {
                        cmd.Parameters.AddWithValue("Name", i.Name);
                        cmd.Parameters.AddWithValue("BindOnPickup", i.ItemBind);
                        cmd.Parameters.AddWithValue("Icon", i.ItemSpells.Count > 0 ? (object)i.ItemSpells.Last().Spell.Icon : !string.IsNullOrWhiteSpace(i.Icon) ? (object)i.Icon : DBNull.Value);
                        cmd.Parameters.AddWithValue("Quality", i.Quality);
                        cmd.Parameters.AddWithValue("SourceId", i.ItemSource.SourceId);
                        cmd.Parameters.AddWithValue("SourceType", i.ItemSource.SourceType);
                        cmd.Parameters.AddWithValue("RecipeId", i.ItemSpells.Any(a => a.Trigger == "ON_LEARN") && recipes.Contains(i.ItemSpells.First(b => b.Trigger == "ON_LEARN").SpellId) ? (object)i.ItemSpells.First(b => b.Trigger == "ON_LEARN").SpellId : DBNull.Value);
                        cmd.Parameters.AddWithValue("ItemId", i.ItemId);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }
Example #9
0
 protected void Page_Load(object sender, EventArgs e)
 {
     Response.ContentType = "text/plain";
     using (SqlConnection conn = new SqlConnection(profilesdb))
     {
         conn.Open();
         using (SqlDataReader dbreader = new SqlCommand("SELECT internalusername, nodeid from [UCSF.].vwPerson", conn).ExecuteReader(CommandBehavior.CloseConnection))
         {
             while (dbreader.Read())
             {
                 Response.Write(dbreader[0].ToString() + ", " + dbreader[1].ToString() + Environment.NewLine);
             }
         }
     }
 }
Example #10
0
        public void readFromDataBase()
        {
            items.Clear();
            SqlDataReader reader = new SqlCommand(string.Format("SELECT * FROM Items ORDER BY Id;SELECT * FROM Jobs ORDER BY Item;SELECT * FROM Jobs ORDER BY Item;"), cn).ExecuteReader();
            //читаем лист items
            while (reader.Read())
            {
                item newItem = new item();
                newItem.id = reader.GetInt32(0);
                newItem.firstName = reader.GetString(1);
                newItem.lastName = reader.GetString(2);
                items.Add(newItem);
            }

            int i;
            int lastid;

            //читаем лист jobs
            reader.NextResult();
            lastid = i = -1;
            while (reader.Read())
            {
                int k = reader.GetInt32(4);
                if (lastid != k)
                {
                    do ++i;
                    while (k != items[i].id);
                    lastid = reader.GetInt32(4);
                }
                items[i].jobs.Add(new job(reader.GetDateTime(0), reader.GetString(1), reader.GetString(2), reader.GetString(3)));
            }

            //читаем лист positions
            reader.NextResult();
            lastid = i = -1;
            while (reader.Read())
            {
                if (lastid != reader.GetInt32(4))
                {
                    do i++;
                    while (reader.GetInt32(4) != items[i].id);
                    lastid = reader.GetInt32(4);
                }
                items[i].positions.Add(new position(reader.GetInt64(0),reader.GetInt64(1),reader.GetInt32(2),reader.GetDateTime(3)));
            }
            reader.Close();
        }
        private void btnAlterar_Click(object sender, EventArgs e)
        {
            try
            {
                var connection = DataBaseConnection.GetConnection();
                connection.Open();
                var value = gridClientes.SelectedRows[0].Cells[0].Value;
                var query = string.Format(" SELECT * FROM tb_clientes where codigo = {0} ", value);
                var reader = new SqlCommand(query, connection).ExecuteReader();
                if (reader.Read())
                {
                    txtCodCliente.Text = reader["codigo"].ToString();
                    txtNome.Text = reader["nome"].ToString();
                    if (reader["sexo"].ToString() == "M")
                        cbSexo.SelectedIndex = 0;
                    else
                        cbSexo.SelectedIndex = 1;
                    txtNacional.Text = reader["nacionalidade"].ToString();
                    txtProfissao.Text = reader["profissao"].ToString();
                    txtDataNasc.Text = reader["data_nascimento"].ToString();
                    if (reader["indicador_fisica_juridica"].ToString() == "F")
                    {
                        rbCpf.Checked = true;
                        txtIdent.Mask = "000,000,000-00";
                    }

                    else
                    {
                        rbCnpj.Checked = true;
                        txtIdent.Mask = "00,000,000/0000-00";
                    }
                    txtIdent.Text = reader["numero_cpf_cnpj"].ToString();
                }
               connection.Close();
               PreencherTelefones(value.ToString());
               PreencherEnderecos(value.ToString());
                LiberaCancelarConfirmar();
                groupCad.Enabled = true;
                EnabledComponent(true);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #12
0
        public void TestUpdate()
        {
            var students = StudentHelper.CreateSample(10).ToArray();
            using (var sqlConnection = DatabaseHelper.OpenSqlConnection(DatabaseName))
            {
                var sqlUpserter1 = new SqlUpserter<Student>(StudentMapper, TableName, students);
                sqlUpserter1.Execute(sqlConnection);

                var expectedChanges = 0;
                foreach (var student in students)
                {
                    if (student.Id%2 == 0)
                    {
                        student.FirstName = student.FirstName + "_Changed";
                        expectedChanges++;
                    }
                }

                var sqlUpserter2 = new SqlUpserter<Student>(StudentMapper, TableName, students);
                sqlUpserter2.Execute(sqlConnection);

                var selectText = "SELECT " + string.Join(",", StudentMapper.Columns.Select(column => column.Name)) +
                                 " FROM " + TableName;
                var reader = new SqlCommand(selectText, sqlConnection).ExecuteReader();
                var row = 0;
                var currentChanges = 0;
                while (reader.Read())
                {
                    var student = students[row];
                    for (var column = 0; column < reader.FieldCount; column++)
                    {
                        var expected = StudentMapper.GetValueAt(column, student);
                        var actual = reader.GetValue(column);
                        if (actual.ToString().EndsWith("_Changed"))
                        {
                            currentChanges++;
                        }
                        Assert.AreEqual(expected, actual);
                    }
                    row++;
                }
                Assert.AreEqual(expectedChanges, currentChanges);
            }
        }
 private static string[] GetEnabledTables(string connectionString)
 {
     SqlDataReader reader = null;
     SqlConnection connection = null;
     ArrayList list = new ArrayList();
     try
     {
         connection = new SqlConnection(connectionString);
         connection.Open();
         reader = new SqlCommand("dbo.AspNet_SqlCacheQueryRegisteredTablesStoredProcedure", connection) { CommandType = CommandType.StoredProcedure }.ExecuteReader();
         while (reader.Read())
         {
             list.Add(reader.GetString(0));
         }
     }
     catch (Exception exception)
     {
         SqlException exception2 = exception as SqlException;
         if ((exception2 != null) && (exception2.Number == 0xafc))
         {
             throw new DatabaseNotEnabledForNotificationException(System.Web.SR.GetString("Database_not_enabled_for_notification", new object[] { connection.Database }));
         }
         throw new HttpException(System.Web.SR.GetString("Cant_get_enabled_tables_sql_cache_dep"), exception);
     }
     finally
     {
         try
         {
             if (reader != null)
             {
                 reader.Close();
             }
             if (connection != null)
             {
                 connection.Close();
             }
         }
         catch
         {
         }
     }
     return (string[]) list.ToArray(Type.GetType("System.String"));
 }
Example #14
0
        public bool CheckLoginData(string username, string password, ref Role role)
        {
            Connect();
            try
            {
                SqlDataReader dataReader = new SqlCommand("SELECT * FROM tbl_login", con).ExecuteReader();

                while (dataReader.Read())
                {
                    if (dataReader["username"].ToString().Trim() == username && dataReader["password"].ToString().Trim() == password)
                    {
                        MessageBox.Show("Login succes");

                        switch((int)dataReader["id"])
                        {
                            case 0:
                                role = Role.Development; break;
                            case 1:
                                role = Role.Finance; break;
                            case 2:
                                role = Role.Sales; break;
                        }

                        dataReader.Close();

                        return true;
                    }
                }
                dataReader.Close();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }

            MessageBox.Show("Wrong username and/or wrong password");
            return false;
        }
Example #15
0
        public DateTime GetDateModifiedUtc(int id, string filename)
        {
            //this.FireAuthorizeEvent(id);
            SqlConnection connectionObj = this.GetConnectionObj();
            connectionObj.Open();
            DateTime result;

            using (connectionObj)
            {
                SqlDataReader sqlDataReader = new SqlCommand(this.modifiedDateQuery, connectionObj)
                {
                    Parameters =
                    {
                        CreateParameter("id", id, SqlDbType.Int),
                        CreateParameter("name", filename, SqlDbType.NVarChar)
                    }
                }.ExecuteReader();

                using (sqlDataReader)
                {
                    if (!sqlDataReader.Read())
                    {
                        result = DateTime.MinValue;
                        return result;
                    }
                    for (var i = 0; i < sqlDataReader.FieldCount; i++)
                    {
                        if (!sqlDataReader.IsDBNull(i) && sqlDataReader.GetValue(i) is DateTime)
                        {
                            result = (DateTime)sqlDataReader.GetValue(i);
                            return result;
                        }
                    }
                }
            }

            return DateTime.MinValue;
        }
Example #16
0
        public long GetUser(string email, string hash)
        {
            long _result = -1;

            if (Connected)
            {
                using (SqlDataReader _reader = new SqlCommand(string.Format("Select * from MarketUser Where Email='{0}'", email), _sql).ExecuteReader())
                {
                    if (_reader.HasRows)
                    {
                        while (_reader.Read())
                        {
                            if (_reader.GetString(_reader.GetOrdinal("Password")).Equals(hash))
                            {
                                _result = _reader.GetInt64(_reader.GetOrdinal("UserId"));
                            }
                        }
                    }
                }
            }

            return _result;
        }
        public void TearDownDatabase()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["TeleConsult"].ConnectionString;
            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (var reader = new SqlCommand("select [Name] from sys.tables WHERE TYPE='U' AND [Name] != '__MigrationHistory'", connection).ExecuteReader(CommandBehavior.CloseConnection))
                {
                    while (reader.Read())
                    {
                        var tableName = reader.GetString(0);
                        using (var connection2 = new SqlConnection(connectionString))
                        {
                            connection2.Open();
                            new SqlCommand(string.Format("DELETE FROM [{0}]", tableName), connection2).ExecuteNonQuery();
                            connection2.Close();
                        }

                    }
                }
                connection.Close();
            }
        }
 public ArrayList GetNotifications(string username)
 {
     ArrayList notificationList = new ArrayList();
     SqlConnection conn = new SqlConnection(connectionString);
     try
     {
         conn.Open();
         string sql = "SELECT Message FROM NOTIFICATION_MESSAGES WHERE UserID IN (SELECT UserID FROM NOTIFICATION_USERS WHERE Username='" + username + "' AND IsDeleted=0) AND IsDeleted=0";
         SqlDataReader dataReader = new SqlCommand(sql, conn).ExecuteReader();
         while (dataReader.Read())
         {
             notificationList.Add(dataReader[0]);
         }
         notificationList.Reverse();
     }
     finally
     {
         if (conn.State == ConnectionState.Open)
         {
             conn.Close();
         }
     }
     return notificationList;
 }
Example #19
0
        public Concert SaveNewConcert(String concertName, String concertDescription, DateTime concertDateTime, ShardDbServerTargetEnum saveToDatabase,  int concertVenueId, int performerId)
        {
            Concert concertToReturn = null; DataSet tempDS = new DataSet();

            #region Insert
            string insertQuery = String.Format(CONST_InsertNewConcert, concertName, concertDescription, concertDateTime, CONST_CONCERTDURATION, concertVenueId, performerId, (int)saveToDatabase);
            using (var insertConnection = new SqlConnection(constructConcertsConnnectString()))
            {
                insertConnection.Open();
                using (var insertCommand = new SqlCommand(insertQuery, insertConnection))
                { insertCommand.ExecuteNonQuery(); }
                insertConnection.Close();
                insertConnection.Dispose();
            }
            #endregion Insert

            #region Get Information
            string getCommandQuery = string.Format("{0} WHERE (concerts.ConcertName='{1}' AND concerts.VenueId={2} AND concerts.PerformerId={3}) {4}",
                CONST_GetAllConcertsQuery, concertName, concertVenueId, performerId, CONST_OrderByConcertDate);
            using (var getConnection = new SqlConnection(constructConcertsConnnectString()))
            {
                getConnection.Open();
                using (var reader = new SqlCommand(getCommandQuery, getConnection).ExecuteReader())
                { if (reader.Read()) concertToReturn = populateSingleConcertFromDbReader(reader); }
                getConnection.Close();
                getConnection.Dispose();
            }
            #endregion Get Information

            #region Populate Ticket Levels
            int i = 1;
            string seatSectionQuery = string.Format(@"SELECT * FROM [SeatSection] Where VenueId={0}", concertVenueId);
            using (var seatCommand = new SqlCommand(seatSectionQuery, new SqlConnection(constructVenuesConnectString())))
            using (var seatDataAdapter = new SqlDataAdapter(seatCommand))
            {
                seatDataAdapter.Fill(tempDS);
                if (tempDS.Tables.Count > 0 && tempDS.Tables[0].Rows.Count > 0)
                    foreach (DataRow drSeat in tempDS.Tables[0].Rows)
                    {
                        string ticketLevelInsert = string.Format(@"INSERT INTO [TicketLevels] (Description, SeatSectionId, ConcertId, TicketPrice) Values('Level-{0}', {0}, {1}, '{2}')", drSeat["SeatSectionId"].ToString(), concertToReturn.ConcertId, (50 + (5 * i++)).ToString() + ".00");
                        using (var ticketConnection = new SqlConnection(constructTicketConnectString()))
                        {
                            ticketConnection.Open();
                            using (var ticketCommand = new SqlCommand(ticketLevelInsert, ticketConnection))
                            { ticketCommand.ExecuteNonQuery(); }
                            ticketConnection.Close();
                            ticketConnection.Dispose();
                        }
                    }
            }
            #endregion Populate Ticket Levels

            VenuesDbContext.LogAction("Added new concert " + concertName + " for venueId " + concertVenueId);
            return concertToReturn;
        }
Example #20
0
        public bool IsToken(long id, string AccessToken)
        {
            bool _result = false;

            if (Connected)
            {
                using (SqlDataReader _reader = new SqlCommand(string.Format("Select * From MarketToken Where UserId='{0}'", id), _sql).ExecuteReader())
                {
                    if (_reader.HasRows)
                    {
                        while (_reader.Read())
                        {
                            if (_reader.GetString(_reader.GetOrdinal("AccessToken")).Equals(AccessToken))
                            {
                                _result = true;

                                break;
                            }
                        }
                    }

                }
            }

            return _result;
        }
Example #21
0
        public void process()
        {
            byte i, round;
            float grDiff;
            int aI = 1, progress;
            string progressTitle;
            string q = @"SELECT Country,League,Season,Round,Date,HomeTeam,AwayTeam,ScoreH,ScoreA FROM dbo.archive ORDER BY Country,League,Season,Round";
            ArchiveKey aKey = new ArchiveKey();
            Dictionary<ArchiveKey, Dictionary<int, RoundValue>> aDict = new Dictionary<ArchiveKey, Dictionary<int, RoundValue>>();
            Dictionary<ArchiveKey, Dictionary<int, RoundValue>> newADict = new Dictionary<ArchiveKey, Dictionary<int, RoundValue>>();
            HistoryValue hVal;
            RoundValue rVal;
            SqlCommand selectCmd;
            SqlDataReader reader;

            mainForm.backgroundWorker.ReportProgress(0, new BGReport("  Building aDict ..."));
            History.errDict = new Dictionary<ArchiveKey, string>();

            using (reader = new SqlCommand(q, this.Connection).ExecuteReader())
            {
                while (reader.Read())
                {
                    aKey.Country = reader["Country"].ToString();
                    aKey.League = reader["League"].ToString();
                    aKey.Season = reader["Season"].ToString();
                    round = (byte)reader["Round"];
                    if (!aDict.ContainsKey(aKey))
                        aDict[aKey] = new Dictionary<int, RoundValue>();
                    else if (aDict[aKey].ContainsKey(round))
                    {
                        rVal = aDict[aKey][round];
                        rVal.calc(reader, aDict[aKey]);
                        aDict[aKey][round] = rVal;
                        continue;
                    }
                    aDict[aKey][round] = new RoundValue(reader, aDict[aKey]);
                }
            }

            mainForm.backgroundWorker.ReportProgress(10, new BGReport("  Inserting/Updating records ..."));

            foreach (var aKVP in aDict)
            {
                newADict[aKVP.Key] = new Dictionary<int, RoundValue>();
                selectCmd = new SqlCommand("SELECT TOP 1 Country FROM dbo.history WHERE Country=@Country AND League=@League AND Season=@Season", this.Connection);
                selectCmd.Parameters.AddWithValue("@Country", aKVP.Key.Country);
                selectCmd.Parameters.AddWithValue("@League", aKVP.Key.League);
                selectCmd.Parameters.AddWithValue("@Season", aKVP.Key.Season);
                using (reader = selectCmd.ExecuteReader()) progressTitle = reader.HasRows ? "  Updating " : "  Inserting ";
                progress = (int)((double)(aI++) / aDict.Count * 80) + 10;
                mainForm.backgroundWorker.ReportProgress(progress, new BGReport(progressTitle + aKVP.Key + " ..."));
                if (History.errDict.ContainsKey(aKVP.Key))
                    mainForm.backgroundWorker.ReportProgress(progress, new BGReport(History.errDict[aKVP.Key], System.Drawing.Brushes.Red));
                foreach (var rKVP in aKVP.Value)
                {
                    var orderedEnum = from item in rKVP.Value.tDict
                                      let diff = item.Value.SumScored - item.Value.SumReceived
                                      orderby item.Value.Points descending, diff descending
                                      select item;
                    rVal = new RoundValue(rKVP.Value);
                    grDiff = (float)(rVal.maxPoints - rVal.minPoints) / 4;
                    i = 1;
                    foreach (var kvp in orderedEnum)
                    {
                        hVal = kvp.Value;
                        hVal.Position = i++;
                        hVal.grLevel = (byte)(Math.Round((rVal.maxPoints - hVal.Points) / grDiff) + 1);
                        if (rKVP.Key == 1) hVal.grStrength = 50;
                        else
                        {
                            //hVal.grStrength = getStrength1(newADict[aKVP.Key][rKVP.Key - 1], kvp);
                            //Console.Write("{0} -> {1}). ", rKVP.Key - 1, rKVP.Key);
                            hVal.grStrength = getStrength2(newADict[aKVP.Key][rKVP.Key - 1], kvp);
                            //Console.WriteLine(", PrevAvgStrength:{0}", hVal.grStrength);
                        }
                        if (insert(aKVP.Key, rKVP.Key, kvp.Key, hVal) == 0) Console.WriteLine("something is wrong [History.process]");
                        //Console.WriteLine("{0}:{1}, {2}, P:{3}({4},{5})", aKVP.Key, rKVP.Key, kvp.Key, hVal.Points, hVal.grLevel, hVal.grStrength);
                        rVal.tDict[kvp.Key] = hVal;
                    }
                    newADict[aKVP.Key][rKVP.Key] = rVal;
                    //Console.WriteLine("-- {0} --\n", rKVP.Value);
                }
            }
        }
Example #22
0
 protected override void Populate()
 {
     Exception exception;
     try
     {
         object obj2;
         List<TreeNode> list = new List<TreeNode>();
         bool flag = false;
         try
         {
             using (IDbConnection connection = base.Repository.Open())
             {
                 if (((base.TreeView != null) && !base.TreeView.IsDisposed) && base.TreeView.IsHandleCreated)
                 {
                     base.TreeView.BeginInvoke(new Action<string>(this.SetStatus), new object[] { "Populating" });
                 }
                 string cmdText = base.Repository.IsAzure ? "select name from sys.databases" : "dbo.sp_MShasdbaccess";
                 using (SqlDataReader reader = new SqlCommand(cmdText, (SqlConnection) connection).ExecuteReader())
                 {
                     while (reader.Read())
                     {
                         Repository r = base.Repository.CreateChild(reader[0].ToString());
                         list.Add(new DynamicSchemaNode(r));
                     }
                 }
                 lock ((obj2 = base.Locker))
                 {
                     if ((base.Worker != Thread.CurrentThread) || !base.WaitForTreeView())
                     {
                         return;
                     }
                     base.TreeView.BeginInvoke(new Action<IEnumerable<TreeNode>>(this.AddNodes), new object[] { list });
                     base.TreeView.BeginInvoke(new Action<string>(this.SetStatus), new object[] { "" });
                 }
                 flag = true;
             }
         }
         catch (Exception exception1)
         {
             exception = exception1;
             if (!base.WaitForTreeView())
             {
                 return;
             }
             lock ((obj2 = base.Locker))
             {
                 if (base.Worker != Thread.CurrentThread)
                 {
                     return;
                 }
                 base.TreeView.BeginInvoke(new Action<string>(this.SetStatus), new object[] { "Error: " + exception.Message });
             }
         }
         finally
         {
             base.Populating = false;
         }
         lock ((obj2 = base.Locker))
         {
             if (base.Worker == Thread.CurrentThread)
             {
                 base.TreeView.BeginInvoke(new Action<bool>(this.SetComplete), new object[] { flag });
             }
         }
     }
     catch (Exception exception2)
     {
         exception = exception2;
         Program.ProcessException(exception);
     }
 }
 private void btnMethod1_Click(object sender, EventArgs e)
 {
     double smallBet, mediumBet, bigBet, minInvest = 0.0, percentTake = 0.0, percentMoneyTake = 0.0;
     parseBets(out smallBet, out mediumBet, out bigBet);
     int groups = 0;
     string topLeaguesValue = "All Leagues";
     Invoke(new MethodInvoker(delegate()
     {
         int.TryParse(cboxGroup.SelectedItem.ToString(), out groups);
         topLeaguesValue = cboxTopLeagues.SelectedItem.ToString();
         numMinMatches.Minimum = groups;
     }));
     string q = @"SELECT sr.Date FROM dbo.Ivnet i, dbo.SportRadar sr
                              WHERE i.Guessed is not null AND i.SportRadarID=sr.ID AND sr.Date>=@FromDate AND sr.Date<=@ToDate
                              GROUP BY sr.Date ORDER BY sr.Date";        // HAVING COUNT(sr.Date)>3
     using (SqlConnection connection = new SqlConnection(MainForm.STRCONN))
     {
         connection.Open();
         SqlCommand selectCmd = new SqlCommand(q, connection);
         selectCmd.Parameters.AddWithValue("@FromDate", dtpFrom.Value.ToString("yyyy-MM-dd"));
         selectCmd.Parameters.AddWithValue("@ToDate", dtpTo.Value.ToString("yyyy-MM-dd"));
         List<string> dates = new List<string>();
         SqlDataReader reader;
         using (reader = selectCmd.ExecuteReader())
         {
             while (reader.Read())
             {
                 dates.Add(reader.GetDateTime(0).ToString("yyyy-MM-dd"));
             }
         }
         Method1 method1 = new Method1();
         q = String.Format("SELECT {0} Country,League FROM dbo.Leagues WHERE Season='2011/12' ORDER BY GuessedPercent DESC",
             topLeaguesValue == "All Leagues" ? "" : topLeaguesValue);
         method1.topCountries = new List<string>();
         method1.topLeagues = new List<string>();
         using (reader = new SqlCommand(q, connection).ExecuteReader())
         {
             while (reader.Read())
             {
                 method1.topCountries.Add(reader["Country"].ToString());
                 method1.topLeagues.Add(reader["League"].ToString());
             }
         }
         method1.Connection = connection;
         method1.groups = groups;
         method1.minMatches = (int)numMinMatches.Value;
         method1.smallBet = smallBet;
         method1.mediumBet = mediumBet;
         method1.bigBet = bigBet;
         method1.isTip1 = cbTip1.Checked;
         method1.isTipX = cbTipX.Checked;
         method1.isTip2 = cbTip2.Checked;
         method1.isScore1 = cbScore1.Checked;
         method1.isScoreX = cbScoreX.Checked;
         method1.isScore2 = cbScore2.Checked;
         method1.isSmallBet = cbSmallBet.Checked;
         method1.isMediumBet = cbMediumBet.Checked;
         method1.isBigBet = cbBigBet.Checked;
         method1.isGroupAll = cbGroupAll.Checked;
         method1.isIncremental = cbIncrement.Checked;
         if (method1.isIncremental)
         {
             double.TryParse(tbMinInvest.Text, out minInvest);
             double.TryParse(tbPercentTake.Text, out percentTake);
             double.TryParse(tbMaxInvest.Text, out method1.maxInvest);
             double.TryParse(tbMaxGroupInvest.Text, out method1.maxGroupInvest);
             method1.minInvest = minInvest;
         }
         foreach (string date in dates)
         {
             method1.propInvest = 1.0;
             method1.processRound(date, false);
             if (method1.isIncremental) method1.propInvest = method1.minInvest / method1.investedMoney;
             //Console.WriteLine(", maxInvest: {0}, investedMoney: {1}", method1.maxInvest, method1.investedMoney);
             //Console.WriteLine("minInvest: {0}, percentMoneyTake: {1}", method1.profit, percentMoneyTake);
             method1.processRound(date);
             if (method1.isIncremental)
             {
                 if (cbPercentTake.Checked && method1.profit > 0)
                 {
                     percentMoneyTake = method1.profit * percentTake / 100;
                     method1.allProfit += percentMoneyTake;
                     method1.profit -= percentMoneyTake;
                 }
                 method1.minInvest = method1.minInvest + method1.profit;
                 if (method1.minInvest < minInvest) method1.minInvest = minInvest;
                 if (cbMaxInvest.Checked && method1.minInvest > method1.maxInvest) method1.minInvest = method1.maxInvest;
             }
         }
         string summary = @"<div style='border-top:3px solid black;'><table>
     <thead>
     <tr cellspan='2'><th>Summary:</th></tr>
     </thead>
     <tbody>
     <tr><td>All Investment:</td><td><b>{0:0.00}</b></td>    <td>&nbsp;&nbsp;</td><td>Won Rounds</td><td><b>{3}</b></td></tr>
     <tr><td>All Profit:</td><td><b>{1:0.00}</b></td>        <td>&nbsp;&nbsp;</td><td>Lost Rounds</td><td><b>{4}</b></td></tr>
     <tr><td>Percent:</td><td><b>{2:0}%</b></td>             <td>&nbsp;&nbsp;</td><td></td><td><b></b></td></tr>
     </tbody>
                     </table></div>";
         summary = String.Format(summary, method1.allInvestment, method1.allProfit, method1.allProfit / method1.allInvestment * 100,
             method1.wonRounds, method1.lostRounds);
         browser.DocumentText = "<html><head></head><body style='font-family:Verdana;font-size:12px;'>" + method1.html + summary + "</body></html>";
     }
 }
Example #24
0
        private void doWorstSituation()
        {
            byte prevReceived, prevScored, received, scored;
            string q = @"SELECT * FROM dbo.history ORDER BY Country,League,Season,Team,Round";
            ulong totalGames = 0;
            DoublingVal dblVal = new DoublingVal();

            prevReceived = prevScored = 0;
            DoublingXForm.dblKey = DoublingXForm.prevDblKey = new DoublingKey();
            using (SqlDataReader reader = new SqlCommand(q, this.connection).ExecuteReader())
            {
                while (reader.Read())
                {
                    DoublingXForm.dblKey.Country = reader["Country"].ToString();
                    DoublingXForm.dblKey.League = reader["League"].ToString();
                    DoublingXForm.dblKey.Season = reader["Season"].ToString();
                    DoublingXForm.dblKey.Team = reader["Team"].ToString();
                    DoublingXForm.round = (byte)reader["Round"];
                    DoublingXForm.date = (DateTime)reader["Date"];
                    scored = (byte)reader["Scored"];
                    received = (byte)reader["Received"];
                    if (!DoublingXForm.dblDict.ContainsKey(DoublingXForm.dblKey))
                    {
                        dblVal.finish(true);
                        dblVal = new DoublingVal();
                        DoublingXForm.lstDblVal = new List<DoublingVal>();
                    }
                    if (received - prevReceived != scored - prevScored)
                    {
                        if (dblVal.rounds == 0)
                        {
                            dblVal.startRound = DoublingXForm.round;
                            dblVal.startDate = DoublingXForm.date;
                        }
                        dblVal.rounds++;
                    }
                    else
                    {
                        dblVal.finish(false);
                        dblVal = new DoublingVal();
                    }
                    DoublingXForm.prevDblKey = DoublingXForm.dblKey;
                    DoublingXForm.prevRound = DoublingXForm.round;
                    DoublingXForm.prevDate = DoublingXForm.date;
                    prevScored = scored;
                    prevReceived = received;
                    totalGames++;
                }
                dblVal.finish(true);
            }

            Dictionary<DoublingKey, List<DoublingVal>> newDblDict = new Dictionary<DoublingKey, List<DoublingVal>>();
            foreach (var kvp in DoublingXForm.dblDict)
                newDblDict[kvp.Key] = (from item in kvp.Value orderby item.rounds descending select item).ToList<DoublingVal>();
            var orderedDblDict = from item in newDblDict orderby item.Value[0].rounds descending select item;

            int badOnes = 0, count = DoublingXForm.dblDict.Count, i = 0, n1 = 0, n2 = 20, progress = 0, totalRuns = 0;
            foreach (var kvp in orderedDblDict)
            {
                if (++i >= n1 && i <= n2)
                {
                    progress = (int)((double)(i) / count * 100);
                    backgroundWorker.ReportProgress(progress, new BGReport(String.Format("{0}", kvp.Key)));
                }
                foreach (DoublingVal val in kvp.Value)
                {
                    if (i >= n1 && i <= n2) backgroundWorker.ReportProgress(progress, new BGReport(String.Format("{0}", val), val.rounds > 9 ? Brushes.Red : Brushes.Black));
                    if (val.rounds > 9) badOnes++;
                    totalRuns++;
                }
            }
            Console.WriteLine("Total games: {0}, Total runs: {1}, Total Teams: {2}, Bad Ones: {3}", totalGames, totalRuns, count, badOnes);
        }
Example #25
0
        private void doBetSomeMoney()
        {
            byte i = DoublingXForm.STARTROUND, j;
            byte? scoreA, scoreH;
            double bank = DoublingXForm.BANKMONEY, bet = DoublingXForm.BETMONEYPERROUND;
            int r;
            string aTeam, hTeam, q = @"SELECT * FROM dbo.archive WHERE Round>=" + DoublingXForm.STARTROUND + " ORDER BY Country,League,Season,Round";
            ArchiveVal aVal;
            Brush color;
            Dictionary<LRTKey, ArchiveVal> aDict = new Dictionary<LRTKey,ArchiveVal>();
            Dictionary<LRTKey, Power> hDict;

            backgroundWorker.ReportProgress(25, new BGReport("Processing dbo.archive ..."));
            using (SqlDataReader reader = new SqlCommand(q, this.connection).ExecuteReader())
            {
                while (reader.Read())
                {
                    aTeam = reader["AwayTeam"].ToString();
                    hTeam = reader["HomeTeam"].ToString();
                    scoreA = reader["ScoreA"] is DBNull ? null : (byte?)reader["ScoreA"];
                    scoreH = reader["ScoreH"] is DBNull ? null : (byte?)reader["ScoreH"];
                    aDict[new LRTKey(reader, hTeam, aTeam)] = new ArchiveVal(scoreH, scoreA, reader["DrawOdds"]);
                    aDict[new LRTKey(reader, aTeam, hTeam)] = new ArchiveVal(scoreA, scoreH, reader["DrawOdds"]);
                }
            }

            backgroundWorker.ReportProgress(50, new BGReport("Processing dbo.history ..."));
            hDict = MethodAForm.getHistoryDict(this.connection);

            var dictSortedByRound = from item in hDict
                                    let otherKey = LRTKey.getOtherKey(item.Key)
                                    where item.Key.Season == "2011/12" && Math.Abs(item.Value.PrevAvgStrength - hDict[otherKey].PrevAvgStrength) <= 1
                                    orderby item.Key.Round select item;
            var dictRound = from item in dictSortedByRound where item.Key.Round == i select item;
            while (dictRound.Count() > 0)
            {
                using (var cursor = dictRound.GetEnumerator())
                {
                    r = (new Random()).Next(dictRound.Count()) + 1;
                    for (j = 0; j < r; j++)
                        cursor.MoveNext();
                    if (aDict[cursor.Current.Key].result == null) {
                        cursor.Reset();
                        while (cursor.MoveNext()) if (aDict[cursor.Current.Key].result != null)
                            break;
                    }
                    aVal = aDict[cursor.Current.Key];
                    if (aVal.result == 0)
                    {
                        bank += bet * (aVal.DrawOdds - 0.15);
                        bet = DoublingXForm.BETMONEYPERROUND;
                        color = Brushes.Blue;
                    }
                    else
                    {
                        bank -= bet;
                        bet *= 2;
                        color = Brushes.Black;
                    }
                    if (bank < 0) color = Brushes.Red;
                    backgroundWorker.ReportProgress(70, new BGReport(
                        String.Format("{0} {1} - Bet:{2} Bank:{3}", cursor.Current.Key, aVal, bet, bank), color
                    ));
                }
                if (bank < 0) break;
                i++;
                dictRound = from item in dictSortedByRound where item.Key.Round == i select item;
            }
        }
Example #26
0
 private void bGetDBt_Click(object sender, EventArgs e) {
     if (!Ut.IsCommand(tbSQLConn)) return;
     using (SqlConnection db = new SqlConnection(tbSQLConn.Text)) {
         db.Open();
         using (SqlDataReader dr = new SqlCommand("SELECT (SELECT name FROM sys.databases WHERE sys.databases.database_id = sys.master_files.database_id)as db,name,physical_name FROM sys.master_files;", db).ExecuteReader()) {
             DataTable dt = new DataTable();
             int cx = dr.FieldCount;
             for (int x = 0; x < cx; x++) {
                 dt.Columns.Add(dr.GetName(x), dr.GetFieldType(x));
             }
             Object[] vals = new Object[cx];
             while (dr.Read()) {
                 dr.GetValues(vals);
                 dt.Rows.Add(vals);
             }
             dt.AcceptChanges();
             gv.DataSource = dt;
             gv.Refresh();
             gv.AutoResizeColumns();
         }
         db.Close();
     }
 }
Example #27
0
        /*public object DLookup(string table, string field, DLookupData[] clauses)
        {
            object data = null;
            try
            {
            }
            catch (Exception ee)
            {
                OnError(ee);
            }
            return data;
        }*/
        public object[] executeSql(string query, SqlTypes type, SqlParameter[] parameters)
        {
            /*if (!Licencing.validate())
                return null;*/

            object[] returnObj = new object[5];
            returnObj[1] = SqlHasReturn.NO;
            //if (key.Equals(SecurityKey))
            {
                bool connectedP = isConnectedDo;
                try
                {

                    if (type == SqlTypes.AUTO)
                    {
                        if (query.ToUpper().StartsWith("INSERT"))
                            type = SqlTypes.INSERT;
                        else if (query.ToUpper().StartsWith("SELECT"))
                            type = SqlTypes.SELECT;
                        else if (query.ToUpper().StartsWith("UPDATE"))
                            type = SqlTypes.UPDATE;
                        else
                            throw new Exception("");

                        if (type == SqlTypes.INSERT & parameters != null)
                            type = SqlTypes.INSERT_CUSTOM;

                    }

                    if (dbType == DatabaseType.MSSQL)
                        query = getQueryDbChanger(query, type);

                    if (type == SqlTypes.STORED_PROCEDURE)
                    {
                        if (dbType == DatabaseType.MSSQL)
                        {
                            SqlCommand command = new SqlCommand();
                            command.CommandType = CommandType.StoredProcedure;
                            command.Parameters.AddRange(parameters);
                            command.Connection = MSSQLConn;
                            command.CommandText = query;
                            DataTable dt = new DataTable();
                            SqlDataAdapter da = new SqlDataAdapter(command);
                            da.Fill(dt);
                            da.Dispose();

                            if (dt.Rows.Count > 0)
                            {
                                returnObj[1] = SqlHasReturn.YES;
                                returnObj[2] = Int32.Parse(dt.Rows[0].ItemArray[0].ToString());
                            }
                        }
                    }
                    else if (type == SqlTypes.STORE_PROCEDURE_VALUE)
                    {
                        if (dbType == DatabaseType.MSSQL)
                        {
                            Object returnValue;
                            SqlCommand command = new SqlCommand();

                            foreach (SqlParameter obj in parameters)
                                command.Parameters.Add(obj);

                            var returnParameter = command.Parameters.Add("@ReturnVal", SqlDbType.Int);
                            returnParameter.Direction = ParameterDirection.ReturnValue;

                            command.CommandType = CommandType.StoredProcedure;
                            command.Connection = MSSQLConn;
                            command.CommandText = query;
                            command.ExecuteNonQuery();

                            returnValue = returnParameter;
                            returnObj[1] = SqlHasReturn.YES;
                            returnObj[2] = returnValue;
                        }
                    }
                    else if (type == SqlTypes.STORED_PROCEDURE_DATATABLE)
                    {
                        if (dbType == DatabaseType.MSSQL)
                        {
                            SqlCommand command = new SqlCommand();
                            command.CommandType = CommandType.StoredProcedure;
                            command.Parameters.AddRange(parameters);
                            command.Connection = MSSQLConn;
                            command.CommandText = query;
                            DataTable dt = new DataTable();
                            SqlDataAdapter da = new SqlDataAdapter(command);
                            da.Fill(dt);
                            da.Dispose();
                            returnObj[1] = SqlHasReturn.YES;
                            returnObj[2] = dt;
                        }
                    }
                    else if (type == SqlTypes.INSERT_RETURN_ID)
                    {
                        if (dbType == DatabaseType.MSSQL)
                        {
                            using (SqlDataReader Dr = new SqlCommand(query + ";SELECT CAST(SCOPE_IDENTITY() as int)", MSSQLConn).ExecuteReader())
                            {
                                if (Dr.Read())
                                {
                                    returnObj[1] = SqlHasReturn.YES;
                                    returnObj[2] = Int32.Parse(Dr[0].ToString());
                                }
                            }
                        }
                    }
                    else if (type == SqlTypes.INSERT)
                    {
                        if (dbType == DatabaseType.MSSQL)
                        {
                            using (SqlCommand commando = new SqlCommand(query, MSSQLConn))
                            {
                                int rws = commando.ExecuteNonQuery();

                                if (rws > 0)
                                    returnObj[1] = SqlHasReturn.YES;

                                returnObj[2] = rws;
                            }
                        }
                        else if (dbType == DatabaseType.MSSQL)
                        {
                            using (MySqlCommand commando = new MySqlCommand(query, MySQLConn))
                            {
                                int rws = commando.ExecuteNonQuery();

                                if (rws > 0)
                                    returnObj[1] = SqlHasReturn.YES;

                                returnObj[2] = rws;
                            }
                        }
                        else if (dbType == DatabaseType.MSACCESS2003 | dbType == DatabaseType.MSACCESS2007)
                        {
                            using (OleDbCommand commando = new OleDbCommand(query, MSDBSQLConn))
                            {
                                int rws = commando.ExecuteNonQuery();

                                if (rws > 0)
                                    returnObj[1] = SqlHasReturn.YES;

                                returnObj[2] = rws;
                            }
                        }
                    }
                    else if (type == SqlTypes.SELECT)
                    {
                        if (dbType == DatabaseType.MSSQL)
                        {
                            SqlDataReader Dr = new SqlCommand(query, MSSQLConn).ExecuteReader();
                            returnObj[1] = SqlHasReturn.YES;
                            returnObj[2] = Dr;
                        }
                        else if (dbType == DatabaseType.MYSQL)
                        {
                            MySqlDataReader Dr = new MySqlCommand(query, MySQLConn).ExecuteReader();
                            returnObj[1] = SqlHasReturn.YES;
                            returnObj[2] = Dr;
                        }
                        else if (dbType == DatabaseType.MSACCESS2003 | dbType == DatabaseType.MSACCESS2007)
                        {
                            OleDbDataReader Dr = new OleDbCommand(query, MSDBSQLConn).ExecuteReader();
                            returnObj[1] = SqlHasReturn.YES;
                            returnObj[2] = Dr;
                        }
                    }
                    else if (type == SqlTypes.SELECT_DATATABLE)
                    {
                        if (dbType == DatabaseType.MSSQL)
                        {
                            SqlDataAdapter a = new SqlDataAdapter(query, MSSQLConn);
                            DataTable dt = new DataTable();
                            a.Fill(dt);
                            returnObj[1] = SqlHasReturn.YES;
                            returnObj[2] = dt;
                            a.Dispose();
                        }
                        else if (dbType == DatabaseType.MYSQL)
                        {
                            MySqlDataAdapter a = new MySqlDataAdapter(query, MySQLConn);
                            DataTable dt = new DataTable();
                            a.Fill(dt);
                            returnObj[1] = SqlHasReturn.YES;
                            returnObj[2] = dt;
                            a.Dispose();
                        }
                        else if (dbType == DatabaseType.MSACCESS2003 | dbType == DatabaseType.MSACCESS2007)
                        {
                            OleDbDataAdapter a = new OleDbDataAdapter(query, MSDBSQLConn);
                            DataTable dt = new DataTable();
                            a.Fill(dt);
                            returnObj[1] = SqlHasReturn.YES;
                            returnObj[2] = dt;
                            a.Dispose();
                        }
                    }
                    else if (type == SqlTypes.UPDATE)
                    {
                        if (dbType == DatabaseType.MSSQL)
                        {
                            SqlDataReader Dr = new SqlCommand(query, MSSQLConn).ExecuteReader();
                            returnObj[1] = SqlHasReturn.YES;
                            returnObj[2] = Dr;
                        }
                        else if (dbType == DatabaseType.MYSQL)
                        {
                            MySqlDataReader Dr = new MySqlCommand(query, MySQLConn).ExecuteReader();
                            returnObj[1] = SqlHasReturn.YES;
                            returnObj[2] = Dr;
                        }
                        else if (dbType == DatabaseType.MSACCESS2003 | dbType == DatabaseType.MSACCESS2007)
                        {
                            OleDbDataReader Dr = new OleDbCommand(query, MSDBSQLConn).ExecuteReader();
                            returnObj[1] = SqlHasReturn.YES;
                            returnObj[2] = Dr;
                        }
                    }
                    else if (type == SqlTypes.INSERT_CUSTOM & parameters != null)
                    {
                        if (dbType == DatabaseType.MSSQL)
                        {
                            using (SqlCommand commanda = new SqlCommand(query, MSSQLConn))
                            {
                                commanda.Parameters.AddRange(parameters);

                                int rws = commanda.ExecuteNonQuery();

                                if (rws > 0)
                                    returnObj[1] = SqlHasReturn.YES;

                                returnObj[2] = rws;
                            }
                        }
                        else if (dbType == DatabaseType.MYSQL)
                        {
                            using (MySqlCommand commanda = new MySqlCommand(query, MySQLConn))
                            {
                                commanda.Parameters.AddRange(parameters);

                                int rws = commanda.ExecuteNonQuery();

                                if (rws > 0)
                                    returnObj[1] = SqlHasReturn.YES;

                                returnObj[2] = rws;
                            }
                        }
                        else if (dbType == DatabaseType.MSACCESS2003 | dbType == DatabaseType.MSACCESS2007)
                        {
                            using (OleDbCommand commanda = new OleDbCommand(query, MSDBSQLConn))
                            {
                                commanda.Parameters.AddRange(parameters);

                                int rws = commanda.ExecuteNonQuery();

                                if (rws > 0)
                                    returnObj[1] = SqlHasReturn.YES;

                                returnObj[2] = rws;
                            }
                        }
                    }
                }
                catch (Exception eee)
                {
                    OnError(eee);
                    returnObj[1] = SqlHasReturn.NO;
                    returnObj[4] = eee;
                }
                finally
                {
                    if (!connectedP & type != SqlTypes.SELECT)
                        closeConnection();
                }
                returnObj[0] = SqlResult.SUCCESS;
                return returnObj;
            }
            /*else
                return new object[] { SqlResult.FAIL, false };*/
        }
 private void btnNewMatches_Click(object sender, EventArgs e)
 {
     SqlDataReader reader;
     string q = @"SELECT sr.Date FROM dbo.Ivnet i, dbo.SportRadar sr
                     WHERE i.Guessed IS NULL AND i.SportRadarID=sr.ID AND sr.Date>=CONVERT(date,GETDATE()) GROUP BY sr.Date ORDER BY sr.Date";
     List<string> dates = new List<string>();
     using (SqlConnection connection = new SqlConnection(MainForm.STRCONN))
     {
         connection.Open();
         using (reader = new SqlCommand(q, connection).ExecuteReader())
         {
             while (reader.Read())
             {
                 dates.Add(reader.GetDateTime(0).ToString("yyyy-MM-dd"));
             }
         }
         int tipWinner, matchIndex = 0;
         double odds, currentInvestment, smallBet, mediumBet, bigBet;
         SqlCommand selectCmd;
         string html = "", rowFormat = @"<tr><td class='checkbox'><input type='checkbox' /></td><td class='No'>{0}</td>
                         <td class='Country'>{1}</td><td class='League'>{2}</td>
                         <td class='HomeTeam'>{3}</td><td class='AwayTeam'>{4}</td><td class='Tip'>{5}</td><td class='Odds'>{6}</td></tr>";
         parseBets(out smallBet, out mediumBet, out bigBet);
         foreach (string date in dates)
         {
             q = @"SELECT i.ID ID, sr.Country Country, sr.League League, sr.Season Season, sr.Round Round, sr.Date Date,
                         sr.HomeTeam HomeTeam, sr.AwayTeam AwayTeam, i.TipGoalsH TipGoalsH, i.TipGoalsA TipGoalsA,
                         sr.HomeOdds HomeOdds, sr.DrawOdds DrawOdds, sr.AwayOdds AwayOdds
                         FROM dbo.Ivnet i, SoccerBase.dbo.SportRadar sr
                         WHERE i.SportRadarID = sr.ID AND i.Guessed IS NULL AND sr.Date = @Date";
             selectCmd = new SqlCommand(q, connection);
             selectCmd.Parameters.AddWithValue("@Date", date);
             using (reader = selectCmd.ExecuteReader())
             {
                 html += String.Format("<p2>{0:dddd, MMMM d, yyyy}:</p2>", DateTime.Parse(date));
                 html += @"<table border='1' style='font-family:Verdana;font-size:12px;'><thead><tr>
                             <th></th><th>No:</th><th>Држава</th><th>Првенство</th>
                             <th>Домашен Тим</th><th>Гостински Тим</th><th>Тип</th><th>BWin Коефициенти</th></tr></thead><tbody>";
                 currentInvestment = 0.0;
                 while (reader.Read())
                 {
                     tipWinner = (byte)reader["TipGoalsH"] - (byte)reader["TipGoalsA"];
                     tipWinner = tipWinner >= 0 ? (tipWinner > 0 ? 0 : 1) : 2;
                     if (tipWinner == 0)
                     {
                         odds = (double)reader["HomeOdds"];
                     }
                     else if (tipWinner == 1)
                     {
                         odds = (double)reader["DrawOdds"];
                     }
                     else
                     {
                         odds = (double)reader["AwayOdds"];
                     }
                     currentInvestment = 0.0;
                     if (odds < 1.25) continue;
                     if (odds >= 1.25 && odds <= 1.5 && cbBigBet.Checked) currentInvestment = bigBet;
                     else if (odds > 1.5 && odds <= 2.2 && cbMediumBet.Checked) currentInvestment = mediumBet;
                     else if (odds > 2.2 && cbSmallBet.Checked) currentInvestment = smallBet;
                     else continue;
                     html += String.Format(rowFormat, ++matchIndex,
                         reader["Country"], reader["League"], reader["HomeTeam"], reader["AwayTeam"],
                         reader["TipGoalsH"] + ":" + reader["TipGoalsA"],
                         reader["HomeOdds"].ToString() + "&nbsp;&nbsp;" + reader["DrawOdds"].ToString() + "&nbsp;&nbsp;" + reader["AwayOdds"].ToString()
                     );
                 }
                 html += "</tbody></table><br/>";
             }
         }
         tempHTML = html;
         browser.DocumentText = @"<html><head>
                         <script type='text/javascript'>
                             function func() {
                                 var inputs = document.getElementsByTagName('input');
                                 var tr;
                                 for (var i = 0; i < inputs.length; i++) {
                                     if (inputs[i].getAttribute('type')=='checkbox') {
                                         inputs[i].onclick = function() {
                                             tr = this.parentNode.parentNode;
                                             if (this.checked) tr.style.backgroundColor = 'cyan';
                                             else tr.style.backgroundColor = '';
                                         }
                                     }
                                 }
                             }
                         </script>
                     </head>
                     <body style='font-family:Verdana;font-size:12px;' onload='func();'>" + html +
             @"<p>Send to email:
                         <select id='emailsSelect'>
                             <option value='err8086@gmail.com'>err8086@gmail.com</option>
                             <option value='bingo_2010_@live.com'>bingo_2010_@live.com</option>
                         </select>
                         <button onclick='window.external.sendEmail(document.getElementById(""emailsSelect"").value);'>Send</button>
                     </p></body></html>";
     }
 }
 /// <summary>
 /// Get tag ID data from the SQL database table.
 /// </summary>
 public void GetData(ListView listview)
 {
     using (sqlConn = new SqlConnection(connectionString))
     {
         sqlConn.Open();
         using (SqlDataReader reader = new SqlCommand("SELECT * FROM TagInfo", sqlConn).ExecuteReader())
         {
             try
             {
                 while (reader.Read())
                 {
                     string[] rowitem = new string[2];
                     rowitem[0] = reader.GetString(reader.GetOrdinal("TagId"));
                     rowitem[1] = reader.GetDateTime(reader.GetOrdinal("TagTime")).ToString();
                     ListViewItem listitem = new ListViewItem(rowitem);
                     //table.Rows.Add(epc, time);
                     listview.Items.Add(listitem);
                 }
                 reader.Close();
             }
             catch (System.Data.SqlClient.SqlException ee)
             {
                 MessageBox.Show(ee.Message.ToString());
             }
         }
         sqlConn.Close();
     }
 }
Example #30
0
        public Stream GetStream(int id, string filename)
        {
            Trace.WriteLine("DBImagePlugin - GetStream");

            var connectionObj = GetConnectionObj();
            connectionObj.Open();
            Stream stream;

            using (connectionObj)
            {
                var sqlDataReader = new SqlCommand(imageBlobQuery, connectionObj)
                {
                    Parameters =
                    {
                        CreateParameter("id", id, SqlDbType.Int),
                        CreateParameter("name", filename, SqlDbType.NVarChar)
                    }
                }.ExecuteReader();

                using (sqlDataReader)
                {
                    if (!sqlDataReader.Read())
                    {
                        throw new FileNotFoundException("Failed to find the specified image " + id + " in the database");
                    }
                    stream = sqlDataReader.GetSqlBytes(0).Stream;
                }
            }

            return stream;
        }