Pop

Curso programación C# - 72. Inteligencia Artificial con C# (1)- Visual Studio 2017

72. Inteligencia Artificial (1). Introducción

 -  En este capítulo del curso de programación en c# con visual studio 2017 vamos a empezar una nueva serie de entradas relacionadas con un tema de moda: la inteligencia artificial.El auge de esta tecnología se de debe al deseo de automatizar distintas tareas hasta ahora realizadas por seres humanos.

- Podemos observar que la  IA se aplica en casi todas partes como por ejemplo:  minería de datos para encontrar relaciones entre individuos cuando obtienes una lista de sugerencias de amigos en Facebook,  recomendaciones de compra en Amazon , cuando jugamos contra la máquina en un videojuego etc...

- Os dejo algunas definiciones destacadas de inteligencia artificial:



- Para completar más datos sobre IA podéis consultar también este enlace de la wikipedia. Una vez vistas algunas definiciones sobre inteligencia artificial podemos definir el concepto de agente: Un agente es una entidad capaz de percibir su entorno y actuar sobre él . La diferencia principal entre un agente y un programa común es que el primero debe ser autónomo; es decir, debe funcionar sin intervención directa de humanos u otros. Una diferencia adicional es que el agente realiza tareas concretas en nombre de alguien.

- En la siguientes entradas del blog y en nuestro canal de youtube trataremos de realizar un juego de ajedrez donde nosotros moveremos las piezas blancas y un agente mueva las piezas negras. Nos basaremos en estos tres  enlaces que dejo. Es importante  echarles un vistazo para seguir los siguientes capítulos con fluidez:



- Os dejo el vídeo donde os cuento todo esto:




Curso básico programación C# - 71. Creando nuestro propio buscador (9) - Visual Studio 2017

71. Nuestro propio buscador  de peliculas (9). Acabamos el buscador.

 -  En este capítulo del curso de programación en c# con visual studio 2017 ,  finalizamos nuestro proyecto consistente en crear nuestro propio buscador. Ya estamos utilizando la API que nos proporciona https://www.themoviedb.org , para realizar consultas  y  mostrar los resultados de una manera estructurada en pantalla.

- En esta nueva  entrada preparamos la aplicación para realizar peticiones  al método  https://developers.themoviedb.org/3/discover/movie-discover . En está ocasión  este método  nos devolverá las peliculas más importantes según un año que previamente elijamos y en función de los votos que haya registrada en esta página. En el video se ve en detalle lo que os cuento:

- En esta entrada finalizamos nuestra buscador. Ya hemos visto como utilizar algunos de los métodos disponible en esta API.Existen multitud de métodos más  si queréis seguir practicando. Las llamadas a los diferentse métodos será muy similares a las que ya hemos visto. Como en capítulos anteriores os dejo el código visto en el video:

  • Página Historiacine.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HistoriaCine.aspx.cs" Inherits="BuscadorWebPeliculas.HistoriaCine" MasterPageFile="~/Site.Master" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <div class="row">
      
            <div style="text-align: center; margin-top:5%">

                   <div style="text-align: center; margin-bottom:5%">
                       <asp:Label runat="server" Text="Seleccione fecha:" ></asp:Label>
                       <asp:DropDownList runat="server" ID="cmbAnios" AutoPostBack="True">
                           <asp:ListItem Text="Año 1960" Value="1960"></asp:ListItem>
                           <asp:ListItem Text="Año 1961" Value="1961"></asp:ListItem>
                           <asp:ListItem Text="Año 1962" Value="1962"></asp:ListItem>
                           <asp:ListItem Text="Año 1963" Value="1963"></asp:ListItem>
                           <asp:ListItem Text="Año 1964" Value="1964"></asp:ListItem>
                           <asp:ListItem Text="Año 1965" Value="1965"></asp:ListItem>
                           <asp:ListItem Text="Año 1966" Value="1966"></asp:ListItem>
                           <asp:ListItem Text="Año 1967" Value="1967"></asp:ListItem>
                           <asp:ListItem Text="Año 1968" Value="1968"></asp:ListItem>
                           <asp:ListItem Text="Año 1969" Value="1969"></asp:ListItem>
                           <asp:ListItem Text="Año 1970" Value="1970"></asp:ListItem>
                           <asp:ListItem Text="Año 1971" Value="1971"></asp:ListItem>
                           <asp:ListItem Text="Año 1972" Value="1972"></asp:ListItem>
                           <asp:ListItem Text="Año 1973" Value="1973"></asp:ListItem>
                           <asp:ListItem Text="Año 1974" Value="1974"></asp:ListItem>
                           <asp:ListItem Text="Año 1975" Value="1975"></asp:ListItem>
                           <asp:ListItem Text="Año 1976" Value="1976"></asp:ListItem>
                           <asp:ListItem Text="Año 1977" Value="1977"></asp:ListItem>
                           <asp:ListItem Text="Año 1978" Value="1978"></asp:ListItem>
                           <asp:ListItem Text="Año 1979" Value="1979"></asp:ListItem>
                           <asp:ListItem Text="Año 1970" Value="1970"></asp:ListItem>
                           <asp:ListItem Text="Año 1971" Value="1971"></asp:ListItem>
                           <asp:ListItem Text="Año 1972" Value="1972"></asp:ListItem>
                           <asp:ListItem Text="Año 1973" Value="1973"></asp:ListItem>
                           <asp:ListItem Text="Año 1974" Value="1974"></asp:ListItem>
                           <asp:ListItem Text="Año 1975" Value="1975"></asp:ListItem>
                           <asp:ListItem Text="Año 1976" Value="1976"></asp:ListItem>
                           <asp:ListItem Text="Año 1977" Value="1977"></asp:ListItem>
                           <asp:ListItem Text="Año 1978" Value="1978"></asp:ListItem>
                           <asp:ListItem Text="Año 1979" Value="1979"></asp:ListItem>
                           <asp:ListItem Text="Año 1980" Value="1980"></asp:ListItem>
                           <asp:ListItem Text="Año 1981" Value="1981"></asp:ListItem>
                           <asp:ListItem Text="Año 1982" Value="1982"></asp:ListItem>
                           <asp:ListItem Text="Año 1983" Value="1983"></asp:ListItem>
                           <asp:ListItem Text="Año 1984" Value="1984"></asp:ListItem>
                           <asp:ListItem Text="Año 1985" Value="1985"></asp:ListItem>
                           <asp:ListItem Text="Año 1986" Value="1986"></asp:ListItem>
                           <asp:ListItem Text="Año 1987" Value="1987"></asp:ListItem>
                           <asp:ListItem Text="Año 1988" Value="1988"></asp:ListItem>
                           <asp:ListItem Text="Año 1989" Value="1989"></asp:ListItem>
                           <asp:ListItem Text="Año 1990" Value="1990"></asp:ListItem>
                           <asp:ListItem Text="Año 1991" Value="1991"></asp:ListItem>
                           <asp:ListItem Text="Año 1992" Value="1992"></asp:ListItem>
                           <asp:ListItem Text="Año 1993" Value="1993"></asp:ListItem>
                           <asp:ListItem Text="Año 1994" Value="1994"></asp:ListItem>
                           <asp:ListItem Text="Año 1995" Value="1995"></asp:ListItem>
                           <asp:ListItem Text="Año 1996" Value="1996"></asp:ListItem>
                           <asp:ListItem Text="Año 1997" Value="1997"></asp:ListItem>
                           <asp:ListItem Text="Año 1998" Value="1998"></asp:ListItem>
                           <asp:ListItem Text="Año 1999" Value="1999"></asp:ListItem>
                           <asp:ListItem Text="Año 2000" Value="2000"></asp:ListItem>
                           <asp:ListItem Text="Año 2001" Value="2001"></asp:ListItem>
                           <asp:ListItem Text="Año 2002" Value="2002"></asp:ListItem>
                           <asp:ListItem Text="Año 2003" Value="2003"></asp:ListItem>
                           <asp:ListItem Text="Año 2004" Value="2004"></asp:ListItem>
                           <asp:ListItem Text="Año 2005" Value="2005"></asp:ListItem>
                           <asp:ListItem Text="Año 2006" Value="2006"></asp:ListItem>
                           <asp:ListItem Text="Año 2007" Value="2007"></asp:ListItem>
                           <asp:ListItem Text="Año 2008" Value="2008"></asp:ListItem>
                           <asp:ListItem Text="Año 2009" Value="2009"></asp:ListItem>
                           <asp:ListItem Text="Año 2010" Value="2010"></asp:ListItem>
                           <asp:ListItem Text="Año 2011" Value="2011"></asp:ListItem>
                           <asp:ListItem Text="Año 2012" Value="2012"></asp:ListItem>
                           <asp:ListItem Text="Año 2013" Value="2013"></asp:ListItem>
                           <asp:ListItem Text="Año 2014" Value="2014"></asp:ListItem>
                           <asp:ListItem Text="Año 2015" Value="2015"></asp:ListItem>
                           <asp:ListItem Text="Año 2016" Value="2016"></asp:ListItem>
                           <asp:ListItem Text="Año 2017" Value="2017" Selected="True"></asp:ListItem>
                           <asp:ListItem Text="Año 2018" Value="2018"></asp:ListItem>
          

                       </asp:DropDownList>
                  </div>

                  <div runat="server"  style="text-align: left" >
                      <table id="tableRes" runat="server" style="width: 100%;" enableviewstate="false">
                   
                    </table>
              
                </div>
             </div>
        
    </div>

</asp:Content>


  • Código de la página Historiacine.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Newtonsoft.Json;
using BuscadorWebPeliculas.Clases;

namespace BuscadorWebPeliculas
{
    public partial class HistoriaCine : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Util u = new Util();
            String resultado = String.Empty;
            String rutaPeticion = ConfigurationManager.AppSettings["cartelera"].ToString();
            JsonSerializerSettings ConfigJson = new JsonSerializerSettings();
            ConfigJson.NullValueHandling = NullValueHandling.Ignore;
            rutaPeticion += "?api_key=" + ConfigurationManager.AppSettings["claveApi"].ToString() + "&language=es-ES&region=ES&sort_by=vote_average.desc&primary_release_year="+ cmbAnios.SelectedValue+ "&include_video=false&&vote_count.gte=50";
            resultado = u.peticionAPI(rutaPeticion, "GET", null);
            RespuestaSearch rest = JsonConvert.DeserializeObject<RespuestaSearch>(resultado);
            pintarControles(rest);

            rutaPeticion = String.Empty;
            rutaPeticion = ConfigurationManager.AppSettings["cartelera"].ToString();
            rutaPeticion += "?api_key=" + ConfigurationManager.AppSettings["claveApi"].ToString() + "&language=es-ES&region=ES&sort_by=vote_average.desc&primary_release_year=" + cmbAnios.SelectedValue + "&include_video=false&&vote_count.gte=50&page=2";
            resultado = u.peticionAPI(rutaPeticion, "GET", null);
            rest = JsonConvert.DeserializeObject<RespuestaSearch>(resultado);
            pintarControles(rest);




        }

        private void pintarControles(RespuestaSearch rest)
        {
       

       
            for (int i = 0; i < rest.results.Count; i++)
            {

                Image img = new Image();
                img.Width = 100;
                img.Height = 125;
                if (rest.results[i].poster_path != String.Empty)
                    img.ImageUrl = "https://image.tmdb.org/t/p/w500/" + rest.results[i].poster_path;
                Label l = new Label();
                l.Text = "<b>"+rest.results[i].title + " Nota:" + rest.results[i].vote_average.ToString() + "  Votos:" + rest.results[i].vote_count.ToString() + "</b>: " + rest.results[i].overview + "<br>";

                System.Web.UI.HtmlControls.HtmlTableRow tRow = new System.Web.UI.HtmlControls.HtmlTableRow();
                System.Web.UI.HtmlControls.HtmlTableCell tCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                System.Web.UI.HtmlControls.HtmlTableCell tCell2 = new System.Web.UI.HtmlControls.HtmlTableCell();
                tCell.Controls.Add(img);
                tCell2.Controls.Add(l);
                tRow.Cells.Add(tCell);
                tRow.Cells.Add(tCell2);
                tCell2.VAlign = "TOP";
                tableRes.Rows.Add(tRow);

            }
        }
    }
}

Curso básico programación C# - 70. Creando nuestro propio buscador (8) - Visual Studio 2017

70. Nuestro propio buscador  de peliculas (8)

 -  En este capítulo del curso de programación en c# con visual studio 2017 ,  continuaremos con nuestro nuevo proyecto consistente en crear nuestro propio buscador. Ya estamos utilizando la API que nos proporciona https://www.themoviedb.org , para realizar consultas  y  mostrar los resultados de una manera estructurada en pantalla.

- En esta entrada preparamos la aplicación para realizar peticiones  a un nuevo método.En esta ocasión realizamos una petición al método https://developers.themoviedb.org/3/discover/movie-discover que nos devolverá las peliculas que están en los cines(en el país que le pasemos como parametro en la consulta) en un rango de fechas que también especificaremos como parametro en la propia petición.
 
- Os dejo  el video con el código al completo donde sacamos las 5 peliculas más desatcadas que hay en cartelera en España a fecha del 5 de mayo de 2018:



  • Os dejo también el código que hemos modificado de la página Default.aspx.cs para permitir realizar esta nueva petición:
using BuscadorWebPeliculas.Clases;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BuscadorWebPeliculas
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            Util u = new Util();
            String resultado = String.Empty;
            String rutaPeticion = ConfigurationManager.AppSettings["cartelera"].ToString();
            JsonSerializerSettings ConfigJson = new JsonSerializerSettings();
            ConfigJson.NullValueHandling = NullValueHandling.Ignore;
            rutaPeticion += "?api_key=" + ConfigurationManager.AppSettings["claveApi"].ToString() + "&language=es-ES&region=ES";
            rutaPeticion += "&primary_release_date.gte="+DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd")+"&primary_release_date.lte=" + DateTime.Now.ToString("yyyy-MM-dd"); ;
            resultado = u.peticionAPI(rutaPeticion, "GET", null);
            RespuestaSearch rest = JsonConvert.DeserializeObject<RespuestaSearch>(resultado);
            pintarControles(rest);

        }

        protected void Unnamed2_Click(object sender, ImageClickEventArgs e)
        {
            if (txtBuscador.Text != String.Empty)
            {
                tableRes.Controls.Clear();
                Util u = new Util();
                String resultado = String.Empty;

                String rutaPeticion = ConfigurationManager.AppSettings["search"].ToString();
                JsonSerializerSettings ConfigJson = new JsonSerializerSettings();
                ConfigJson.NullValueHandling = NullValueHandling.Ignore;
                rutaPeticion += "?api_key=" + ConfigurationManager.AppSettings["claveApi"].ToString() + "&language=es-ES";
                rutaPeticion += "&query=" + txtBuscador.Text;
                resultado = u.peticionAPI(rutaPeticion, "GET", null);
                RespuestaSearch rest = JsonConvert.DeserializeObject<RespuestaSearch>(resultado);
                pintarControles(rest);
                guardarDatosBusquedas();
            }
        }
   

        private void guardarDatosBusquedas()
        {
            try
            {
                string userip = Request.UserHostAddress;
                string navegador = Request.Browser.Browser;
                string plataforma = Request.Browser.Platform;

                //LLAMAR A BBDD
                Util u = new Util();
                u.guardarBusquedasUsuarios(userip, navegador, plataforma, txtBuscador.Text);
            }
            catch (Exception ex)
            {
                //DE MOMENTO LO DEJO VACIA TRATAR COMO SE QUIERA
            }
           
        }

        private void pintarControles(RespuestaSearch rest)
        {
          
            for (int i = 0; i < rest.results.Count; i++)
            {

                Image img = new Image();
                img.Width = 100;
                img.Height = 125;
                if (rest.results[i].poster_path != String.Empty)
                    img.ImageUrl = "https://image.tmdb.org/t/p/w500/" + rest.results[i].poster_path;
                Label l = new Label();
                l.Text = "<b>" + rest.results[i].release_date + " " + rest.results[i].title + "</b>: " + rest.results[i].overview + "<br>";

                System.Web.UI.HtmlControls.HtmlTableRow tRow = new System.Web.UI.HtmlControls.HtmlTableRow();
                System.Web.UI.HtmlControls.HtmlTableCell tCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                System.Web.UI.HtmlControls.HtmlTableCell tCell2 = new System.Web.UI.HtmlControls.HtmlTableCell();
                tCell.Controls.Add(img);
                tCell2.Controls.Add(l);
                tRow.Cells.Add(tCell);
                tRow.Cells.Add(tCell2);
                tCell2.VAlign = "TOP";
                tableRes.Rows.Add(tRow);

            }
        }

    }
     

}

  •  Os dejo también el código que hemos modificado de la página Default.aspx: 


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BuscadorWebPeliculas._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <div class="row">
      
            <div style="text-align: center; margin-top:5%">
         <div style="text-align: center; margin-bottom:5%">
            <asp:Label runat="server" Text="<b>Mis pelis:</b>" Font-Size="Medium"></asp:Label>
            <asp:TextBox ID="txtBuscador" runat="server" Width="30%" placeholder="Busca tus peliculas favoritas"></asp:TextBox>
            <asp:ImageButton runat="server" ImageUrl="images/magnifier-24270_640.png"  width="21px" height="20px" OnClick="Unnamed2_Click"/><br />
           <asp:Label runat="server" Text="" ID="lblResultado"></asp:Label>
             </div>
                <div runat="server"  style="text-align: left" >
                      <table id="tableRes" runat="server" style="width: 100%;" enableviewstate="false">
                   
                    </table>
              
                </div>
           </div>
       </div>
</asp:Content>

Curso básico programación C# - 69. Creando nuestro propio buscador (7) - Visual Studio 2017

69. Nuestro propio buscador  de peliculas (7)

 -  En este capítulo del curso de programación en c# con visual studio 2017 ,  continuaremos con nuestro nuevo proyecto consistente en crear nuestro propio buscador. Ya estamos utilizando la API que nos proporciona https://www.themoviedb.org , para realizar consultas  y  mostrar los resultados de una manera estructurada en pantalla. Además ya tenemos preparada la estructura de base de datos necesaria para almacenar información.

- En esta entrada preparamos la aplicación para realizar peticiones a nuestra base datos para poder almacenar la información en la tabla que preparamos en el capítulo anterior. Este ejemplo pretende ser un simil, a pequeña escala, de lo que hacen los grandes buscadores cada vez que realizamos una petición. Con cada busquedas  que hacemos damos datos con los que crean perfiles orientados al marketing para su propio beneficio.Nada es gratis en internet, aunque lo parezca.
 
- Os dejo  el video con el ejemplo:


- Una vez visto el video os dejo el código de la página aspx que relizan la petición y de nuestra clase Uitl.

  • Clase Util.cs:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace BuscadorWebPeliculas
{
    public class Util
    {


        public string peticionAPI(string pathPeticion, string tipoPeticion, byte[] Datos)
        {
            string Resultado = String.Empty;
            HttpWebRequest WReq = (HttpWebRequest)HttpWebRequest.Create(pathPeticion);
            WReq.ContentType = "application/json; charset=UTF-8";
            if (Datos != null)
            {
            WReq.ContentLength = Datos.Length;
            WReq.GetRequestStream().Write(Datos, 0, Datos.Length);
            }
            WReq.Method = tipoPeticion;
            HttpWebResponse res = (HttpWebResponse)WReq.GetResponse();
            Encoding Codificacion = ASCIIEncoding.UTF8;
            StreamReader SReader = new StreamReader(res.GetResponseStream(), Codificacion);
            Resultado = SReader.ReadToEnd();

            return Resultado;
        }

        public  object format_json(string json)
        {
            dynamic parsedJson = JsonConvert.DeserializeObject(json);
            return parsedJson;
        }

        public void guardarBusquedasUsuarios(string ip, string navegador, string plataforma, string busqueda)
        {

            SqlConnection conexion = new SqlConnection(ConfigurationManager.ConnectionStrings["EmpresaConnectionString"].ConnectionString);
             try
            {
                conexion.Open();
                SqlCommand com = conexion.CreateCommand();
                com.CommandType = System.Data.CommandType.StoredProcedure;
                com.CommandText = "dbo.GuardarBusquedas";
                com.Parameters.Add("@ip", SqlDbType.VarChar, 500).Value = ip;
                com.Parameters.Add("@navegador", SqlDbType.VarChar, 500).Value = navegador;
                com.Parameters.Add("@plataforma ", SqlDbType.VarChar, 500).Value = plataforma;
                com.Parameters.Add("@busqueda ", SqlDbType.VarChar, 500).Value = busqueda;
                com.ExecuteNonQuery();
                      }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());

            }
            finally
            {
                if (conexion != null && conexion.State == System.Data.ConnectionState.Open)
                    conexion.Close();

                conexion.Dispose();
            }

        }
    }

}


  • Clase Default.aspx.cs:
 using BuscadorWebPeliculas.Clases;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BuscadorWebPeliculas
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Unnamed2_Click(object sender, ImageClickEventArgs e)
        {
            if (txtBuscador.Text != String.Empty)
            {
                tableRes.Controls.Clear();
                Util u = new Util();
                String resultado = String.Empty;

                String rutaPeticion = ConfigurationManager.AppSettings["search"].ToString();
                JsonSerializerSettings ConfigJson = new JsonSerializerSettings();
                ConfigJson.NullValueHandling = NullValueHandling.Ignore;
                rutaPeticion += "?api_key=" + ConfigurationManager.AppSettings["claveApi"].ToString() + "&language=es-ES";
                rutaPeticion += "&query=" + txtBuscador.Text;
                resultado = u.peticionAPI(rutaPeticion, "GET", null);
                RespuestaSearch rest = JsonConvert.DeserializeObject<RespuestaSearch>(resultado);

                for (int i = 0; i < rest.results.Count; i++)
                {

                    Image img = new Image();
                    img.Width = 100;
                    img.Height = 125;
                    if (rest.results[i].poster_path != String.Empty)
                        img.ImageUrl = "https://image.tmdb.org/t/p/w500/" + rest.results[i].poster_path;
                    Label l = new Label();
                    l.Text = "<b>" + rest.results[i].release_date + " " + rest.results[i].title + "</b>: " + rest.results[i].overview + "<br>";

                    System.Web.UI.HtmlControls.HtmlTableRow tRow = new System.Web.UI.HtmlControls.HtmlTableRow();
                    System.Web.UI.HtmlControls.HtmlTableCell tCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                    System.Web.UI.HtmlControls.HtmlTableCell tCell2 = new System.Web.UI.HtmlControls.HtmlTableCell();
                    tCell.Controls.Add(img);
                    tCell2.Controls.Add(l);
                    tRow.Cells.Add(tCell);
                    tRow.Cells.Add(tCell2);
                    tCell2.VAlign = "TOP";
                    tableRes.Rows.Add(tRow);

                }
                guardarDatosBusquedas();
            }
        }


        private void guardarDatosBusquedas()
        {
            try
            {
                string userip = Request.UserHostAddress;
                string navegador = Request.Browser.Browser;
                string plataforma = Request.Browser.Platform;

                //LLAMAR A BBDD
                Util u = new Util();
                u.guardarBusquedasUsuarios(userip, navegador, plataforma, txtBuscador.Text);
            }
            catch (Exception ex)
            {
                //DE MOMENTO LO DEJO VACIA TRATAR COMO SE QUIERA
            }
           
        }

    }
     

}



Curso básico programación C# - 68. Creando nuestro propio buscador (6) - Visual Studio 2017

68. Nuestro propio buscador  de peliculas (6)

 -  En este capítulo del curso de programación en c# con visual studio 2017 ,  continuaremos con nuestro nuevo proyecto consistente en crear nuestro propio buscador. Ya estamos utilizando la API que nos proporciona https://www.themoviedb.org , para realizar consultas  y  mostrar los resultados de una manera estructurada en pantalla.

- En esta entrada nos crearemos una tabla en nuestra base de datos  SQL SERVER  donde almacenaremos algunos datos relevantes de los usuarios que realicen las busquedas en nuestro navegador.En el video lo podemos ver con más detalle:


- La estructura de tabla que hemos utilizado en el video para preparar nuestro entorno de base de datos para almacenar las consultas es la que muestro en la imagen:



- Además hemo creado  un procedimiento almacenado que llamaremos desde el código de nuestra aplicación. Este procedimiento es que realmente ejuctarará la sentencia que introduzca los datos en nuestra tabla. Os dejo el código SQL del procedimiento:

ALTER PROCEDURE [dbo].[GuardarBusquedas]
    @ip varchar(500),
    @navegador varchar(500),
    @plataforma varchar(500),
    @busqueda varchar(500)

AS
BEGIN

    SET NOCOUNT ON;

    INSERT INTO dbo.BUSQUEDAS_HISTORICO
     (IP,Navegador,Plataforma,Busqueda,FechaBusqueda)
     VALUES
           (@ip,@navegador,@plataforma,@busqueda,GETDATE())

END


Curso básico programación C# - 67. Creando nuestro propio buscador (5) - Visual Studio 2017

67. Nuestro propio buscador  de peliculas (5)

 -  En este capítulo del curso de programación en c# con visual studio 2017 ,  continuaremos con nuestro nuevo proyecto consistente en crear nuestro propio buscador. Ya estamos utilizando la API que nos proporciona https://www.themoviedb.org , para realizar consultas  y obtener la información solicitada. Ahora nos disponemos a estructurar y mostrar por pantalla los datos recibidos despues de hacer las peticiones a nuestra API.

- En el video muestro como ver los resultados de las diferentes busquedas que vamos haciendo en nuestro ejemplo:


- Una vez vista la manera en que podemos estructurar y mostrar la información por pantalla de una forma más decente, os dejo el código de la página del buscador.

  • Página Default.aspx: 
 <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BuscadorWebPeliculas._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <div class="row">
      
            <div style="text-align: center; margin-top:5%">
        
            <asp:Label runat="server" Text="<b>Mis pelis:</b>" Font-Size="Medium"></asp:Label>
            <asp:TextBox ID="txtBuscador" runat="server" Width="30%" placeholder="Busca tus peliculas favoritas:"></asp:TextBox>
            <asp:ImageButton runat="server" ImageUrl="images/magnifier-24270_640.png"  width="21px" height="20px" OnClick="Unnamed2_Click"/>
           <asp:Label runat="server" Text="" ID="lblResultado"></asp:Label>
                <div runat="server"  style="text-align: left" >
                      <table id="tableRes" runat="server" style="width: 100%;" enableviewstate="false">
                   
                    </table>
              
                </div>
                  

               
            </div>
        
    </div>

</asp:Content>

  • Página Default.aspx.cs:
 using BuscadorWebPeliculas.Clases;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BuscadorWebPeliculas
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Unnamed2_Click(object sender, ImageClickEventArgs e)
        {
              if (txtBuscador.Text != String.Empty)
            {
                tableRes.Controls.Clear();
            Util u = new Util();
            String resultado = String.Empty;

            String rutaPeticion = ConfigurationManager.AppSettings["search"].ToString();
            JsonSerializerSettings ConfigJson = new JsonSerializerSettings();
            ConfigJson.NullValueHandling = NullValueHandling.Ignore;
            rutaPeticion += "?api_key=" + ConfigurationManager.AppSettings["claveApi"].ToString() + "&language=es-ES";
            rutaPeticion += "&query=" + txtBuscador.Text;

        
            resultado = u.peticionAPI(rutaPeticion, "GET", null);


            RespuestaSearch rest = JsonConvert.DeserializeObject<RespuestaSearch>(resultado);

            for (int i = 0; i < rest.results.Count; i++)
            {

                Image img = new Image();
                img.Width = 100;
                img.Height = 130;
                if(rest.results[i].poster_path!=String.Empty)
                     img.ImageUrl = "https://image.tmdb.org/t/p/w500/" + rest.results[i].poster_path;
                Label l = new Label();
                l.Text = "<b>" + rest.results[i].release_date + " " + rest.results[i].title + "</b>: " + rest.results[i].overview + "<br>";

                System.Web.UI.HtmlControls.HtmlTableRow tRow = new System.Web.UI.HtmlControls.HtmlTableRow();
              

                System.Web.UI.HtmlControls.HtmlTableCell tCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                System.Web.UI.HtmlControls.HtmlTableCell tCell2 = new System.Web.UI.HtmlControls.HtmlTableCell();
                tCell.Controls.Add(img);
                tCell2.Controls.Add(l);
                tRow.Cells.Add(tCell);
                tRow.Cells.Add(tCell2);
                    tCell2.Align = "TOP";
                tableRes.Rows.Add(tRow);
                
                }
        }
        }
    }
}

- El código de las otras clases utilizadas la tenemos en entradas anteriores.Si queréis seguir este ejemplo al completo debéis obtener vuestra propia clave de API, que podéis obtener en https://www.themoviedb.org.

Curso básico programación C# - 66. Creando nuestro propio buscador (4) - Visual Studio 2017

66. Nuestro propio buscador  de peliculas (4)

 -  En este capítulo del curso de programación en c# con visual studio 2017 ,  continuaremos con nuestro nuevo proyecto consistente en crear nuestro propio buscador. Ya estamos utilizando la API que nos proporciona https://www.themoviedb.org , para realizar consultas  y obtener la información solicitada.

- En este capítulo después de realizar las primeras llamadas a la API empezaremos a definir los objetos necesarios para poder trabajar con los datos que nos develvuelven las diferentes peticiones hechas. En el video muestro como hacemos esto:


  •  A modo de ejemplo os dejo la respuesta de a una de las búsquedas vistas en el video. En este ejemplo hemos hecho una petición buscando la pelicula  Trainspotting , la cual que nos devulve esta respuesta en formato JSON:

{
 "page":1,
 "total_results":3,
 "total_pages":1,
 "results":
 [
    {

     "vote_count":3700,
     "id":627,"video":false,
     "vote_average":7.9,
     "title":"Trainspotting",
     "popularity":26.120268,
     "poster_path":"\/fj9PqztvKLuZh3DA40gsZFiShsY.jpg",
     "original_language":"en",
     "original_title":"Trainspotting",
     "genre_ids":[18,80],
     "backdrop_path":"\/yfNhWKqJFWTRvSo3Qf2x1IFteG3.jpg",
     "adult":false,
     "overview":"Mark Renton es un joven escocés adicto a la heroína, al igual que el resto de sus amigos Todos ellos viven en un mundo aparte, al margen de la realidad.
     Dentro del grupo hay un violento y alcohólico psicópata, un drogadicto desesperado, un mujeriego con un conocimiento enciclopédico de Sean Connery y un entusiasta de las caminatas y de Iggy Pop.",
     "release_date":"1996-02-23"
    },
    {
     "vote_count":1193,
     "id":180863,
     "video":false,
     "vote_average":7,
     "title":"T2: Trainspotting",
     "popularity":12.44352,
     "poster_path":"\/g4lbA6mtdm801mi1LVdTf44G8gQ.jpg",
     "original_language":"en",
     "original_title":"T2 Trainspotting",
     "genre_ids":[80,18],
     "backdrop_path":"\/kR48L1E3OLOkQcnlmpi5wDj7ZZt.jpg",
     "adult":false,
     "overview":"Han pasado 20 años desde que Mark Renton abandonara Escocia, y la heroína. Ahora, Renton vuelve a su Edimburgo natal con el objetivo de rehacer su vida y reencontrarse
     con sus amigos de toda la vida: David \"Spud\" Murphy, y Simon \"Sick Boy\" Williamson; al mismo tiempo que Francis \"Franco\" Begbie sale de la prisión con sed de venganza. Secuela de 'Trainspotting' (1996),
     basada en 'Porno', la siguiente novela de Irvine Welsh, aunque el director Boyle aseguró que el guión de John Hodge no será demasiado fiel al libro.",
     "release_date":"2017-01-27"
    },
    {
    "vote_count":14,
    "id":42758,
    "video":false,
    "vote_average":6.4,
    "title":"Small Faces",
    "popularity":2.356753,
    "poster_path":"\/s9I3gLu9ySsfyM3JvlpSW9KrszF.jpg",
    "original_language":"en",
    "original_title":"Small Faces",
    "genre_ids":[],
    "backdrop_path":null,
    "adult":false,"overview":"",
    "release_date":"1996-04-05"
    }
 ]
}


  • Para manejar mejor la información que nos devulve la API nos creamos una clases con la ayuda de la web https://jsonutils.com/ . Os dejo la clases definidas:
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BuscadorWebPeliculas.Clases
{
    public class RespuestaSearch
    {
        public int page { get; set; }
        public int total_results { get; set; }
        public int total_pages { get; set; }
        public IList<Result> results { get; set; }
    }

    public class Result
    {
        public int vote_count { get; set; }
        public int id { get; set; }
        public bool video { get; set; }
        public double vote_average { get; set; }
        public string title { get; set; }
        public double popularity { get; set; }
        public string poster_path { get; set; }
        public string original_language { get; set; }
        public string original_title { get; set; }
        public IList<int> genre_ids { get; set; }
        public string backdrop_path { get; set; }
        public bool adult { get; set; }
        public string overview { get; set; }
        public string release_date { get; set; }
    }
}


  • Finalmente utilizando esta clases  y ayudandonos de la dll NewtonSoft podemos tener la información de una manera más manejable  en el objeto que hemos definido como rest con esta llamada:
  RespuestaSearch rest = JsonConvert.DeserializeObject<RespuestaSearch>(resultado);

Curso básico programación C# - 65. Creando nuestro propio buscador (3) - Visual Studio 2017

65. Nuestro propio buscador  de peliculas (3)

 -  En este capítulo del curso de programación en c# con visual studio 2017 ,  continuaremos con nuestro nuevo proyecto consistente en crear nuestro propio buscador. La idea es utilizar la API que nos proporciona https://www.themoviedb.org , para realizar consultas  y mostrar la información de las busquedas solicitadas en pantalla.

- En este capítulo haremos las primeras peticiones a la API y mostraremos los resultados obtenidos en pantalla según recibamos la petición sin tratar los datos recibidos. En el video vemos las clases creadas para poder realizar las peticiones de una manera fácil.


  •   Según hemos visto en el video nos hemos creado un clase para poder realizar las peticiones a la que hemos llamado Util.cs:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace BuscadorWebPeliculas
{
    public class Util
    {


        public string peticionAPI(string pathPeticion, string tipoPeticion, byte[] Datos)
        {
            string Resultado = String.Empty;
            HttpWebRequest WReq = (HttpWebRequest)HttpWebRequest.Create(pathPeticion);
            WReq.ContentType = "application/json; charset=UTF-8";
            if (Datos != null)
            {
            WReq.ContentLength = Datos.Length;
            WReq.GetRequestStream().Write(Datos, 0, Datos.Length);
            }
            WReq.Method = tipoPeticion;
            HttpWebResponse res = (HttpWebResponse)WReq.GetResponse();
            Encoding Codificacion = ASCIIEncoding.UTF8;
            StreamReader SReader = new StreamReader(res.GetResponseStream(), Codificacion);
            Resultado = SReader.ReadToEnd();

            return Resultado;
        }
    }
}

  • Además en página default.aspx.cs hacemo uso de esta clase para poder llamar a la API:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BuscadorWebPeliculas
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Unnamed2_Click(object sender, ImageClickEventArgs e)
        {
            Util u = new Util();

          
            String rutaPeticion = ConfigurationManager.AppSettings["search"].ToString();
            JsonSerializerSettings ConfigJson = new JsonSerializerSettings();
            ConfigJson.NullValueHandling = NullValueHandling.Ignore;
            rutaPeticion += "?api_key=" + ConfigurationManager.AppSettings["claveApi"].ToString() + "&language=es-ES";
            rutaPeticion += "&query=" + txtBuscador.Text;
            lblResultado.Text= u.peticionAPI(rutaPeticion, "GET", null);
      



        }
    }
}

  • Y en la en aspx de la página default mostramos los resultados:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BuscadorWebPeliculas._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <div class="row">
      
            <div style="text-align: center; margin-top:5%">
        
            <asp:Label runat="server" Text="<b>Mis pelis:</b>" Font-Size="Medium"></asp:Label>
            <asp:TextBox ID="txtBuscador" runat="server" Width="30%" placeholder="Busca tus peliculas favoritas:"></asp:TextBox>
            <asp:ImageButton runat="server" ImageUrl="images/magnifier-24270_640.png"  width="21px" height="20px" OnClick="Unnamed2_Click"/>
           <asp:Label runat="server" Text="" ID="lblResultado"></asp:Label>
            </div>
        
    </div>

</asp:Content>

Curso básico programación C# - 64. Creando nuestro propio buscador (2) - Visual Studio 2017


64. Nuestro propio buscador  de peliculas (2)

 -  En este capítulo del curso de programación en c# con visual studio 2017 ,  continuaremos con nuestro nuevo proyecto consistente en crear nuestro propio buscador. La idea es utilizar la API que nos proporciona https://www.themoviedb.org , para realizar consultas  y mostrar la información de las busquedas solicitadas en pantalla.

- En la entrada anterior comenzamos este nuevo proyecto y en este empezaremos con el desarrollo. En este video veremos como crear nuestra plantilla de proyecto y como conseguimos nuestra clave para consumir la API para empezar a realizar peticiones. Una vez tenemos nuestra clave podremos empezar a realizar peticiones y obtener nuestras respuestas en formato JSON.

- En el video esta pixelada la clave para hacer peticiones porque identifica de manera unívoca a quien realiza la petición. La idea es que los que estés interesados en seguir este tutorial obtengaís vuestra propia clave.


- Una vez tenemos nuestra clave ya podemos hacer las peticiones. De momento os dejo el código fuente de la página aspx y de la pagina Master donde esta nuestro buscador. Aunque en esta ocasión el proyecto tiene muchas más cosas y debéis ser vosotros los que os generéis vuestro propio proyecto utilizando la plantilla que hemos visto en el video.

  •  Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BuscadorWebPeliculas._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <div class="row">
      
            <div style="text-align: center; margin-top:5%">
        
            <asp:Label runat="server" Text="<b>Mis pelis:</b>" Font-Size="Medium"></asp:Label>
            <asp:TextBox ID="txtBuscador" runat="server" Width="30%" placeholder="Busca tus peliculas favoritas:"></asp:TextBox>
            <asp:ImageButton runat="server" ImageUrl="images/magnifier-24270_640.png"  width="21px" height="20px" OnClick="Unnamed2_Click"/>
           <asp:Label runat="server" Text="" ID="lblResultado"></asp:Label>
            </div>
        
    </div>

</asp:Content>

  • MasterPage
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BuscadorWebPeliculas.SiteMaster" %>

<!DOCTYPE html>

<html lang="es">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><%: Page.Title %> - Mi aplicación ASP.NET</title>

    <asp:PlaceHolder runat="server">
        <%: Scripts.Render("~/bundles/modernizr") %>
    </asp:PlaceHolder>

    <webopt:bundlereference runat="server" path="~/Content/css" />
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />

</head>
<body>
    <form runat="server">
        <asp:ScriptManager runat="server">
            <Scripts>
                <%--Para obtener más información sobre la unión de scripts en ScriptManager, consulte https://go.microsoft.com/fwlink/?LinkID=301884 --%>
                <%--Scripts de marco--%>
                <asp:ScriptReference Name="MsAjaxBundle" />
                <asp:ScriptReference Name="jquery" />
                <asp:ScriptReference Name="bootstrap" />
                <asp:ScriptReference Name="respond" />
                <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
                <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
                <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
                <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
                <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
                <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
                <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
                <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
                <asp:ScriptReference Name="WebFormsBundle" />
                <%--Scripts del sitio--%>
            </Scripts>
        </asp:ScriptManager>

        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" runat="server" href="~/">Mis Pelis</a>
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li><a runat="server" href="~/">Inicio</a></li>
                        <li><a runat="server" href="~/About">Acerca de</a></li>
                        <li><a runat="server" href="~/Contact">Contacto</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            <asp:ContentPlaceHolder ID="MainContent" runat="server">
            </asp:ContentPlaceHolder>
            <hr />
            <footer>
                <p>&copy; <%: DateTime.Now.Year %> - Mis Pelis</p>
            </footer>
        </div>

    </form>
</body>
</html>

Curso .NET Core en C# - 34.Creamos nuestro propio log

34.Creamos nuestro propio log Hola a todos. En este curso, analizaremos todos los conceptos básicos, intermedios y avanzados de  ASP.NET...