Tuesday, October 27, 2009

Simple Delegate example in C#


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

namespace DelegateExample
{
    public class Program
    {
      
        public delegate int Calculate(int a,int b);
        static void Main(string[] args)
        {
            myClass objMC;
            objMC = new myClass();
            // Creating objects / instances of delegate and assigning them methods of myClass
            Calculate add = new Calculate(objMC.add);
            Calculate sub = new Calculate(objMC.sub);

            // Calling myclass methods via delegate
            Console.WriteLine("2  + 3 =" + add(2, 3));
            Console.WriteLine("10  - 3 =" + sub(10, 3));
            Console.ReadLine();

  

        }
    }

    public class myClass
    {
        public myClass()
        {
        }
        public int add(int n1, int n2)
        {
            return n1 + n2;
        }
        public int sub(int n1, int n2)
        {
            return n1 - n2;
        }
    }
   
}

Monday, October 19, 2009

Using Enum in C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        public enum BillType { OPD, IPD, STORE }
        static void Main(string[] args)
        {
            generateInvloce(BillType.IPD);
        }
        public static bool generateInvloce(BillType billType)
        {
            switch (billType)
            {
                case BillType.IPD:
                    Console.WriteLine((int)BillType.IPD);
                    break;
                case BillType.OPD:
                    Console.WriteLine(BillType.OPD.ToString());
                    break;
                case BillType.STORE:
                    Console.WriteLine(BillType.STORE.ToString());
                    break;
                default:
                    break;
            }
            Console.ReadKey();
            return true;
        }
    }
}

C# CSV to Table and Table to CSV converter




using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;

///
/// Summary description for CSVTools
///
namespace Tools
{
    public class CSVTools
    {
        public CSVTools()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        static void ExportTableToCsvFile(DataTable table, bool printHeaders, String fileName)
        {
            StringBuilder sb = new StringBuilder();
            StreamWriter CSVFile = new StreamWriter(fileName);

            if (printHeaders)
            {
                //write the headers.
                for (int colCount = 0;
                     colCount < table.Columns.Count; colCount++)
                {
                    sb.Append(table.Columns[colCount].ColumnName);
                    if (colCount != table.Columns.Count - 1)
                    {
                        sb.Append(",");
                    }
                    else
                    {
                        sb.AppendLine();
                    }
                }
            }

            // Write all the rows.
            for (int rowCount = 0;
                 rowCount < table.Rows.Count; rowCount++)
            {
                for (int colCount = 0;
                     colCount < table.Columns.Count; colCount++)
                {
                    sb.Append(table.Rows[rowCount][colCount]);
                    if (colCount != table.Columns.Count - 1)
                    {
                        sb.Append(",");
                    }
                }
                if (rowCount != table.Rows.Count - 1)
                {
                    sb.AppendLine();
                }
            }
            CSVFile.Write(sb.ToString());
            CSVFile.Close();
            //return sb.ToString();
        }

        public static DataTable csvToDataTable(string file, bool isRowOneHeader)
        {

            DataTable csvDataTable = new DataTable();

            //no try/catch - add these in yourselfs or let exception happen
            String[] csvData = File.ReadAllLines(HttpContext.Current.Server.MapPath(file));

            //if no data in file ‘manually’ throw an exception
            if (csvData.Length == 0)
            {
                throw new Exception("CSV File Appears to be Empty");
            }

            String[] headings = csvData[0].Split(',');
            int index = 0; //will be zero or one depending on isRowOneHeader

            if (isRowOneHeader) //if first record lists headers
            {
                index = 1; //so we won’t take headings as data

                //for each heading
                for (int i = 0; i < headings.Length; i++)
                {
                    //replace spaces with underscores for column names
                    headings[i] = headings[i].Replace(" ", "_");

                    //add a column for each heading
                    csvDataTable.Columns.Add(headings[i], typeof(string));
                }
            }
            else //if no headers just go for col1, col2 etc.
            {
                for (int i = 0; i < headings.Length; i++)
                {
                    //create arbitary column names
                    csvDataTable.Columns.Add("col" + (i + 1).ToString(), typeof(string));
                }
            }

            //populate the DataTable
            for (int i = index; i < csvData.Length; i++)
            {
                //create new rows
                DataRow row = csvDataTable.NewRow();

                for (int j = 0; j < headings.Length; j++)
                {
                    //fill them

                    row[j] = csvData[i].Split(',')[j];
                }

                //add rows to over DataTable
                csvDataTable.Rows.Add(row);
            }

            //return the CSV DataTable
            return csvDataTable;

        }

    }

}




FTP oprations in C#, GET and PUT oprations, Checking FTP Directory Listing




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;

///
/// Summary description for FTP
///
namespace Tools
{
    public class FTP
    {
        public FTP()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static void downloadFiles(List<String> files, String targetFolder, string FTPAddress,string username, string password)
        {
            foreach (string fileToDownload in files)
            {
                downloadFile(FTPAddress, fileToDownload, targetFolder, username, password);
            }
        }
        public static void downloadFile(string FTPAddress, string filename,String targetFolder, string username, string password)
        {
            byte[] downloadedData = new byte[0];

            try
            {
               
                //Create FTP request
                //Note: format is ftp://server.com/file.ext
                FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest;

                //Get the file size first (for progress bar)
                request.Method = WebRequestMethods.Ftp.GetFileSize;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = true; //don't close the connection

                int dataLength = (int)request.GetResponse().ContentLength;

                //Now get the actual data
                request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest;
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false; //close the connection when done

                //Streams
                FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                Stream reader = response.GetResponseStream();

                //Download to memory
                //Note: adjust the streams here to download directly to the hard drive
                MemoryStream memStream = new MemoryStream();
                byte[] buffer = new byte[1024]; //downloads in chuncks

                while (true)
                {
                   

                    //Try to read the data
                    int bytesRead = reader.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        break;
                    }
                    else
                    {
                        //Write the downloaded data
                        memStream.Write(buffer, 0, bytesRead);
                                              
                    }
                }

                //Convert the downloaded stream to a byte array
                downloadedData = memStream.ToArray();
               
                // Save File to Disk
                FileStream newFile = new FileStream(targetFolder + "\\" + filename, FileMode.Create);
                newFile.Write(downloadedData, 0, downloadedData.Length);
                newFile.Close();
               
                //Clean up
                reader.Close();
                memStream.Close();
                response.Close();

                //MessageBox.Show("Downloaded Successfully");
            }
            catch (Exception)
            {
                //MessageBox.Show("There was an error connecting to the FTP Server.");
            }

            //txtData.Text = downloadedData.Length.ToString();
            //this.Text = "Download Data through FTP";

            //username = string.Empty;
            //password = string.Empty;
        }

        public static List<String> getFileList(string FTPAddress, string username, string password)
        {
            List<string> files = new List<string>();

            try
            {

                //Create FTP request
                FtpWebRequest request = FtpWebRequest.Create(FTPAddress) as FtpWebRequest;


                request.Method = WebRequestMethods.Ftp.ListDirectory;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;



                FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);

                while (!reader.EndOfStream)
                {
                    //Application.DoEvents();
                    files.Add(reader.ReadLine());
                }

                //Clean-up
                reader.Close();
                responseStream.Close(); //redundant
                response.Close();
                return files;
            }
            catch (Exception)
            {
                //MessageBox.Show("There was an error connecting to the FTP Server");
                files.RemoveRange(0, files.Count - 1);
                return files;
            }
        }
        public static bool uploadFile(string FTPAddress, string filePath, string username, string password)
        {
            try
            {
                string finePathName = Path.GetFileName(filePath);
                //Create FTP request
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + "/" + Path.GetFileName(filePath));

                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;

                //Load the file
                FileStream stream = File.OpenRead(filePath);
                byte[] buffer = new byte[stream.Length];

                stream.Read(buffer, 0, buffer.Length);
                stream.Close();

                //Upload file
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

    }
}



Followers

Search This Blog