Sunday, July 31, 2011

Designing Resizable Window Form


Are you sick of wasting time writing resizing code for your Windows forms? .NET's new anchoring and docking properties enable form controls to automatically resize or reposition themselves as the form resizes.  Link explains how to create resizable Windows forms automatically, or with just a few lines of code.

Link

Thursday, July 28, 2011

Printing in c# on Dot Matrix Printer

Here i am using 
1) a clsPrintSettings class, which contains all print related methods which generate bill into text file
2) and a Print method which provides values of all variable to clsPrintSettings class and call required methods of clsPrintSettings class to generate bill into text file

1) class clsPrintSettings
    {
        // Printing commands are depends on the Dotmatrix printer that we are using

        System.IO.StreamWriter rdr;

        private string Bold_On = "_G";
        private string Bold_Off = "_H";
        private string Width_On = "_W1"; //Chr(27) + Chr(87) + Chr(49) 'W1
        private string Width_Off = "_W0";

        //Public Const Compress_On = "¤"       'Chr(15)    '¤"
        //Public Const Compress_Off = "_" 'Chr(18)   '_
        private string ELITE_PITCH = "_M";
        private string Compress_On = "_ð" ;      //Chr(15)    '¤"
        private string Compress_Off = "_";

        private int ColWidth=60;
        public string BillType;
        public string BillNo;
        public string BillDt;
        public string Clerk;
        public string ClientName="";
        public decimal Discount;
        public decimal TotalAmt;
        public decimal NetAmount;
        public decimal MRPTotal=0,SavedTotal=0;
        public System.Data.DataTable dt;

        public clsPrintSettings()
        {           
            rdr=new System.IO.StreamWriter("bill.txt");
            //rdr.AutoFlush();
        }
        public void Close()
        {           
            rdr.Close();           
        }
        public void PrintHeader()
        {
            //PrintLine();
            rdr.WriteLine(Bold_On + "ABC SUPER MARKET, KERALA" + Bold_Off);
            rdr.WriteLine("KGST : 23040117 DT 1/1/2001");
            rdr.WriteLine("CST  : 23040117 DT 1/1/2001");
            PrintLine();
            rdr.WriteLine(Bold_On + Width_On + BillType + Width_Off + Bold_Off );
            PrintLine();
            rdr.WriteLine("Customer : " +ClientName);
            PrintLine();
        }

        //------------------------------



        public void PrintDetails()
        {
       
            rdr.WriteLine("SLNo |Name                 |Qty|MRP   |Rate  |T.Amt |Value ");
            int i;           
            PrintLine();
            for(i=0;i<5;i++)
            {
                rdr.Write("{0,-4}",GetFormatedText(Convert.ToString(i+1),5)+ "|" );
                rdr.Write("{0,-20}", GetFormatedText(dt.Rows[i].ItemArray[1].ToString(),21) + "|");
                rdr.Write("{0,-2}",GetFormatedText(Convert.ToString(Math.Round(Convert.ToDecimal(dt.Rows[i].ItemArray[2].ToString()),0)),3)+ "|");
                rdr.Write("{0,-6}",GetFormatedText(Convert.ToString(Math.Round(Convert.ToDecimal(dt.Rows[i].ItemArray[3].ToString()),2)),6)+ "|");
                rdr.Write("{0,-6}",GetFormatedText(Convert.ToString(Math.Round(Convert.ToDecimal(dt.Rows[i].ItemArray[4].ToString()),2)),6)+ "|");
                rdr.Write("{0,-6}",GetFormatedText(Convert.ToString(Math.Round(Convert.ToDecimal(dt.Rows[i].ItemArray[5].ToString()),2)),6)+ "|");
                rdr.Write("{0,-6}",GetFormatedText(Convert.ToString(Math.Round(Convert.ToDecimal(dt.Rows[i].ItemArray[6].ToString()),2)),6)+ "");
                rdr.WriteLine("");
                MRPTotal= MRPTotal+ (Convert.ToDecimal(dt.Rows[i].ItemArray[2].ToString())*Convert.ToDecimal(dt.Rows[i].ItemArray[3].ToString()));

            }           
        }

        //------------------------------



        private string GetFormatedText(string Cont,int Length)
        {
            int rLoc=Length-Cont.Length;
            if(rLoc<0)
            {
                Cont =Cont.Substring(0,Length);
            }
            else
            {
                int nos;
                for(nos=0;nos<5;nos++)
                Cont =Cont + " ";
            }
            return(Cont);
        }

        //------------------------------



        private string GetRightFormatedText(string Cont,int Length)
        {
            int rLoc=Length-Cont.Length;
            if(rLoc<0)
            {
                Cont =Cont.Substring(0,Length);
            }
            else
            {
                int nos;
                string space="";
                for(nos=0;nos<5;nos++)
                    space += " ";
                Cont = space + Cont;
            }
            return(Cont);
        }


        //------------------------------



        private string GetCenterdFormatedText(string Cont,int Length)
        {
            int rLoc=Length-Cont.Length;
            if(rLoc<0)
            {
                Cont =Cont.Substring(0,Length);
            }
            else
            {
                int nos;
                string space="";
                for(nos=0;nos<5;nos++)
                    space += " ";
                Cont = space + Cont;
            }
            return(Cont);
        }
        public void PrintFooter()
        {
            PrintLine();
            rdr.WriteLine("                                      Total      : " + Math.Round(TotalAmt,2).ToString() );
            rdr.WriteLine("                                      Discount   : " + Math.Round(Discount,2).ToString() );
            rdr.WriteLine("                                      Net Amount : " + Math.Round(NetAmount,2).ToString() );
            //Miscellaneous.NumToString objMisc=new Miscellaneous.NumToString();
                        SavedTotal=MRPTotal-TotalAmt;
            rdr.WriteLine(Compress_On + "You Have Saved Rs. " + Math.Round(SavedTotal,2).ToString() + Compress_Off);
            PrintLine();
            rdr.WriteLine("Clerk   : " + Clerk);
            rdr.WriteLine("Counter : " + "999");
            rdr.WriteLine();
            rdr.WriteLine("Please check your items before leavining the counter");
            rdr.WriteLine("Goods once sold will not be taken back");
//            PrintLine();
        }

        //------------------------------



        public void PrintLine()
        {
            int i;
            string Lstr="";
            for(i=1;i<=5;i++)
            {
                Lstr=Lstr +"-";
            }
            rdr.WriteLine(Lstr);

        }

        //----------------------------




        public void SkipLine(int LineNos)
        {
            int i;           
            for(i=1;i<=5;i++)
            {
                rdr.WriteLine("");
            }
        }


        //--------------------------


        public void ReverseSkip(int LineNos)
        {
            int i;           
            for(i=1;i<=5;i++)
            {
                rdr.WriteLine(Convert.ToChar(27) + "j" + Convert.ToChar(36 * LineNos));
            }
        }

        public void PrintBuffer()
        {
            //Create a batch File "Bill.bat"
            //type bill.txt>prn
            //exit
            System.Diagnostics.Process.Start("bill.bat");
       
        }

}

2)    private void Form1_Load(object sender, EventArgs e)
        {
            PrintBill();
        }

        private void PrintBill()
        {
            if (MessageBox.Show("Do You want to Print the Bill", "Sales Bill", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                clsPrintSettings obj = new clsPrintSettings();
                obj.ReverseSkip(2);
         
    obj.BillType = "Restaurant" + " BILL";
                obj.BillNo = "1000";
                obj.BillDt = DateTime.Now.ToShortDateString();
                obj.ClientName = "Mukul";
                obj.Clerk = "Nishant";
                obj.TotalAmt = Convert.ToDecimal("750");
                obj.Discount = Convert.ToDecimal("0");
                obj.NetAmount = Convert.ToDecimal("750");

                DataTable dt1 = new DataTable();
                               
                dt1.Columns.Add(new DataColumn("SLNo", typeof(string)));
                dt1.Columns.Add(new DataColumn("Name", typeof(string)));
                dt1.Columns.Add(new DataColumn("Qty", typeof(string)));
                dt1.Columns.Add(new DataColumn("MRP", typeof(string)));
                dt1.Columns.Add(new DataColumn("Rate", typeof(string)));
                dt1.Columns.Add(new DataColumn("T.Amt", typeof(string)));
                dt1.Columns.Add(new DataColumn("Value", typeof(string)));
                for (int i = 0; i < 5; i++)
                {
                    DataRow newrow = dt1.NewRow();
                    newrow["SLNo"] = Convert.ToString(i + 1);
                    newrow["Name"] = "Easy";
                    newrow["Qty"] = "10";
                    newrow["MRP"] = "101";
                    newrow["Rate"] = "100";
                    newrow["T.Amt"] = "1000";
                    newrow["Value"] = "1000";
                    dt1.Rows.Add(newrow);
                }

                obj.dt = dt1;
                obj.PrintHeader();
                obj.PrintDetails();
                obj.PrintFooter();
                obj.SkipLine(3);
                obj.Close();
                //obj.PrintBuffer();
                obj = null;
            }
        }
Help taken from this link



Sunday, July 3, 2011

How to Capture Function Key in Window Application

Below code is use for capture F2 key in window form:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
            if (keyData == Keys.F2)
            {
                object sender=null;
                LinkLabelLinkClickedEventArgs e=null;
                linkLabel1_LinkClicked(sender,e);
            }

            return base.ProcessCmdKey(ref msg, keyData);
}


Taken from this link



Copy File from One location to Another location with same file name

Example: I have the file Path for input file "C:/Documents/Sample.txt" now I want to use this path to get the File and then Save it to a Different Location with same file name like "E:/Downloads/Sample.txt".
Answer:
string sourcePath = @"C:\Documents\Sample.txt";
string fileName = System.IO.Path.GetFileName(sourcePath);
string destinationPath = System.IO.Path.Combine (@"E:\Downloads", fileName);  
// will result in E:\Downloads\Sample.txt
System.IO.File.Copy(sourcePath,destinationPath,true);  eg: Path: "c:\\sampletest.jpg"
                     true use for- if file already exists in destination path then it overwrites.



Execute external application through C#

Use below code to open MS Picture Manager through Window Application:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    proc.StartInfo.FileName = "ois.exe";
                    proc.StartInfo.Arguments = FilePath;//path should not have spaces. like "c:\\test.jpg"
                    proc.Start();

Saturday, July 2, 2011

Read and Write an Image into Access Database


This code is use for save the image into Access database where image column is OLE object data type:

String sourcefilepath = @"c:\windows\coffee bean.bmp";

public void File2OleDbBlob(string SourceFilePath)
        {
            try
            {
                OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb;");

                //OleDbCommand cmd = new OleDbCommand("UPDATE ImageStore SET ImageData=? WHERE SNo='1'", cn);
                OleDbCommand cmd = new OleDbCommand("insert into ImageStore(ImageData) values(?)", cn);
                System.IO.FileStream fs =
                                new System.IO.FileStream(SourceFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                Byte[] b = new Byte[fs.Length];
                fs.Read(b, 0, b.Length);
                fs.Close();
                OleDbParameter P = new OleDbParameter("@ImageData", OleDbType.VarBinary, b.Length,
                 ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, b);

                cmd.Parameters.Add(P);
                cn.Open();
                if (cmd.ExecuteNonQuery() == 1)
                    MessageBox.Show("Your images stored successfully");
                cn.Close();
            }
            catch (OleDbException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Below code is use for read the image from Access database:

String destfilepath = @"c:\mytest.bmp";

public void OleDbBlob2File(string DestFilePath)
        {
            try
            {
                int PictureCol = 0; // the column # of the BLOB field
                OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb;");

                OleDbCommand cmd = new OleDbCommand("SELECT ImageData FROM ImageStore " +
                 "WHERE SNo='1'", cn);

                cn.Open();
                OleDbDataReader dr = cmd.ExecuteReader();
                dr.Read();
                Byte[] b = new Byte[(dr.GetBytes(PictureCol, 0, null, 0, int.MaxValue))];
                dr.GetBytes(PictureCol, 0, b, 0, b.Length);
                dr.Close();
                cn.Close();
                System.IO.FileStream fs =
                 new System.IO.FileStream(DestFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);

                fs.Write(b, 0, b.Length);
                fs.Close();
                MessageBox.Show("Image written to file successfully");
            }
            catch (OleDbException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Taken from this link: http://support.microsoft.com/default.aspx?scid=kb;en-us;317016&Product=vcSnet