Blog de Francisco Velázquez

otro blog personal

Archive for the ‘.net’ Category

Exportar a csv desde c#

leave a comment »

Una pequeña utilidad para exportar listas genéricas a csv, usando expresiones lambda.

public class ExportExcel<T> where T : class
    {
        private StringBuilder sb;        

        public ExportExcel()
        {            
            sb = new StringBuilder();
            if (HttpContext.Current != null)
                Context = HttpContext.Current;
        }

        public string Filename { get; set; }
        public HttpContext Context { get; set; }

        public void Export(List<T> l, Expression<Func<T, object>> expression)
        {
            if (string.IsNullOrEmpty(Filename))
                return;

            build(l, expression);

            Context.Response.AddHeader("content-disposition", "attachment;filename=" + Filename);
            Context.Response.Charset = string.Empty;
            Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Context.Response.ContentType = "application/CSV";            
            Context.Response.Write(sb.ToString());
            Context.Response.End();
        }

        public string ToString(List<T> l, Expression<Func<T, object>> expression)
        {            
            build(l, expression);
            return sb.ToString();
        }

        private void build(List<T> l, Expression<Func<T, object>> expression)
        {
            sb = new StringBuilder();
            List<string> propertiesName = new List<string>();
            NewArrayExpression array = expression.Body as NewArrayExpression;
            foreach (object obj in (IEnumerable<object>)(array.Expressions))
            {
                string propertyName = obj.ToString().Remove(0, obj.ToString().IndexOf(".") + 1);
                propertyName = propertyName.Replace(")", "");
                sb.Append(propertyName + ";");
                propertiesName.Add(propertyName);
            }
            sb.AppendLine();

            foreach (var i in l)
            {
                foreach (var propertyName in propertiesName)
                {
                    sb.Append(getPropertyValue(i, propertyName).ToString() + ";");
                }
                sb.AppendLine();
            }
        }

        internal static object getPropertyValue(object obj, string propertyName)
        {
            const System.Reflection.BindingFlags bindingFlags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance;

            var pi = typeof(T).GetProperties(bindingFlags).Where(prop => prop.Name == propertyName).SingleOrDefault();
            return pi.GetValue(obj, null);
        }
    }
Advertisements

Written by fravelgue

September 27, 2012 at 7:36 pm

Posted in .net

Tagged with , ,

Arquitectura CQRS y DDD

leave a comment »

Me pareció muy ilustrativa esta diapositiva.

via.

Written by fravelgue

March 17, 2011 at 7:04 pm

Posted in .net

Tagged with , ,

Abstrayendo operaciones básicas en business objects

with one comment

Tras leer el buen artículo de Matt Long, se me ocurrió que tal podría aplicar estos principios para facilitar mi trabajo con Gentle.NET (increíble pero cierto) y tal vez que fuera el origen de un cambio en el motor de persistencia.

Así podríamos tener una clase base para todos nuestros objetos de negocio.


public class BusinessObject<T> : Persistent
        where T : class
    {
        static protected PersistenceBroker persistenceBroker;
        protected Type _type;
        static protected BusinessObject<T> _objToRetrieve = null;
        protected bool _empty = true;
        protected bool _changed = false;

        
        [TableColumn("id", NotNull = true), PrimaryKey(AutoGenerated = false)]
        public int Id { get; set; }

        public bool Changed
        { 
            get { return _changed; } 
        }

        static BusinessObject()
        {
            // TODO Singleton
            if (_objToRetrieve == null) _objToRetrieve = new BusinessObject<T>();
            if (persistenceBroker == null) 
                    persistenceBroker = new PersistenceBroker(typeof(T));
        }

        static public T Retrieve(int id)
        {
            return _objToRetrieve.retrieve(id);         
        }

        protected T retrieve(int id)
        {
            Key key = new Key(typeof(T), true, "Id", id);
            return ((PersistenceBroker)persistenceBroker).RetrieveInstance(typeof(T), key) as T;
        }

        public override void Persist()
        {
            if (Changed || !IsPersisted)
            {
                base.Persist();
                _changed = false;
            }
        }

        public override void Remove()
        {
            base.Remove();            
        }

        // TODO FindBy

        public override bool Equals(object obj)
        {
            bool result = false;
            if (obj != null)
                result = ((this.GetType() == obj.GetType()) 
                    && (((BusinessObject<T>)this).Id == ((BusinessObject<T>)obj).Id));
            return result;
        }

        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }
    }

[Serializable]
    [TableName("Example")]
    class Exmple : BusinessObject<Example>
    {
        [TableColumn("name", NotNull = false)]
        public string Name { get; set; }

        [TableColumn("description", NotNull = false)]
        public string Description { get; set; }

        [TableColumn("date", NotNull = false)]
        public DateTime Date { get; set; }

        [TableColumn("error", NotNull = false)]
        public bool Error { get; set; }
    }

Written by fravelgue

December 11, 2010 at 12:41 pm

Posted in .net

Tagged with , , ,

Consumir un WebService con autenticación básica desde .NET

leave a comment »

El título describe bastante bien lo que vamos a solucionar en este post.

public class SecureWebService : ThirdPartyWebService
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri);
        NetworkCredential credentials = Credentials as NetworkCredential;
        if (credentials != null)
        {
            string authInfo =
            ((credentials.Domain != null) && (credentials.Domain.Length > 0) ?
            credentials.Domain + @"\" : string.Empty) +
            credentials.UserName + ":" + credentials.Password;
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            webRequest.Headers["Authorization"] = "Basic " + authInfo;
        }
        return webRequest;
    }
}

via.

Written by fravelgue

October 5, 2010 at 12:38 pm

Posted in .net

Tagged with , , ,

Microsoft lanza Silverlight (WPF/E)

leave a comment »

Con él pretende competir con  Abobe Flash. Supongo que habrá que ojearlo…

A su vez Adobe continua desarrollando Flex, para intentar tomar cuota del mercado de aplicaciones empresariales (dominadas por .Net y JavaEE).

Written by fravelgue

April 16, 2007 at 12:59 pm

Posted in .net