Archive for agosto 28th, 2011

Trabajando con Datos

Trabajar con Datos

Podemos crear una base de datos de Sql Server Compact

Sacar Datos de la Base de Datos

Creamos un archivo ListProduct.cshtml

@{

    var db = Database.Open(“prueba”);

    var selectQueryString = “SELECT * FROM Product ORDER BY Name”;

 }

<!DOCTYPE html>

<html>

 <head>

   <title>Small Bakery Products</title>

   <style>

       table, th, td {

         border: solid 1px #bbbbbb;

         border-collapse: collapse;

         padding: 2px;

       }

    </style>

 </head>

 <body>

   <h1>Small Bakery Products</h1>

   <table>

       <thead>

           <tr>

               <th>Id</th>

               <th>Product</th>

               <th>Description</th>

       <th>Price</th>

           </tr>

       </thead>

       <tbody>

           @foreach(var row in db.Query(selectQueryString)){

            <tr>

               <td>@row.Id</td>

                   <td>@row.Name</td>

                   <td>@row.Description</td>

                   <td>@row.Price</td>

            </tr>

           }

       </tbody>

   </table>

 </body>

</html>

2.- Insertar

@{

    var db = Database.Open(“prueba”);

    var Name = Request["Name"];

    var Description = Request["Description"];

    var Price = Request["Price"];

 

    if (IsPost) {

 

        // Read product name.

        Name = Request["Name"];

        if (Name.IsEmpty()) {

           ModelState.AddError(“Name”, “Product name is required.”);

        }

 

        // Read product description.

        Description = Request["Description"];

        if (Description.IsEmpty()) {

          ModelState.AddError(“Description”,

                “Product description is required.”);

         }

 

        // Read product price

        Price = Request["Price"];

        if (Price.IsEmpty()) {

          ModelState.AddError(“Price”, “Product price is required.”);

        }

 

        // Define the insert query. The values to assign to the

        // columns in the Product table are defined as parameters

        // with the VALUES keyword.

        if(ModelState.IsValid) {

            var insertQuery = “INSERT INTO Product (Name, Description, Price) ” +

                “VALUES (@0, @1, @2)”;

            db.Execute(insertQuery, Name, Description, Price);

            // Display the page that lists products.

            Response.Redirect(@Href(“~/ListProducts”));

        }

    }

}

 

<!DOCTYPE html>

<html>

<head>

   <title>Add Products</title>

   <style type=”text/css”>

      label {float:left; width: 8em; text-align: right;

               margin-right: 0.5em;}

      fieldset {padding: 1em; border: 1px solid; width: 35em;}

      legend {padding: 2px 4px; border: 1px solid; font-weight:bold;}

      .validation-summary-errors {font-weight:bold; color:red; font-size: 11pt;}

   </style>

</head>

<body>

   <h1>Add New Product</h1>

 

   @Html.ValidationSummary(“Errors with your submission:”)

 

   <form method=”post” action=”">

       <fieldset>

           <legend>Add Product</legend>

           <div>

               <label>Name:</label>

               <input name=”Name” type=”text” size=”50″ value=”@Name” />

           </div>

           <div>

               <label>Description:</label>

               <input name=”Description” type=”text” size=”50″

                   value=”@Description” />

           </div>

           <div>

               <label>Price:</label>

               <input name=”Price” type=”text” size=”50″ value=”@Price” />

           </div>

           <div>

               <label>&nbsp;</label>

               <input type=”submit” value=”Insert” />

           </div>

       </fieldset>

 

   </form>

</body>

</html>

3.- Actualizar Datos

@{

    var db = Database.Open(“prueba”);

    var selectQueryString = “SELECT * FROM Product ORDER BY Name”;

 

}

<!DOCTYPE html>

<html>

<head>

    <title>Edit Products</title>

    <style type=”text/css”>

        table, th, td {

          border: solid 1px #bbbbbb;

          border-collapse: collapse;

          padding: 2px;

        }

    </style>

</head>

<body>

    <h1>Edit Small Bakery Products</h1>

    <table>

      <thead>

        <tr>

          <th>&nbsp;</th>

          <th>Name</th>

          <th>Description</th>

          <th>Price</th>

        </tr>

      </thead>

      <tbody>

        @foreach (var row in db.Query(selectQueryString)) {

          <tr>

            <td><a href=”@Href(“~/UpdateProducts”, row.Id)”>Edit</a></td>

            <td>@row.Name</td>

            <td>@row.Description</td>

            <td>@row.Price</td>

          </tr>

        }

      </tbody>

    </table>

</body>

</html>

Creamos otro archivo llamado UpdateProduct

@{

    var db = Database.Open(“prueba”);

    var selectQueryString = “SELECT * FROM Product WHERE Id=@0″;

 

    var ProductId  = UrlData[0];

 

    if (ProductId.IsEmpty()) {

         Response.Redirect(@Href(“~/EditProducts”));

     }

 

    var row = db.QuerySingle(selectQueryString, ProductId);

 

    var Name = row.Name;

    var Description = row.Description;

    var Price = row.Price;

 

    if (IsPost) {

         Name = Request["Name"];

         if (String.IsNullOrEmpty(Name)) {

           ModelState.AddError(“Name”, “Product name is required.”);

         }

 

        Description = Request["Description"];

        if (String.IsNullOrEmpty(Description)) {

          ModelState.AddError(“Description”,

              “Product description is required.”);

        }

 

        Price = Request["Price"];

        if (String.IsNullOrEmpty(Price)) {

          ModelState.AddError(“Price”, “Product price is required.”);

        }

 

        if(ModelState.IsValid) {

            var updateQueryString =

              “UPDATE Product SET Name=@0, Description=@1, Price=@2 WHERE Id=@3″ ;

            db.Execute(updateQueryString, Name, Description, Price, ProductId);

            Response.Redirect(@Href(“~/EditProducts”));

        }

    }

}

 

<!DOCTYPE html>

<html>

<head>

    <title>Add Products</title>

    <style type=”text/css”>

       label { float: left; width: 8em; text-align: right;

                margin-right: 0.5em;}

       fieldset { padding: 1em; border: 1px solid; width: 35em;}

       legend { padding: 2px 4px;  border: 1px solid; font-weight: bold;}

       .validation-summary-errors {font-weight:bold; color:red; font-size:11pt;}

    </style>

</head>

<body>

    <h1>Update Product</h1>

 

    @Html.ValidationSummary(“Errors with your submission:”)

 

    <form method=”post” action=”">

        <fieldset>

            <legend>Update Product</legend>

            <div>

                <label>Name:</label>

                <input name=”Name” type=”text” size=”50″ value=”@Name” />

            </div>

            <div>

                <label>Description:</label>

                <input name=”Description” type=”text” size=”50″

                   value=”@Description” />

            </div>

            <div>

                <label>Price:</label>

                <input name=”Price” type=”text” size=”50″ value=”@Price” />

            </div>

            <div>

                <label>&nbsp;</label>

                <input type=”submit” value=”Update” />

            </div>

        </fieldset>

    </form>

</body>

</html>

4. Borrar Datos

Creamos el archivo ListProductsForDelete.cshtml

@{

  var db = Database.Open(“prueba”);

  var selectQueryString = “SELECT * FROM Product ORDER BY Name”;

}

<!DOCTYPE html>

<html>

<head>

    <title>Delete a Product</title>

    <style>

        table, th, td {

          border: solid 1px #bbbbbb;

          border-collapse: collapse;

          padding: 2px;

        }

     </style>

</head>

<body>

  <h1>Delete a Product</h1>

  <form method=”post” action=”" name=”form”>

    <table border=”1″>

      <thead>

        <tr>

          <th>&nbsp;</th>

          <th>Name</th>

          <th>Description</th>

          <th>Price</th>

        </tr>

      </thead>

      <tbody>

        @foreach (var row in db.Query(selectQueryString)) {

          <tr>

            <td><a href=”@Href(“~/DeleteProduct”, row.Id)”>Delete</a></td>

            <td>@row.Name</td>

            <td>@row.Description</td>

            <td>@row.Price</td>

          </tr>

        }

      </tbody>

    </table>

  </form>

</body>

</html>

Creamos DeleteProduct

@{

  var db = Database.Open(“prueba”);

  var ProductId = UrlData[0];

  if (ProductId.IsEmpty()) {

    Response.Redirect(@Href(“~/ListProductsForDelete”));

  }

  var prod = db.QuerySingle(“SELECT * FROM PRODUCT WHERE ID = @0″, ProductId);

  if( IsPost && !ProductId.IsEmpty()) {

    var deleteQueryString = “DELETE FROM Product WHERE Id=@0″;

    db.Execute(deleteQueryString, ProductId);

    Response.Redirect(“~/ListProductsForDelete”);

  }

}

 

<!DOCTYPE html>

<html

<head>

    <title>Delete Product</title>

</head>

<body>

  <h1>Delete Product – Confirmation</h1>

  <form method=”post” action=”" name=”form”>

    <p>Are you sure you want to delete the following product?</p>

 

    <p>Name: @prod.Name <br />

       Description: @prod.Description <br />

       Price: @prod.Price</p>

    <p><input type=”submit” value=”Delete” /></p>

  </form>

</body>

</html>

5.- Conectando a la base de datos

Podemos conectar a la base de datos de dos formas:

La primera es usar Database.Open y especificar el nombre del fichero de la base de datos

var db = Database.Open("prueba");

La segunda opción es utilizar una cadena de conexión en el archivo web.xml

<?xml version=”1.0″ encoding=”utf-8″ ?>

<configuration>

  <connectionStrings>

   <add

     name=”SQLServerConnectionString”

     connectionString= “server=myServer;database=myDatabase;uid=username;pwd=password”

     providerName=”System.Data.SqlClient” />

  </connectionStrings>

</configuration>

 

@{

    var db = Database.Open(“SQLServerConnectionString”);

}

 

 

Trabajando con Formularios

Trabajando con Formularios

Creamos un archivo Form.cshtml

<!DOCTYPE html>

<html>

    <head>

        <title>Customer Form</title>

    </head>

    <body>

      <form method=”post” action=”">

        <fieldset>

          <legend>Add Customer</legend>

          <div>

            <label for=”CompanyName”>Company Name:</label>

            <input type=”text” name=”CompanyName” value=”" />

          </div>

          <div>

            <label for=”ContactName”>Contact Name:</label>

            <input type=”text” name=”ContactName” value=”" />

          </div>

          <div>

            <label for=”Employees”>Employee Count:</label>

            <input type=”text” name=”Employees” value=”" />

          </div>

          <div>

            <label>&nbsp;</label>

            <input type=”submit” value=”Submit” />

          </div>

        </fieldset>

      </form>

    </body>

</html>

1.- Leer entrada de usuario desde Form

Al principio de Form colocamos

@{

    if (IsPost) {

        string companyname = Request["companyname"];

        string contactname = Request["contactname"];

        int employeecount = Request["employees"].AsInt();

 

        <text>

          You entered: <br />

          Company Name: @companyname <br />

          Contact Name: @contactname <br />

          Employee Count: @employeecount <br />

        </text>

    }

}

2.- Validar entrada de usuario

En form reemplazamos el código inicial por:

@{

    if (IsPost)  {

        var errors = false;

        var companyname = Request["companyname"];

        if (companyname.IsEmpty()) {

            errors = true;

            @:Company name is required.<br />

        }

        var contactname = Request["contactname"];

        if (contactname.IsEmpty()) {

            errors = true;

            @:Contact name is required.<br />

        }

        var employeecount = 0;

        if (Request["employees"].IsInt()) {

            employeecount = Request["employees"].AsInt();

        } else {

            errors = true;

            @:Employee count must be a number.<br />

        }

        if (errors == false) {

            <text>

              You entered: <br />

              Company Name: @companyname <br />

              Contact Name: @contactname <br />

              Employee Count: @employeecount <br />

            </text>

        }    }

}

3.- Restaura Valores de Formulario después de PostBack

<!DOCTYPE html>

<html>

    <head>

        <title>Customer Form</title>

    </head>

    <body>

      <form method=”post” action=”">

        <fieldset>

          <legend>Add Customer</legend>

          <div>

            <label for=”CompanyName”>Company Name:</label>

            <input type=”text” name=”CompanyName”

                   value=”@Request["companyname"]” />

          </div>

          <div>

            <label for=”ContactName”>Contact Name:</label>

            <input type=”text” name=”ContactName”

                   value=”@Request["contactname"]” />

          </div>

          <div>

            <label for=”Employees”>Employee Count:</label>

            <input type=”text” name=”Employees” value=”@Request["employees"]” />

          </div>

          <div>

            <label>&nbsp;</label>

            <input type=”submit” value=”Submit” />

          </div>

        </fieldset>

      </form>

    </body>

</html>

Crear un aspecto uniforme con WebMatrix

1.- Bloques de contenido reusable

Muchos sitios web tienen contenido que se muestra en cada
página, como un encabezado y pie de página o un cuadro que indica a los
usuarios que están registrados.

ASP.NET le permite crear un archivo separado con un bloque
de contenido que puede contener texto, marcado y código, al igual que una
página web normal.

A continuación, puede
insertar el bloque de contenido de otras páginas en el sitio donde desea que
aparezca la información.

De esa manera usted no
tiene que copiar y pegar el mismo contenido en cada página. La creación de
contenidos comunes, como esto también hace que sea más fácil de actualizar su
sitio.

Si necesita cambiar
el contenido, sólo tiene que actualizar un solo archivo, y los cambios se
reflejan en todas partes el contenido se ha insertado.

Vamos a crear una página que hace referencia a dos bloques
de código de contenido que se encuentran en archivos separados.

<!DOCTYPE html>

<html>

<head>

<title>Main Page</title>

</head>

<body>

 

<h1>Index Page Content</h1>

<p>This is the content of the main page.</p>

 

</body>

</html>

Creamos una carpeta Shared

Creamos un fichero llamado _Header.cshtml

<div>This is header text.</div>

ASP.NET no enviará un archivo que comience con _

Creamos
otro archivo _Footer.cshmtl

<div>&copy; 2010 Contoso Pharmaceuticals. All rights reserved.

</div>

En el Index

<!DOCTYPE html>

<html>

<head>

<title>Main Page</title>

</head>

<body>

 

@RenderPage(“/Shared/_Header.cshtml”)

 

<h1>Index Page Content</h1>

<p>This is the content of the main page.</p>

 

@RenderPage(“/Shared/_Footer.cshtml”)

 

</body>

</html>

Al ejecutar la página, en el navegador llega el siguiente
código

<!DOCTYPE html>

<html>

<head>

<title>Main Page</title>

</head>

<body>

 

<div>This is header text.</div>

 

<h1>Index Page
Content</h1>

<p>This is the
content of the main page.</p>

 

<div>&copy;
2010 Contoso Pharmaceuticals. All rights reserved.

</div>

 

</body>

</html>

 

2.- Creación de un aspecto coherente utilizando páginas de diseño

Hasta ahora hemos visto que es fácil incluir el mismo
contenido en varias páginas.

Un enfoque más estructurado para crear un aspecto coherente para
un sitio es el uso de páginas de diseño.

Una página de diseño
define la estructura de una página web, pero no contiene ningún contenido real.

Después de haber
creado una página de diseño, puede crear páginas web que contienen el contenido
y luego vincularlos a la página de diseño. Cuando estas páginas se muestran,
van a ser formateadas de acuerdo con la página de diseño.

El diseño de página es igual que cualquier página HTML, excepto que contiene una
llamada al método RenderBody. La posición del método RenderBody en el diseño de
página determina donde se incluye  la
información de la página de contenido.

El siguiente diagrama muestra cómo las páginas de contenido y páginas de diseño
se combinan en tiempo de ejecución para producir la página web terminado.

El navegador solicita
una página de contenido. La página de contenido tiene un código que especifica que
en la página de diseño para el uso de la estructura de la página.

En la página de diseño, el contenido se insertará en el
punto donde se llama al método RenderBody.

Los  Bloques de
contenido también se pueden insertar en la página de diseño llamando al método RenderPage.

EN la carpeta Shared creamos un archivo llamado
_Layout1.cshtml

<!DOCTYPE html>

<head>

<title> Structured Content </title>

<link href=”@Href(“/Styles/Site.css”)” rel=”stylesheet” type=”text/css” />

</head>

<body>

@RenderPage(“/Shared/_Header2.cshtml”)

<div id=”main”>

@RenderBody()

</div>

<div id=”footer”>

&copy; 2010 Contoso Pharmaceuticals.
All rights reserved.

</div>

</body>

</html>

Usamos el método RenderPage en la página de layout para
insertar los bloques de contenido.

Una página de Layout sólo puede tener una llamada a
RenderBody.

En la carpeta Shared creamos el archivo _Header2.cshtml

En la raíz creamos una carpeta llamada Styles

Creamos un archivo syte.css

h1 {
border-bottom: 3px solid #cc9900;

font: 2.75em/1.75em Georgia, serif;

color: #996600;

}

 

ul {

list-style-type: none;

}

 

body {

margin: 0;

padding: 1em;

background-color: #ffffff;

font: 75%/1.75em “Trebuchet MS”,
Verdana, sans-serif;

color: #006600;

}

 

#list {

margin: 1em 0 7em -3em;

padding: 1em 0 0 0;

background-color: #ffffff;

color: #996600;

width: 25%;

float: left;

}

 

#header, #footer {

margin: 0;
padding: 0;
color: #996600;

}

EN la carpeta raiz creamos un archivo Content1.cshtml

@{

Layout = “/Shared/_Layout1.cshtml”;

}

 

<h1> Structured Content </h1>

<p>Lorem ipsum dolor sit amet, consectetur
adipisicing elit,

sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris

nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in

reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla

pariatur. Excepteur sint occaecat cupidatat non proident, sunt in

culpa qui officia
deserunt mollit anim id est laborum.</p>

Ejecutamos
Content1.cshtml

3.- Diseño de páginas Layout que tienen Múltiples secciones de contenido

Una página de contenido puede tener varias secciones, lo
cual es útil si desea usar diseños que tienen varias áreas de contenido reemplazable.

En la página de
contenido, dar a cada sección un nombre único. (En la sección por defecto se
deja sin nombre.)

En la página de diseño, agregue un método RenderBody para especificar
el de  la sección que debe aparecer.

A continuación,
agrega métodos distintos RenderSection el fin de hacer llamadas a las secciones
individualmente.

En la carpeta Shared creamos un archivo _Layout2.cshtml

<!DOCTYPE html>

<html>

<head>

<title>Multisection Content</title>

<link href=”@Href(“/Styles/Site.css”)” rel=”stylesheet” type=”text/css” />

</head>

<body>

<div id=”header”>

@RenderSection(“header”)

</div>

<div id=”list”>

@RenderSection(“list”)

</div>

<div id=”main”>

@RenderBody()

</div>

<div id=”footer”>

&copy; 2010 Contoso Pharmaceuticals.
All rights reserved.

</div>
</body>

</html>

Usamos RenderSection para renderizar ambas secciones.

En la raiz creamos Content2.cshtml

@{

Layout = “/Shared/_Layout2.cshtml”;

}

 

@section header {

<div id=”header”>

Chapter 3: Creating a
Consistent Look

</div>

}

 

@section list {

<ul>

<li>Lorem</li>

<li>Ipsum</li>

<li>Dolor</li>

<li>Consecte</li>

<li>Eiusmod</li>

<li>Tempor</li>

<li>Incididu</li>

</ul>

}

 

<h1>Multisection Content</h1>

<p>Lorem ipsum dolor sit amet, consectetur
adipisicing elit,

sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris

nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in

reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla

pariatur. Excepteur sint occaecat cupidatat non proident, sunt in

culpa qui officia
deserunt mollit anim id est laborum.</p>

4.- Secciones de Contenido opcionales

En Content2 quitamos

@section header {

<div id=”header”>

Chapter 3: Creating a
Consistent Look

</div>

}

Obtenemos un error porque no disponemos de la sección
header

Podemos marcar una sección como opcional de la siguiente
forma

@RenderSection(“header”,
required: false)

Otra posibilidad puede ser:

@if (IsSectionDefined(“header”)) {
@RenderSection(“header”)

}

5.- Pasar Datos a la página de Layout

Es posible que haya datos definidos en la página de
contenido que es necesario hacer referencia en una página de diseño.

Si es así, tiene que
pasar los datos de la página de contenido a la página de diseño. Por ejemplo,
puede que desee mostrar el estado de conexión de un usuario, o es posible que
desee mostrar u ocultar las áreas de contenido sobre la base de datos del
usuario.

EN la raiz creamos Content3

@{
Layout = “/Shared/_Layout3.cshtml”;

 

PageData["Title"] = “Passing Data”;

PageData["ShowList"] = true;

 

if (IsPost) {

if (Request["list"] == “off”) {

PageData["ShowList"] = false;

}

}

}

 

@section header {

<div id=”header”>

Chapter 3: Creating a
Consistent Look

</div>

}

 

<h1>@PageData["Title"]</h1>

<p>Lorem ipsum dolor sit amet, consectetur
adipisicing elit,

sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris

nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in

reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla

pariatur. Excepteur sint occaecat cupidatat non proident, sunt in

culpa qui officia deserunt mollit anim id est laborum.</p>

 

@if (PageData["ShowList"] == true) {

<form method=”post” action=”">

<input type=”hidden” name=”list” value=”off” />

<input type=”submit” value=”Hide
List” />

</form>

}

else {

<form method=”post” action=”">

<input type=”hidden” name=”list” value=”on” />

<input type=”submit” value=”Show
List” />

</form>

}

El código almacena datos en PageData.

En la carpeta Shared creamos Layout3

<!DOCTYPE html>

 

<html>

<head>

<title>@PageData["Title"]</title>

<link href=”@Href(“/Styles/Site.css”)” rel=”stylesheet” type=”text/css” />

</head>

<body>

<div id=”header”>

@RenderSection(“header”)

</div>

@if (PageData["ShowList"] == true) {

<div id=”list”>

@RenderPage(“/Shared/_List.cshtml”)

</div>

}

<div id=”main”>

@RenderBody()

</div>

<div id=”footer”>

&copy; 2010 Contoso Pharmaceuticals.
All rights reserved.

</div>

</body>

</html>

En la carpeta Shared creamos un archivo _List

<ul>
<li>Lorem</li>
<li>Ipsum</li>
<li>Dolor</li>
<li>Consecte</li>
<li>Eiusmod</li>
<li>Tempor</li>
<li>Incididu</li>

</ul>

6.- Crear y Usar Helper

Creamos una carpeta App_Code

Creamos un archivo llamado MyHelpers

@helper MakeNote(string content) {
<div style=”border: 1px solid black; width: 90%; padding: 5px; margin-left: 15px;”>

<p>

<strong>Note</strong>&nbsp;&nbsp; @content

</p>
</div>

}

El código usa @helper para declarar un nuevo helper
llamado MakeNote

En la raiz creamos un archivo TextHelper

<!DOCTYPE html>

<head>

<title>Test Helpers Page</title>

</head>

<body>

<p>This is some opening paragraph text.</p>

 

<!– Insert the call to your note helper here. –>

@MyHelpers.MakeNote(“My test note content.”)

 

<p>This is some following text.</p>

</body>

</html>

 

Powered by WordPress | Compare the Best Cell Phones at Bestincellphones.com. | Thanks to CD Rates, 0 credit cards and Home Information Packs