Sunday, April 7, 2013

Read from File and Insert Data into Database

 Save abc.txt file as :
PORT_OF_DESTINATION|DESCRIPTION_OF_GOODS|CUSTOMS_TARIFF_HEADING|QUANTITY|UNIT_QUANTITY_CODE|VALUE_OF_GOODS_in_rupees
Piraeus|HESSIAN CLOTH (DETL AS PER INV)(C.E.SEALCARGO)(WE SHALL CLAIM THE BENEFITS AS ADMISSIBLE UNDER CHAPTER 3 OF FTP)|53101013|10880|MTR|540320.75
Piraeus|HESSIAN CLOTH (DETL AS PER INV)(C.E.SEALCARGO)(WE SHALL CLAIM THE BENEFITS AS ADMISSIBLE UNDER CHAPTER 3 OF FTP)|53101013|16000|YDS|603674.53
Singapore|GALV.NON ALLOY STEEL WIRE ROPE (WIRESTEEL CORE) C.E. SEAL, WE INTEND TOCLAIM BENEFITF UNDER CHAPTER 3|73121020|4000|MTR|515590.49
Singapore|UNGALV. STEEL WIRE ROPES (WIRE STEELCORE) C.E. SEAL, WE INTEND TO CLAIMBENEFITF UNDER CHAPTER 3|73121010|1500|MTR|684033.55
Jebel Ali|ELECTROLYTIC TIN PLATE AS PER INVOICE  |72101210|11.115|MTS|598274.78
Jebel Ali|ELECTROLYTIC TIN PLATE AS PER INVOICE  |72101210|24.149|MTS|1235039.42

 then

  public partial class Upload : Form
    {
        DBConnection dbObj = new DBConnection();
        public Upload()
        {
            InitializeComponent();
        }
      
        private void btnInsert_Click(object sender, EventArgs e)
        {
             try
            {
                string directoryPath = string.Empty;

                DialogResult result = openFileDialog1.ShowDialog();
                if (result == DialogResult.OK) // Test result.
                {
                    directoryPath = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
                    MessageBox.Show(directoryPath);                  
                }             
                string allReadText = File.ReadAllText(directoryPath);
                string[] listOfValue = allReadText.Replace("'", "\"").Split('|', '\n');
                string[] list = new string[100000];
                for (int i = 6, k = 0; i < listOfValue.Length; )
                {
                    string temp = string.Empty;
                    int j = 1;
                    while (j < 7)
                    {

                        temp = temp + listOfValue[i] + "|";
                        i++;
                        j++;
                    }                 
                    string[] text = temp.Split('|');
                    Records objRecord = new Records();
                    objRecord.FileId = 1;//take value from Database
                    objRecord.PortOfDescription = text[0];
                    objRecord.DescOfGoods = text[1];
                    objRecord.CustomTariff = text[2];
                    objRecord.Quantity = text[3];
                    objRecord.Unit = text[4];
                    objRecord.RateOfGoods = text[5];
                    objRecord.RecordDate = System.DateTime.Now.Date;//Take date from file creation.
                    dbObj.InsertDataIntoDataBase(objRecord);
                  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Table is finished.");
            }
        }
    }

and use dbconnection class:
 public class DBConnection
    {
        private static string connection = System.Configuration.ConfigurationSettings.AppSettings["ConStr"].ToString();
        private int result = 0;

        /// <summary>
        /// Inserts the data into data base.
        /// </summary>
        /// <param name="objRecord">The obj record.</param>
        internal void InsertDataIntoDataBase(Records objRecord)
        {
            SqlConnection con = null;
            try
            {
                using (con = new SqlConnection(connection))
                {
                    con.Open();

                    using (SqlCommand cmd = new SqlCommand("spInsertSiteRecords", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@FileId",objRecord.FileId);
                        cmd.Parameters.AddWithValue("@PortDest",objRecord.PortOfDescription);
                        cmd.Parameters.AddWithValue("@DescOfGoods",objRecord.DescOfGoods);
                        cmd.Parameters.AddWithValue("@CutomTrf",objRecord.CustomTariff);
                        cmd.Parameters.AddWithValue("@Quantity",objRecord.Quantity);
                        cmd.Parameters.AddWithValue("@Unit",objRecord.Unit);
                        cmd.Parameters.AddWithValue("@RateInRupees",objRecord.RateOfGoods);
                        cmd.Parameters.AddWithValue("@RecordDate",objRecord.RecordDate);
                        result = cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                VMSLog(ex.Message);
                VMSLog(ex.StackTrace);

            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }

        /// <summary>
        /// VMSs the log.
        /// </summary>
        /// <param name="Message">The message.</param>
        public void VMSLog(string Message)
        {
            StreamWriter sw = null;
            try
            {
                string sMonth = "";
                string sLogFormat = DateTime.Now.ToShortDateString().ToString() + DateTime.Now.ToLongTimeString().ToString() + " : ";
                string sPathName = ".\\";
                string sYear = DateTime.Now.Year.ToString();
                if (DateTime.Now.Month < 10)
                    sMonth = "0" + DateTime.Now.Month.ToString();
                else
                    sMonth = DateTime.Now.Month.ToString();
                string sDay = DateTime.Now.Day.ToString();
                string sErrorTime = sDay + "-" + sMonth + "-" + sYear;
                sw = new StreamWriter(sPathName + "VMSLog " + sErrorTime + ".txt", true);
                sw.WriteLine(sLogFormat + Message);
                sw.Flush();

            }
            catch (Exception ex)
            {
                VMSLog(ex.Message);

            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                    sw.Close();
                }
            }
        }
    }

and Recordsclass is data object class:
 public class Records
    {
        public int FileId { get; set; }
        public string PortOfDescription { get; set; }
        public string DescOfGoods { get; set; }
        public string CustomTariff { get; set; }
        public string Quantity { get; set; }
        public string Unit { get; set; }
        public string RateOfGoods { get; set; }
        public DateTime RecordDate { get; set; }

    }

and in App.config file :
 <appSettings>
    <add key="ConStr" value="Data Source=BELAKUR-PC;Initial Catalog=IceGateDB;Integrated Security=True"/>
  </appSettings>

No comments:

Post a Comment