Utilizar jquery ui con ASP .NET

Colocando esta linea de codigo funcionó los componentes de jquery ui con .NET

html aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AsistenteVentas.aspx.cs" Inherits="Mantenimientos.AsistenteVentas" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title></title>
 <link href="css/custom.css" rel="stylesheet" />
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
 <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" />
 <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
 <script type="text/javascript">
 function InIEvent()
 {
 $(function () {
 var xdialog;
xdialog = $('#BuscaPersonal').dialog({
 modal: true,
 autoOpen: false,
 height: 300,
 width: 650
 });
$('#xbtn_buscar').on('click', function () {
 xdialog.dialog('open');
 $('#hddorigen').val('ASISTVTA');
 });
xdialog.parent().appendTo($('form:first'));
 });
 }
$(document).ready(InIEvent);
 
 </script>
<body>
 <form id="form1" runat="server">
 <asp:ScriptManager runat="server"></asp:ScriptManager>
 <script type="text/javascript">
 Sys.WebForms.PageRequestManager.getInstance().add_endRequest(InIEvent);
 </script>
 <div class="contenido">
 <h2>Asistentes de Ventas</h2>
 <div>
 <div>
 <table>
 <tr>
 <td> 
 <asp:ImageButton ID="btnNuevoAsisVta" runat="server" ImageUrl="~/img/nuevo.png" Width="16px" OnClick="btnNuevoAsisVta_Click" />
 </td>
 </tr>
 </table>
 </div>
 <%-- Panel de mantenimiento de asistentes de ventas --%>
 <asp:UpdatePanel ID="updpnlMtoAsistVta" runat="server" UpdateMode="Conditional">
 <ContentTemplate>
 <asp:Panel ID="pnlmtoAsistVta" runat="server">
 <table class="form-tabla">
 <tr>
 <td>Codigo</td>
 <td>:</td>
 <td><asp:TextBox ID="txtcodigoAsistvta" runat="server" ReadOnly="true" Width="50px"></asp:TextBox></td>
 <td><img src="img/search.png" width="32" alt="" id="xbtn_buscar" class="img-boton" /></td>
 </tr>
 <tr>
 <td>Nombres y Apellidos</td>
 <td>:</td>
 <td colspan="2"><asp:TextBox ID="txtnomyape" runat="server" ReadOnly="true" Width="200px"></asp:TextBox></td>
 </tr>
 <tr>
 <td>Correo Electrónico</td>
 <td>:</td>
 <td colspan="2"><asp:TextBox ID="txtcorreo" runat="server" ReadOnly="true" Width="200px"></asp:TextBox></td>
 </tr>
 <tr>
 <td>L&iacute;nea</td>
 <td>:</td>
 <td colspan="2"><asp:DropDownList ID="ddl_linea" runat="server" Width="150px"></asp:DropDownList></td>
 </tr>
 <tr class="form-fila-botones">
 <td colspan="2"><asp:ImageButton ID="btnguardarAsisVta" runat="server" ImageUrl="~/img/save.png" Width="32" /></td>
 <td colspan="2"><asp:ImageButton ID="btnregresarAsisVta" runat="server" ImageUrl="~/img/back.png" Width="32" OnClick="btnregresarAsisVta_Click" /></td>
 </tr>
 </table>
 <asp:Label ID="lblmensaje1" runat="server"></asp:Label>
 </asp:Panel>
 </ContentTemplate>
 <Triggers>
 <asp:AsyncPostBackTrigger ControlID="btnguardarAsisVta" EventName="Click" />
 <asp:AsyncPostBackTrigger ControlID="btnregresarAsisVta" EventName="Click" />
 <asp:AsyncPostBackTrigger ControlID="btnNuevoAsisVta" EventName="Click" />
 </Triggers>
 </asp:UpdatePanel>
<div> 
 <%-- Grilla de asistentes de ventas --%>
<asp:GridView ID="gvAsistentes" runat="server" AutoGenerateColumns="False">
 <Columns>
 <asp:TemplateField HeaderText="ID"> 
 <ItemTemplate>
 <asp:LinkButton ID="lnkID" runat="server" Text='<%# Eval("codigo").ToString() %>'></asp:LinkButton>
 </ItemTemplate>
 </asp:TemplateField>
 <asp:BoundField DataField="linea" HeaderText="Linea" />
 <asp:BoundField DataField="nombres" HeaderText="Nombres y Apellidos" />
 <asp:BoundField DataField="correo" HeaderText="Correo electronico" />
 <asp:TemplateField>
 <ItemTemplate>
 <asp:ImageButton ID="btneliminar" runat="server" ImageUrl="~/img/eliminar.png" Width="16" /> 
 </ItemTemplate>
 </asp:TemplateField>
 </Columns>
 </asp:GridView>
 </div>
 <div id="BuscaPersonal" class="widget" title="Busqueda de personal">
 <div>
 <%-- LA BUSQUEDA DE PERSONAL --%>
 <asp:Panel ID="pnl_buscar" runat="server" DefaultButton="btn_buscar">
 <table class="form-tabla">
 <tr>
 <td>Ingrese nombres o correo electrónico</td>
 <td>:</td>
 <td><asp:TextBox ID="txtbuscar" runat="server" Width="300px"></asp:TextBox></td>
 <td><asp:ImageButton ID="btn_buscar" runat="server" ImageUrl="~/img/search.png" Width="32" OnClick="btn_buscar_Click" /></td>
 </tr>
 </table> 
 </asp:Panel>
 </div>
 <asp:UpdatePanel ID="upd1" runat="server" UpdateMode="Conditional">
 <ContentTemplate>
 <asp:GridView ID="gvpersonal" runat="server" AutoGenerateColumns="False" CssClass="grid-net" >
 <Columns>
 <asp:TemplateField HeaderText="Codigo"> 
 <ItemTemplate>
 <asp:LinkButton ID="lnkpersonal" runat="server" Text='<%# Eval("CodigoPersona").ToString() %>'></asp:LinkButton>
 </ItemTemplate>
 </asp:TemplateField>
 <asp:BoundField DataField="NombresApellidos" HeaderText="Nombres y Apellidos" />
 <asp:BoundField DataField="CorreoElectronico" HeaderText="Correo electronico" />
 </Columns>
 </asp:GridView> 
 <asp:HiddenField ID="hddorigen" runat="server" /> 
 </ContentTemplate>
 <Triggers>
 <asp:AsyncPostBackTrigger ControlID="btn_buscar" EventName="Click" />
 </Triggers>
 </asp:UpdatePanel> 
 <div>
</div>
 </div>
<div>
 <%-- LA BUSQUEDA DE PERSONAL --%>
 <h3>Personal de Ventas</h3>
 <div>
 <table>
 <tr>
 <td><asp:ImageButton ID="img_nuevo_vta" runat="server" ImageUrl="~/img/nuevo.png" Width="16px" /></td>
 </tr>
 </table>
 </div>
 <div>
 <asp:GridView ID="gv_ventas" runat="server" AutoGenerateColumns="False">
 <Columns>
 <asp:BoundField DataField="codigo" HeaderText="Codigo" />
 <asp:BoundField DataField="nombres" HeaderText="Nombres y Apellidos" />
 <asp:BoundField DataField="correo" HeaderText="Correo electrónico" />
 <asp:TemplateField>
 <ItemTemplate>
 <asp:ImageButton ID="img_eliminar_vta" runat="server" ImageUrl="~/img/eliminar.png" Width="16px" />
 </ItemTemplate>
 </asp:TemplateField>
 </Columns>
 </asp:GridView>
 </div>
 </div>
 <div>
 <table>
 <tr>
 <td>
</td>
 </tr>
 </table>
 </div>
 </div>
 </div>
 </form>
</body>
</html>

Codigo C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DTO;
using ENT;

namespace Mantenimientos
{
 public partial class AsistenteVentas : System.Web.UI.Page
 {
 protected void Page_Load(object sender, EventArgs e)
 {
 if (!(Page.IsPostBack))
 {
 DTOAsistVta obj = new DTOAsistVta();
 List<ENTLinea> lstLinea = obj.ListarLineas();

 if (lstLinea.Count == 1 && lstLinea[0].Mensaje != null)
 {
 ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", string.Format("alert('Ha ocurrido un error: {0}", lstLinea[0].Mensaje), true);
 return;
 }

 this.ddl_linea.DataSource = lstLinea;
 this.ddl_linea.DataTextField = "NombreLinea";
 this.ddl_linea.DataValueField="CodigoLinea";
 this.DataBind();

 this.ddl_linea.Items.Insert(0, new ListItem("...Seleccione", "0"));
 //this.pnlmtoAsistVta.Style.Add(HtmlTextWriterStyle.Display, "none");
 this.pnlmtoAsistVta.Visible = false;
 }
 }

 protected void btn_buscar_Click(object sender, ImageClickEventArgs e)
 {
 DTOAsistVta obj = new DTOAsistVta();

 List<ENTPersona> lstpersona = obj.ListarColaboradores(this.txtbuscar.Text.Trim());
 
 //Verificando que no haya error

 if (lstpersona.Count == 1 && lstpersona[0].Mensaje != null)
 {
 ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", string.Format("alert('Ha ocurrido un error: {0}", lstpersona[0].Mensaje), true);
 return;
 }

 this.gvpersonal.DataSource = lstpersona;
 this.gvpersonal.DataBind();
 }

 protected void btnNuevoAsisVta_Click(object sender, ImageClickEventArgs e)
 {
 //this.pnlmtoAsistVta.Style.Add(HtmlTextWriterStyle.Display, "inline");
 this.pnlmtoAsistVta.Visible = true;
 }

 protected void btnregresarAsisVta_Click(object sender, ImageClickEventArgs e)
 {
 this.pnlmtoAsistVta.Visible = false;
 }


 }
}

No ejecutan controles de servidor ASP.NET con Jquery UI

Hay que agregar la ultima linea luego de configurar el dialog jqueryui

jQuery(function() {
    var dlg = jQuery("#dialog").dialog({
                         draggable: true,
                         resizable: true,
                         show: 'Transfer',
                         hide: 'Transfer',
                         width: 320,
                         autoOpen: false,
                         minHeight: 10,
                         minwidth: 10
                     });
    dlg.parent().appendTo(jQuery("form:first"));
})

Solucion error WCF IIS: Memoria disponible menor al 5%

El detalle del error mostrado por IIS es:

Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InsufficientMemoryException: Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element

Se ha solucionado añadiendo las siguientes lineas en el web config de la aplicación

<system.serviceModel> 
    <serviceHostingEnvironment minFreeMemoryPercentageToActivateService="0" />
</system.serviceModel> 

Envio de correos electronicos usando .NET

public static string EnviarEmail(String pServidor,
String pFrom,
String pTO,
String pCorreoCopia,
String pSubject,
String pBody,
String pArchivoAtachado,
System.Net.Mail.MailPriority pPrioridad)
{
if (pServidor.Trim() == «»)
{
return «EnviarEmail() – No se pudo enviar el correo electronico, no se especifico ningun servidor SMTP»;
}

if (pTO.Trim() == «»)
{
return «EnviarEmail() – No se pudo enviar el correo electronico, No hay destinatarios»;
}
System.Net.Mail.MailMessage correo = new System.Net.Mail.MailMessage();
correo.From = new System.Net.Mail.MailAddress(pFrom);

String[] StrListaCorreos = pTO.Split(‘;’);
foreach (String strCorreoEncopia in StrListaCorreos)
{
if (strCorreoEncopia.Trim().Length > 0)
{
if (correo.To.IndexOf(new MailAddress(strCorreoEncopia)) == -1)
{
correo.To.Add(strCorreoEncopia);
}
}
}
if (pCorreoCopia.Trim() != «»)
{
String[] StrCopiados = pCorreoCopia.Split(‘;’);
foreach (String strCorreoEncopia in StrCopiados)
{
if (strCorreoEncopia.Trim().Length > 0)
{
correo.CC.Add(strCorreoEncopia);
}
}
}

correo.Subject = pSubject;
correo.Body = pBody;
correo.IsBodyHtml = true;
correo.Priority = pPrioridad;

System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(pServidor);
try
{
smtp.Send(correo);
}
catch (Exception ex)
{
return «EnviarEmail()- » + ex.ToString();
}
return «»;
}

Encryptar / Desencryptar QueryString ASP NET

HTML Markup
Page 1
The following HTML Markup consists of a TextBox, a DropDownList and a Button. The value from the TextBox and the DropDownLists will be encrypted and send using QueryString Parameters to the next page on Button click.
<table border=»0″ cellpadding=»0″ cellspacing=»0″>
    <tr>
        <td>
            Name:
        </td>
        <td>
            <asp:TextBox ID=»txtName» runat=»server» Text=»Mudassar Khan» />
        </td>
    </tr>
    <tr>
        <td>
            Technology:
        </td>
        <td>
            <asp:DropDownList ID = «ddlTechnology» runat=»server»>
                <asp:ListItem Text=»ASP.Net» Value = «ASP.Net» />
                <asp:ListItem Text=»PHP» Value = «PHP» />
                <asp:ListItem Text=»JSP» Value = «JSP» />
            </asp:DropDownList>
        </td>
    </tr>
</table>
<hr />
<asp:Button ID=»Button1″ Text=»Submit» runat=»server» OnClick = «Submit» />
 
Page 2
The following HTML Markup consists of two Label controls which will be used to display the QueryString Parameter values received on the page.
<table border=»0″ cellpadding=»0″ cellspacing=»0″>
    <tr>
        <td>
            Name:
        </td>
        <td>
            <asp:Label ID=»lblName» runat=»server» Text=»» />
        </td>
    </tr>
    <tr>
        <td>
            Technology:
        </td>
        <td>
            <asp:Label ID=»lblTechnology» runat=»server» Text=»» />
        </td>
    </tr>
</table>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Text;
using System.Security.Cryptography;
VB.Net
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
 
 
AES Algorithm Encryption and Decryption functions
Below are the functions for Encryption and Decryption which will be used for the Encrypting or Decrypting QueryString Parameter Values.
Note: The following functions have been explained in the article AES Encryption Decryption (Cryptography) Tutorial with example in ASP.Net using C# and VB.Net
 
 
Encrypting the QueryString Parameter Values
When the Button is clicked the following event handler is executed. Here the values of the TextBox and the DropDownList are first encrypted using the AES Symmetric Key Algorithm and then encoded using the UrlEncode method of the HttpUtility class. Finally these values are sent as QueryString Parameters to the next page.
Note: Here Encoding is required as the Encrypted string contains special characters and it is necessary to encode special characters before sending them as QueryString parameter.
C#
protected void Submit(object sender, EventArgs e)
{
    string name = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim()));
    string technology = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value));
    Response.Redirect(string.Format(«~/CS2.aspx?name={0}&technology={1}», name, technology));
}
private string Encrypt(string clearText)
{
    string EncryptionKey = «MAKV2SPBNI99212»;
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            clearText = Convert.ToBase64String(ms.ToArray());
        }
    }
    return clearText;
}
 
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
    Dim name As String = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim()))
    Dim technology As String = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value))
    Response.Redirect(String.Format(«~/VB2.aspx?name={0}&technology={1}», name, technology))
End Sub
Private Function Encrypt(clearText As String) As String
    Dim EncryptionKey As String = «MAKV2SPBNI99212»
    Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText)
    Using encryptor As Aes = Aes.Create()
        Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
         &H65, &H64, &H76, &H65, &H64, &H65, _
         &H76})
        encryptor.Key = pdb.GetBytes(32)
        encryptor.IV = pdb.GetBytes(16)
        Using ms As New MemoryStream()
            Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)
                cs.Write(clearBytes, 0, clearBytes.Length)
                cs.Close()
            End Using
            clearText = Convert.ToBase64String(ms.ToArray())
        End Using
    End Using
    Return clearText
End Function
 
 
Decrypting the QueryString Parameter Values
In the Page Load event of the page, the values of the TextBox and DropDownList sent from the previous page are first fetched from the QueryString Parameters and then are decoded using the UrlDecode method of the HttpUtility class.
After decoding the string is decrypted using the AES Symmetric Key Algorithm and then the decrypted values are displayed using Label controls.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString[«name»]));
        lblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString[«technology»]));
    }
}
private string Decrypt(string cipherText)
{
    string EncryptionKey = «MAKV2SPBNI99212»;
    cipherText = cipherText.Replace(» «, «+»);
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText;
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString(«name»)))
        lblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString(«technology»)))
    End If
End Sub
Private Function Decrypt(cipherText As String) As String
    Dim EncryptionKey As String = «MAKV2SPBNI99212»
    cipherText = cipherText.Replace(» «, «+»)
    Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText)
    Using encryptor As Aes = Aes.Create()
        Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
         &H65, &H64, &H76, &H65, &H64, &H65, _
         &H76})
        encryptor.Key = pdb.GetBytes(32)
        encryptor.IV = pdb.GetBytes(16)
        Using ms As New MemoryStream()
            Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)
                cs.Write(cipherBytes, 0, cipherBytes.Length)
                cs.Close()
            End Using
            cipherText = Encoding.Unicode.GetString(ms.ToArray())
        End Using
    End Using
    Return cipherText
End Function
 

Encrypt and Decrypt QueryString Parameter Values in ASP.Net using C# and VB.Net

Encrypt and Decrypt QueryString Parameter Values in ASP.Net using C# and VB.Net

Capa modal al hacer postback ASP

<script type=»text/javascript»>
function initializeRequest(sender, args) {
$find(‘js_modal’).show();
}

function endRequest(sender, args) {
$find(‘js_modal’).hide();
}

Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(initializeRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
</script>

Consumir REST desde C#

Hace algunos días atras buscaba una forma decente y elegante de crear mi propia api utilizando RESTful para Celestic .. de esa forma fue que llegue a StackOverflow y muchas preguntas de usuarios necesitando código para consumir servicios basados en REST.. En este sitio todavía no colaboro por lo que no quize responder, ya pensándolo bien fue que decidí escribir este artículo.

Sé que hay otra manera de hacerlo.. pero para este ejemplo utilizaremos el objeto HttpWebRequest y HttpWebResponse, entonces comenzamos:

var postString = new {clave1:valor1, clave2:valor2};
byte[] data = UTF8Encoding.UTF8.GetBytes(postString);
 
HttpWebRequest request;
request = WebRequest.Create("http://localhost/ejemplo/api") as HttpWebRequest;
request.Timeout = 10 * 1000;
request.Method = "POST";
request.ContentLength = data.Length;
request.ContentType = "application/json; charset=utf-8";

Básicamente lo que se hace es instanciar de HttpWebRequest y setear algunos parámetros, entre ellos y mas importante el método (Method), la longitud de la petición (ContentLength) y el tipo de dato a enviar (ContentType). No pierdan de vista que estoy enviando postString que a su vez es un objeto tipo Json.

La mayoría de servicios basados en REST requieren autenticación básica.. y pues es una de las más fáciles de utilizar.. inclusive desde el navegador se puede hacer, lo único que se requiere es un usuario y una clave de acceso..

string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("usuario:clave"));
request.Headers.Add("Authorization", "Basic " + credentials);

Esto es como algunas páginas en internet que piden autenticación para entrar, donde puedes escribir la url y esperar a que aparezca el formulario de inicio de sesion o escribirlo directamente en la url.. de la forma: “usuario:clave@http://localhost/ejemplo/api”

Ahora lo siguiente y último paso es enviar los datos y obtener la respuesta..

Stream postStream = request.GetRequestStream();
postStream.Write(data, 0, data.Length);
 
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
string body = reader.ReadToEnd();

Y para finalizar body es el contenido de lo que ha respondido el servicio, recuerden que la respuesta es tipo Json.. por lo que pueden interpretarla facilmente con javascript o hacer algo más complejo si desean parsearlo desde .NET.

Consumir servicio REST desde .NET

http://www.lm-tech.it/Blog/post/2013/05/06/How-to-consume-a-RESTful-service-from-Net-Framework-40.aspx

 

In the post Design a RESTful service with .NET framework 4.0 i’ve shown how to create a RESTful service using .Net Framework 4.0.

Let’s see now how to consume the service through a .Net client application. We will use theWebClient class defined in the System.Net namespace for sending and receiving data to or from the RESTful service, and the DataContractJsonSerializer class to serialize and deserialize an instance of a type to or from a JSON document.

The sample assume that the service is deployed at the address http://localhost:49193/Contacts.svc:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;namespace Test
{
class Program
{
static void Main(string[] args)
{
// add a contact
Contact contact = new Contact() {
fName = «John»,
lName = «Smith»,
eMail = «j.smith@xxx.com»
};

contact = Add(contact);

// update a contact
contact.eMail = «j.smith@tempuri.com»;
Update(contact);

// get a single contact
string id = contact.ContactId.ToString();
contact = GetContact(id);

// get all contacts
List<Contact> contactList = GetAll();

// delete a contact
Delete(id);
}

/// <summary>
/// Get all contacts
/// </summary>
/// <returns></returns>
static List<Contact> GetAll()
{
// web client
WebClient client = new WebClient();
client.Headers[«Content-type»] = «application/json»;

// invoke the REST method
byte[] data = client.DownloadData(
«http://localhost:49193/Contacts.svc/GetAll»);

// put the downloaded data in a memory stream
MemoryStream ms = new MemoryStream();
ms = new MemoryStream(data);

// deserialize from json
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(List<Contact>));

List<Contact> result = ser.ReadObject(ms) as List<Contact>;

return result;
}

/// <summary>
/// Get a single contact
/// </summary>
/// <param name=«id»></param>
/// <returns></returns>
static Contact GetContact(string id)
{
// web client
WebClient client = new WebClient();
client.Headers[«Content-type»] = «application/json»;

// invoke the REST method
byte[] data = client.DownloadData(
«http://localhost:49193/Contacts.svc/GetContact/» + id);

// put the downloaded data in a memory stream
MemoryStream ms = new MemoryStream();
ms = new MemoryStream(data);

// deserialize from json
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(Contact));
Contact result = ser.ReadObject(ms) as Contact;

return result;
}

/// <summary>
/// Add a contact
/// </summary>
/// <param name=«c»></param>
/// <returns></returns>
static Contact Add(Contact c)
{
// web client
WebClient client = new WebClient();
client.Headers[«Content-type»] = «application/json»;

// serialize the object data in json format
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(Contact));
ser.WriteObject(ms, c);

// invoke the REST method
byte[] data = client.UploadData(
«http://localhost:49193/Contacts.svc/Add»,
«ADD»,
ms.ToArray());

// deserialize the data returned by the service
ms = new MemoryStream(data);
Contact result = ser.ReadObject(ms) as Contact;

return result;
}

/// <summary>
/// Update the contact
/// </summary>
/// <param name=«c»></param>
static void Update(Contact c)
{
// web client
WebClient client = new WebClient();
client.Headers[«Content-type»] = «application/json»;

// serialize the object data in json format
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(Contact));
ser.WriteObject(ms, c);

// invoke the REST method
client.UploadData(
«http://localhost:49193/Contacts.svc/Update»,
«PUT»,
ms.ToArray());
}

/// <summary>
/// Delete the contact
/// </summary>
/// <param name=«id»></param>
static void Delete(string id)
{
// web client
WebClient client = new WebClient();
client.Headers[«Content-type»] = «application/json»;

// serialize the object data in json format
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(string));
ser.WriteObject(ms, id);

// invoke the REST method
byte[] data = client.UploadData(
«http://localhost:49193/Contacts.svc/Delete»,
«DELETE»,
ms.ToArray());

}
}

public class Contact
{
public int ContactId { get; set; }
public string fName { get; set; }
public string lName { get; set; }
public string eMail { get; set; }
}

}