我是C#development的新手。有人请给出带有文本文件的示例解决方案,以便用SQL进行读/写。
答案 0 :(得分:0)
FXCalculation.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.Text.RegularExpressions;
using System.Globalization;
namespace EmployeeValidator
{
class FXCalculation
{
public void ProcessData( string sourcefolder,string sourcefilename,stringerrorfolder,string errorfilename,string archievefolder,string archievefile,stringsqlcon)
{
//call all the method inside this
// throw user defined exception “FXCalculationException if folder or files doesn’t exists
FXCalculation fxcalculation = new FXCalculation();
List<Trade> trades = new List<Trade>();
trades = fxcalculation.ReadAlltextfromfile(sourcefolder,sourcefilename);
List<Trade> validtrades = fxcalculation.PickValidTradeDetails(trades, errorfolder, errorfilename);
fxcalculation.SendValidTradeDetailsToDB(validtrades, sqlcon);
List<FxRate> fxrates= fxcalculation.CalculateFXRate(sqlcon);
SaveFxRatestoDB(fxrates, sqlcon);
}
public List<Trade> ReadAlltextfromfile(string sourcefolder,string sourcefilename)
{
List<Trade> trades = new List<Trade>();
//read all the text from file
//return it in a list
try
{
trades = File.ReadLines(sourcefolder + sourcefilename)
.Select(i => i.Split(','))
.Select(g => new Trade()
{
tradeId = g[0],
ISIN = g[1],
tradedate = g[2],
maturitydate = g[3],
currency = g[4],
amount = g[5],
tradetype = g[6],
schemename = g[7]
}).ToList();
return trades;
}
catch (FileNotFoundException ex)
{
throw;
}
}
public List<Trade> PickValidTradeDetails(List<Trade> list,stringerrorlogfolder,string errorlogfile)
{
List<Trade> validtrades = new List<Trade>();
List<Trade> invalidTrades = new List<Trade>();
bool isvalid = true;
//get the valid details based on below conditions and return it in list
//call method SendInvalidTradingdetailsToLog() for invalid details
//tradeId should starts with “TR” and not be null
//ISIN should starts with “INSI” and followed by 3 numeric digits
//trade date should be in format(mm/dd/yyyy)
//maturity date should be in format(mm/dd/yyyy) and maturity years should be greater than 5 from trade date
//schemename should not be numeric
//tradetype should not be null,
//Currency should be 3 digits
//Amount should be numeric and not null
Regex IsTradeId = new Regex(@"^[TR][0-9]+$");
Regex IsISIN = new Regex(@"^[INSI][0-9]{3}$");
Regex Isscheme = new Regex(@"^[a-zA-Z]+$");
Regex Iscur = new Regex(@"^[A-Z]{3}$");
Regex IsAmo = new Regex(@"^[0-9]+$");
foreach (var item in list)
{
DateTime oparsed, dparsed;
if ((item.tradeId.Substring(0,2) == "TR" && item.tradeId != string.Empty) &&
(item.ISIN.Substring(0,4) == "INSI" && Regex.Match(item.ISIN, @"\d{3}$").Success) &&
(DateTime.TryParseExact(item.tradedate, "MM/dd/yyyy", CultureInfo.InvariantCulture,DateTimeStyles.None,out oparsed) &&
(DateTime.TryParseExact(item.maturitydate, "MM/dd/yyyy",CultureInfo.InvariantCulture,DateTimeStyles.None, out dparsed) &&
(Regex.Match(item.schemename,@"^[a-zA-Z]+$").Success))))
{
if((DateTime.ParseExact(item.tradedate,"MM/dd/yyyy", newCultureInfo("en-US")) -
}
if (!IsTradeId.IsMatch(item.tradeId) || !IsISIN.IsMatch(item.ISIN) || !Isscheme.IsMatch(item.schemename) || !Iscur.IsMatch(item.currency) || !IsAmo.IsMatch(item.amount))
{
isvalid = false;
}
if (item.tradetype == null || item.tradetype==string.Empty)
{
isvalid = false;
}
DateTime outdatetime,outdatetime1;
if (!DateTime.TryParse(item.tradedate, new CultureInfo("en-US"), DateTimeStyles.None,out outdatetime))
{
isvalid = false;
}
if (!DateTime.TryParse(item.maturitydate,new CultureInfo("en-US"),DateTimeStyles.None,out outdatetime1))
{
isvalid = false;
}
if (!isvalid)
{
invalidTrades.Add(item);
}
else
{
validtrades.Add(item);
}
}
if (invalidTrades.Count()>0)
{
SendInvalidTradingdetailsToLog(invalidTrades, errorlogfolder, errorlogfile);
}
return validtrades;
}
public bool SendInvalidTradingdetailsToLog(List<Trade> trades,stringerrorfolder,string errorfilename)
{
//Send invalid details to error log folder with filename extensions ErrorLog_mm/dd
//return true if the file is saved successfully
using (StreamWriter sw = File.AppendText(errorfolder + errorfilename + "ErrorLog_mm/dd"))
{
foreach (var item in trades)
{
sw.WriteLine(item.tradeId + ',' + item.ISIN + ',' + item.tradedate + ',' + item.maturitydate + ',' + item.currency + ',' + item.amount + ',' + item.tradetype + ',' + item.schemename);
}
}
return true;
}
public bool SendValidTradeDetailsToDB(List<Trade> trades,string slconn)
{
// save the values inside the validtrade list
// save the details to DB to the TradingDetails_Table
int i = -1;
SqlConnection con = new SqlConnection(slconn);
foreach (var item in trades)
{
using (SqlCommand cmd = new SqlCommand("Insert into TradingDetails_Table Values(@TradeId,@ISIN,@TradeDate,@MaturityDate,@Currency,@Amount,@Tradetype,@Schemename)", con))
{
cmd.Parameters.AddWithValue("@TradeId", item.tradeId);
cmd.Parameters.AddWithValue("@ISIN", item.ISIN);
cmd.Parameters.AddWithValue("@TradeDate", item.tradedate);
cmd.Parameters.AddWithValue("@MaturityDate", item.maturitydate);
cmd.Parameters.AddWithValue("@Currency", item.currency);
cmd.Parameters.AddWithValue("@Amount", item.amount);
cmd.Parameters.AddWithValue("@Tradetype", item.tradetype);
cmd.Parameters.AddWithValue("@Schemename", item.schemename);
con.Open();
i=cmd.ExecuteNonQuery();
con.Close();
}
}
//if its saved successfully
if (i > -1)
{
return true;
}
else
return false;
}
public List<FxRate> CalculateFXRate(string sqlconn)
{
List<FxRate> Fxrates = new List<FxRate>();
SqlConnection con = new SqlConnection(sqlconn);
// get the trade details from the DB where Tradetype = “FX”
// calculate FX rate based on the below conditions
// If Currency = “USD” then CalculatedFxrate = amount * 0.5
// If Currency = “BPS” then amount *0.6
// If Currency = “EUR” then amount *0.7
// If Currency = “GER” then amount *1
using (SqlCommand cmd= new SqlCommand("select TradeId,Currency,Amount From TradeDetails_Table Where Tradetype='FX'",con))
{
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
FxRate fx = new FxRate();
fx.tradeId = dt.Rows[i][0].ToString();
fx.currency = dt.Rows[i][1].ToString();
fx.amount = dt.Rows[i][2].ToString();
switch (fx.currency)
{
case "USD":
fx.appliedFxrate = Convert.ToString(0.5);
fx.calculatedFxRate = Convert.ToString(Convert.ToInt32(fx.amount) * 0.5);
break;
case "BPS":
fx.appliedFxrate = Convert.ToString(0.6);
fx.calculatedFxRate = Convert.ToString(Convert.ToInt32(fx.amount) * 0.6);
break;
case "EUR":
fx.appliedFxrate = Convert.ToString(0.7);
fx.calculatedFxRate = Convert.ToString(Convert.ToInt32(fx.amount) * 0.7);
break;
case "GER":
fx.appliedFxrate = Convert.ToString(1);
fx.calculatedFxRate = Convert.ToString(Convert.ToInt32(fx.amount) * 1);
break;
}
Fxrates.Add(fx);
}
}
return Fxrates;
//it in a list Fxrates
}
//0.5, 0.6… appliedFxRate
public void SaveFxRatestoDB(List<FxRate> list,string SqlConn)
{
//Save the calculatedFXrates along with tradeId, currency and amount in the table FxRates_Table
// return true if it is saved successfully
int i = -1;
SqlConnection con = new SqlConnection(SqlConn);
foreach (var item in list)
{
using (SqlCommand cmd = new SqlCommand("Insert into FxRate_Table Values(@TradeId,@Currency,@Amount,@AppliedFxrate,@CalculatedFxRate)", con))
{
cmd.Parameters.AddWithValue("@TradeId", item.tradeId);
cmd.Parameters.AddWithValue("@Currency", item.currency);
cmd.Parameters.AddWithValue("@Amount", item.amount);
cmd.Parameters.AddWithValue("@AppliedFxrate", item.appliedFxrate);
cmd.Parameters.AddWithValue("@CalculatedFxRate", item.calculatedFxRate);
con.Open();
i = cmd.ExecuteNonQuery();
con.Close();
}
}
}
public void Copyfiletoarchieve(string sourcefolderWithName,stringdestinationfolderWithName)
{
//Copy the file from input folder to the achieve folder with file extension “Filname_Processed”
// If the file already exists delete it and add the new one
if (File.Exists(destinationfolderWithName))
File.Delete(destinationfolderWithName);
File.Copy(sourcefolderWithName, destinationfolderWithName);
File.AppendText(destinationfolderWithName + "Filname_Processed");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
namespace EmployeeValidation
{
public class Program
{
public static void Main()
{
/*
* Pass the file path, file names and connection string if any in this method alone.
* Do not hardcode in any other methods
*/
SqlConnection connection = new SqlConnection(@"Data Source=PC233649;Initial Catalog=DBEmployeeValidation;Integrated Security=True");
EmployeeValidator empValidator = new EmployeeValidator();
empValidator.ProcessData(@"C:\Users\153239\Desktop\Input File\", "Emp_122014.xml", connection);
}
}
}
EmployeeValidator.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Serialization;
using System.Text.RegularExpressions;
using System.Xml;
namespace EmployeeValidation
{
public class EmployeeValidator
{
/*
* Do not remove the attached TestProject. It is meant for auto evaluation of your source code.
* Do not attach any test classess to the attached test project.
* Do not attach any new test projects.
* You are not required to write any automated test cases. You are supposed to write only the code.
*/
public void ProcessData(string xmlFilePath, string xmlFileName, SqlConnectionconnection)
{
EmployeeValidator empVal = new EmployeeValidator();
List<Employee> lstemp = new List<Employee>();
lstemp = empVal.ReadAllEmployeesFromXmlFile(xmlFilePath, xmlFileName);
lstemp = empVal.PickValidEmployees(lstemp);
empVal.SaveValidEmployeesToDB(lstemp, connection);
}
public List<Employee> ReadAllEmployeesFromXmlFile(string xmlFilePath, stringxmlFileName)
{
try
{
List<Employee> empList = new List<Employee>();
XElement xelement = XElement.Load(xmlFilePath + xmlFileName);
IEnumerable<XElement> allEmployees = xelement.Elements();
foreach (var allEmployee in allEmployees)
{
empList.Add(new Employee()
{
EmployeeId = allEmployee.Element("EmployeeId").Value,
EmployeeName = allEmployee.Element("EmployeeName").Value,
EmailId = allEmployee.Element("EmailId").Value,
DateOfJoining = allEmployee.Element("DateOfJoining").Value
});
}
return empList;
}
catch (FileNotFoundException ex)
{
throw new EmployeeValidatorException(ex.Message);
}
}
public List<Employee> PickValidEmployees(List<Employee> employees)
{
List<Employee> empList = new List<Employee>();
Regex IsNumeric = new Regex(@"^\D+$");
Regex IsAlphaNumeric = new Regex(@"\W+$");
Regex IsvalidEmail = new Regex(@"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$");
empList = employees.Select(x => employees.Find(
m => m.EmployeeName != null && m.EmployeeName != string.Empty
&& !IsNumeric.IsMatch(m.EmployeeId.ToString()) && !IsAlphaNumeric.IsMatch(m.EmployeeName)
)).Distinct().ToList();
return empList;
}
public void SaveValidEmployeesToDB(List<Employee> employees, SqlConnectionconnection)
{
string query = @"Insert into SBA.Employees(EmployeeId,EmployeeName,DateOfJoining,EmailId)
Values(@EmployeeId,@EmployeeName,@DateOfJoining,@EmailId)";
connection.Open();
using (SqlCommand cmd = new SqlCommand(query, connection))
{
foreach (Employee emp in employees)
{
cmd.Parameters.AddWithValue("@EmployeeId", emp.EmployeeId);
cmd.Parameters.AddWithValue("@EmployeeName", emp.EmployeeName);
cmd.Parameters.AddWithValue("@EmailId", emp.EmailId);
cmd.Parameters.AddWithValue("@DateOfJoining", emp.DateOfJoining);
int i = cmd.ExecuteNonQuery();
}
}
connection.Close();
}
}
}
Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmployeeValidation
{
public class Employee
{
/*
* Do not modify the return types of the below properties
*
*/
public string EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string EmailId { get; set; }
public string DateOfJoining { get; set; }
}
// Do not add new constructors
}
Employeevalidatorexception.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EmployeeValidation
{
public class EmployeeValidatorException : Exception
{
public EmployeeValidatorException()
: base()
{
}
public EmployeeValidatorException(string message)
: base(message)
{
Console.WriteLine(message);
}
}
}
FxRate.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EmployeeValidator
{
class FxRate
{
public string tradeId { get; set; }
public string currency { get; set; }
public string amount { get; set; }
public string appliedFxrate { get; set; }
public string calculatedFxRate { get; set; }
}
}
Trade.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EmployeeValidator
{
public class Trade
{
public string tradeId { get; set; }
public string ISIN { get; set; }
public string tradedate { get; set; }
public string maturitydate { get; set; }
public string currency { get; set; }
public string amount { get; set; }
public string tradetype { get; set; }
public string schemename { get; set; }
}
}
答案 1 :(得分:0)
Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmployeeValidation
{
public class Employee
{
/*
* Do not modify the return types of the below properties
*
*/
public string EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string EmailId { get; set; }
public string DateOfJoining { get; set; }
}
// Do not add new constructors
}
Program.cs
public class Program
{
public static void Main()
{
SqlConnection connection = new SqlConnection(@"Data Source=PC233649;Initial Catalog=DBEmployeeValidation;Integrated Security=True");
EmployeeValidator empValidator = new EmployeeValidator();
empValidator.ProcessData(@"C:\Users\a\Desktop\Input File\","Emp_122.xml", connection);
}
EmployeeValidator.cs
public class EmployeeValidator
{
public void ProcessData(string xmlFilePath, string xmlFileName, SqlConnection connection)
{
EmployeeValidator empVal = new EmployeeValidator();
List<Employee> lstemp = new List<Employee>();
lstemp = empVal.ReadAllEmployeesFromXmlFile(xmlFilePath, xmlFileName);
lstemp = empVal.PickValidEmployees(lstemp);
empVal.SaveValidEmployeesToDB(lstemp, connection);
}
EmployeeValidator.cs
public List<Employee> ReadAllEmployeesFromXmlFile(string xmlFilePath, string xmlFileName)
{
List<Employee> empList = new List<Employee>();
XElement xelement = XElement.Load(xmlFilePath + xmlFileName);
IEnumerable<XElement> allEmployees = xelement.Elements();
foreach (var allEmployee in allEmployees)
{
empList.Add(new Employee()
{
EmployeeId = allEmployee.Element("EmployeeId").Value,
EmployeeName = allEmployee.Element("EmployeeName").Value,
EmailId = allEmployee.Element("EmailId").Value,
DateOfJoining = allEmployee.Element("DateOfJoining").Value
});
}
return empList;
}
EmployeeValidator.cs
public List<Employee> PickValidEmployees(List<Employee> employees)
{
List<Employee> empList = new List<Employee>();
Regex IsNumeric = new Regex(@"^\D+$");
Regex IsAlphaNumeric = new Regex(@"\W+$");
Regex IsvalidEmail = new Regex(@"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$");
empList = employees.Select(x => employees.Find( m => m.EmployeeName != null && m.EmployeeName != string.Empty
&& !IsNumeric.IsMatch(m.EmployeeId.ToString()) && !IsAlphaNumeric.IsMatch(m.EmployeeName)
)).Distinct().ToList();
return empList;
}
(or)
extractuniquelist = employees.GroupBy(x => x.EmployeeId).Select(y => y.First()).ToList();
foreach (var emp in extractuniquelist)
{
if ((IsNumeric.IsMatch(emp.EmployeeName)) && (emp.EmployeeId != "") && (IsAlphaNumeric.IsMatch(emp.EmployeeName)) && (emp.EmployeeName != "") && (email.IsMatch(emp.EmailId)))
{
empList.Add(new Employee
{
EmployeeId = emp.EmployeeId,
EmployeeName = emp.EmployeeName,
EmailId = emp.EmailId,
DateOfJoining = emp.DateOfJoining
});
}
}
EmployeeValidator.cs
public void SaveValidEmployeesToDB(List<Employee> employees, SqlConnection connection)
{
string query = @"Insert into SBA.Employees(EmployeeId,EmployeeName,DateOfJoining,EmailId) Values(@EmployeeId,@EmployeeName,@DateOfJoining,@EmailId)";
connection.Open();
using (SqlCommand cmd = new SqlCommand(query, connection))
{
foreach (Employee emp in employees)
{
cmd.Parameters.AddWithValue("@EmployeeId", emp.EmployeeId);
cmd.Parameters.AddWithValue("@EmployeeName", emp.EmployeeName);
cmd.Parameters.AddWithValue("@EmailId", emp.EmailId);
cmd.Parameters.AddWithValue("@DateOfJoining", emp.DateOfJoining);
int i = cmd.ExecuteNonQuery();
}
}
connection.Close();
}
Read from TEXT file
public List<Employee> ReadValuesfromTextfile(string fpath, string fname)
{
List<Employee> readedValues = new List<Employee>();
if (Directory.Exists(fpath))
{
if (File.Exists(fpath + fname))
{
using (StreamReader sr = new StreamReader(fpath + fname))
{
while (!sr.EndOfStream)
{
string readline = sr.ReadLine();
if (readline != null && readline != "")
{
readedValues.Add(new Employee
{
EmployeeId = readline.Split(',')[0],
EmployeeName = readline.Split(',')[1],
EmailId = readline.Split(',')[2],
DateOfJoining = readline.Split(',')[3]
});
}
}
}
}
}
return readedValues;
}
Read From XML file
public List<Employee> ReadFromXmlFile(string FilePath, string FileName)
{
List<Employee> emplist = new List<Employee>();
if (Directory.Exists(FilePath))
{
if (File.Exists(FilePath + FileName))
{
StreamReader sr = new StreamReader(FilePath + FileName);
XmlSerializer xSerializer = new XmlSerializer(typeof(List<Employee>),
new XmlRootAttribute("Employees"));
emplist = (List<Employee>)xSerializer.Deserialize(sr);
}
}
return emplist;
}
Read From Database
public List<Employee> savefromDBtoTextfile(SqlConnection connetion)
{
DataTable dt = new DataTable();
List<Employee> selectlist = new List<Employee>();
string query = "select * from SBA.Employees";
connetion.Open();
using (SqlCommand cmd = new SqlCommand(query, connetion))
{
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
connetion.Close();
foreach (DataRow emp in dt.Rows)
{
selectlist.Add(new Employee
{
EmployeeId = emp["EmployeeId"].ToString(),
EmployeeName = emp["EmployeeName"].ToString(),
EmailId = emp["EmailId"].ToString(),
DateOfJoining = emp["DateOfJoining"].ToString()
});
}
return selectlist;
}
Write to Text File
public void WritetoTextFile(List<Employee> writelist, string FilePath)
{
using (StreamWriter sw = File.CreateText(FilePath + "newtxtfile.txt"))
{
foreach (var emp in writelist)
{
sw.WriteLine(emp.EmployeeId + " " + emp.EmployeeName + " " +emp.EmailId + " " + emp.DateOfJoining + " ");
}
}
}
Write to XML File
public void writeXmlfile(List<Employee> epmlist)
{
var fileName = @"K:\redir\Desktop\TestDotnet\Input File\TestFile.xml";
using (StreamWriter sw = new StreamWriter(fileName))
{
XmlSerializer xmlsr = new XmlSerializer(typeof(List<Employee>), new XmlRootAttribute("Employees"));
xmlsr.Serialize(sw, epmlist);
sw.Flush();
sw.Close();
}
}
Insert into Database
public void SaveValidEmployeesToDB(List<Employee> employees, SqlConnection connection)
{
string query = @"Insert into SBA.Employees(EmployeeId,EmployeeName,DateOfJoining,EmailId) Values(@EmployeeId,@EmployeeName,@DateOfJoining,@EmailId)";
connection.Open();
using (SqlCommand cmd = new SqlCommand(query, connection))
{
foreach (Employee emp in employees)
{
cmd.Parameters.AddWithValue("@EmployeeId", emp.EmployeeId);
cmd.Parameters.AddWithValue("@EmployeeName", emp.EmployeeName);
cmd.Parameters.AddWithValue("@EmailId", emp.EmailId);
cmd.Parameters.AddWithValue("@DateOfJoining", emp.DateOfJoining);
int i = cmd.ExecuteNonQuery();
}
}
connection.Close();
}