コード例 #1
0
ファイル: ICrudHelper.cs プロジェクト: oscarito9410/wpHotel
        public async Task<int> getMaxAsync(String tableName,String id)
        {
            int max = 0;
            using (MySqlConnection MidbConexion = new MySqlConnection(this.dbPath))
            {
                MidbConexion.Open();
                MySqlCommand miComando = new MySqlCommand()
                {
                    Connection = MidbConexion,
                    CommandText = String.Format("SELECT Max({0}) AS MAXIMO FROM {1}", id, tableName)

                };
                var  reader = await miComando.ExecuteReaderAsync();
                while (reader.Read())
                {
                    if (!reader.IsDBNull(reader.GetOrdinal("Maximo")))
                    {
                        max = Convert.ToInt32(reader[0]) + 1;
                    }
                    else
                    {
                        max = 1;
                    }
                }


            }
            return max;


        }
コード例 #2
0
ファイル: Database.cs プロジェクト: Hotallday/iXat-Server
 public static async Task<List<object>> FetchArrayList(string query) {
     var list = new List<object>();
     using (var command = new MySqlCommand(query, Connection)) {
         using (var reader = await command.ExecuteReaderAsync()) {
             while (reader.Read()) {
                 for (var i = 0; i < reader.FieldCount; i++) {
                     var value = reader[i];
                     list.Add(value);
                 }
             }
         }
     }
     return list;
 }
コード例 #3
0
ファイル: Database.cs プロジェクト: Hotallday/iXat-Server
 public static async Task<Dictionary<string, object>> FetchArray(string query) {
     var dictionary = new Dictionary<string, object>();
     using (var command = new MySqlCommand(query, Connection)) {
         using (var reader = await command.ExecuteReaderAsync()) {
             while (reader.Read()) {
                 for (var i = 0; i < reader.FieldCount; i++) {
                     var key = reader.GetName(i);
                     var value = reader[i];
                     dictionary.Add(key, value);
                 }
             }
         }
     }
     return dictionary;
 }
コード例 #4
0
        private async void GetOverallDuration()
        {
            int calculatedaverage = new Int32();
            MySqlDataReader dbReader = null;

            using (MySqlConnection dbConn = new MySqlConnection("Server=" + ICResponse.Properties.Settings.Default.DBServer +
                                                ";Database=" + ICResponse.Properties.Settings.Default.DBName +
                                                ";Uid=" + ICResponse.Properties.Settings.Default.DBUser +
                                                ";Pwd=" + ICResponse.Properties.Settings.Default.DBPass + ";"))
            {
                dbConn.Open();
                using (MySqlCommand cmd = new MySqlCommand(ICResponse.Properties.Settings.Default.GetOverallAverageTime, dbConn))
                {
                    dbReader = (MySqlDataReader)await cmd.ExecuteReaderAsync();
                    while (dbReader.Read())
                    {
                        int receivedaverage = Convert.ToInt32(dbReader["OverallAverageDuration"]);
                        calculatedaverage = (receivedaverage / 60);
                    }
                }
                dbConn.Close();
            }           
            
            ATT.Content = Convert.ToString(calculatedaverage);
            if (calculatedaverage >= 20)
            {
                ATT.Foreground = Brushes.Red;
            }
            if (calculatedaverage < 20 && calculatedaverage > 10)
            {
                ATT.Foreground = Brushes.Yellow;
            }
            if (calculatedaverage <= 10)
            {
                ATT.Foreground = Brushes.Chartreuse;
            }
        }
コード例 #5
0
        private async void GetAgentStats()
        {
            try
            {
                MySqlConnection dbConn = null;
                MySqlDataReader dbReader = null;
                string receivedemail = string.Empty;
                int receivedNumOfRows = 0;
                _counts.Clear();
                _times.Clear();
                _missed.Clear();
                using (dbConn = new MySqlConnection("Server=" + ICResponse.Properties.Settings.Default.DBServer +
                                                ";Database=" + ICResponse.Properties.Settings.Default.DBName +
                                                ";Uid=" + ICResponse.Properties.Settings.Default.DBUser +
                                                ";Pwd=" + ICResponse.Properties.Settings.Default.DBPass + ";"))
                {
                    dbConn.Open();

                    using (MySqlCommand cmd = new MySqlCommand(ICResponse.Properties.Settings.Default.GetGroupedCalls, dbConn))
                    {
                        dbReader = (MySqlDataReader)await cmd.ExecuteReaderAsync();
                        while (dbReader.Read())
                        {
                            receivedemail = Convert.ToString(dbReader["tech"]);
                            string formalname = GetAgentACDname(receivedemail);
                            receivedNumOfRows = Convert.ToInt32(dbReader["NumOfRows"]);
                            int averageduration = Convert.ToInt32(dbReader["TechAverageDuration"]);
                            int convertedduration = (averageduration / 60);
                            int missedcounts = GetAgentMissedCalls(formalname);                            

                            _counts.Add(new DailyAgent() { Agent = formalname, Count = receivedNumOfRows });
                            _times.Add(new DailyAgent() { Agent = formalname, Count = convertedduration });
                            _missed.Add(new DailyAgent() { Agent = formalname, Count = missedcounts });                            
                        }
                    }
                    dbReader.Close();
                    dbConn.Close();
                }               
            }
            catch (MySqlException err)
            {
                System.Diagnostics.Debug.WriteLine(err);
            }
        }
コード例 #6
0
ファイル: CrudCliente.cs プロジェクト: oscarito9410/wpHotel
        public async Task<ObservableCollection<Model.Cliente>> getAll()
        {
            ObservableCollection<Model.Cliente> listClientes = new ObservableCollection<Model.Cliente>();

            using (MySqlConnection MidbConexion = new MySqlConnection(this.dbPath))
            {
                MidbConexion.Open();
                MySqlCommand miComando = new MySqlCommand()
                {
                    Connection = MidbConexion,
                    CommandText = String.Format("SELECT*FROM cliente_detalles")
                };
                var reader =await miComando.ExecuteReaderAsync();
                while (reader.Read())
                {
                    Model.Cliente cliente = new Model.Cliente();
                    cliente.id = Convert.ToInt32(reader["id_cliente"]);
                    cliente.acompaniantes =Convert.ToInt32(reader["numpersonas"]);
                    cliente.nombre = Convert.ToString(reader["nombre"]);
                    cliente.origen = Convert.ToString(reader["lugar_procedencia"]);
                    cliente.email = Convert.ToString(reader["correo"]);
                    cliente.tarjeta = Convert.ToString(reader["numtarjeta"]);
                    cliente.dateEntrada= Convert.ToDateTime(reader["dia_entrada"]);
                    cliente.dateSalida = Convert.ToDateTime(reader["dia_salida"]);
                    cliente.diasEstancia = getDias(cliente.dateEntrada, cliente.dateSalida);
                    cliente.email = Convert.ToString(reader["correo"]);
                    cliente.telefono = Convert.ToString(reader["telefono"]);
                    
                    listClientes.Add(cliente);

                }
                return listClientes;

            }
        }
コード例 #7
0
ファイル: CrudCliente.cs プロジェクト: oscarito9410/wpHotel
        public async Task<int> getClienteGasto(int idCliente)
        {
            int clave = 1;
            using (MySqlConnection MidbConexion = new MySqlConnection(this.dbPath))
            {
                MidbConexion.Open();
                MySqlCommand miComando = new MySqlCommand()
                {
                    Connection = MidbConexion,
                    CommandText = String.Format("SELECT clv_gasto AS Clave FROM gastos WHERE id_cliente=?id_cliente")
                };
                miComando.Parameters.AddWithValue("?id_cliente", idCliente);
                var reader = await miComando.ExecuteReaderAsync();
                while (reader.Read())
                {
                    if (!reader.IsDBNull(reader.GetOrdinal("Clave")))
                    {
                        clave = Convert.ToInt32(reader[0]);
                    }
                }

            }
            return clave;
        }
コード例 #8
0
ファイル: ICrudHelper.cs プロジェクト: oscarito9410/wpHotel
        public async Task<ObservableCollection<Model.Habitacion>> getHabitacionesDisponibles(String tamanio)
        {
            ObservableCollection<Model.Habitacion> listHabitaciones = new ObservableCollection<Model.Habitacion>();

            using (MySqlConnection MidbConexion = new MySqlConnection(this.dbPath))
            {
                MidbConexion.Open();
                MySqlCommand miComando = new MySqlCommand()
                {
                    Connection = MidbConexion,
                    CommandText = String.Format("SELECT*FROM view_disponibles WHERE tamanio='{0}'", tamanio)
                };
                 var  reader = await miComando.ExecuteReaderAsync();
                while (reader.Read())
                {
                    Model.Habitacion habitacion = new Model.Habitacion();
                    habitacion.numero = Convert.ToInt32(reader["num_habitacion"]);
                    habitacion.estado = true;
                    habitacion.tamanio = Convert.ToString(reader["tamanio"]);
                    habitacion.telefono = Convert.ToString(reader["telefono"]);
                    habitacion.precio = Convert.ToDouble(reader["precio"]);
                    listHabitaciones.Add(habitacion);

                }
                return listHabitaciones;

            }
        }
コード例 #9
0
        private async ValueTask WriteToServerAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
#endif
        {
            var tableName = DestinationTableName ?? throw new InvalidOperationException("DestinationTableName must be set before calling WriteToServer");

            var bulkLoader = new MySqlBulkLoader(m_connection)
            {
                CharacterSet            = "utf8mb4",
                EscapeCharacter         = '\\',
                FieldQuotationCharacter = '\0',
                FieldTerminator         = "\t",
                LinePrefix          = null,
                LineTerminator      = "\n",
                Local               = true,
                NumberOfLinesToSkip = 0,
                Source              = this,
                TableName           = QuoteIdentifier(tableName),
                Timeout             = BulkCopyTimeout,
            };

            var closeConnection = false;

            if (m_connection.State != ConnectionState.Open)
            {
                m_connection.Open();
                closeConnection = true;
            }

            // if no user-supplied column mappings, compute them from the destination schema
            if (ColumnMappings.Count == 0)
            {
                using var cmd    = new MySqlCommand("select * from " + QuoteIdentifier(tableName) + ";", m_connection, m_transaction);
                using var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync(CommandBehavior.SchemaOnly, ioBehavior, cancellationToken).ConfigureAwait(false);

                var schema = reader.GetColumnSchema();
                for (var i = 0; i < schema.Count; i++)
                {
                    if (schema[i].DataTypeName == "BIT")
                    {
                        ColumnMappings.Add(new MySqlBulkCopyColumnMapping(i, $"@col{i}", $"`{reader.GetName(i)}` = CAST(@col{i} AS UNSIGNED)"));
                    }
                    else if (schema[i].DataTypeName == "YEAR")
                    {
                        // the current code can't distinguish between 0 = 0000 and 0 = 2000
                        throw new NotSupportedException("'YEAR' columns are not supported by MySqlBulkLoader.");
                    }
                    else
                    {
                        var type = schema[i].DataType;
                        if (type == typeof(byte[]) || (type == typeof(Guid) && (m_connection.GuidFormat == MySqlGuidFormat.Binary16 || m_connection.GuidFormat == MySqlGuidFormat.LittleEndianBinary16 || m_connection.GuidFormat == MySqlGuidFormat.TimeSwapBinary16)))
                        {
                            ColumnMappings.Add(new MySqlBulkCopyColumnMapping(i, $"@col{i}", $"`{reader.GetName(i)}` = UNHEX(@col{i})"));
                        }
                        else
                        {
                            ColumnMappings.Add(new MySqlBulkCopyColumnMapping(i, reader.GetName(i)));
                        }
                    }
                }
            }

            // set columns and expressions from the column mappings
            for (var i = 0; i < m_valuesEnumerator !.FieldCount; i++)
            {
                var columnMapping = ColumnMappings.FirstOrDefault(x => x.SourceOrdinal == i);
                if (columnMapping is null)
                {
                    bulkLoader.Columns.Add("@`\uE002\bignore`");
                }
                else
                {
                    if (columnMapping.DestinationColumn.Length == 0)
                    {
                        throw new InvalidOperationException("MySqlBulkCopyColumnMapping.DestinationName is not set.");
                    }
                    if (columnMapping.DestinationColumn[0] == '@')
                    {
                        bulkLoader.Columns.Add(columnMapping.DestinationColumn);
                    }
                    else
                    {
                        bulkLoader.Columns.Add(QuoteIdentifier(columnMapping.DestinationColumn));
                    }
                    if (columnMapping.Expression is object)
                    {
                        bulkLoader.Expressions.Add(columnMapping.Expression);
                    }
                }
            }

            await bulkLoader.LoadAsync(ioBehavior, cancellationToken).ConfigureAwait(false);

            if (closeConnection)
            {
                m_connection.Close();
            }

#if !NETSTANDARD2_1 && !NETCOREAPP3_0
            return(default);
コード例 #10
0
ファイル: UserRepository.cs プロジェクト: GNewsCo/DrawPub
        public async Task<IList<string>> GetUserRole(int userId)
        {
            IList<string> roles = new List<string>();

            string query = @"SELECT
                                Role
                             FROM 
                                userrole
                              WHERE
                                UserId = ?UserId;";


            MySqlCommand command = new MySqlCommand();

            command.CommandText = query;

            command.Parameters.AddWithValue("UserId", userId);

            using (MySqlConnection connection = (MySqlConnection)await _connectionProvider.GetAsync())
            {
                command.Connection = connection;
                await connection.OpenAsync();

                using (var reader = await command.ExecuteReaderAsync())
                {
                    while (reader.Read())
                    {
                        roles.Add(reader.GetString(0));
                    }
                }

                await connection.CloseAsync();
            }

            return roles;

        }
コード例 #11
0
        /// <summary>
        /// Execute a SQL prepared statement on the database.
        /// </summary>
        /// <param name="stmt"></param>
        /// <returns></returns>
        public async Task<DataTable> Execute(MySqlCommand stmt, bool enforceConstraints = true, string[] pKeys = null)
        {
            DataTable result = null;
            if (connState == ConnectionState.Open)
            {
                using (DbDataReader reader = await stmt.ExecuteReaderAsync())
                {
                    var dt = new DataTable();
                    if (!enforceConstraints)
                    {
                        var ds = new DataSet();
                        ds.EnforceConstraints = false;
                        ds.Tables.Add(dt);
                    }

                    if (pKeys != null)
                    {
                        DataColumn[] keys = new DataColumn[pKeys.Length];
                        for (int i = 0; i < pKeys.Length; i++)
                        {
                            dt.Columns.Add(pKeys[i]);
                            keys[i] = dt.Columns[pKeys[i]];
                        }
                        dt.PrimaryKey = keys;
                    }

                    dt.Load(reader);
                    result = dt;
                }
            }
            return result;
        }
コード例 #12
0
ファイル: LogIn.xaml.cs プロジェクト: Toffer305/icresponse2
        private async void attemptLogin()
        {
            try
            {
                string enteredEmail = this.Login_Email.Text + "@icrealtime.com";
                string enteredPassword = this.Login_Password.Password;
                string receivedPassword = string.Empty;
                string receivedLevel = string.Empty;

                // DB Connection
                dbConn = new MySqlConnection("Server=" + ICResponse.Properties.Settings.Default.DBServer + ";Database=" + ICResponse.Properties.Settings.Default.DBName + ";Uid=" + ICResponse.Properties.Settings.Default.DBUser + ";Pwd=" + ICResponse.Properties.Settings.Default.DBPass + ";");
                await dbConn.OpenAsync();
                // DB Command Preparation
                cmd = new MySqlCommand(ICResponse.Properties.Settings.Default.SelectAgentByEmail, dbConn);
                cmd.Parameters.AddWithValue("@email", enteredEmail);
                cmd.Prepare();
                // DB Reader Execution
                dbReader = (MySqlDataReader) await cmd.ExecuteReaderAsync();
                // Loop through results
                while (await dbReader.ReadAsync())
                {
                    receivedPassword = Convert.ToString(dbReader["password"]);
                    receivedLevel = Convert.ToString(dbReader["level"]);
                }

                if (enteredPassword != receivedPassword)
                {
                    ModernDialog msgbox = new ModernDialog();
                    msgbox.Title = "Not found";
                    msgbox.Content = "Incorrect Username or Password.";
                    msgbox.Buttons = new[] { msgbox.OkButton };
                    msgbox.ShowDialog();
                    dbReader.Close();
                }
                else
                {
                    ICResponse.Properties.Settings.Default.LoginUsername = Convert.ToString(dbReader["email"]);
                    ICResponse.Properties.Settings.Default.AgentID = Convert.ToInt32(dbReader["agentID"]);
                    ICResponse.Properties.Settings.Default.AgentFirstName = Convert.ToString(dbReader["first"]);
                    ICResponse.Properties.Settings.Default.AgentLastName = Convert.ToString(dbReader["last"]);
                    ICResponse.Properties.Settings.Default.LoginPassword = receivedPassword;
                    ICResponse.Properties.Settings.Default.LoginLevel = receivedLevel;
                    ICResponse.Properties.Settings.Default.LoginNick = ICResponse.Properties.Settings.Default.LoginUsername.Replace("@icrealtime.com", "");
                    ICResponse.Properties.Settings.Default.Save();
                    dbReader.Close();

                    var mainWindow = new MainWindow();
                    var loginWindow = Window.GetWindow(this);
                    mainWindow.Show();
                    if (loginWindow != null) loginWindow.Close();
                }

            }
            catch (MySqlException err)
            {
                System.Diagnostics.Debug.WriteLine(err);
            }
            finally
            {
                if (dbConn != null)
                {
                    dbConn.Close(); //close the connection
                }
            }
        }
コード例 #13
0
        private async ValueTask WriteToServerAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
#endif
        {
            var tableName = DestinationTableName ?? throw new InvalidOperationException("DestinationTableName must be set before calling WriteToServer");

            m_wasAborted = false;

            Log.Info("Starting bulk copy to {0}", tableName);
            var bulkLoader = new MySqlBulkLoader(m_connection)
            {
                CharacterSet            = "utf8mb4",
                EscapeCharacter         = '\\',
                FieldQuotationCharacter = '\0',
                FieldTerminator         = "\t",
                LinePrefix          = null,
                LineTerminator      = "\n",
                Local               = true,
                NumberOfLinesToSkip = 0,
                Source              = this,
                TableName           = tableName,
                Timeout             = BulkCopyTimeout,
            };

            var closeConnection = false;

            if (m_connection.State != ConnectionState.Open)
            {
                m_connection.Open();
                closeConnection = true;
            }

            // merge column mappings with the destination schema
            var columnMappings     = new List <MySqlBulkCopyColumnMapping>(ColumnMappings);
            var addDefaultMappings = columnMappings.Count == 0;

            using (var cmd = new MySqlCommand("select * from " + tableName + ";", m_connection, m_transaction))
                using (var reader = await cmd.ExecuteReaderAsync(CommandBehavior.SchemaOnly, ioBehavior, cancellationToken).ConfigureAwait(false))
                {
                    var schema = reader.GetColumnSchema();
                    for (var i = 0; i < Math.Min(m_valuesEnumerator !.FieldCount, schema.Count); i++)
                    {
                        var destinationColumn = reader.GetName(i);
                        if (schema[i].DataTypeName == "BIT")
                        {
                            AddColumnMapping(columnMappings, addDefaultMappings, i, destinationColumn, $"@`\uE002\bcol{i}`", $"%COL% = CAST(%VAR% AS UNSIGNED)");
                        }
                        else if (schema[i].DataTypeName == "YEAR")
                        {
                            // the current code can't distinguish between 0 = 0000 and 0 = 2000
                            throw new NotSupportedException("'YEAR' columns are not supported by MySqlBulkLoader.");
                        }
                        else
                        {
                            var type = schema[i].DataType;
                            if (type == typeof(byte[]) || (type == typeof(Guid) && (m_connection.GuidFormat == MySqlGuidFormat.Binary16 || m_connection.GuidFormat == MySqlGuidFormat.LittleEndianBinary16 || m_connection.GuidFormat == MySqlGuidFormat.TimeSwapBinary16)))
                            {
                                AddColumnMapping(columnMappings, addDefaultMappings, i, destinationColumn, $"@`\uE002\bcol{i}`", $"%COL% = UNHEX(%VAR%)");
                            }
                            else if (addDefaultMappings)
                            {
                                Log.Debug("Adding default column mapping from SourceOrdinal {0} to DestinationColumn {1}", i, destinationColumn);
                                columnMappings.Add(new MySqlBulkCopyColumnMapping(i, destinationColumn));
                            }
                        }
                    }
                }

            // set columns and expressions from the column mappings
            for (var i = 0; i < m_valuesEnumerator.FieldCount; i++)
            {
                var columnMapping = columnMappings.FirstOrDefault(x => x.SourceOrdinal == i);
                if (columnMapping is null)
                {
                    Log.Debug("Ignoring column with SourceOrdinal {0}", i);
                    bulkLoader.Columns.Add("@`\uE002\bignore`");
                }
                else
                {
                    if (columnMapping.DestinationColumn.Length == 0)
                    {
                        throw new InvalidOperationException("MySqlBulkCopyColumnMapping.DestinationName is not set for SourceOrdinal {0}".FormatInvariant(columnMapping.SourceOrdinal));
                    }
                    if (columnMapping.DestinationColumn[0] == '@')
                    {
                        bulkLoader.Columns.Add(columnMapping.DestinationColumn);
                    }
                    else
                    {
                        bulkLoader.Columns.Add(QuoteIdentifier(columnMapping.DestinationColumn));
                    }
                    if (columnMapping.Expression is object)
                    {
                        bulkLoader.Expressions.Add(columnMapping.Expression);
                    }
                }
            }

            foreach (var columnMapping in columnMappings)
            {
                if (columnMapping.SourceOrdinal < 0 || columnMapping.SourceOrdinal >= m_valuesEnumerator.FieldCount)
                {
                    throw new InvalidOperationException("SourceOrdinal {0} is an invalid value".FormatInvariant(columnMapping.SourceOrdinal));
                }
            }

            var rowsInserted = await bulkLoader.LoadAsync(ioBehavior, cancellationToken).ConfigureAwait(false);

            if (closeConnection)
            {
                m_connection.Close();
            }

            Log.Info("Finished bulk copy to {0}", tableName);

            if (!m_wasAborted && rowsInserted != RowsCopied)
            {
                Log.Error("Bulk copy to DestinationTableName={0} failed; RowsCopied={1}; RowsInserted={2}", tableName, RowsCopied, rowsInserted);
                throw new MySqlException(MySqlErrorCode.BulkCopyFailed, "{0} rows were copied to {1} but only {2} were inserted.".FormatInvariant(RowsCopied, tableName, rowsInserted));
            }

#if !NETSTANDARD2_1 && !NETCOREAPP3_0
            return(default);
コード例 #14
0
        private async ValueTask WriteToServerAsync(IValuesEnumerator values, IOBehavior ioBehavior, CancellationToken cancellationToken)
#endif
        {
            var tableName = DestinationTableName ?? throw new InvalidOperationException("DestinationTableName must be set before calling WriteToServer");

            var bulkLoader = new MySqlBulkLoader(m_connection)
            {
                CharacterSet            = "utf8mb4",
                EscapeCharacter         = '\\',
                FieldQuotationCharacter = '\0',
                FieldTerminator         = "\t",
                LinePrefix                                 = null,
                LineTerminator                             = "\n",
                Local                                      = true,
                NumberOfLinesToSkip                        = 0,
                Source                                     = values ?? throw new ArgumentNullException(nameof(values)),
                                                 TableName = tableName,
                                                 Timeout   = BulkCopyTimeout,
            };

            var closeConnection = false;

            if (m_connection.State != ConnectionState.Open)
            {
                m_connection.Open();
                closeConnection = true;
            }

            using (var cmd = new MySqlCommand("select * from " + QuoteIdentifier(tableName) + ";", m_connection, m_transaction))
                using (var reader = (MySqlDataReader)await cmd.ExecuteReaderAsync(CommandBehavior.SchemaOnly, ioBehavior, cancellationToken).ConfigureAwait(false))
                {
                    var schema = reader.GetColumnSchema();
                    for (var i = 0; i < schema.Count; i++)
                    {
                        if (schema[i].DataTypeName == "BIT")
                        {
                            bulkLoader.Columns.Add($"@col{i}");
                            bulkLoader.Expressions.Add($"`{reader.GetName(i)}` = CAST(@col{i} AS UNSIGNED)");
                        }
                        else if (schema[i].DataTypeName == "YEAR")
                        {
                            // the current code can't distinguish between 0 = 0000 and 0 = 2000
                            throw new NotSupportedException("'YEAR' columns are not supported by MySqlBulkLoader.");
                        }
                        else
                        {
                            var type = schema[i].DataType;
                            if (type == typeof(byte[]) || (type == typeof(Guid) && (m_connection.GuidFormat == MySqlGuidFormat.Binary16 || m_connection.GuidFormat == MySqlGuidFormat.LittleEndianBinary16 || m_connection.GuidFormat == MySqlGuidFormat.TimeSwapBinary16)))
                            {
                                bulkLoader.Columns.Add($"@col{i}");
                                bulkLoader.Expressions.Add($"`{reader.GetName(i)}` = UNHEX(@col{i})");
                            }
                            else
                            {
                                bulkLoader.Columns.Add(QuoteIdentifier(reader.GetName(i)));
                            }
                        }
                    }
                }

            await bulkLoader.LoadAsync(ioBehavior, cancellationToken).ConfigureAwait(false);

            if (closeConnection)
            {
                m_connection.Close();
            }

#if !NETSTANDARD2_1 && !NETCOREAPP3_0
            return(default);
コード例 #15
0
        public async Task ReadStateAsync(string grainType, GrainReference grainReference, GrainState grainState)
        {
            var con = await GetFreeConnection();

            var table = GetTableName(grainState);
            string keyAsString = GetKey(grainReference);

            string query;

            if (CustomTable)
                query = string.Format("select * from `{0}` where `guid` = \"{1}\";", table,
                    MySqlHelper.EscapeString(keyAsString));
            else
                query = string.Format("select * from `{0}` where `guid` = \"{1}\" AND `type` = \"{2}\";", table,
                    MySqlHelper.EscapeString(keyAsString), MySqlHelper.EscapeString(grainType));

            using (var cmd = new MySqlCommand(query, con))
            {
                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    if (await reader.ReadAsync())
                    {
                        Dictionary<string, object> dict = new Dictionary<string, object>();

                        for (int i = 0; i < reader.FieldCount; ++i)
                            dict.Add(reader.GetName(i), reader.GetValue(i));

                        if (dict.ContainsKey("data"))
                        {
                            try
                            {
                                var data =
                                    (GrainState)
                                        Newtonsoft.Json.JsonConvert.DeserializeObject(dict["data"].ToString(),
                                            grainState.GetType());
                                grainState.SetAll(data.AsDictionary());
                            }
                            catch
                            {
                                grainState.SetAll(null); /* corruption? */
                            }
                        }
                        else
                            grainState.SetAll(null);
                    }
                }
            }

            await AddFreeConnection(con);
        }
コード例 #16
0
        private async void GetCallVolumes()
        {
            try
            {
                MySqlConnection dbConn = null;
                MySqlDataReader dbReader = null;
                string receivedDT = string.Empty;
                DateTime receivedtime = DateTime.Now;
                int nine2ten = 0;
                int ten2eleven = 0;
                int eleven2twelve = 0;
                int twelve2thirteen = 0;
                int thirteen2fourteen = 0;
                int fourteen2fifteen = 0;
                int fifteen2sixteen = 0;
                int sixteen2seventeen = 0;
                int seventeen2eighteen = 0;
                int eighteen2nineteen = 0;
                int nineteen2twenty = 0;
                int twenty2twentyone = 0;
                _volume.Clear();
                volumebyHour.Clear();

                using (dbConn = new MySqlConnection("Server=" + ICResponse.Properties.Settings.Default.DBServer +
                                                ";Database=" + ICResponse.Properties.Settings.Default.DBName +
                                                ";Uid=" + ICResponse.Properties.Settings.Default.DBUser +
                                                ";Pwd=" + ICResponse.Properties.Settings.Default.DBPass + ";"))
                {
                    dbConn.Open();
                    using (MySqlCommand cmd = new MySqlCommand(ICResponse.Properties.Settings.Default.GetCallVolume, dbConn))
                    {
                        dbReader = (MySqlDataReader)await cmd.ExecuteReaderAsync();
                        while (dbReader.Read())
                        {
                            receivedDT = Convert.ToString(dbReader["startTime"]);
                            receivedtime = DateTime.Parse(receivedDT);
                            volumebyHour.Add(receivedtime);
                        }
                    }                    
                    dbReader.Close();
                    dbConn.Close();

                    for (int i = 0; i < volumebyHour.Count; i++)
                    {
                        int hourcomponent = Int32.Parse(volumebyHour[i].Hour.ToString()); 
                        switch (hourcomponent)
                        {
                            case 9:
                                nine2ten++;
                                break;
                            case 10:
                                ten2eleven++;
                                break;
                            case 11:
                                eleven2twelve++;
                                break;
                            case 12:
                                twelve2thirteen++;
                                break;
                            case 13:
                                thirteen2fourteen++;
                                break;
                            case 14:
                                fourteen2fifteen++;
                                break;
                            case 15:
                                fifteen2sixteen++;
                                break;
                            case 16:
                                sixteen2seventeen++;
                                break;
                            case 17:
                                seventeen2eighteen++;
                                break;
                            case 18:
                                eighteen2nineteen++;
                                break;
                            case 19:
                                nineteen2twenty++;
                                break;
                            case 20:
                                twenty2twentyone++;
                                break;
                            default:
                                break;
                        }
                    }
                }
                
                _volume.Add(new CallVolumeChart() { Time = "Nine", Count = nine2ten });
                _volume.Add(new CallVolumeChart() { Time = "Ten", Count = ten2eleven });
                _volume.Add(new CallVolumeChart() { Time = "Eleven", Count = eleven2twelve });
                _volume.Add(new CallVolumeChart() { Time = "Twelve", Count = twelve2thirteen });
                _volume.Add(new CallVolumeChart() { Time = "One", Count = thirteen2fourteen });
                _volume.Add(new CallVolumeChart() { Time = "Two", Count = fourteen2fifteen });
                _volume.Add(new CallVolumeChart() { Time = "Three", Count = fifteen2sixteen });
                _volume.Add(new CallVolumeChart() { Time = "Four", Count = sixteen2seventeen });
                _volume.Add(new CallVolumeChart() { Time = "Five", Count = seventeen2eighteen });
                _volume.Add(new CallVolumeChart() { Time = "Six", Count = eighteen2nineteen });
                _volume.Add(new CallVolumeChart() { Time = "Seven", Count = nineteen2twenty });
                _volume.Add(new CallVolumeChart() { Time = "Eight", Count = twenty2twentyone });

            }
            catch (Exception err)
            {
                System.Diagnostics.Debug.WriteLine(err);
            }
        }