Blog de Francisco Velázquez

otro blog personal

Posts Tagged ‘csharp

Helper para ConfigurationElementCollection

leave a comment »

Interesante utilidad que ayuda muchísimo para trabajar con colecciones en archivos de configuración.

    [ConfigurationCollection(typeof(ConfigurationElement))]
    public class ConfigurationElementCollection<T> :
        ConfigurationElementCollection, IEnumerable<T> where T : ConfigurationElement, new()
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new T();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((T)(element)).ToString();
        }
        public T this[int idx]
        {
            get { return (T)BaseGet(idx); }
        }

        public new IEnumerator<T> GetEnumerator()
        {
            int count = base.Count;
            for (int i = 0; i < count; i++)
                yield return base.BaseGet(i) as T;
        }
Advertisements

Written by fravelgue

September 6, 2011 at 4:41 pm

Posted in development

Tagged with , , ,

Simple cache para BusinessObjects

leave a comment »

Debido a la naturaleza de mi trabajo, aplicaciones multitenant, y servicios M2M, para mejorar el rendimiento suelo cachear muchos objectos que tienen un tasa de lectura muy alta y de cambios muy muy pequeño. Así que para facilitar el trabajo, me he decido crear una pequeña utilidad.

    /// <summary>
    /// Concurrent cache for BusinessObject.  It doesn´t clean cache, useful for small data.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BusinessObjectCache<T>
        where T : BusinessObject<T>
    {
        static ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
        static volatile Dictionary<object, T> storage;

        static BusinessObjectCache()
        {
            Locker.EnterWriteLock();
            try
            {
                storage = new Dictionary<object, T>();
            }
            finally { Locker.ExitWriteLock(); }
        }

        public T Get(object id)
        {
            T o = null;
            Locker.EnterReadLock();
            try
            {
                if (storage.ContainsKey(id))
                {
                    o = storage[id];
                    return o;
                }
            }
            finally { Locker.ExitReadLock(); }

            if (o == null)
            {
                Locker.EnterUpgradeableReadLock();
                try
                {
                    if (!storage.ContainsKey(id))
                        o = BusinessObject<T>.Retrieve(id);

                    if (o != null)
                    {
                        Locker.EnterWriteLock();
                        try
                        {
                            storage[id] = o;
                        }
                        finally { Locker.ExitWriteLock(); }
                    }
                }
                finally { Locker.ExitUpgradeableReadLock(); }
            }

            return o;
        }
    }

A ver si me lo curro y la hago LRU.

Written by fravelgue

July 21, 2011 at 5:44 pm

Posted in development

Tagged with , ,

Simple HTTP GET en C#

leave a comment »

La verdad es que, a veces, cosas sencillas se hacen  complicadas en .NET y en mi opinión esta es una de ellas. Nada que objetar a que un framework tiene que ser lo menos restrictivo posible, pero en este caso no encuentro el sentido de que un error HTTP tenga que lanzar una excepción, yo personalmente la definiría como excepción vexing. Y bueno como estamos para ayudar pues con esta pequeña función todo será un poco más sencillo.

        public static int Get(string uri, int timeout, out string response)
        {
            int statusCode = -1;
            response = string.Empty;

            HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
            request.KeepAlive = false;
            request.Timeout = timeout;

            try
            {
                using (HttpWebResponse res = (HttpWebResponse)request.GetResponse() as HttpWebResponse)
                {
                    statusCode = (int)res.StatusCode;
                    using (Stream dataStream = res.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(dataStream))
                        {
                            response = reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (WebException wex)
            {
                //http://msdn.microsoft.com/en-us/library/es54hw8e.aspx
                if (wex.Status == WebExceptionStatus.ProtocolError)
                {
                    // If status is WebExceptionStatus.ProtocolError,
                    // there has been a protocol error and a WebResponse
                    // should exist. Display the protocol error.
                    using (HttpWebResponse res = wex.Response as HttpWebResponse)
                    {
                        if (res != null)
                        {
                            statusCode = (int)res.StatusCode;

                            using (Stream s = wex.Response.GetResponseStream())
                            using (StreamReader reader = new StreamReader(s))
                            {
                                response = reader.ReadToEnd();
                            }
                        }
                        else
                        {   // no http status code available
                            throw wex;
                        }
                    }
                }
                else
                {   // no http status code available
                    throw wex;
                }
            }

            return statusCode;
        }

Cuanto más veo ese código, menos me gusta como está diseñado.
Un par de enlaces.

Written by fravelgue

July 19, 2011 at 7:27 pm

Posted in development

Tagged with , , , , ,

Basic Authentication en HTTP Post

leave a comment »

string uri = string.Empty, user = string.Empty, password = string.Empty, postData = string.Empty, responseData = string.Empty;
            string encodedAuthorization = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(user + ":" + password));
HttpWebRequest webRequest = WebRequest.Create(uri) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Headers = new WebHeaderCollection();
webRequest.Headers.Add("Authorization: Basic "+encodedAuthorization);

using (StreamWriter rw = new StreamWriter(webRequest.GetRequestStream()))
{
            rw.Write(postData);
}

using (StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
            responseData = sr.ReadToEnd();
}

Written by fravelgue

February 10, 2010 at 10:58 pm

Posted in development

Tagged with , , , ,

Enumerados mejorados en C#

leave a comment »

Un par de artículos que explican como extender la funcionalidad de los Enumerados en c#. via.

Written by fravelgue

October 28, 2009 at 11:06 pm

Posted in development

Tagged with , , ,

Enumerados y Atributos

leave a comment »

Siempre me ha encantado la manera en que Gentle.NET maneja los errores, usando enumerados y atributos.

	/// <summary>
	/// This enumeration lists all common error conditions, their severity and a
	/// default error message.
	/// Unspecified errors or errors with no severity attribute are treated as critical.
	/// At this time almost all errors have been brainlessly classified as critical pending
	/// a review at some future time.
	/// </summary>
	public enum Error
	{
		/// <summary>
		/// This error is used when no connection to the database server could be
		/// established. This is usually caused by errors in the connection
		/// string, but can also be due to network or database server problems.
		/// </summary>
		[Level( Severity.Critical ),
		 Message( "The database backend (provider {0}) could not be reached.\r\n" +
		          "Check the connection string: {1}" )]
		DatabaseUnavailable,

		/// <summary>
		/// This error is used when an error in the use of Gentle was detected
		/// (e.g. invalid use of or missing custom attributes). No default message
		/// is provided for this error (if used via the Check class the first
		/// argument will be used as format string for remaining arguments).
		/// </summary>
		[Level( Severity.Error )]
		DeveloperError

Hoy he estado usando esta técnica en un proyecto.  Además he encontrado esta librería que también me ha servido de inspiración.

Written by fravelgue

September 8, 2009 at 4:30 pm

Posted in development

Tagged with , , , ,

POST multipart message MIME

leave a comment »

Written by fravelgue

March 2, 2009 at 10:29 am

Posted in development

Tagged with , , , , ,