Archive for the ‘Sin categoría’ Category

Sacar ventana de WPF en otro monitor

Desde el evento Loaded de la ventana llamamos al siguiente código

privatevoid ShowInMonitor(int screen)

{

this.WindowStartupLocation = System.Windows.WindowStartupLocation.Manual;

this.Left = System.Windows.Forms.Screen.AllScreens[screen].Bounds.Left;

this.Top = System.Windows.Forms.Screen.AllScreens[screen].Bounds.Top;

this.Width = System.Windows.Forms.Screen.AllScreens[screen].Bounds.Width;

this.Height = System.Windows.Forms.Screen.AllScreens[screen].Bounds.Height;

this.WindowState = WindowState.Maximized;

this.Topmost = true;

WindowState = System.Windows. WindowState.Maximized;

this.Show();

}

 

Acceder a un control definido en una plantilla WPF

Supongamos que tenemos

 <ContentControl Name="cntNuevoProducto" Margin="10,10,20,10"
                        ContentTemplate="{StaticResource itemVentaDT}"></ContentControl>
Queremos acceder a los controles definidos en la DataTemplate "itemVentaDT"
 DependencyObject oooo=VisualTreeHelper.GetChild(cntNuevoProducto,0);
 ContentPresenter cp=(ContentPresenter)oooo;
 TextBox n = (TextBox)cntNuevoProducto.ContentTemplate.FindName("txtboxDescripItem",cp );

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>

 

Programar Web ASP.NET con Razor

Programar Web ASP.NET con Razor

1.- Añadir código a una página con @

El carácter @ comienza expresiones en línea, los bloques de una sola declaración, y bloques de varias declaraciones:

<!DOCTYPE html>

<html lang=”en”>

    <head>

        <meta charset=”utf-8″ />

        <title>Pruebas</title>

    </head>

    <body>

        <!– Single statement blocks  –>

@{ var total = 7; }

@{ var myMessage = “Hello World”; }

 

<!– Inline expressions –>

<p>The value of your account is: @total </p>

<p>The value of myMessage is: @myMessage</p>

 

<!– Multi-statement block –>

@{

    var greeting = “Welcome to our site!”;

    var weekDay = DateTime.Now.DayOfWeek;

    var greetingMessage = greeting + ” Today is: ” + weekDay;

}

<p>The greeting is: @greetingMessage</p>

    </body>

</html>

2.- Incluir los bloques de código entre llaves

<!DOCTYPE html>

<html lang=”en”>

    <head>

        <meta charset=”utf-8″ />

        <title>Pruebas</title>

    </head>

    <body>

        <!– Single statement block.  –>

@{ var theMonth = DateTime.Now.Month; }

<p>The numeric value of the current month: @theMonth</p>

 

<!– Multi-statement block. –>

@{

    var outsideTemp = 79;

    var weatherMessage = “Hello, it is ” + outsideTemp + ” degrees.”;

}

<p>Today’s weather: @weatherMessage</p>

    </body>

</html>

3.- Dentro de un bloque, se termina cada instrucción de código con un punto y coma

<!DOCTYPE html>

<html lang=”en”>

    <head>

        <meta charset=”utf-8″ />

        <title>Pruebas</title>

    </head>

    <body>

      <!– Single-statement block –>

@{ var theMonth = DateTime.Now.Month; }

 

<!– Multi-statement block –>

@{

    var outsideTemp = 79;

    var weatherMessage = “Hello, it is ” + outsideTemp + ” degrees.”;

}

 

<!– Inline expression, so no semicolon –>

<p>Today’s weather: @weatherMessage</p>

    </body>

</html>

4.- Usar variables para almacenar datos

<!DOCTYPE html>

<html lang=”en”>

    <head>

        <meta charset=”utf-8″ />

        <title>Pruebas</title>

    </head>

    <body>

     <!– Storing a string –>

@{ var welcomeMessage = “Welcome, new members!”; }

<p>@welcomeMessage</p>

 

<!– Storing a date –>

@{ var year = DateTime.Now.Year; }

 

<!– Displaying a variable –>

<p>Welcome to our new members who joined in @year!</p>

    </body>

</html>

5.- Incluir los valores de cadena literal entre comillas dobles

Una cadena es una secuencia de caracteres que se tratan como texto.

Para especificar una cadena, se pone entre comillas dobles:

@{ var myString = “This is a string literal”; }

Si la cadena que desea mostrar contiene un carácter de barra invertida (\) o comillas dobles.

<!DOCTYPE html>

<html lang=”en”>

    <head>

        <meta charset=”utf-8″ />

        <title>Pruebas</title>

    </head>

    <body>

   <!– Embedding a backslash in a string –>

@{ var myFilePath = @”C:\MyFolder\”; }

<p>The path is: @myFilePath</p>

    </body>

</html>

Para incrustar comillas dobles, utilice una cadena literal y repetir las comillas:

<!DOCTYPE html>

<html lang=”en”>

    <head>

        <meta charset=”utf-8″ />

        <title>Pruebas</title>

    </head>

    <body>

   <!– Embedding double quotation marks in a string –>

@{ var myQuote = @”The person said: “”Hello, today is Monday.”"”; }

<p>@myQuote</p>

    </body>

</html>

6.- El código es sensible a mayúsculas

  @{

    var lastName = “Smith”;

    var LastName = “Jones”;

}

7.- Gran parte de su codificación implica objetos

<!DOCTYPE html>

<html lang=”en”>

    <head>

        <meta charset=”utf-8″ />

        <title>Pruebas</title>

    </head>

    <body>

 <table border=”1″>

<tr>

    <td>Requested URL</td>

    <td>Relative Path</td>

    <td>Full Path</td>

    <td>HTTP Request Type</td>

</tr>

<tr>

    <td>@Request.Url</td>

    <td>@Request.FilePath</td>

    <td>@Request.MapPath(Request.FilePath)</td>

    <td>@Request.RequestType</td>

</tr>

</table>

    </body>

</html>

8.- Se puede escribir código que tome decisiones

@{

   var result = “”;

   if(IsPost)

   {

      result = “This page was posted using the Submit button.”;

   }

   else

   {

      result = “This was the first request for this page.”;

   }

}

 

<!DOCTYPE html>

<html>

    <head>

        <title></title>

    </head>

<body>

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

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

  <p>@result</p>

</form>

</body>

</html>

    </body>

</html>

9.- Ejemplo de código

@{

    var total = 0;

    var totalMessage = “”;

    if(IsPost) {

 

        // Retrieve the numbers that the user entered.

        var num1 = Request["text1"];

        var num2 = Request["text2"];

 

        // Convert the entered strings into integers numbers and add.

        total = num1.AsInt() + num2.AsInt();

        totalMessage = “Total = ” + total;

    }

}

 

<!DOCTYPE html>

<html lang=”en”>

  <head>

    <title>Add Numbers</title>

    <meta charset=”utf-8″ />

    <style type=”text/css”>

      body {background-color: beige; font-family: Verdana, Arial;

            margin: 50px; }

      form {padding: 10px; border-style: solid; width: 250px;}

    </style>

  </head>

<body>

  <p>Enter two whole numbers and then click <strong>Add</strong>.</p>

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

    <p><label for=”text1″>First Number:</label>

      <input type=”text” name=”text1″ />

    </p>

    <p><label for=”text2″>Second Number:</label>

      <input type=”text” name=”text2″ />

    </p>

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

  </form>

 

  <p>@totalMessage</p>

 

</body>

</html>

10.- La sintaxis Razor, Server Code, y ASP.NET

La sintaxis de Razor es una sintaxis de programación sencillo para incrustar código basado en servidor en una página web. En una página web que utiliza la sintaxis Razor, hay dos tipos de contenidos: El contenido de código de cliente y servidor.

Contenido del cliente es el material que está acostumbrado en las páginas web: el formato HTML (elementos), información de estilo como CSS, el script de cliente, como JavaScript, y el texto.

La sintaxis de Razor le permite agregar el código del servidor para este contenido cliente. Si no hay código de servidor en la página, el servidor ejecuta el código en primer lugar, antes de enviar la página al navegador. Ejecutando en el servidor, el código puede realizar tareas que pueden ser mucho más complejas que solo el contenido del cliente, como acceso a bases de datos basadas en servidor. Lo más importante es que el código del servidor puede crear dinámicamente el contenido del cliente – puede generar código HTML o de otros contenidos sobre la marcha y luego enviarlo al navegador, junto con todo el código HTML estático que la página puede contener. Desde el contenido del navegador del cliente perspectiva, que se genera por el código del servidor no es diferente de cualquier contenido de otros clientes. Como ya has visto, el código del servidor que se necesita es bastante simple.

Las páginas web que incluyen la sintaxis Razor tienen una extensión de archivo especial (. Cshtml o vbhtml.). El servidor reconoce estas extensiones, se ejecuta el código que está marcado con la sintaxis de Razor, y luego envía la página al navegador.

La Sintaxis Razor se basa en una tecnología de Microsoft llamada ASP.NET, que a su vez se basa en la plataforma Microsoft. NET Framework. The.NET Framework es un framework grande, la programación completa de Microsoft para el desarrollo de prácticamente cualquier tipo de aplicación informática.

ASP.NET es la parte de. NET Framework, que está específicamente diseñado para la creación de aplicaciones web. Los desarrolladores han utilizado ASP.NET para crear muchos de los sitios web más grandes y de mayor tráfico del mundo. (Cada vez que veas la extensión de nombre de archivo. Aspx como parte de la URL de un sitio, usted sabrá que el sitio fue creado con ASP.NET.)

La sintaxis de Razor le da todo el poder de ASP.NET, pero con una sintaxis simplificada que es más fácil de utilizar si usted es un. A pesar de que esta sintaxis es muy simple de usar, su relación familiar con ASP.NET y. NET Framework significa que a medida que sus sitios web se vuelven más sofisticados, tienen el poder de los frameworks más grandes disponibles para usted.

 

11.- Combinando Texto, Markup, y Código en Bloques de Código

Escriba el texto en un elemento HTML como <p> </ p> o <em> </ em>:

@if(IsPost) {

    // This line has all content between matched <p> tags.

    <p>Hello, the time is @DateTime.Now and this page is a postback!</p>

} else {

    // All content between matched tags, followed by server code.

    <p>Hello <em>stranger</em>, today is: <br /> </p>  @DateTime.Now

}

Utilice el  operador @: o el elemento <text>.

La  salida @: se utiliza para una sola línea de contenido que contienen texto o etiquetas HTML

El elemento <text> encierra varias líneas de producción. Estas opciones son útiles cuando no se desea representar un elemento HTML, como parte de la producción.

@if(IsPost) {

    // Plain text followed by an unmatched HTML tag and server code.

    @: The time is: <br /> @DateTime.Now

    // Server code and then plain text, matched tags, and more text.

    @DateTime.Now @:is the <em>current</em> time.

}

Si desea la salida de varias líneas de texto o etiquetas HTML puede preceder a cada línea con @: o puede incluir la línea en un elemento <text>. Al igual que el @: operador, las  etiquetas <text> son utilizados por ASP.NET para identificar el contenido del texto.

@if(IsPost) {

    // Repeat the previous example, but use <text> tags.

    <text>

    The time is: <br /> @DateTime.Now

    @DateTime.Now is the <em>current</em> time.

    </text>

}

 

@{

    var minTemp = 75;

    <text>It is the month of @DateTime.Now.ToString(“MMMM”), and

    it’s a <em>great</em> day! <br /><p>You can go swimming if it’s at

    least @minTemp degrees. </p></text>

}

12.- Código y Comentarios

Empezamos el comentario con @* y cerramos con *@.

@*  A one-line code comment. *@

 

@*

    This is a multiline code comment.

    It can continue for any number of lines.

*@     

 

Comentario dentro de un bloque de código

@{

    @* This is a comment. *@

    var theVar = 17;

}

13.- Variables y Tipos de datos

@{

    // Assigning a string to a variable.

    var greeting = “Welcome!”;

 

    // Assigning a number to a variable.

    var theCount = 3;

 

    // Assigning an expression to a variable.

    var monthlyTotal = theCount + 5;

 

    // Assigning a date value to a variable.

    var today = DateTime.Today;

 

    // Assigning the current page’s URL to a variable.

    var myPath = this.Request.Url;

 

    // Declaring variables using explicit data types.

    string name = “Joe”;

    int count = 5;

    DateTime tomorrow = DateTime.Now.AddDays(1);

}

@{

    // Embedding the value of a variable into HTML markup.

    <p>@greeting, friends!</p>

 

    // Using variables as part of an inline expression.

    <p>The predicted annual total is: @( monthlyTotal * 12)</p>

 

    // Displaying the page URL with a variable.

    <p>The URL to this page is: @myPath</p>

}

14.- Convertir y Testear Tipos de Datos

@{

    var total = 0;

 

    if(IsPost) {

        // Retrieve the numbers that the user entered.

        var num1 = Request["text1"];

        var num2 = Request["text2"];

        // Convert the entered strings into integers numbers and add.

        total = num1.AsInt() + num2.AsInt();

    }

}

15.- El Operador ~.

Raiz del path virtual.

@{

    var myImagesFolder = “~/images”;

    var myStyleSheet = “~/styles/StyleSheet.css”;

}

16.- Server.MapPath

Convierte el path virtual a físico

@{

    var dataFilePath = “~/dataFile.txt”;

}

<!– Displays a physical path C:\Websites\MyWebSite\datafile.txt  –>

<p>@Server.MapPath(dataFilePath)</p>

17.- El método Href.

Convierte las rutas que se crea en el código del servidor a path que entiende los navegadores.

@{

    var myImagesFolder = “~/images”;

    var myStyleSheet = “~/styles/StyleSheet.css”;

}

 

<!– This code creates the path “../images/Logo.jpg” in the src attribute. –>

<img src=”@Href(myImagesFolder)/Logo.jpg” />

 

<!– This produces the same result, using a path with ~  –>

<img src=”@Href(“~/images”)/Logo.jpg” />

 

<!– This creates a link to the CSS file. –>

<link rel=”stylesheet” type=”text/css” href=”@Href(myStyleSheet)” />

18.- Condiciones

@{

  var showToday = true;

  if(showToday)

  {

    @DateTime.Today;

  }

}

 

@{

  var showToday = false;

  if(showToday)

  {

    @DateTime.Today;

  }

  else

  {

    <text>Sorry!</text>

  }

}

 

También podemos utilizar else if

@{

    var theBalance = 4.99;

    if(theBalance == 0)

    {

        <p>You have a zero balance.</p>

    }

    else if (theBalance  > 0 && theBalance <= 5)

    {

        <p>Your balance of $@theBalance is very low.</p>

    }

    else

    {

        <p>Your balance is: $@theBalance</p>

    }

}

 

Otro ejemplo:

@{

    var weekday = “Wednesday”;

    var greeting = “”;

 

    switch(weekday)

    {

        case “Monday”:

            greeting = “Ok, it’s a marvelous Monday”;

            break;

        case “Tuesday”:

            greeting = “It’s a tremendous Tuesday”;

            break;

        case “Wednesday”:

            greeting = “Wild Wednesday is here!”;

            break;

        default:

            greeting = “It’s some other day, oh well.”;

            break;

    }

 

    <p>Since it is @weekday, the message for today is: @greeting</p>

}

19.- Iteraciones

Utilizamos @for

@for(var i = 10; i < 21; i++)

{

    <p>Line #: @i</p>

}

En este caso utilizamos @foreach

@foreach (var myItem in Request.ServerVariables)

{

    <li>@myItem</li>

}

Un While

@{

    var countNum = 0;

    while (countNum < 50)

    {

        countNum += 1;

        <p>Line #@countNum: </p>

    }

}

20.- Objeto Request

@{

    var path = Request.FilePath;

}

@{

    var path1 = this.Request.FilePath;

}

@{

    // Access the page’s Request object to retrieve the Url.

    var pageUrl = this.Request.Url;

}

<a href=”@pageUrl”>My page</a>

21.- Colecciones de Objetos

<ul>

@* Array block 1: Declaring a new array using braces. *@

@{

    <h3>Team Members</h3>

    string[] teamMembers = {“Matt”, “Joanne”, “Robert”, “Nancy”};

    foreach (var person in teamMembers)

    {

        <p>@person</p>

    }

}

</ul>

 

Otro ejemplo

@{

    string[] teamMembers = {“Matt”, “Joanne”, “Robert”, “Nancy”};

    <p>The number of names in the teamMembers array: @teamMembers.Length </p>

    <p>Robert is now in position: @Array.IndexOf(teamMembers, “Robert”)</p>

    <p>The array item at position 2 (zero-based) is @teamMembers[2]</p>

    <h3>Current order of team members in the list</h3>

    foreach (var name in teamMembers)

    {

        <p>@name</p>

    }

    <h3>Reversed order of team members in the list</h3>

    Array.Reverse(teamMembers);

    foreach (var reversedItem in teamMembers)

    {

        <p>@reversedItem</p>

    }

}

Un Diccionario

@{

    var myScores = new Dictionary<string, int>();

    myScores.Add(“test1″, 71);

    myScores.Add(“test2″, 82);

    myScores.Add(“test3″, 100);

    myScores.Add(“test4″, 59);

}

<p>My score on test 3 is: @myScores["test3"]%</p>

@(myScores["test4"] = 79)

<p>My corrected score on test 4 is: @myScores["test4"]%</p>

22.- Excepciones

@{

    var dataFilePath = “~/dataFile.txt”;

    var fileContents = “”;

    var physicalPath = Server.MapPath(dataFilePath);

    var userMessage = “Hello world, the time is ” + DateTime.Now;

    var userErrMsg = “”;

    var errMsg = “”;

 

    if(IsPost)

    {

        // When the user clicks the “Open File” button and posts

        // the page, try to open the created file for reading.

        try {

            // This code fails because of faulty path to the file.

            fileContents = File.ReadAllText(@”c:\batafile.txt”);

 

            // This code works. To eliminate error on page,

            // comment the above line of code and uncomment this one.

            //fileContents = File.ReadAllText(physicalPath);

        }

        catch (FileNotFoundException ex) {

            // You can use the exception object for debugging, logging, etc.

            errMsg = ex.Message;

            // Create a friendly error message for users.

            userErrMsg = “A file could not be opened, please contact ”

                + “your system administrator.”;

        }

        catch (DirectoryNotFoundException ex) {

            // Similar to previous exception.

            errMsg = ex.Message;

            userErrMsg = “A directory was not found, please contact ”

                + “your system administrator.”;

        }

    }

    else

    {

        // The first time the page is requested, create the text file.

        File.WriteAllText(physicalPath, userMessage);

    }

}

 

<!DOCTYPE html>

<html lang=”en”>

    <head>

        <meta charset=”utf-8″ />

        <title>Try-Catch Statements</title>

    </head>

    <body>

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

      <input type=”Submit” name=”Submit” value=”Open File”/>

    </form>

 

    <p>@fileContents</p>

    <p>@userErrMsg</p>

 

    </body>

</html>

 

Empezando con WebMatrix y ASP.NET Web Pages

Empezando con WebMatrix y ASP

WebMatrix

WebMatrix es una suite de herramientas lanzada por Microsoft. Pretende que los usuarios con poca experiencia en desarrollo puedan crear sus propias aplicaciones facilmente.

Está basado en la plataforma .NET 4, integra una serie de herramientas necesarias para desplegar una aplicación web. IIS 7.5, Sql Server Compact, Mysql, el propio entorno de trabajo de WebMatrix, y plantillas de diferentes aplicaciones como WordPress, Jomla, etc.

La descarga es totalmente gratuita y sin registro.

Con WebMatrix aparece un concepto nuevo, el de las ASP.NET Web Pages.

Las Asp.Net Web Pages proporcionan una manera fácil de
conexión a bases de datos o añadir contenido de redes sociales o añadir
contenido de redes sociales con server code dinámico mezclado con HTML usando
la nueva y lliviana sintaxis ‘Razor’.

La caracteristicas más importantes que podemos indicar sobre ASP.NET Web Pages y Razor son:

  • No hay necesidad de entender las clases de
    programación orientada a objetos
  • No requiere configuración adicional para
    funcionar
  • SEO por defecto, optimizado para buscadores
  • Fácil utilización de helpers para la mayoria de
    las tareas comunes de desarrollo web
  • No requiere herramientas adicionales, funciona
    con el notepad o cualquier editor
  • Transición natural a proyectos ASP.NET MVC y
    Visual Studio

El código incrustado es más limpio.

 

Cursos Conetic

Inadeco, comienza en septiembre la impartición de dos cursos de teleformación, por el Conetic.

Uno es de ADO.NET 4 http://www.aulas-inadeco.com/adonet.php

El otro es de LINUX. http://www.aulas-inadeco.com/linux.php

 

 

 

Soporte Filestream en Sql Server 2008

Si agregamos soporte a FileStream despues de lainstalación en Sql Server 2008.

Desde el Configuration Manager.

Faltaría otro paso.

Acceder a las propiedades del servidor desde el Sql Management Studio, acceder a Avanzado, NIvel de acceso de Secuencia de Archivos y establecer en Acceso total habilitado

 

 

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