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> 

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; }
}

}