public async Task <IActionResult> Post([FromBody] Lenguaje lenguaje)
        {
            _context.Add(lenguaje);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("Post", lenguaje));
        }
示例#2
0
        public static List <Lenguaje> comboLenguaje()
        {
            SqlConnection   cn    = null;
            List <Lenguaje> lista = new List <Lenguaje>();

            try
            {
                cn = new SqlConnection(cadenaConexion);
                cn.Open();
                string        sqlText = "SELECT idLenguaje, nombre FROM LenguajesDeProgramacion";
                SqlCommand    cmd     = new SqlCommand(sqlText, cn);
                SqlDataReader dr      = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Lenguaje lenguaje   = new Lenguaje();
                    int      idLenguaje = dr.GetInt32(dr.GetOrdinal("idLenguaje"));
                    lenguaje.idLenguaje = idLenguaje;
                    String nombre = dr.GetString(dr.GetOrdinal("nombre"));
                    lenguaje.nombre = nombre;
                    lista.Add(lenguaje);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                {
                    cn.Close();
                }
            }
            return(lista);
        }
示例#3
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Nombre,Version")] Lenguaje lenguaje)
        {
            if (id != lenguaje.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(lenguaje);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!LenguajeExists(lenguaje.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(lenguaje));
        }
示例#4
0
        public ActionResult DeleteConfirmed(int id)
        {
            Lenguaje lenguaje = db.Lenguajes.Find(id);

            db.Lenguajes.Remove(lenguaje);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
示例#5
0
        /*Devuelve la ruta en para insertar las memorias */
        public bool InsertMemoria(string lang1, string lang2)
        {
            try
            {
                Lenguaje lenguaje = new Lenguaje();
                string   query    = "SELECT * FROM Lenguajes WHERE CodLenguaje_origen = {0} AND CodLenguaje_destino = {1}";
                lenguaje = ctx.Lenguajes.FromSql(query, lang1, lang2).FirstOrDefault();
                var url = "wwwroot/uploads/" + HttpContext.Session.GetTituloProyecto() + "/" + lang1 + "-" + lang2;

                if (lenguaje == null)
                {
                    lenguaje = new Lenguaje {
                        CodLenguaje_origen  = lang1,
                        CodLenguaje_destino = lang2
                    };
                    ctx.Lenguajes.Add(lenguaje);
                }

                if (!Directory.Exists(url))
                {
                    Directory.CreateDirectory(url);
                }

                var memoria = new Memoria {
                    Fecha_modificacion = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"),
                    LenguajeId         = lenguaje
                };

                query = "SELECT * FROM Proyectos WHERE Id = {0}";
                Proyecto pr = ctx.Proyectos.FromSql(query, HttpContext.Session.GetIdProyecto()).First();

                var proyecto_memoria = new Proyecto_Memoria {
                    ProyectoId = pr,
                    MemoriaId  = memoria
                };
                ctx.Memorias.Add(memoria);
                ctx.Proyecto_Memorias.Add(proyecto_memoria);

                var result = ctx.Proyectos.SingleOrDefault(b => b.Id == pr.Id);
                result.Actualizado        = false;
                result.Fecha_modificacion = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");

                ctx.SaveChanges();

                return(true);
            }
            catch (System.Exception e)
            {
                ErrorLog error = new ErrorLog()
                {
                    NOMBRE_PROYECTO = HttpContext.Session.GetTituloProyecto(),
                    ERROR           = e.Message
                };
                Log4NetProvider.logError("Memoria", "InsertMemoria", JsonConvert.SerializeObject(error));
                return(false);
            }
        }
示例#6
0
 public ActionResult Edit([Bind(Include = "id,name_lenguaje")] Lenguaje lenguaje)
 {
     if (ModelState.IsValid)
     {
         db.Entry(lenguaje).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(lenguaje));
 }
示例#7
0
        public async Task <IActionResult> Create([Bind("Id,Nombre,Version")] Lenguaje lenguaje)
        {
            if (ModelState.IsValid)
            {
                _context.Add(lenguaje);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(lenguaje));
        }
示例#8
0
        public ActionResult Create([Bind(Include = "Id,Nombre")] Lenguaje lenguaje)
        {
            if (ModelState.IsValid)
            {
                db.Lenguajes.Add(lenguaje);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(lenguaje));
        }
示例#9
0
 private void Awake()
 {
     if (instance == null)
     {
         instance = this;
         DontDestroyOnLoad(gameObject);
     }
     else
     {
         Destroy(gameObject);
     }
 }
示例#10
0
        public static bool CreateCMFile(String ruta, DBMotor motor, Lenguaje lenguaje)
        {
            InstanciateArray();
            StreamReader sr        = null;
            String       extension = ".cs";
            String       NS        = "";

            switch (lenguaje)
            {
            case Lenguaje.CSharp:
                extension = ".cs";    //se reemplazan las cosas
                sr        = new StreamReader(CMConfig.CM_CS);
                NS        = CMConfig.CSNAMESPACE;
                NEW[0]    = DATA[0][(int)motor, 0];
                NEW[1]    = DATA[0][(int)motor, 1];
                NEW[2]    = DATA[0][(int)motor, 2];
                NEW[3]    = DATA[0][(int)motor, 3];
                break;

            case Lenguaje.Java:
                extension = ".java";    //se reemplazan las cosas
                sr        = new StreamReader(CMConfig.CM_JAVA);
                NS        = CMConfig.JAVANAMESPACE;
                NEW[0]    = DATA[1][(int)motor, 0];
                NEW[1]    = DATA[1][(int)motor, 1];
                NEW[2]    = DATA[1][(int)motor, 2];
                NEW[3]    = DATA[1][(int)motor, 3];
                break;

            case Lenguaje.Python3:
                extension = ".py";    //se reemplazan las cosas
                sr        = new StreamReader(CMConfig.CM_PY);
                NEW[0]    = DATA[2][(int)motor, 0];
                NEW[1]    = DATA[2][(int)motor, 1];
                NEW[2]    = DATA[2][(int)motor, 2];
                NEW[3]    = DATA[2][(int)motor, 3];
                break;
            }

            cont_CM = sr.ReadToEnd();
            cont_CM = cont_CM.Replace("CommandManager", motor.ToString() + "CommandManager");
            cont_CM = cont_CM.Replace("CUSTOMNAMESPACE", NS);
            cont_CM = cont_CM.Replace("IMPORTS", NEW[0]);
            cont_CM = cont_CM.Replace("MOTORCOMMAND", NEW[1]);
            cont_CM = cont_CM.Replace("MOTORCON", NEW[2]);
            cont_CM = cont_CM.Replace("DATAREADER", NEW[3]);
            StreamWriter sw = new StreamWriter(ruta + "\\" + motor.ToString() + "CommandManager" + extension);

            sw.Write(cont_CM);
            sr.Close();
            sw.Close();
            return(true);
        }
示例#11
0
        // GET: Lenguajes/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Lenguaje lenguaje = db.Lenguajes.Find(id);

            if (lenguaje == null)
            {
                return(HttpNotFound());
            }
            return(View(lenguaje));
        }
示例#12
0
        public ClassesFileManager()
        {
            customNamespace = CMConfig.CUSTOMNAMESPACE;
            Lenguaje     lenguaje = Lenguaje.CSharp;
            StreamReader sr       = new StreamReader(CMConfig.CS_PC);
            String       str      = sr.ReadToEnd();

            String[] s1 = str.Split('"');
            foreach (var item in s1)
            {
                Bases.Add(item);
            }
            sr.Close();
        }
        public static void Initialize(LenguajesDbContext context)
        {
            context.Database.EnsureCreated();

            if (context.Lenguajes.Any())
            {
                return; // DB has been seeded
            }
            var lenguajes = new Lenguaje[]
            {
                new Lenguaje()
                {
                    Name   = "Javascript",
                    Logo   = "javascript.png",
                    Rating = 3
                },
                new Lenguaje()
                {
                    Name   = "Java",
                    Logo   = "java.png",
                    Rating = 1
                },
                new Lenguaje()
                {
                    Name   = "PHP",
                    Logo   = "php.png",
                    Rating = 1
                },
                new Lenguaje()
                {
                    Name   = "Python",
                    Logo   = "python.png",
                    Rating = 2
                },
                new Lenguaje()
                {
                    Name   = "C#",
                    Logo   = "csharp.jpg",
                    Rating = 3
                }
            };

            foreach (Lenguaje l in lenguajes)
            {
                context.Lenguajes.Add(l);
            }
            context.SaveChanges();
        }
示例#14
0
        /// <summary>
        /// Controla la acción de las teclas Enter, Backspace y Tab
        /// Enter -> Añade un SFOG>>> y elimina el último > , esto ayuda a colocar el cursor al final de la cadena y que se muestre de la forma SFOG>>
        /// Backspace -> Verifica que la última línea se mayor a 6 caracteres (de la cadena SFOG>>) quita 1 caracter y coloca al final de la cadena el cursor
        /// Tab -> Evita la acción de Tabular
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtArea_KeyPress(object sender, KeyPressEventArgs e)
        {
            String[] lineaCodigo = TxtArea.Lines;
            int      rowsCodigo  = lineaCodigo.Length;
            int      lenCodigo   = lineaCodigo[rowsCodigo - 1].Length;

            //Enter
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                e.Handled = true;
                if (lenCodigo > 6)
                {
                    //Obtiene la cadena a Escanear
                    String cadenaEscanear = lineaCodigo[rowsCodigo - 1].Substring(iniciales.Length);
                    //Manda al analizador toda esta onda
                    ListaSimple analizador = new Lenguaje().AnalizarCadena(cadenaEscanear);
                    //Guarda la cadena
                    Cola AEjecutar = GuardarTokens(analizador);
                    //Determina si la cadena se ejecuta o no
                    if (Escanear(analizador))
                    {
                        //Ejecuta la cadena
                        EjecutarToken(AEjecutar);
                    }
                }
                NuevaLinea();
            }
            //Backspace
            else if (e.KeyChar == Convert.ToChar(Keys.Back))
            {
                e.Handled = true;
                //Coloca el cursor al final del txtbox
                if (lenCodigo > iniciales.Length)
                {
                    //Elimina un caracter del final de la última linea
                    TxtArea.Text = TxtArea.Text.Substring(0, TxtArea.Text.Length - 1);
                }
            }
            //Tabular
            else if (e.KeyChar == Convert.ToChar(Keys.Tab))
            {
                e.Handled = true;
            }
            //Coloca el cursor al final del txtbox
            TxtArea.Focus();
            TxtArea.Select(TxtArea.Text.Length, 0);
            TxtArea.ScrollToCaret();
        }
示例#15
0
        public void Create(Lenguaje lenguaje)
        {
            try
            {
                var c = crudLenguaje.Retrieve <Lenguaje>(lenguaje);

                if (c != null)
                {
                    //Lenguaje already exists.
                    throw new BussinessException(3);
                }
                crudLenguaje.Create(lenguaje);
            }
            catch (Exception ex)
            {
                ExceptionManager.GetInstance().Process(ex);
            }
        }
示例#16
0
        protected void gvLenguajes_SelectedIndexChanged(object sender, EventArgs e)
        {
            int             id       = Convert.ToInt32(gvLenguajes.SelectedDataKey["idLenguaje"].ToString());
            List <Lenguaje> lista    = (List <Lenguaje>)Session["listaLenguaje"];
            Lenguaje        eliminar = new Lenguaje();

            foreach (Lenguaje lenguaje in lista)
            {
                if (lenguaje.idLenguaje == id)
                {
                    eliminar = lenguaje;
                }
            }
            lista.Remove(eliminar);
            Session["listaLenguaje"] = lista;
            gvLenguajes.DataSource   = lista;
            gvLenguajes.DataBind();
        }
示例#17
0
        protected void btnAgregarLenguaje_Click(object sender, EventArgs e)
        {
            Lenguaje lenguaje   = new Lenguaje();
            int      idLenguaje = Convert.ToInt32(cbLenguaje.SelectedValue);

            lenguaje.idLenguaje = idLenguaje;

            String nombre = cbLenguaje.SelectedItem.ToString();

            lenguaje.nombre = nombre;

            int idNivelLenguaje = Convert.ToInt32(cbNivelLenguaje.SelectedValue);

            lenguaje.idNivel = idNivelLenguaje;
            String nivel = cbNivelLenguaje.SelectedItem.ToString();

            lenguaje.nivel = nivel;
            cargarGrillaLenguajes(lenguaje);
        }
示例#18
0
        public void cargarGrillaLenguajes(Lenguaje lenguaje)
        {
            if (Session["listaLenguaje"] == null)
            {
                List <Lenguaje> listaLenguaje = new List <Lenguaje>();
                listaLenguaje.Add(lenguaje);
                gvLenguajes.DataSource = listaLenguaje;
                gvLenguajes.DataBind();
                Session["listaLenguaje"] = listaLenguaje;
            }
            else
            {
                List <Lenguaje> listaLenguaje = (List <Lenguaje>)Session["listaLenguaje"];
                listaLenguaje.Add(lenguaje);

                gvLenguajes.DataSource = listaLenguaje;
                gvLenguajes.DataBind();
                Session["listaLenguaje"] = listaLenguaje;
            }
        }
示例#19
0
        private void b_correr_Click(object sender, EventArgs e)
        {
            //Lenguaje
            string dato = richTextBox1.Text;

            fila = dato.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            identificadores creacionIdentificador = new identificadores();

            Analizador analiz = new Analizador();

            Lenguaje mensaje = new Lenguaje();

            for (var i = 0; i < fila.Length; i++)
            {
                creacionIdentificador.recogerAsignacion(fila[i]);
                creacionIdentificador.identificadoresAsignacion(i);
            }

            for (var i = 0; i < fila.Length; i++)
            {
                if (i == 0 || i == 1)
                {
                    mensaje.asignacion(fila[i]);

                    mensaje.reacomodarCadena();
                }
                else
                {
                    mensaje.asignacion(fila[i], i);//Asignar operador

                    mensaje.reacomodarCadena();
                }
                analiz.Analizador_cadena(dato);
                analiz.generarLista();
                comen.Text = analiz.getRetorno();


                lis_toks = new List <Token>();
                lis_toks = analiz.getListaTokens();
            }
        }
示例#20
0
        private void __BtnCompilar_Click(object sender, EventArgs e)
        {
            Console.Clear();
            __TxtRConsola.Text = "";
            _TablaTokens.Clear();
            _TablaAtributos.Clear();
            //FileStream(_PathProyect, FileMode.Open, FileAccess.Read)
            using (var writeStrm = new StreamWriter(_PathProyect, false, Encoding.ASCII))
                writeStrm.Write(__TxtRCsFile.Text);
            using (var readStrm = new StreamReader(_PathProyect)) {
                try {
                    Lenguaje test = new Lenguaje(readStrm);
                    test.Compilar(_InitPath + @"\ASM.asm");

                    foreach (var item in test.OutPut)
                    {
                        __TxtRConsola.Text += item;
                    }

                    foreach (var token in test.LogTokens)
                    {
                        _TablaTokens.Rows.Add(token.ID, token.Valor);
                    }

                    foreach (var atrib in test.LogAtributos)
                    {
                        _TablaAtributos.Rows.Add(atrib.Nombre, "" + atrib.Valor,
                                                 atrib.TipoDato, atrib.Acceso);
                    }

                    using (var streamRd = new StreamReader(_InitPath + @"\ASM.asm"))
                        __TxtRASM.Text = streamRd.ReadToEnd();
                } catch (InvalidDataException exc) {
                    __TxtRConsola.Text = "!!! " + exc.Message + "\n";
                } catch (NullReferenceException exc) {
                    __TxtRConsola.Text = "!!! " + exc.Message + "\n";
                } catch (Exception exc) {
                    __TxtRConsola.Text = "!!! " + exc.Message + "\n";
                }
            }
        }
示例#21
0
        public static List <Lenguaje> recuperarLenguajes(Curriculum cv)
        {
            SqlConnection   cn           = null;
            List <Lenguaje> listLenguaje = new List <Lenguaje>();

            if (cv != null)
            {
                try
                {
                    cn = new SqlConnection(cadenaConexion);
                    cn.Open();
                    String sql = "SELECT LC.idLenguaje, LC.idNivel, L.nombre, N.nombre nombre2 ";
                    sql = sql + "FROM LenguajesXCurriculum LC, LenguajesDeProgramacion L, Nivel N  ";
                    sql = sql + "WHERE L.idLenguaje=LC.idLenguaje AND LC.idNivel=N.idNivel AND LC.idCurriculum=" + cv.idCurriculum;
                    SqlCommand    cmd = new SqlCommand(sql, cn);
                    SqlDataReader dr  = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        Lenguaje lenguaje = new Lenguaje();
                        lenguaje.idLenguaje = dr.GetInt32(dr.GetOrdinal("idLenguaje"));
                        lenguaje.idNivel    = dr.GetInt32(dr.GetOrdinal("idNivel"));
                        lenguaje.nombre     = dr.GetString(dr.GetOrdinal("nombre"));
                        lenguaje.nivel      = dr.GetString(dr.GetOrdinal("nombre2"));
                        listLenguaje.Add(lenguaje);
                    }
                }
                catch (Exception e)
                {
                    throw new Exception(e.ToString());
                }

                finally
                {
                    if (cn != null && ConnectionState.Open == cn.State)
                    {
                        cn.Close();
                    }
                }
            }
            return(listLenguaje);
        }
示例#22
0
        public ActionResult Detail(int?id, Lenguaje model)
        {
            LanguageRepository objlang = new LanguageRepository(SessionCustom);

            objlang.Entity = model.EntityLanguage;

            try
            {
                SessionCustom.Begin();
                if (objlang.Entity.IsDefault.Value)
                {
                    objlang.UpdateLanguage();
                }

                if (id != null)
                {
                    objlang.Entity.LanguageId = id;
                    objlang.Update();

                    this.InsertAudit("Update", this.Module.Name + " -> " + objlang.Entity.Name);
                }
                else
                {
                    objlang.Entity.IsDefault = false;
                    objlang.Insert();
                    this.InsertAudit("Insert", this.Module.Name + " -> " + objlang.Entity.Name);
                }

                this.SessionCustom.Commit();
            }
            catch (Exception ex)
            {
                this.SessionCustom.RollBack();
                Utils.InsertLog(this.SessionCustom, "Error " + this.Module.Name, ex.ToString());
            }

            HttpContext.Cache.Remove("languages");

            return(this.RedirectToAction("Index", "Lenguaje"));
        }
示例#23
0
 public Lenguaje CrearLenguaje(string codOrigen, string codDestino)
 {
     try
     {
         var lenguaje = new Lenguaje {
             CodLenguaje_origen  = codOrigen,
             CodLenguaje_destino = codDestino
         };
         ctx.Lenguajes.Add(lenguaje);
         ctx.SaveChanges();
         return(lenguaje);
     }
     catch (System.Exception e)
     {
         ErrorLog error = new ErrorLog()
         {
             NOMBRE_PROYECTO = HttpContext.Session.GetTituloProyecto(),
             ERROR           = e.Message
         };
         Log4NetProvider.logError("Gestion", "CrearLenguaje", JsonConvert.SerializeObject(error));
         throw;
     }
 }
示例#24
0
 internal void Update(Lenguaje lenguaje)
 {
     crudLenguaje.Update(lenguaje);
 }
示例#25
0
 internal void Delete(Lenguaje lenguaje)
 {
     crudLenguaje.Delete(lenguaje);
 }
示例#26
0
 public Lenguaje RetrieveById(Lenguaje lenguaje)
 {
     return(crudLenguaje.Retrieve <Lenguaje>(lenguaje));
 }
示例#27
0
        /// <summary>
        /// Consulta los Tokens de la cola recibida y determina la lista en donde guardar los argumentos
        /// </summary>
        /// <param name="instrucciones"></param>
        private void EjecutarToken(Cola instrucciones)
        {
            //Convierte en un array de String la Cola recibida para facilitar su acceso
            string[] instruccion = instrucciones.VolverArray();            // = (string)instrucciones.Desencolar();
            //A través de la instrucción del primer espacio determina que hacer con lo contenido en el resto del Array
            switch (instruccion[0])
            {
            //1
            case "iniciarA":
                if (string.IsNullOrEmpty(focusedPDF) || focusedPDF.Equals(""))                        //Verifica que no haya ya un PDF iniciado
                {
                    //Intentará instanciar un PDF
                    try
                    {
                        //Verifica que no existan nombres duplicados
                        if (!pdf.Buscar(pdf.BuscarPDF(instruccion[1])))
                        {
                            //Crea la instancia de PDF
                            pdf.Enlistar(new PDF(pdf.GetLargo() + 1, instruccion[1]));
                            //Informa al usuario de la creacion de la instancia PDF
                            TxtArea.Text += Environment.NewLine + "Instancia " + instruccion[1] + " creada";
                        }
                        else
                        {
                            //Si existe duplicado se informa al usuario
                            TxtArea.Text += Environment.NewLine + "El PDF " + instruccion[1] + " ya existe. Consulte el Manual de Usuario <mostrar> <ManualUsuario>";
                            //Agrega error a la lista de errores
                            err.Enlistar(new Error(err.GetLargo() + 1, instruccion[1], -1, instruccion[0].Length + 2, "Nombre <PDF> Duplicado"));
                        }
                    }
                    catch (IndexOutOfRangeException)
                    {
                        //Informa al error de un error (generico) sintáctico
                        TxtArea.Text += Environment.NewLine + "Se esperaba Nombre";
                        //No hay argumentos después de iniciar
                        err.Enlistar(new Error(err.GetLargo() + 1, null, -1, instruccion[0].Length + 2, "Se esperaba Nombre"));
                    }
                }
                else
                {
                    //Si ya un PDF ingresado se informa al usuario
                    TxtArea.Text += Environment.NewLine + "Instrucción fuera de entorno. Consulte el Manual de Usuario <mostrar> <ManualUsuario>";
                    //Agrega el error a la lista
                    err.Enlistar(new Error(err.GetLargo() + 1, instruccion[0], -1, 1, "Error de Entorno. Hay un PDF enfocado"));
                }
                break;

            //2
            case "ingresarAPdf":
                //Busca el PDF en la lista de PDF, si existe focusedPDF = instruccion[1]. Sino informa al usuario
                if (pdf.Buscar(pdf.BuscarPDF(instruccion[1])))
                {
                    //Pone en global el nombre del pdf
                    focusedPDF = instruccion[1];
                    //Informa al usuario
                    TxtArea.Text += Environment.NewLine + "Instancia " + instruccion[1] + " enfocada";
                }
                else
                {
                    //Informa al usuario de que no se pudo encontrar el PDF en cuestión
                    TxtArea.Text += Environment.NewLine + "No se pudo encontrar el PDF " + instruccion[1] + ". Intente iniciarA " + instruccion[1] + " y pruebe de nuevo";
                    //Agrega al error a la lista
                    err.Enlistar(new Error(err.GetLargo() + 1, instruccion[1], -1, instruccion[0].Length + 2, "PDF no se encontró"));
                }
                break;

            //3
            case "crear":
                //Determina el largo del String[], si == 3 entonces solo crea, si == 4 abre de una vez el PDF
                if (pdf.Buscar(pdf.BuscarPDF(focusedPDF)))
                {
                    //Obtiene la instancia de PDF
                    LFP_P1.IO.PDF aux = pdf.BuscarPDF(focusedPDF);
                    //Genera el PDF
                    TxtArea.Text += Environment.NewLine + aux.GenerarPDF(new Ruta().GetAbsolutePath(instruccion[2]), this.indiceEdicion, this.texto, this.imagen, this.tabla, this.fila);
                    //Si Abrir esta presente lo abre
                    if (instruccion.Length == 4 && instruccion[3].Equals("Abrir"))
                    {
                        TxtArea.Text += Environment.NewLine + aux.AbrirPDF(new Ruta().GetAbsolutePath(instruccion[2]) + (char)92 + aux.nombre + ".pdf");
                    }
                    //Elimina el PDF de la lista
                    pdf.Remover(aux);
                    //Desenfoca el PDF
                    focusedPDF = null;
                    //Reinicia el indice
                    this.indiceEdicion = 1;
                }
                else
                {
                    //Sino informa al usuario
                    TxtArea.Text += Environment.NewLine + "PDF sin enfocar " + instruccion[1] + ". Intente ingresarAPdf " + instruccion[1] + " y pruebe de nuevo";
                    //Agrega el error a la lista
                    err.Enlistar(new Error(err.GetLargo() + 1, instruccion[1], -1, instruccion[0].Length + 2, "Error de entorno. PDF sin enfocar"));
                }
                break;

            //4
            case "escribirTexto":
                //Determina si el entorno es correcto, buscando el PDF enfocado actualmente
                if (string.IsNullOrEmpty(focusedPDF) || focusedPDF.Equals(""))
                {
                    //Informa al usuario del error y el sistema agrega a la lista el error
                    TxtArea.Text += Environment.NewLine + "Instrucción fuera de entorno. No ha ingresado a PDF, consulte el Manual de Usuario";
                    err.Enlistar(new Error(err.GetLargo() + 1, instruccion[0], -1, 1, "Error de Entorno. No hay PDF enfocado"));
                }
                else
                {
                    //Determina si se subraya o no
                    if (instruccion.Length < 4)
                    {
                        //Añade un texto subrayado
                        texto.Encolar(new Texto(instruccion[1], instruccion[2][0], (char)48, this.indiceEdicion++));
                    }
                    else
                    {
                        //Añade un texto sin subrayar
                        texto.Encolar(new Texto(instruccion[1], instruccion[2][0], instruccion[3][0], this.indiceEdicion++));
                    }
                    //Informa al usuario
                    TxtArea.Text += Environment.NewLine + "Se escribió texto";
                }
                break;

            //5
            case "imagen":
                if (string.IsNullOrEmpty(focusedPDF) || focusedPDF.Equals(""))
                {
                    TxtArea.Text += Environment.NewLine + "Instrucción fuera de entorno. No ha ingresado a PDF, consulte el Manual de Usuario";
                    err.Enlistar(new Error(err.GetLargo() + 1, instruccion[0], -1, 1, "Error de Entorno. No hay PDF enfocado"));
                }
                else
                {
                    //Determina la existencia del archivo de imagen
                    if (File.Exists(new Ruta().GetAbsolutePath(instruccion[1])))
                    {
                        this.imagen.Encolar(new Imagen(new Ruta().GetAbsolutePath(instruccion[1]), instruccion[2], indiceEdicion++));
                        TxtArea.Text += Environment.NewLine + "Imagen agregada correctamente";
                    }
                    else
                    {
                        TxtArea.Text += Environment.NewLine + "No se pudo encontrar la imagen en la ruta especificada.";
                        err.Enlistar(new Error(err.GetLargo() + 1, instruccion[1], -1, instruccion[0].Length + 2, "Archivo no Encontrado. Ruta inválida"));
                    }
                }
                break;

            //6
            case "crearTabla":
                if (string.IsNullOrEmpty(focusedPDF) || focusedPDF.Equals(""))
                {
                    //Informa al usuario que no hay ningun PDF enfocado y lista el error
                    TxtArea.Text += Environment.NewLine + "Instrucción fuera de entorno. No ha ingresado a PDF, consulte el Manual de Usuario";
                    err.Enlistar(new Error(err.GetLargo() + 1, instruccion[0], -1, 0, "Error de Entorno. No hay PDF enfocado."));
                }
                else
                {
                    //Añade la tabla a la cola e informa al usuario
                    this.tabla.Encolar(new Tabla(instruccion[1], instruccion[2], indiceEdicion++));
                    TxtArea.Text += Environment.NewLine + "Tabla agregada correctamente";
                }
                break;

            //7
            case "crearFila":
                if (string.IsNullOrEmpty(focusedPDF) || focusedPDF.Equals(""))
                {
                    //Informa al usuario que no hay ningun PDF enfocado y enlista el error
                    TxtArea.Text += Environment.NewLine + "Instrucción fuera de entorno. No ha ingresado a PDF. Consulte el Manual de Usuario <mostrar> <ManualUsuario>";
                    err.Enlistar(new Error(err.GetLargo() + 1, instruccion[0], -1, 0, "Error de Entorno. No hay PDF enfocado."));
                }
                else
                {
                    //Agrega una nueva fila a la lista e informa al usuario
                    this.fila.Enlistar(new Fila(instruccion[1], instruccion[2]));
                    TxtArea.Text += Environment.NewLine + "Fila agregada a " + instruccion[2];
                }
                break;

            //8
            case "ejecutar":
                if (string.IsNullOrEmpty(focusedPDF) || focusedPDF.Equals(""))
                {
                    //Verifica si hay más de una instrucción ejecutar, es decir si se encuentra un Ruta
                    if (instruccion.Length > 1)
                    {
                        //Verifica que el archivo exista y que sea .If
                        if (File.Exists(new Ruta().GetAbsolutePath(instruccion[1])) && (instruccion[1].Substring(instruccion[1].Length - 3, 3).Equals(".If") || instruccion[1].Substring(instruccion[1].Length - 3, 3).Equals(".if")))
                        {
                            //Limpia el editor y agrega el texto obtenido del archivo
                            this.TxtEditor.Text = new Ruta().GetTextFromFile(new Ruta().GetAbsolutePath(instruccion[1]));
                        }
                        else
                        {
                            //No se encuentra el archivo y se informa al usuario
                            TxtArea.Text += Environment.NewLine + "El archivo no se encuentra en la ruta especificada o la extensión es incorrecta";
                            err.Enlistar(new Error(err.GetLargo() + 1, instruccion[1], -1, instruccion[0].Length + 2, "Archivo no Encontrado. Ruta inválida"));
                        }
                    }
                    //lineaCodigo guarda todo lo que contiene el txt en un array , separados por filas
                    String[] lineaCodigo = TxtEditor.Lines;
                    //Obtiene el número de filas que tiene el array lineaCodigo
                    int rowsCodigo = lineaCodigo.Length;
                    //Instancia un Lenguaje de esta forma se mantiene las filas y columnas
                    Lenguaje leng = new Lenguaje();
                    for (int i = 0; i < rowsCodigo; i++)
                    {
                        //Obtiene la cadena a Escanear
                        String cadenaEscanear = lineaCodigo[i];
                        //Verifica que la cadena no esté vacía y evita crear un loop
                        if (!string.IsNullOrEmpty(cadenaEscanear) && !cadenaEscanear.Equals("") && !cadenaEscanear.Contains("ejecutar"))
                        {
                            //Manda al analizador toda esta onda
                            ListaSimple analizador = leng.AnalizarCadena(cadenaEscanear + (char)10);
                            //Guarda la cadena
                            Cola AEjecutar = GuardarTokens(analizador);
                            //Determina si la cadena se ejecuta o no
                            if (Escanear(analizador))
                            {
                                //Ejecuta la cadena
                                EjecutarToken(AEjecutar);
                            }
                        }
                    }
                }
                else
                {
                    //Informa a usuario que no hay ningun PDF enfocado y lo agrega a la lista
                    TxtArea.Text += Environment.NewLine + "Instrucción fuera de entorno. Consulte el Manual de Usuario <mostrar> <ManualUsuario>";
                    err.Enlistar(new Error(err.GetLargo() + 1, instruccion[0], -1, 0, "Error de entorno. Hay un PDF enfocado"));
                }
                break;

            //9
            case "mostrar":
                if (instruccion[1].Equals("ManualUsuario"))
                {
                    new PDF().AbrirPDF(new Ruta().GetAbsolutePath("raiz/ManualUsuario.pdf"));
                }
                if (instruccion[1].Equals("ManualTecnico"))
                {
                    new PDF().AbrirPDF(new Ruta().GetAbsolutePath("raiz/ManualTecnico.pdf"));
                }
                break;

            //10
            case "reporteTokens":
                //Crea y despliega el pvto >:V HTML xdDXdX
                new Ruta().GenerarYAbrirFile(new Ruta().ReporteTokens(token, err), "ReporteTokens", ".html", true);
                break;

            //11
            case "acercaDe":
                MessageBox.Show("201602782 - Sergio Fernando Otzoy Gonzalez", "Lenguajes Formales y de Programación");
                break;

            default:
                TxtArea.Text += Environment.NewLine + "«" + instruccion[0] + "» no se reconoce como instruccion. Consulte los Manuales -> <mostrar> <ManualUsuario> ó <ManualTecnico>";
                break;
            }
            TxtArea.Text += Environment.NewLine;
        }
示例#28
0
        public Linea Reducir(Linea _lineaEntrada, string _contexto)
        {
            Linea linea = _lineaEntrada.Clone();


            bool encontrado    = false;
            int  total         = linea.instrucciones.Count();
            int  tomar         = total;
            int  posibilidades = 1;


            while (!encontrado && posibilidades <= total)
            {
                //Buscar cada una de las posibilidades
                for (int x = 1; x <= posibilidades; x++)
                {
                    if (!encontrado)
                    {
                        string             cadenaDeTokens = "";
                        string             contenido      = "";
                        int                inicio         = x - 1;
                        int                fin            = tomar;
                        List <Instruccion> temp           = linea.instrucciones.GetRange(inicio, fin).ToList();
                        foreach (Instruccion i in temp)
                        {
                            if (i.token != null)
                            {
                                cadenaDeTokens += i.token.Substring(0, 4) + " ";
                            }
                            if (!String.IsNullOrEmpty(i.contenido))
                            {
                                contenido += i.contenido + " ";
                            }
                        }
                        if (cadenaDeTokens.Count() > 0)
                        {
                            string query = $"SELECT TOP 1 titulo FROM {_contexto} WHERE contenido = '{cadenaDeTokens.Substring(0, cadenaDeTokens.Count() - 1)}'";

                            SqlCommand cmd = new SqlCommand(query);

                            conexion.Abrir();
                            cmd.Connection  = conexion.SQLServerConexion;
                            cmd.CommandText = query;
                            SqlDataReader rdr = cmd.ExecuteReader();
                            if (rdr.HasRows)
                            {
                                List <Instruccion> primeros = new List <Instruccion>();
                                List <Instruccion> ultimos  = new List <Instruccion>();
                                try
                                {
                                    primeros = linea.instrucciones.GetRange(0, x - 1);
                                }
                                catch { }
                                try
                                {
                                    int k = linea.instrucciones.Count - ((x - 1) + tomar);
                                    int p = ((x - 1) + tomar);
                                    ultimos = linea.instrucciones.GetRange(p, k);
                                }
                                catch { }

                                Instruccion n = new Instruccion("xd", "error");
                                encontrado = true;
                                while (rdr.Read())
                                {
                                    n           = new Instruccion(rdr[0].ToString(), rdr[0].ToString());
                                    linea.logs += "│ \n";
                                    linea.logs += $"├──> Produccion encontrada: [{cadenaDeTokens.Substring(0, cadenaDeTokens.Count() - 1)}] \n";
                                    linea.logs += "│ \n";
                                    linea.logs += $"├─> Valor: [{rdr[0].ToString()}] \n";
                                    linea.logs += "│ \n";
                                }



                                linea.instrucciones.Clear();
                                linea.instrucciones.AddRange(primeros);
                                linea.instrucciones.Add(n);
                                linea.instrucciones.AddRange(ultimos);
                                linea.logs += $"├─> Analisis actual: [{linea.ToString()}] \n";
                                linea.logs += "│ \n";
                            }
                            conexion.Cerrar();
                        }
                    }
                }
                tomar--;
                posibilidades++;
            }


            if (_contexto == "producciones")
            {
                //Se trata de una asignacion de variables
                if (linea.instrucciones.Count > 0)
                {
                    if (linea.instrucciones[0].token == "MO04")
                    {
                        Lenguaje mateo = Lenguaje.ObtenerInstancia();

                        string keyVar        = "";
                        Linea  valorConjunto = new Linea();
                        valorConjunto.instrucciones = new List <Instruccion>();
                        bool asignacion = false;
                        foreach (Instruccion i in _lineaEntrada.instrucciones)
                        {
                            if (i.token == "ID00" && keyVar == "")
                            {
                                keyVar = i.contenido;
                            }
                            if (asignacion)
                            {
                                if (i.token != "ES08")
                                {
                                    if (i.token == "ID00")
                                    {
                                        Instruccion nueva = (Instruccion)i.Clone();
                                        nueva.token = mateo.CodigoEntrada.BuscarTipoDeDato(i.tokenIncrementable);
                                        valorConjunto.instrucciones.Add(nueva);
                                    }
                                    else
                                    {
                                        valorConjunto.instrucciones.Add((Instruccion)i.Clone());
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                            if (i.token == "OP10")
                            {
                                asignacion = true;
                            }
                        }

                        Linea abs = mateo.CodigoEntrada.BuscarMinimaExpresion(valorConjunto, "definicionesTipoDeDato");

                        if (abs.instrucciones.Count == 1)
                        {
                            mateo.CodigoEntrada.EstablecerTipo(keyVar, abs.instrucciones[0].token);
                        }
                    }
                }
            }



            return(linea);
        }
 void Awake()
 {
     Instance = this;
     CheckAndSetLanguage();
 }
示例#30
0
        // Modificar Material
        protected void btnModificar_Click(object sender, EventArgs e)
        {
            try
            {
                Boolean fileOK       = false;
                String  rutaMaterial = Server.MapPath("~/App_Data/Materiales/");
                String  rutaImagen   = Server.MapPath("~/Vista/imgMateriales/");

                if (FileUploadMaterial.HasFile)
                {
                    String   fileExtension      = System.IO.Path.GetExtension(FileUploadMaterial.FileName).ToLower();
                    String[] extensionesValidas = { ".zip", ".rar", ".iso" };

                    for (int i = 0; i < extensionesValidas.Length; i++)
                    {
                        if (fileExtension == extensionesValidas[i])
                        {
                            fileOK = true;
                        }
                    }

                    if (fileOK)
                    {
                        String fileName = FileUploadMaterial.FileName;
                        rutaMaterial += fileName;
                        FileUploadMaterial.SaveAs(rutaMaterial);
                        //labelMaterial.Text = "Archivo Cargado!";
                    }
                    else
                    {
                        throw new Exception("Solo se adminten archivos de tipo .rar .zip o .iso");
                        //labelMaterial.Text = "Cannot accept files of this type.";
                    }
                }

                if (FileUploadImg.HasFile)
                {
                    String   fileExtension      = System.IO.Path.GetExtension(FileUploadImg.FileName).ToLower();
                    String[] extensionesValidas = { ".jpg", ".jpeg", ".png", ".gif" };

                    for (int i = 0; i < extensionesValidas.Length; i++)
                    {
                        if (fileExtension == extensionesValidas[i])
                        {
                            fileOK = true;
                        }
                    }

                    if (fileOK)
                    {
                        String fileName = FileUploadImg.FileName;
                        rutaImagen += fileName;
                        FileUploadImg.SaveAs(rutaImagen);
                        //labelMaterial.Text = "Archivo Cargado!";
                    }
                    else
                    {
                        throw new Exception("Solo se adminten archivos de tipo .jpg .jpeg .png o .gif");
                        //labelMaterial.Text = "Cannot accept files of this type.";
                    }
                }

                Material    objMaterial   = new Material();
                Area[]      objAreas      = new Area[listBoxArea.Items.Count];
                Audiencia[] objAudiencias = new Audiencia[listBoxAudiencia.Items.Count];
                Autor[]     objAutores    = new Autor[listBoxAutor.Items.Count];
                Formato[]   objFormatos   = new Formato[listBoxFormato.Items.Count];
                Keyword[]   objKeywords   = new Keyword[listBoxKeyword.Items.Count];
                Lenguaje[]  objLenguajes  = new Lenguaje[listBoxLenguaje.Items.Count];


                objMaterial.IdMaterial     = txtIdmaterial.Text;
                objMaterial.Titulo         = txtTitulomaterial.Text;
                objMaterial.Descripcion    = txtDescripcion.Text;
                objMaterial.Requerimientos = txtRequerimientos.Text;
                objMaterial.Tipo           = txtTipomaterial.Text;
                objMaterial.Ruta           = rutaMaterial;
                objMaterial.Imagen         = rutaImagen;
                //objMaterial.FechaIngreso = DateTime.Parse(txtfechaIngreso.Text);
                //objMaterial.FechaModificacion = DateTime.Parse(txtFechamodificacion.Text);
                objMaterial.Propietario = txtPropietario.Text;
                objMaterial.Movil       = checkMovil.Checked;
                objMaterial.Costo       = Double.Parse(txtCosto.Text);

                for (int i = 0; i < listBoxArea.Items.Count; i++)
                {
                    // replicar en los demás metadatos
                    Console.WriteLine("listBoxArea: " + listBoxArea.ToString());
                    Console.WriteLine("listBoxArea.Itemns.Count: " + listBoxArea.Items.Count);
                    objAreas[i]        = new Area();
                    objAreas[i].Nombre = listBoxArea.Items[i].Text;
                    Console.WriteLine("objAreas[" + i + "]: " + objAreas[i].Nombre);
                }

                for (int i = 0; i < listBoxAudiencia.Items.Count; i++)
                {
                    objAudiencias[i]        = new Audiencia();
                    objAudiencias[i].Nombre = listBoxAudiencia.Items[i].Text;
                }

                for (int i = 0; i < listBoxAutor.Items.Count; i++)
                {
                    objAutores[i]        = new Autor();
                    objAutores[i].Nombre = listBoxAutor.Items[i].Text;
                }

                for (int i = 0; i < listBoxFormato.Items.Count; i++)
                {
                    objFormatos[i]        = new Formato();
                    objFormatos[i].Nombre = listBoxFormato.Items[i].Text;
                }

                for (int i = 0; i < listBoxKeyword.Items.Count; i++)
                {
                    objKeywords[i]        = new Keyword();
                    objKeywords[i].Nombre = listBoxKeyword.Items[i].Text;
                }

                for (int i = 0; i < listBoxLenguaje.Items.Count; i++)
                {
                    objLenguajes[i]        = new Lenguaje();
                    objLenguajes[i].Nombre = listBoxLenguaje.Items[i].Text;
                }

                objMaterial.Areas     = objAreas;
                objMaterial.Audiencia = objAudiencias;
                objMaterial.Autores   = objAutores;
                objMaterial.Formatos  = objFormatos;
                objMaterial.Keywords  = objKeywords;
                objMaterial.Lenguajes = objLenguajes;

                controlMaterial objControl = new controlMaterial(objMaterial);
                labelMaterial.Text = objControl.modificarMaterial();
            }
            catch (Exception objExc)
            {
                labelMaterial.Text = objExc.Message;
            }
        }