Friday, 24 July 2015

Generic methods for xml serialization

Serialization XML
 
       public static string Serialize<T>(T param) where T:class
        {
            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(T));
                StringWriter sw = new StringWriter();
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                ser.Serialize(sw, param, ns);
                return sw.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
 
Deserialization XML
 
        public static T Deserialize<T>(string xml) where T : class
        {
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(T));
                StreamReader sw = new StreamReader(stream);
                var dto = (T)ser.Deserialize(sw);
                return dto;
            }
            catch
            {
                return null;
            }
            finally
            {
                stream.Flush();
                stream.Dispose();
            }
        }

Wednesday, 22 July 2015

Ignore property to be serialized in xml serializer

Conditionaly ignore any property to be serialized in xml using XML serializer. You can achieve it using ShouldSerialize{Property Name} method. E.g
 
        public string PropertyName { get; set; }
        public bool ShouldSerialize PropertyName ()
        {
    // Condition for property which return true/false
               return !string.IsNullOrEmpty(PropertyName); 
        }
 
 
 
Serializable class :
 
[XmlRoot("TestXML")]
    public class Testxml
    {
        [XmlElement]
        public int Id { get; set; }
 
        [XmlElement]
        public string Name { get; set; }
 
        [XmlElement]
        public string City { get; set; }
        public bool ShouldSerializeCity()
        {
            return !string.IsNullOrEmpty(City);
        }
    }
 
Method to serialize :
 
Testxml xml = new Testxml();
xml.Id= 10;
xml.Name = "Ajay";
xml.City = "";
XmlSerializer ser = new XmlSerializer(typeof(Testxml));
StringWriter sw = new StringWriter();
ser.Serialize(sw, xml);
 
Results :
 
When  xml.City = "Kalol"; Then XML looks like below :
 
<?xml version="1.0" encoding="utf-16" ?>
<testxml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <id>10</id>
    <name>Ajay</name>
    <city>Kalol</city>
</testxml>
 
When  xml.City = ""; Then XML looks like below :
 
<?xml version="1.0" encoding="utf-16" ?>
<testxml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <id>10</id>
    <name>Ajay</name>
</testxml>

Wednesday, 8 July 2015

Generic class with optional parameter

public class Generic<T>
      where T : new()
    {
        private T objClass;
        public T ClassInstance
        {
            get
            {
                if (objClass == null)
                {
                    objClass = new T();
                }
 
                return objClass;
            }
        }
    }
 
    public class Generic<T, T1> : Generic<T>
        where T1 : new()
        where T : new()
    {
        private T1 objClass1;
        public T1 ClassInstance1
        {
            get
            {
                if (objClass1 == null)
                {
                    objClass1 = new T1();
                }
 
                return objClass1;
            }
        }
    }

Friday, 1 May 2015

Revised : Generic data access for repository pattern


public class GenericDAL<T> : IDisposable
        where T : class
    {
        private EDMX.RMSModel model;
        private DbSet<T> dbSet;
        public GenericDAL()
        {
            model = new RMSModel();
            dbSet = model.Set<T>();
        }

        // Pass order by fields. form multiple fields pass fields by Comma(;) separated
         public IEnumerable<T> GetList(Expression<Func<T, bool>> where = null,
                                                        string orderBy = null,
                                                        SortDirection sortDir = SortDirection.Ascending)
        {
            IQueryable<T> query = dbSet;
            if (where != null)
            {
                query = query.Where(where);
            }

            if (!string.IsNullOrWhiteSpace(orderBy))
            {
                var orderFields = orderBy.Split(';');
                return OrderByDynamic(query, orderFields, sortDir);
            }
            else
            {
                return query.ToList();
            }
        }

        public T GetDetails(Expression<Func<T, bool>> where)
        {
            if (where != null)
            {
                IQueryable<T> query = dbSet;
                return query.Where(where).FirstOrDefault();
            }

            return null;
        }

        public int Insert(T entity)
        {
            dbSet.Add(entity);
            return model.SaveChanges();
        }

        public int Update(T entity)
        {
            dbSet.Attach(entity);
            model.Entry(entity).State = EntityState.Modified;
            return model.SaveChanges();
        }

        public int Delete(Expression<Func<T, bool>> where)
        {
            IQueryable<T> query = dbSet;
            T entity = query.Where(where).FirstOrDefault();
            dbSet.Remove(entity);
            return model.SaveChanges();
        }

        private List<T> OrderByDynamic(IQueryable<T> query = null, string[] sortExpressions = null,
                                                         SortDirection direction = SortDirection.Ascending)
        {
            // No sorting needed
            if ((sortExpressions == null) || (sortExpressions.Length <= 0))
            {
                return query.ToList();
            }

            // Let us sort it
            IOrderedEnumerable<T> orderedQuery = null;
            for (int i = 0; i < sortExpressions.Length; i++)
            {
                var index = i;
                Func<T, object> expression = item => item.GetType()
                                .GetProperty(sortExpressions[index])
                                .GetValue(item, null);

                if (direction == SortDirection.Ascending)
                {
                    orderedQuery = (index == 0) ?
                                              query.OrderBy(expression):
                                              orderedQuery.ThenBy(expression);
                }
                else
                {
                    orderedQuery = (index == 0) ?
                                              query.OrderByDescending(expression):
                                              orderedQuery.ThenByDescending(expression);
                }
            }

            return orderedQuery.ToList();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                model.Dispose();
            }

            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

    }