Monday, July 1, 2013

Predefined class and generate properties alone at runtime

To generate a properties at run-time and using pre-defined class.

using System;
using System.Data;
using System.Reflection;
using System.Collections.Generic;

namespace ReportEngine
{
    class Program
    {
        static void Main(string[] args)
        {

            DataTable table = InputGeneration.GetTable();

            //InputGeneration.DisplayTable(table);


            #region "Method1 - Predefined class and generate properties alone at runtime"

            Console.WriteLine("\n---Method1 - Predefined class and generate properties alone at runtime------\n");

            List<string> PropertyNames = Method1.GenerateProperties(table);

            ListDynamicClass> DynamicClassList = Method1.GenerateClass(PropertyNames, table);

            Method1.DisplayClass(DynamicClassList, PropertyNames);

            #endregion

            Console.WriteLine("\n---------------------------------------------------------\n");

            Console.ReadLine();
        }
    }
}

InputGeneration:

using System;
using System.Data;

namespace ReportEngine
{
    public static class InputGeneration
    {
        public static DataTable GetTable()
        {
            //
            // Here we create a DataTable with four columns.
            //
            DataTable table = new DataTable();
            table.Columns.Add("Dosage", typeof(int));
            table.Columns.Add("Drug", typeof(string));
            table.Columns.Add("Patient", typeof(string));
            table.Columns.Add("Date", typeof(DateTime));

            //
            // Here we add five DataRows.
            //
            table.Rows.Add(25, "Indocin", "David", DateTime.Now);
            table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
            table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
            table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
            table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
            return table;
        }

        public static void DisplayTable(DataTable dt)
        {
            if (dt.Rows.Count > 0)
            {
                foreach (DataColumn column in dt.Columns)
                {
                    Console.Write("\t{0}\t", column.ColumnName);
                }
                Console.WriteLine("\t");
                foreach (DataRow row in dt.Rows)
                {
                    foreach (DataColumn column in dt.Columns)
                        Console.Write("\t{0}\t", row[column]);

                    Console.WriteLine("\t");
                }
            }
            else
                Console.WriteLine("No Current Rows Found");
        }
    }
}

Method1:

using System;
using System.Data;
using System.Collections.Generic;
using ReportEngine.PropertyAtRuntime;

namespace ReportEngine
{
    public static class Method1
    {
        public static List<string> GenerateProperties(DataTable table)
        {
            List<string> PropertyNames = new List<string>();
            foreach (DataColumn column in table.Columns)
            {
                PropertyNames.Add(column.ColumnName.ToUpper());
            }

            return PropertyNames;
        }

        public static List<DynamicClass> GenerateClass(List<string> PropertyNames, DataTable table)
        {
            List<DynamicClass> DynamicClassList = new List<DynamicClass>();

            foreach (DataRow row in table.Rows)
            {
                var dynamicClass = new DynamicClass();

                foreach (string PropertyName in PropertyNames)
                {
                    dynamicClass.property[PropertyName] = row[PropertyName].ToString();
                }

                DynamicClassList.Add(dynamicClass);
            }
            return DynamicClassList;
        }

        public static void DisplayClass(List<DynamicClass> DynamicClassList, List<string> PropertyNames)
        {
            foreach (string PropertyName in PropertyNames)
            {
                Console.Write("{0}\t", PropertyName);
            }
            Console.WriteLine("\n");

            foreach (DynamicClass dynamicClass in DynamicClassList)
            {
                foreach (string PropertyName in PropertyNames)
                {
                    Console.Write("{0}\t", dynamicClass.property[PropertyName]);
                }
                Console.WriteLine("\n");
            }
        }
    }
}


DynamicClass:

using System;

namespace ReportEngine.PropertyAtRuntime
{
    public class DynamicClass
    {
        // property is a class that will create dynamic properties at runtime
        private DynamicProperty _property = new DynamicProperty();

        public DynamicProperty property
        {
            get { return _property; }
            set { _property = value; }
        }
    }
}

DynamicProperty:

using System;
using System.Collections.Generic;

namespace ReportEngine.PropertyAtRuntime
{
    public class DynamicProperty
    {
        // a Dictionary that hold all the dynamic property values
        private Dictionary<string, object> properties = new Dictionary<string, object>();

        // the property call to get any dynamic property in our Dictionary, or "" if none found.
        public object this[string name]
        {
            get
            {
                if (properties.ContainsKey(name))
                {
                    return properties[name];
                }
                return "";
            }
            set
            {
                properties[name] = value;
            }
        }
    }
}

Wednesday, March 6, 2013

Read csv file and import its data into List(object) with Linq
 
           var arrTitle = File.ReadAllLines(csvFileFolderPath)
                                .Select(x => x.Split(','))
                                .First();

            List lstUser = File.ReadAllLines(csvFileFolderPath)
                                                .Select(x => x.Split(','))
                                                .Skip(1)
                                                .Select(x =>
                                                     new Users
                                                     {
                                                         USERID = x[0],
                                                         LASTNAME = x[1],
                                                         FIRSTNAME = x[2],
                                                         PASSWORD = x[3]
                                                     }).ToList ();


 Read csv file and import its data into Datatable with Linq

            DataTable dt = new DataTable();

            var c1 = File.ReadAllLines(csvFileFolderPath)
                                    .Select(x => x.Split(','))
                                    .First().ToArray();

            var col = from cl in c1
                        select new DataColumn(cl);

            dt.Columns.AddRange(col.ToArray());

            var tableData = File.ReadAllLines(csvFileFolderPath)
                                .Select(x => x.Split(','))
                                .Skip(1)
                                .ToList();

            (from st in tableData
                    select dt.Rows.Add(st)).ToList();


Class File:

Public class Users
{
      public virtual string USERID { get; set; }
      public virtual string LASTNAME { get; set; }
      public virtual string FIRSTNAME { get; set; }
      public virtual string PASSWORD { get; set; }
}


A Simple String Compression Algorithm

Data compression is always useful for encoding information using fewer bits than the original representation it would use. There are many applications where the size of information would be critical. In data communication, the size of data can affect the cost too.


Form Code-Behind:

public byte[] ret;
SixBitEnDec obj = new SixBitEnDec();

private void Form1_Load(object sender, EventArgs e)
{
btnDecrypt.Enabled = false;
}

private void btnEncrypt_Click_1(object sender, EventArgs e)
{
ret = obj.encode(txtInput.Text, Convert.ToInt32(txtbit.Text));
     btnDecrypt.Enabled = true;
}

private void btnDecrypt_Click(object sender, EventArgs e)
{
txtResult.Text = obj.decode(ret, Convert.ToInt32(txtbit.Text));
}

Class File:

public class SixBitEnDec
    {
        static public int SIX_BIT = 6;
        static public int FIVE_BIT = 5;

        public SixBitEnDec() {

        }

        public byte[] encode(String txt, int bit)
        {
            int length = txt.Length;
            float tmpRet1 = 0, tmpRet2 = 0;

            if (bit == 6)
            {
                tmpRet1 = 3.0f;
                tmpRet2 = 4.0f;
            }
            else if (bit == 5)
            {
                tmpRet1 = 5.0f;
                tmpRet2 = 8.0f;
            }


            byte[] encoded = new byte[(int)(tmpRet1 * Math.Ceiling(length / tmpRet2))];
            char[] str = new char[length];

            int startIndex = 0;
            char[] chars = txt
                  .Where((c, i) => i >= startIndex && i < startIndex + length).ToArray();

            String temp;
            String strBinary = string.Empty;

            for (int i = 0; i < length; i++)
            {
                temp = Convert.ToString((toValue(chars[i])), 2);
                while (temp.Length % bit != 0)
                {
                    temp = "0" + temp;
                }
                strBinary = strBinary + temp;
            }

            while (strBinary.Length % 8 != 0)
            {
                strBinary = strBinary + "0";
            }

            Int32 tempInt = 0;
            for (int i = 0; i < strBinary.Length; i = i + 8)
            {
                tempInt = Convert.ToInt32(strBinary.Substring(i, 8), 2);
                encoded[i / 8] = Convert.ToByte(tempInt);
            }
            return encoded;
        }

        public String decode(byte[] encoded, int bit)
        {
            String strTemp = string.Empty;
            String strBinary = string.Empty;
            String strText = string.Empty;
            Int32 tempInt = 0;
            Int32 intTemp = 0;

            for (int i = 0; i < encoded.Length; i++)
            {
                if (encoded[i] < 0)
                {
                    intTemp = (int)encoded[i] + 256;
                }
                else
                    intTemp = (int)encoded[i];

                strTemp = Convert.ToString(intTemp, 2);

                while (strTemp.Length % 8 != 0)
                {
                    strTemp = "0" + strTemp;
                }
                strBinary = strBinary + strTemp;
            }
            for (int i = 0; i < strBinary.Length; i = i + bit)
            {
                tempInt = Convert.ToInt32(strBinary.Substring(i, bit), 2);
                strText = strText + toChar(Convert.ToInt32(tempInt));
            }
            return strText;
        }

        int toValue(char ch)
        {
            int chaVal = 0;
            switch (ch)
            {
                case ' ': chaVal = 0; break;
                case 'a': chaVal = 1; break;
                case 'b': chaVal = 2; break;
                case 'c': chaVal = 3; break;
                case 'd': chaVal = 4; break;
                case 'e': chaVal = 5; break;
                case 'f': chaVal = 6; break;
                case 'g': chaVal = 7; break;
                case 'h': chaVal = 8; break;
                case 'i': chaVal = 9; break;
                case 'j': chaVal = 10; break;
                case 'k': chaVal = 11; break;
                case 'l': chaVal = 12; break;
                case 'm': chaVal = 13; break;
                case 'n': chaVal = 14; break;
                case 'o': chaVal = 15; break;
                case 'p': chaVal = 16; break;
                case 'q': chaVal = 17; break;
                case 'r': chaVal = 18; break;
                case 's': chaVal = 19; break;
                case 't': chaVal = 20; break;
                case 'u': chaVal = 21; break;
                case 'v': chaVal = 22; break;
                case 'w': chaVal = 23; break;
                case 'x': chaVal = 24; break;
                case 'y': chaVal = 25; break;
                case 'z': chaVal = 26; break;
                case '.': chaVal = 27; break;
                case '*': chaVal = 28; break;
                case ',': chaVal = 29; break;
                case '\'': chaVal = 30; break;
                case '2': chaVal = 31; break;
                case 'A': chaVal = 32; break;
                case 'B': chaVal = 33; break;
                case 'C': chaVal = 34; break;
                case 'D': chaVal = 35; break;
                case 'E': chaVal = 36; break;
                case 'F': chaVal = 37; break;
                case 'G': chaVal = 38; break;
                case 'H': chaVal = 39; break;
                case 'I': chaVal = 40; break;
                case 'J': chaVal = 41; break;
                case 'K': chaVal = 42; break;
                case 'L': chaVal = 43; break;
                case 'M': chaVal = 44; break;
                case 'N': chaVal = 45; break;
                case 'O': chaVal = 46; break;
                case 'P': chaVal = 47; break;
                case 'Q': chaVal = 48; break;
                case 'R': chaVal = 49; break;
                case 'S': chaVal = 50; break;
                case 'T': chaVal = 51; break;
                case 'U': chaVal = 52; break;
                case 'V': chaVal = 53; break;
                case 'W': chaVal = 54; break;
                case '0': chaVal = 55; break;
                case '1': chaVal = 56; break;
                case '3': chaVal = 57; break;
                case '4': chaVal = 58; break;
                case '5': chaVal = 59; break;
                case '6': chaVal = 60; break;
                case '7': chaVal = 61; break;
                case '8': chaVal = 62; break;
                case '9': chaVal = 63; break;
                default: chaVal = 0; break;

            }
            return chaVal;
        }

        char toChar(int val)
        {
            char ch = ' ';
            switch (val)
            {
                case 0: ch = ' '; break;
                case 1: ch = 'a'; break;
                case 2: ch = 'b'; break;
                case 3: ch = 'c'; break;
                case 4: ch = 'd'; break;
                case 5: ch = 'e'; break;
                case 6: ch = 'f'; break;
                case 7: ch = 'g'; break;
                case 8: ch = 'h'; break;
                case 9: ch = 'i'; break;
                case 10: ch = 'j'; break;
                case 11: ch = 'k'; break;
                case 12: ch = 'l'; break;
                case 13: ch = 'm'; break;
                case 14: ch = 'n'; break;
                case 15: ch = 'o'; break;
                case 16: ch = 'p'; break;
                case 17: ch = 'q'; break;
                case 18: ch = 'r'; break;
                case 19: ch = 's'; break;
                case 20: ch = 't'; break;
                case 21: ch = 'u'; break;
                case 22: ch = 'v'; break;
                case 23: ch = 'w'; break;
                case 24: ch = 'x'; break;
                case 25: ch = 'y'; break;
                case 26: ch = 'z'; break;
                case 27: ch = '.'; break;
                case 28: ch = '*'; break;
                case 29: ch = ','; break;
                case 30: ch = '\''; break;
                case 31: ch = '2'; break;
                case 32: ch = 'A'; break;
                case 33: ch = 'B'; break;
                case 34: ch = 'C'; break;
                case 35: ch = 'D'; break;
                case 36: ch = 'E'; break;
                case 37: ch = 'F'; break;
                case 38: ch = 'G'; break;
                case 39: ch = 'H'; break;
                case 40: ch = 'I'; break;
                case 41: ch = 'J'; break;
                case 42: ch = 'K'; break;
                case 43: ch = 'L'; break;
                case 44: ch = 'M'; break;
                case 45: ch = 'N'; break;
                case 46: ch = 'O'; break;
                case 47: ch = 'P'; break;
                case 48: ch = 'Q'; break;
                case 49: ch = 'R'; break;
                case 50: ch = 'S'; break;
                case 51: ch = 'T'; break;
                case 52: ch = 'U'; break;
                case 53: ch = 'V'; break;
                case 54: ch = 'W'; break;
                case 55: ch = '0'; break;
                case 56: ch = '1'; break;
                case 57: ch = '3'; break;
                case 58: ch = '4'; break;
                case 59: ch = '5'; break;
                case 60: ch = '6'; break;
                case 61: ch = '7'; break;
                case 62: ch = '8'; break;
                case 63: ch = '9'; break;
                default: ch = ' '; break;
            }
            return ch;
        }
    }

Note:
Above code works fine for 6 bit encryption and decryption. Shortly i'll upload the code for 5 bit also.

For Referrences:
 http://www.codeproject.com/Articles/223610/A-Simple-String-Compression-Algorithm

Tuesday, January 8, 2013

Dynamically create ListView and thier templates at runtime

I have created a Composite control, which contains a listview to display a table of items. I am using a ListView in Asp.NET and define the templates in the code-behind.

using System;
using System.Web;
using System.Web.UI;

public partial class Report1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
      {
    }

    protected override void CreateChildControls()
        {
            base.CreateChildControls();

            ListView view = new ListView();

        view.ID = "view";
            view.LayoutTemplate = new LayoutTemplate();
        view.GroupTemplate = new GroupTemplate();
            view.ItemTemplate = new ItemTemplate();

            view.DataSource = FibonacciSequence();    //assign List objects for custom design
            view.DataBind();

            pnl.Controls.Add(view);
        }

    public int Iterations { get; set; }

    private IEnumerable FibonacciSequence()
      {
            int i1 = 0;
            int i2 = 1;
            Iterations = 5;
            for (int i = 0; i < Iterations; i++)
            {
                yield return i1 + i2;
                int temp = i1 + i2;
                i1 = i2;
                i2 = temp;
            }
            yield break;
      }

    public class LayoutTemplate : ITemplate
      {
            public void InstantiateIn(Control container)
            {
                var div = new HtmlGenericControl("div") { ID = "groupPlaceholder" };
                container.Controls.Add(div);
            }
      }

    public class GroupTemplate : ITemplate
      {
            public void InstantiateIn(Control container)
            {
                var tbl1 = new HtmlGenericControl("table");
                tbl1.Attributes.Add("cellpadding", "0");
                tbl1.Attributes.Add("cellspacing", "0");
                tbl1.Attributes.Add("border", "0");
                tbl1.Attributes.Add("class", "tblBorder");
                tbl1.Attributes.Add("width", "100%");
                var tr1 = new HtmlGenericControl("tr");
                var td1 = new HtmlGenericControl("td");
                td1.Style.Add("padding", "5px");

                var tbl2 = new HtmlGenericControl("table");
                tbl2.Attributes.Add("cellpadding", "3px");
                tbl2.Attributes.Add("cellspacing", "0");
                tbl2.Attributes.Add("border", "0");
                tbl2.Attributes.Add("width", "100%");
                var tr2 = new HtmlGenericControl("tr") { ID = "itemPlaceholder" };

                tbl2.Controls.Add(tr2);
                td1.Controls.Add(tbl2);
                tr1.Controls.Add(td1);
                tbl1.Controls.Add(tr1);
                container.Controls.Add(tbl1);
            }
      }

        public class ItemTemplate : ITemplate
      {
            public void InstantiateIn(Control container)
            {
                var tr = new HtmlGenericControl("tr");
                tr.DataBinding += DataBinding;
                container.Controls.Add(tr);
            }

            public void DataBinding(object sender, EventArgs e)
            {
                var container = (HtmlGenericControl)sender;
                var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;

                container.Controls.Add( new Literal(){Text = dataItem.ToString() });

            //For custom design
            //container.Controls.Add( new Literal(){Text = GetValue(dataItem) });
            }

        protected string GetValue(object obj)
            {
            //parse object and do customized design

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj.GetType());

                    string SVALUE, SNAME = string.Empty;

            foreach (PropertyDescriptor prop in properties)
                    {
                        if (prop.GetValue(obj) != null)
                        {
                            SVALUE = prop.GetValue(obj).ToString() ?? DBNull.Value.ToString();
                            SNAME = prop.Name;
                }
            }
        }
        }
}