----------------------------------------------------ClsCommon.cs----------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Data.SqlClient;
namespace ImportCDRsShedule
{
public class ClsCommon
{
public static string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
}
public static DataSet Convert(string File, string TableName, string delimiter)
{
//The DataSet to Return
DataSet result = new DataSet();
//Open the file in a stream reader.
StreamReader sd = new StreamReader(File);
double mycount = 0;
string COl = "Column";
string myCOl = "";
//Split the first line into the columns
string[] columns = sd.ReadLine().Split(delimiter.ToCharArray());
//Add the new DataTable to the RecordSet
result.Tables.Add(TableName);
//Cycle the colums, adding those that don't exist yet
//and sequencing the one that do.
foreach (string col in columns)
{
bool added = false;
string next = "";
int i = 0;
while (!added)
{
////Build the column name and remove any unwanted characters.
string columnname = col + next;
//columnname = columnname.Replace(";", "");
//columnname = columnname.Replace("#", "");
//columnname = columnname.Replace("'", "");
//columnname = columnname.Replace("&", "");
//columnname = columnname.Replace(";;", "");
//See if the column already exists
if (!result.Tables[TableName].Columns.Contains(columnname))
{
mycount = mycount + 1;
myCOl = COl + mycount;
//if it doesn't then we add it here and mark it as added
result.Tables[TableName].Columns.Add(myCOl);
added = true;
}
else
{
//if it did exist then we increment the sequencer and try again.
i++;
next = "_" + i.ToString();
}
}
}
StreamReader sdk = new StreamReader(File);
//Read the rest of the data in the file.
string AllData = sdk.ReadToEnd();
//Split off each row at the Carriage Return/Line Feed
//Default line ending in most windows exports.
//You may have to edit this to match your particular file.
//This will work for Excel, Access, etc. default exports.
char[] delimiters = new char[] { '\n' };
string[] rows = AllData.Split(delimiters);
//Now add each row to the DataSet
foreach (string r in rows)
{
//Split the row at the delimiter.
string[] items = r.Split(delimiter.ToCharArray());
//Add the item
result.Tables[TableName].Rows.Add(items);
}
//remove empty row
for (int i = result.Tables[TableName].Rows.Count - 1; i >= 0; i--)
{
if (result.Tables[TableName].Rows[i][1] == DBNull.Value)
{
result.Tables[TableName].Rows[i].Delete();
}
}
result.Tables[TableName].AcceptChanges();
//Return the imported data.
return result;
}
public void createsqltable(DataTable dt, string tablename)
{
//string table = "";
//table += "IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + tablename + "]') AND type in (N'U'))";
//table += "BEGIN ";
//table += "create table " + tablename + "";
//table += "(";
//for (int i = 0; i < dt.Columns.Count; i++)
//{
// if (i != dt.Columns.Count - 1)
// table += dt.Columns[i].ColumnName + " " + "varchar(max)" + ",";
// else
// table += dt.Columns[i].ColumnName + " " + "varchar(max)";
//}
//table += ") ";
//table += "END";
//InsertQuery(table);
CopyData(dt, tablename);
}
public void InsertQuery(string qry)
{
SqlConnection connection = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = qry;
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
public static void CopyData(DataTable dt, string tablename)
{
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(GetConnectionString(), SqlBulkCopyOptions.TableLock))
{
bulkCopy.DestinationTableName = tablename;
bulkCopy.WriteToServer(dt);
}
}
public static void Log(string logMessage, TextWriter w)
{
w.Write("\r\nLog Entry : ");
w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
w.WriteLine(" :");
w.WriteLine(" :{0}", logMessage);
w.WriteLine("-------------------------------");
}
public static void DumpLog(StreamReader r)
{
string line;
while ((line = r.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
----------------------------------------------------Program.cs----------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace ImportCDRsShedule
{
public class Program
{
public static string tablename;
public static void Main()
{
ClsCommon objCommon = new ClsCommon();
var dateString = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
var filenameString = "T" + dateString;
tablename = "adeelTCDR" + dateString;
objCommon.InsertQuery(" exec spCDRTableCreate " + tablename);
using (StreamWriter w = File.AppendText(@"D:\LogImportCDRsShedule.txt"))
{
ClsCommon.Log("Sucessfully log", w);
}
using (StreamReader r = File.OpenText(@"D:\LogImportCDRsShedule.txt"))
{
ClsCommon.DumpLog(r);
}
// Put all txt files in root directory into array.
string[] arrayMSC1 = Directory.GetFiles(@"D:\MSC1\", filenameString + "*.CDR"); // <-- Case
// Console.WriteLine("--- CDR Files: ---");
foreach (string name in arrayMSC1)
{
FileInfo f = new FileInfo(name);
long s1 = f.Length;
if (s1 > 0)
{
DataSet ds = ClsCommon.Convert(name, "MyNewTable", ";");
if (ds.Tables[0].Rows.Count != 0)
{
DataTable dt = ds.Tables["MyNewTable"];
ClsCommon.CopyData(dt, tablename);
dt = null;
ds = null;
}
}
}
// Put all txt files in root directory into array.
string[] arrayMSC2 = Directory.GetFiles(@"D:\MSC2\", filenameString + "*.CDR"); // <-- Case
//string[] array2 = Directory.GetFiles(@"D:\MSC2\", "*.CDR"); // <-- Case
// Console.WriteLine("--- CDR Files: ---");
foreach (string name in arrayMSC2)
{
FileInfo f = new FileInfo(name);
long s1 = f.Length;
if (s1 > 0)
{
DataSet ds = ClsCommon.Convert(name, "MyNewTable", ";");
if (ds.Tables[0].Rows.Count != 0)
{
DataTable dt = ds.Tables["MyNewTable"];
ClsCommon.CopyData(dt, tablename);
dt = null;
ds = null;
}
}
}
}
}
}
----------------------------------------------------App.config----------------------------------
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="DBConnectionString" connectionString="Data Source=.;Initial Catalog=Billing_2015;Integrated Security=True" providerName="SystemSqlclient"/>
</connectionStrings>
</configuration>
No comments :
Post a Comment