Thursday, November 11, 2010

Generic Data Link Layer

 This Data Link Layer returns Objects of the Classes. I tried to give a generic look so tht it can be used in any project. It will require small changes.


using System;
using System.Data;
//using System.Configuration;
using System.Linq;
//using System.Web;
//using System.Xml.Linq;
using System.Data.SqlClient;
using McAfee.Utilities.DatabaseHelper;
using System.Collections.Generic;

namespace Blog.BO
{
    ///
    /// Summary description for Database_Connection
    ///

    public class Database_Connection
    {
        private string sql_Connection_String = new ConnectionString().GetConnectionString();
        public List Connection_Select_Database(Type objType, string sqlQuery,int input_Size ,params string[] parameters_List)         {             List listObjects = new List(2);             string objecttype = objct_type(objType);             SqlCommand sql_command = sql_command_builder(sqlQuery,input_Size, parameters_List);             if (sql_command == null) return null;             try             {                 using (SqlConnection conn = new SqlConnection(sql_Connection_String))                 {                     sql_command.Connection = conn;                     conn.Open();                     SqlDataReader rdr;                     using (rdr = sql_command.ExecuteReader())                     {                         List reader_names = new List(2);                                              DataTable schema = rdr.GetSchemaTable();                         foreach (DataRow row in schema.Rows)                         {                             reader_names.Add((string)row.ItemArray[0]);                         }                         while (rdr.Read())                         {                             switch (objecttype)                             {                                 case "User": listObjects.Add(new UserObject_Logic().Forobject(rdr, reader_names));                                     break;                                 case "Article": listObjects.Add(new ArticleObject_Logic().Forobject(rdr, reader_names));                                     break;                                 case "Comment": listObjects.Add(new CommentObject_Logic().Forobject(rdr, reader_names));                                     break;                             }                         }                     }                                         return listObjects;                 }             }             catch             {                 return null;             }         }         public List Add_into_List(SqlDataReader rdr, Type object_Type)         {             List listObjects = new List(2);             List reader_names = new List(2);             string typeObject = objct_type(object_Type);             DataTable schema = rdr.GetSchemaTable();             foreach (DataRow row in schema.Rows)             {                 reader_names.Add((string)row.ItemArray[0]);             }             while (rdr.Read())             {                 switch (typeObject)                 {                     case "User": listObjects.Add(new UserObject_Logic().Forobject(rdr, reader_names));                         break;                     case "Article": listObjects.Add(new ArticleObject_Logic().Forobject(rdr, reader_names));                         break;                     case "Comment": listObjects.Add(new CommentObject_Logic().Forobject(rdr, reader_names));                         break;                 }             }             return listObjects;         }         public SqlParameter[] Default_Parameter(SqlParameter[] sqlParams, int input_size)         {             if(sqlParams==null)             {             sqlParams = new SqlParameter[1];             }             int len = sqlParams.Length;             sqlParams[len-1] = new SqlParameter("@return", SqlDbType.Int, input_size);             sqlParams[len-1].Direction = ParameterDirection.ReturnValue;             return sqlParams;         }         public List Exec_Select_Query(string stored_Procdure_Name,SqlParameter[] sql_Params,Type object_Type,int input_Size)         {                            sql_Params = Default_Parameter(sql_Params,input_Size);             int returnvalue = -1;             List Objects;             SqlDataReader rdr;             using (rdr = SQLHelper.ExecuteReader(new ConnectionString().GetConnectionString(), CommandType.StoredProcedure, stored_Procdure_Name, out returnvalue, sql_Params))             {                 Objects = Add_into_List(rdr, object_Type);             }             return Objects;         }         protected string objct_type(Type obj)         {             if (obj == typeof(UserObject))                 return "User";             if (obj == typeof(ArticleObject))                 return "Article";             return "Comment";         }         public int Connection_Del_Inset_Update(string sqlQuery,int input_Size, params string[] parameters_list)         {             int result = 0;             SqlCommand sql_command = sql_command_builder(sqlQuery,input_Size ,parameters_list);             if (sql_command == null) return 0;             try             {                 using (SqlConnection conn = new SqlConnection(sql_Connection_String))                 {                     sql_command.Connection = conn;                     conn.Open();                     result = sql_command.ExecuteNonQuery();                     return result;                 }             }             catch             {                 return 0;             }         }         public SqlCommand sql_command_builder(string sql_Query,int input_Size, params string[] parameters_list)         {             SqlCommand sql_command = new SqlCommand(sql_Query);             SqlParameter parameter_value;             string[] parameters_name = sql_Query.Split(new char[] { '=', ' ', '(', ')', ',' });             List oparam = new List();             int index = 0;             foreach (string parameter in parameters_name)             {                 if (parameter.Contains('@')) oparam.Add(parameter);             }             if (parameters_list.Count() != oparam.Count())                 return null;             foreach (string parameter in parameters_list)             {                 parameter_value = new SqlParameter(oparam[index], parameter);                                 parameter_value.DbType = DbType.String;                 parameter_value.Size = input_Size;                 sql_command.Parameters.Add(parameter_value);                 index++;             }             return sql_command;         }     } }             
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Class Logic



public UserObject Forobject(SqlDataReader reader, List names)//(string name, object val)
        {
            UserObject new_User = new UserObject();
            foreach (string name in names)
            {
                switch (name)
                {
                    case "userId": new_User.UserId = (string)reader[name];
                        break;
                    case "username": new_User.UserName = (string)reader[name];
                        break;
                }
            }
            return new_User;
        }
              
      
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Class

 public class UserObject
    {
        public string UserName { get; set; }
        public string UserId { get; set; }
        public string Password { get; set; }
    

    } 
   

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Example which uses this:

public List GetData()
        {
            int input_Size = 10;
            SqlParameter[] sql_Param= null;
            List dataResult = new Database_Connection().Exec_Select_Query(Stored_Procedure_Names.GetUsersInfo, sql_Param, object_Type, input_Size);//(typeof(ArticleObject), sqlQuery, input_Size, article.ArticleId.ToString());             if (dataResult == null) return null;             List users = new List(2);             if (dataResult == null) return null;             foreach (Object obj in dataResult)             {                 users.Add((UserObject)obj);             }             return users;             //List objects;             //string sqlQuery = "select userId,username from userinfo where userId <> 'admin'";             //int input_Size = 10;             //objects = new Database_Connection().Connection_Select_Database(typeof(UserObject), sqlQuery, input_Size);         }

XML Readers use

Checking the efficency by 3 readers.
1.XMl Document
2.Xml Reader
3.XPath Naviagtor


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using System.Diagnostics;
using System.IO;

namespace EffeciencyCheckInXMLReadOperations
{
    public partial class Form1 : Form
    {
        string m_fileName = @"DataFile.xml";
        string m_XPath = "configuration/appSettings";
        string m_Path = "appSettings";
        string m_File_string;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            m_File_string = File.ReadAllText(m_fileName);
        }

        private IEnumerable ReadXML(XmlReader reader)
        {
            Member member = null;
            if (!reader.ReadToFollowing(m_Path))
                yield return member;

            while (reader.Read() && reader.NodeType != XmlNodeType.EndElement)
            {
                if (!reader.HasAttributes)
                    continue;
                member = new Member();
                member.Data = reader.GetAttribute("key", "");
                member.Value = reader.GetAttribute("value", "");
                yield return member;
            }
        }   
       

        private IEnumerable ReadXML(XPathNavigator xPathNav)
        {
            Member member = null;
            xPathNav = xPathNav.SelectSingleNode(m_XPath);
            if (xPathNav == null)
                yield return member;
           
            xPathNav.MoveToFirstChild();
                do
                {
                    if (!xPathNav.HasAttributes)
                        continue;
                    member = new Member();
                    member.Data = xPathNav.GetAttribute("key", "");
                    member.Value = xPathNav.GetAttribute("value", "");
                    yield return member;
                } while (xPathNav.MoveToNext());
           
        }
        private IEnumerable ReadXML(XmlDocument xmlDoc)
        {
            xmlDoc.LoadXml(m_File_string);
            Member member = null;
            XmlNode node = xmlDoc.SelectSingleNode(m_XPath);
            if (node == null)
                yield return member;
            foreach (XmlNode child in node.ChildNodes)
            {
                if (child.NodeType == XmlNodeType.Comment)
                    continue;
                member = new Member();
                member.Data = child.Attributes[0].Value;
                member.Value = child.Attributes[1].Value;
                yield return member;
            }
        }

        private void XMLReader_Click(object sender, EventArgs e)
        {

            DateTime startWatch = DateTime.Now;
            StringReader rdr = new StringReader(m_File_string);
            using (XmlReader reader = XmlReader.Create(rdr))
            {
                dataGridView1.DataSource = ReadXML(reader).ToList();
            }
            DateTime stopWatch = DateTime.Now;
            TimeSpan time = stopWatch - startWatch;
            MessageBox.Show(time.ToString());
        }

        private void XPathDocument_Click(object sender, EventArgs e)
        {
            DateTime startWatch = DateTime.Now;
            StringReader rdr = new StringReader(m_File_string);
            dataGridView1.DataSource = ReadXML(new XPathDocument(rdr).CreateNavigator()).ToList();
            DateTime stopWatch = DateTime.Now;
            TimeSpan time = stopWatch - startWatch;
            MessageBox.Show(time.ToString());
        }

        private void XMLDocument_Click(object sender, EventArgs e)
        {
            DateTime startWatch = DateTime.Now;
            dataGridView1.DataSource = ReadXML(new XmlDocument()).ToList();
            DateTime stopWatch = DateTime.Now;
            TimeSpan time = stopWatch - startWatch;
            MessageBox.Show(time.ToString());
        }
       
    }       

       
   

    class Member
    {
        public string Data { get; set; }
        public string Value { get; set; }
    }


}




XML file:



How To Use Streams in C#

 Chk this out. If possible Give me a better solution.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Compression;
using System.IO;

namespace StreamTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputFile= "c:/u.log.gz";
            Console.WriteLine("Enter File Path");
           // inputFile=Console.ReadLine();
            FileInfo file = new FileInfo(inputFile);
            if (file.Exists)
            {
                Decompress(file);
            }
        }

        public static void Decompress(FileInfo file)
        {
            using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
            {
                if (file.Extension == ".gz")
                {
                    Display(new GZipStream(fs, CompressionMode.Decompress, false));
                }
                else
                    Display(fs);

            }
        }

        static void Display(Stream stream)
        {
            Console.WriteLine("Enter No. of lines wanted to Display");
            try
            {
                int n = Int32.Parse(Console.ReadLine());
                int count = -4;
                foreach (string line in ReadFile(stream))
                {
                    if (!line.Contains("#") || count < 0)
                    {
                        Console.WriteLine(line);
                        Console.ReadKey();
                        count++;

                    }
                    if (count == n)
                        break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Enter numbers");
            }
 
        }

        static IEnumerable ReadFile(Stream stream)
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                string line=null;
                while ((line = reader.ReadLine()) != null)
                {
                    yield return line;
                }
            }
        }

    }
}






In this program I am using Gzip stream to printout line by line of the file. Here I learned how to use stream.

Wednesday, March 24, 2010

Letter to Editor

Dear Sir,

In reference to the front page article in Kolkata Edition, dated 24th March'10.The news is about the blaze at Park Street, Kolkata where more than 16 people lost their lives. It is very disturbing news and the whole nation mourn about this incident. I felt it very offensive, the way this news was published on the front page of TOI. Is the author trying to create an humorous environment by stating that "A woman, in a sand- colored salwar stood framed against a burning window. She waved for a while, either to plead for help or say goodbye, no one will ever know.Then, as people on the ground screamed 'no,no', she jumped. The sickening thud and a piercing wall pushed the shocked crowd a fer steps back.Then they surfed back. The window no longer existed.There was just a wall of flame." Is he writing a novel or a news? Should I laugh at the woman who was waving for help or saying goodbye ? What do the author think about it ? Standing on 5th floor and waving her hand doesn't means she was in a mood to have party over their and saying Goodbye.

Apart from that a picture shows the dead body of the woman ,who jumped from 5th floor, with a girl crying for help. The photographer here is busy in taking good pictures. Dont he have any moral responsibility to help the victims instead of taking pictures for the newspaper? I think Pictures are more important than human lives.

Thirdly, the front page news shows a dead body picture which I think, is totally inappropriate. How its going to affect the mindsets of children who reads your newspaper before going to school?

I am a regular reader of TOI and I am deeply depressed, the way this news has been covered. It might feel you offensive but I think some ethics and moral responsibility should have been showned by your team.Its disheartening that TOI has lowered its standard, for which it is known.

Hope you will understand the gravity of the situation and would present the news in appropriate manner.

Thursday, February 4, 2010

4th feb

In the diaspora, after spending some time with faucet, he Unfurled the sleeves and walk down the aisle in search of auguries. He was didactics by the interlocutor to carry carcass along with the cart. His bags was full of filigree taken surreptitiously from the treasury. After few hours he reached an attic construction where a man was bleating with pain. His face was full of cuts. In the state of melancholia he moved slowly to look for the dentures which were lying aside and were shining under the sun.hitherto he was living in his milieu free of fear.he moved lambently towards the man.

Alma Mater

On the very first Day, after getting enrolled in the APEX institute, I visited my institute's computer lab. It was fully occupied human aliens(as no one except me was well dressed and in full senses). I was so impressed by the way the lab was designed. Fully equipped with 40-45 PC with geek on each terminal. Moving down the aisle i looked at various screens. Many folks were busy in chatting abt girls and some of them were busy surfing on net. My whole intention was to chat with my school mates though yahoo mesg. Before going into deep conversation I must tell u i always used Yahoo mesg. on Windows before this day.
So the story is like this....
I asked one of the boy (not man) for help to assign me a pc as in cyber cafes this was tradition. He was tall , simple and sober in nature(i learned later). He said politely to grab any revolving chair and get connected to the WORLD. Bravely,as if i have won the level 1 of the game, I moved towards a blue covered chair to claim my name. But a strange hand came from dark and pushed me to move outside.that time i discovered i am blocking the gate. I felt remorse. but nevertheless i was more excited with the APEX institute feeling that may be he is busy with some tricky problem.
I moved to pickup a remote chair or she picked me , either case, I looked at the aesthetic condition of the seat.I unfurled a newpaper lying near it N put it down on the seat. A terminal was also free near it. Cheers..Second Victory of the Day :).
As I have never worked on any OS other than Windows I was amused by the blue fedora wallpaper and the icons shape. I thought " This is really a gr8 institute as students over here have changed the face of Bill Gate's Windows. After 5 yrs I wll also be in a position to change the shape of MS. Wow its awesome."
Next target : which icon will open a browser and which icon will lead me to Yahoo Mesg.
I admit, that this level was the toughest in terms of my day's achievements.For me the mouse was working as it used to work in cyber cafe's pc but where should I go. I serached the most idle person in the LAB...the LAb Admin. I open the face my barrel and fired at him.Sir will you please tell me which one is Internet Explorer.
He was amazed with my question and I thought wow Dude gr8 work. He asked me some basic question like ur in junior batch,first time in lab etc. I satisfied all the queries and the interlocutor gave me the cheat code. "Just Click on icon which is having a Globe."

Well thts it ... it was my first day and I learned how to use internet in LABs. :)

Marathi Manoos

Marathi Manoos ... Its quite strange political parties fighting for a name in Mumbai ...
Who can be know as "MM".. who was born in Munbai or who is working for the development of Mumbai. As declared by MNS,Shiv Sena ..only those are entitlted to be called as MM who were born in Mumbai N know Marathi ...
I think this is an absurd theory as even senior leaders of Shiv Sena , may hav been born in mumbai but their ancestors were not frm this land.So according to me they are not entitled to get that tag with them. May be only those people can be known as MM whose ancestors were never born on other land.

Fighting over MM is not justifiable as its an part of india. Who really works for the development of Mumbai can be termed as MM. Recently acc. to a report Mr. Bala Saheb has asked Mr. Bachcan for the Movie Rann to be telecasted in his home. Irony of the situation is tht few days back he was opposing MR.BB for the origin N now is asking for his help.