Proyecto final: Aplicación "Data Exporter"

Es una aplicación tipo web forms (con lenguaje Visual C#) hecha en Visual Studio 2017, cuyo propósito es:

1. Cargar un archivo .txt, y encontrar los valores de los siguientes campos:

*CodeID
*Name
*Date
*Department

2. Un iterador recorrerá todo el archivo, y al encontrar los campos anteriormente mencionados, sacará el respectivo resultado y los irá almacenando en arreglos.

3. Tras finalizada la iteración, entonces ya se insertarán en la base de datos.

4. Al mismo tiempo que se insertan a la base de datos, se insertan, también, en una tabla en la aplicación. En esa tabla se muestran 2 funciones básicas:
*Editar
*Borrar
Solo los campos Name, Date y Department se pueden editar.

Evidencia:

La tabla "DataRetrieved" contiene 4 campos: CodeID, Name, Date y Department
La misión es extraer toda la información competente a esos 4 campos de un archivo .txt llamado "UserInfo.txt". Dicho archivo contiene lo siguiente:


Ahora, el programa principal:
Lo primero que debemos hacer es presionar el botón "choose file" para buscar el archivo en cuestión:

Seleccionamos "UserInfo":
Se puede apreciar que ya cargó con éxito el programa. Ahora, presionar el botón verde "insertar". Tras hacerlo, aparecerán todos los datos tanto en la base de datos como en un "Gridview":




Como se aprecia en la parte derecha de cada fila en la tabla, están las opciones de "Editar" y "Borrar. 
Primero pulsemos "Editar", para tener lo siguiente:
Como se puede ver, solo sobresalen las opciones que son editables (¡el código no se puede editar!). Ahora, haremos un cambio en el departamento de "Álan Alexander Valdez Casas"--de IT a SISTEMAS COMP.
Por último, presionar "Update", para que los cambios tomen efecto:
Como pueden ver, ya aparece "SISTEMAS COMP." en lugar de "IT". También, por supuesto, cambió en la base de datos:
Después, tenemos la opción de "Borrar". Hagamos click en la fila donde está mi nombre, y nos preguntará si deseamos borrar el registro:
Pulsemos "OK" y nos dirá que el borrado fue exitoso:
¡Voilá! El registro con mi nombre ya no existe. Ah, tampoco en la base de datos.


Con esto concluyo el proyecto personal para la materia de Administración de Bases de Datos, cuyo propósito era demostrar el uso compartido entre un IDE con la base de datos.

A continuación, el método que permite extraer la información de los archivos de texto:

protected void FileReader()
        {
            SqlConnection DBSql = new SqlConnection(DbSqlConnStr);
            int counter = 0;
            string fileName = FupdArchivo.FileName;
            //string[] vErrorLog = new string[2];
            string vCodeID = "", vName = "", vDate = "", vTime ="", vDepartment = "";
            bool vInsertAll = false;
            DBSql.Open();
            StreamReader reader = new StreamReader(FupdArchivo.FileContent);
            SqlCommand SqlCom = new SqlCommand();
            SqlCom.Connection = DBSql;
            SqlCom.CommandText = "Ins_RetrievedInfo";
            SqlCom.CommandType = CommandType.StoredProcedure;

            #region Leer archivo

            if (FupdArchivo.HasFile)
            {
                try
                {
               
                    lblFileName.Text = fileName;
                    string[] lineas = File.ReadAllLines("C:/Users/MiUsuario/Documents/Visual Studio 2017/Projects/DataExporter/"+fileName);

                    List<string> IDGroup = new List<string>();
                    List<string> NameGroup = new List<string>();
                    List<string> DateGroup = new List<string>();
                    List<string> TimeGroup = new List<string>();
                    List<string> DepartmentGroup = new List<string>();
                    string[] AllCodesArray = new string[] { };
                    string[] AllNamesArray = new string[] { };
                    string[] AllDatesArray = new string[] { };
                    string[] AllTimesArray = new string[] { };
                    string[] AllDepartmentsArray = new string[] { };
                    counter = 0;

                    #region ObtenerInfo
                    SqlCom.Parameters.Add(new SqlParameter("@CodeID", SqlDbType.VarChar, 50));
                    SqlCom.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar, 50));
                    SqlCom.Parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime));
                    SqlCom.Parameters.Add(new SqlParameter("@Department", SqlDbType.VarChar, 50));

                    foreach(var line in lineas)
                    {

                        if (line.Contains("CodeID:"))
                        {
                            vCodeID = line;
                            vCodeID = vCodeID.Trim().Remove(0, 8);
                            IDGroup.Select(vCodesGen => vCodeID.ToString().ToList());
                            IDGroup.Add(vCodeID);
                            AllCodesArray = IDGroup.ToArray();
                 
                        }

                        if (line != null && vCodeID != "")
                        {
                            SqlCom.Parameters["@CodeID"].Value = vCodeID;
                            vCodeID = "";
                        }

                        if (line.Contains("Name:"))
                        {
                            vName = line;
                            vName = vName.Trim().Remove(0, 6);
                            NameGroup.Select(vNamesGen => vName.ToString().ToList());
                            NameGroup.Add(vName);
                            AllNamesArray = NameGroup.ToArray();
                     
                        }

                        if (line != null && vName != "")
                        {
                            SqlCom.Parameters["@Name"].Value = vName;
                            vName = "";
                        }

                        if (line.Contains("DateStart:"))
                        {
                            vDate = line;
                            vDate = vDate.Trim().Remove(0, 11);
                            DateGroup.Select(vDatesGen => vDate.ToString().ToList());
                            DateGroup.Add(vDate);
                            AllDatesArray = DateGroup.ToArray();
               
                        }

                        if (line.Contains("TimeStart:"))
                        {
                            vTime = line;
                            vTime = vTime.Trim().Remove(0, 11);
                            TimeGroup.Select(vTimesGen => vTime.ToString().ToList());
                            TimeGroup.Add(vTime);
                            AllTimesArray = TimeGroup.ToArray();
                   
                        }

                        if(line != null && vDate != "" && vTime != "")
                        {
                            SqlCom.Parameters["@Date"].Value = Convert.ToDateTime(vDate + ", " + vTime);
                            vDate = "";
                            vTime = "";
                        }

                        if (line.Contains("Department:"))
                        {
                            vDepartment = line;
                            vDepartment = vDepartment.Trim().Remove(0, 12);
                            DepartmentGroup.Select(vDepartmentGen => vDepartment.ToString().ToList());
                            DepartmentGroup.Add(vDepartment);
                            AllDepartmentsArray = DepartmentGroup.ToArray();
                     
                        }

                        if(line != null && vDepartment != "")
                        {
                            SqlCom.Parameters["@Department"].Value = vDepartment;
                            vDepartment = "";
                            vInsertAll = true;
                        }

                        if(AllCodesArray.Length.Equals(1) && AllNamesArray.Length.Equals(1) && AllDatesArray.Length.Equals(1) && AllDepartmentsArray.Length.Equals(1) && vInsertAll == true)
                        {
                             SqlCom.ExecuteNonQuery();
                             IDGroup = new List<string>();
                             NameGroup = new List<string>();
                             DateGroup = new List<string>();
                             TimeGroup = new List<string>();
                             DepartmentGroup = new List<string>();
                             AllCodesArray = new string[] { };
                             AllNamesArray = new string[] { };
                             AllDatesArray = new string[] { };
                             AllTimesArray = new string[] { };
                             AllDepartmentsArray = new string[] { };

                        }
                        counter++;
                    }
                    #endregion

                    Response.Write("<script>alert('Datos migrados exitosamente.\n" +
                        "Total de líneas: " +counter.ToString()+ "\n" +
                        "Gracias por usar el programa');</script>");
                    fillGrid();
                }

                catch (Exception ex)
                {
                    lblStatus.Text = "Error: " + ex.Message.ToString();
                }
           
            }
            else
            {
                lblStatus.Text = "No hay archivo cargado";
                return;
            }
            #endregion
        }

Programa usado: Visual Studio 2017 Community Edition.
SGBD: Microsoft SQL Server 2012 con Management Studio.







Comentarios

Entradas populares de este blog

1.4 - Nuevas tecnologías y aplicaciones de los sistemas de bases de datos

Unidad 4 - Operación y mantenibilidad

1.1. Administrador de Base de Datos (DBA).